1   package com.atlassian.core.util.filter;
2   
3   import junit.framework.Assert;
4   import junit.framework.TestCase;
5   
6   import java.util.ArrayList;
7   import java.util.Arrays;
8   import java.util.Iterator;
9   import java.util.List;
10  
11  public class TestListFilter extends TestCase
12  {
13      private List testList = Arrays.asList(new String[]{"a", "b", null, "c"});
14  
15      public void testFilter()
16      {
17          testFilter("a", new String[]{"b", null, "c"});
18          testFilter("b", new String[]{"a", null, "c"});
19          testFilter(null, new String[]{"a", "b", "c"});
20          testFilter("c", new String[]{"a", "b", null});
21      }
22  
23      public void testRemove()
24      {
25          List myList = new ArrayList(testList);
26          Filter filter = new Filter()
27          {
28              public boolean isIncluded(Object o)
29              {
30                  return o == null || !o.equals("b");
31              }
32          };
33  
34          String[] expected = new String[]{"a", null, "c"};
35  
36          Iterator it = new ListFilter(filter).filterIterator(myList.iterator());
37          int i = 0;
38          while (it.hasNext())
39          {
40              Assert.assertEquals(expected[i++], it.next());
41              it.remove();
42          }
43  
44          Assert.assertEquals(1, myList.size());
45          Assert.assertEquals("b", myList.get(0));
46      }
47  
48      private void testFilter(String filterOut, String[] expected)
49      {
50          final String fo = filterOut;
51          Filter filter = new Filter()
52          {
53              public boolean isIncluded(Object o)
54              {
55                  if (o == null)
56                  {
57                      return o != fo;
58                  }
59  
60                  return !o.equals(fo);
61              }
62          };
63  
64          Assert.assertEquals(Arrays.asList(expected), new ListFilter(filter).filterList(testList));
65  
66          Iterator it = new ListFilter(filter).filterIterator(testList.iterator());
67          int i = 0;
68          while (it.hasNext())
69          {
70              // make sure we can keep calling it.hasNext()
71              Assert.assertTrue(it.hasNext());
72              Assert.assertEquals(expected[i++], it.next());
73          }
74  
75          // check we can call hasNext again after the end of the list
76          Assert.assertFalse(it.hasNext());
77          Assert.assertEquals("correct number in iterator", expected.length, i);
78      }
79  }