1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.spf4j.test.log;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.List;
21 import javax.annotation.concurrent.ThreadSafe;
22 import org.hamcrest.Description;
23 import org.hamcrest.Matcher;
24 import org.hamcrest.StringDescription;
25
26
27
28
29 @ThreadSafe
30 public final class ExactLogStreamMatcher implements LogStreamMatcher {
31
32 private final Matcher<TestLogRecord>[] matchers;
33
34 private final List<TestLogRecord> matched;
35
36 private int at;
37
38 private final boolean assertSeen;
39
40 private final Object sync;
41
42 public ExactLogStreamMatcher(final boolean assertSeen, final Matcher<TestLogRecord>... matchers) {
43 if (matchers.length < 1) {
44 throw new IllegalArgumentException("You need to provide at least a matcher " + Arrays.toString(matchers));
45 }
46 this.matchers = matchers;
47 this.matched = new ArrayList<>(matchers.length);
48 this.at = 0;
49 this.assertSeen = assertSeen;
50 this.sync = new Object();
51 }
52
53
54 @Override
55 public boolean isMatched() {
56 if (assertSeen) {
57 synchronized (sync) {
58 return at >= matchers.length;
59 }
60 } else {
61 synchronized (sync) {
62 return at < matchers.length;
63 }
64 }
65 }
66
67 @Override
68 public void accept(final TestLogRecord record) {
69 synchronized (sync) {
70 if (at < matchers.length && matchers[at].matches(record)) {
71 at++;
72 record.attach(Attachments.ASSERTED);
73 matched.add(record);
74 }
75 }
76 }
77
78 @Override
79 public void describeTo(final Description description) {
80 if (assertSeen) {
81 description.appendText("Expected: ");
82 } else {
83 description.appendText("Not expected: ");
84 }
85 matchers[0].describeTo(description);
86 for (int i = 1; i < matchers.length; i++) {
87 description.appendText("\n");
88 matchers[i].describeTo(description);
89 }
90 description.appendText("\n");
91 description.appendValueList("Matched:\n", ",", " logs", matched);
92 }
93
94 @Override
95 public String toString() {
96 StringDescription sd = new StringDescription();
97 describeTo(sd);
98 return sd.toString();
99 }
100
101 }