1package com.xtremelabs.robolectric.shadows;
2
3import android.content.UriMatcher;
4import android.net.Uri;
5import com.xtremelabs.robolectric.Robolectric;
6import com.xtremelabs.robolectric.WithTestDefaultsRunner;
7import com.xtremelabs.robolectric.shadows.ShadowUriMatcher.MatchNode;
8import org.junit.Before;
9import org.junit.Test;
10import org.junit.runner.RunWith;
11
12import static org.hamcrest.CoreMatchers.is;
13import static org.hamcrest.CoreMatchers.nullValue;
14import static org.junit.Assert.assertThat;
15import static org.junit.matchers.JUnitMatchers.hasItem;
16
17@RunWith(WithTestDefaultsRunner.class)
18public class UriMatcherTest {
19	static final String AUTH = "com.foo";
20	static final int NO_MATCH = -2;
21
22	UriMatcher matcher;
23	MatchNode root;
24    Uri URI;
25
26	@Before public void getMatcher() {
27        URI = Uri.parse("content://" + AUTH);
28		matcher = new UriMatcher(NO_MATCH);
29		root = Robolectric.shadowOf(matcher).rootNode;
30	}
31
32	@Test public void canInstantiate() {
33		assertThat(root.code, is(NO_MATCH));
34		assertThat(root.map.isEmpty(), is(true));
35		assertThat(root.number, is(nullValue()));
36		assertThat(root.text, is(nullValue()));
37	}
38
39	@Test public void canAddBasicMatch() {
40		MatchNode node = root;
41		String path = "bar/cat";
42
43		matcher.addURI(AUTH, path, 1);
44		assertThat(node.map.keySet(), hasItem(AUTH));
45
46		node = node.map.get(AUTH);
47		assertThat(node.map.keySet(), hasItem("bar"));
48
49		node = node.map.get("bar");
50		assertThat(node.map.keySet(), hasItem("cat"));
51
52		node = node.map.get("cat");
53		assertThat(node.code, is(1));
54	}
55
56	@Test public void canAddWildcardMatches() {
57		matcher.addURI(AUTH, "#", 1);
58		matcher.addURI(AUTH, "*", 2);
59		MatchNode node = root.map.get(AUTH);
60
61		assertThat(node.number.code, is(1));
62		assertThat(node.text.code, is(2));
63	}
64
65	@Test public void canMatch() {
66		matcher.addURI(AUTH, "bar", 1);
67		assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(1));
68
69		matcher.addURI(AUTH, "bar/#", 2);
70		assertThat(matcher.match(Uri.withAppendedPath(URI, "bar/1")), is(2));
71
72		matcher.addURI(AUTH, "*", 3);
73		assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(1));
74		assertThat(matcher.match(Uri.withAppendedPath(URI, "cat")), is(3));
75
76		matcher.addURI(AUTH, "transport/*/#/type", 4);
77		assertThat(matcher.match(Uri.withAppendedPath(URI, "transport/land/45/type")), is(4));
78	}
79
80	@Test public void returnsRootCodeForIfNoMatch() {
81		matcher.addURI(AUTH, "bar/#", 1);
82		assertThat(matcher.match(Uri.withAppendedPath(URI, "cat")), is(NO_MATCH));
83		assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(NO_MATCH));
84		assertThat(matcher.match(Uri.withAppendedPath(URI, "bar/cat")), is(NO_MATCH));
85	}
86
87}
88