1package org.owasp.html; 2 3import java.util.Arrays; 4import java.util.List; 5 6import javax.annotation.Nullable; 7 8import org.junit.Test; 9 10import junit.framework.TestCase; 11 12import com.google.common.collect.ImmutableList; 13import com.google.common.collect.Lists; 14 15import static org.owasp.html.ElementPolicy.REJECT_ALL_ELEMENT_POLICY; 16import static org.owasp.html.ElementPolicy.IDENTITY_ELEMENT_POLICY; 17import static org.owasp.html.ElementPolicy.Util.join; 18 19public final class ElementPolicyTest extends TestCase { 20 21 static class HasCharElementPolicy implements ElementPolicy { 22 final char ch; 23 24 HasCharElementPolicy(char ch) { 25 this.ch = ch; 26 } 27 28 public @Nullable 29 String apply(String elementName, List<String> attrs) { 30 attrs.clear(); 31 return elementName.indexOf(ch) >= 0 ? elementName : null; 32 } 33 34 @Override 35 public String toString() { 36 return "(has '" + ch + "')"; 37 } 38 } 39 40 private static void assertPassed(ElementPolicy p, String... expected) { 41 List<String> attrs = Lists.newArrayList(); 42 ImmutableList.Builder<String> actual = ImmutableList.builder(); 43 for (String elName : TEST_EL_NAMES) { 44 if (p.apply(elName, attrs) != null) { 45 actual.add(elName); 46 } 47 } 48 assertEquals(p.toString(), Arrays.asList(expected), actual.build()); 49 } 50 51 private static List<String> TEST_EL_NAMES = ImmutableList.of( 52 "abacus", "abracadabra", "bar", "foo", "far", "cadr", "cdr"); 53 54 @Test 55 public static final void testJoin() { 56 ElementPolicy a = new HasCharElementPolicy('a'); 57 ElementPolicy b = new HasCharElementPolicy('b'); 58 ElementPolicy c = new HasCharElementPolicy('c'); 59 ElementPolicy d = new HasCharElementPolicy('d'); 60 assertPassed(REJECT_ALL_ELEMENT_POLICY); 61 assertPassed(IDENTITY_ELEMENT_POLICY, 62 TEST_EL_NAMES.toArray(new String[0])); 63 assertPassed(a, "abacus", "abracadabra", "bar", "far", "cadr"); 64 assertPassed(c, "abacus", "abracadabra", "cadr", "cdr"); 65 assertPassed(d, "abracadabra", "cadr", "cdr"); 66 ElementPolicy a_b = join(a, b); 67 ElementPolicy b_a = join(b, a); 68 assertPassed(a_b, "abacus", "abracadabra", "bar"); 69 assertPassed(b_a, "abacus", "abracadabra", "bar"); 70 assertPassed(join(b_a, b_a), "abacus", "abracadabra", "bar"); 71 assertPassed(join(a_b, c), "abacus", "abracadabra"); 72 assertPassed(join(c, REJECT_ALL_ELEMENT_POLICY)); 73 assertPassed(join(REJECT_ALL_ELEMENT_POLICY, a_b)); 74 } 75 76} 77