1 package com.atlassian.webdriver.utils.element;
2
3 import com.google.common.collect.Iterables;
4 import org.hamcrest.Description;
5 import org.hamcrest.FeatureMatcher;
6 import org.hamcrest.Matcher;
7 import org.hamcrest.Matchers;
8 import org.hamcrest.TypeSafeMatcher;
9 import org.openqa.selenium.WebElement;
10
11 import javax.annotation.Nonnull;
12 import javax.annotation.Nullable;
13
14 import static com.google.common.base.Preconditions.checkNotNull;
15
16
17
18
19
20
21
22 public final class WebElementMatchers
23 {
24
25 private WebElementMatchers()
26 {
27 throw new AssertionError("Don't instantiate me");
28 }
29
30
31 public static <T> Matcher<Iterable<T>> containsAtLeast(final Matcher<T> elementMatcher, final int numberOfMatchingItems)
32 {
33 return new TypeSafeMatcher<Iterable<T>>()
34 {
35 @Override
36 public boolean matchesSafely(Iterable<T> elements)
37 {
38 if (Iterables.size(elements) < numberOfMatchingItems)
39 {
40 return false;
41 }
42 int matchCount = 0;
43 for (T item : elements)
44 {
45 if (elementMatcher.matches(item))
46 {
47 matchCount++;
48 }
49 }
50 return matchCount >= numberOfMatchingItems;
51 }
52
53 public void describeTo(Description description)
54 {
55 description.appendText("Contains at least ").appendValue(numberOfMatchingItems)
56 .appendText(" items matching ").appendDescriptionOf(elementMatcher);
57 }
58 };
59 }
60
61
62
63
64
65
66 @Nonnull
67 public static Matcher<WebElement> withText(@Nullable String expectedText) {
68 return withTextThat(Matchers.is(expectedText));
69 }
70
71
72
73
74
75
76 @Nonnull
77 public static Matcher<WebElement> withTextThat(@Nonnull Matcher<String> textMatcher) {
78 return new FeatureMatcher<WebElement, String>(textMatcher, "text", "text") {
79
80 @Override
81 protected String featureValueOf(WebElement actual)
82 {
83 return actual.getText();
84 }
85 };
86 }
87
88 public static Matcher<WebElement> tagNameEqual(final String expectedTagName)
89 {
90 checkNotNull(expectedTagName);
91 return new TypeSafeMatcher<WebElement>()
92 {
93 @Override
94 public boolean matchesSafely(WebElement item)
95 {
96 return expectedTagName.equals(item.getTagName());
97 }
98
99 public void describeTo(Description description)
100 {
101 description.appendText("Tag name should be equal to ").appendValue(expectedTagName);
102 }
103 };
104 }
105 }