Use hamcrest regex matcher rather than our own (#104457)

The difference is that our matcher uses .find() to search for a regex match anywhere in the string, whereas the hamcrest one uses .matches() to check the whole string against the regex. This leads to more specific regex checks.

I've left our own one for YAML tests, as that way we don't need to mangle the regex to add .* either side, which might be confusing in test failures.
This commit is contained in:
Simon Cooper 2024-02-22 16:15:36 +00:00 committed by GitHub
parent 39dd09bb3d
commit b752169ee9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 100 additions and 97 deletions

View file

@ -101,13 +101,13 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import static org.elasticsearch.snapshots.AbstractSnapshotIntegTestCase.forEachFileRecursively; import static org.elasticsearch.snapshots.AbstractSnapshotIntegTestCase.forEachFileRecursively;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
@ -1286,7 +1286,7 @@ public class InstallPluginActionTests extends ESTestCase {
) )
); );
assertEquals(ExitCodes.IO_ERROR, e.exitCode); assertEquals(ExitCodes.IO_ERROR, e.exitCode);
assertThat(e, hasToString(matches("checksum file at \\[.*\\] is not for this plugin"))); assertThat(e, hasToString(matchesRegex(".*checksum file at \\[.*\\] is not for this plugin.*")));
} }
public void testInvalidShaFileContainingExtraLine() throws Exception { public void testInvalidShaFileContainingExtraLine() throws Exception {

View file

@ -22,12 +22,13 @@ import org.elasticsearch.test.rest.ObjectPath;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.matchesRegex;
public class Netty4BadRequestIT extends ESRestTestCase { public class Netty4BadRequestIT extends ESRestTestCase {
@ -63,7 +64,7 @@ public class Netty4BadRequestIT extends ESRestTestCase {
); );
assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(BAD_REQUEST.getStatus())); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(BAD_REQUEST.getStatus()));
assertThat(e, hasToString(containsString("too_long_http_line_exception"))); assertThat(e, hasToString(containsString("too_long_http_line_exception")));
assertThat(e, hasToString(matches("An HTTP line is larger than \\d+ bytes"))); assertThat(e, hasToString(matchesRegex(Pattern.compile(".*An HTTP line is larger than \\d+ bytes.*", Pattern.DOTALL))));
} }
public void testInvalidParameterValue() throws IOException { public void testInvalidParameterValue() throws IOException {

View file

@ -26,7 +26,6 @@ import org.elasticsearch.core.PathUtils;
import org.elasticsearch.env.Environment; import org.elasticsearch.env.Environment;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
@ -48,7 +47,9 @@ import static org.elasticsearch.core.Strings.format;
import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
public class EvilLoggerTests extends ESTestCase { public class EvilLoggerTests extends ESTestCase {
@ -82,14 +83,14 @@ public class EvilLoggerTests extends ESTestCase {
+ System.getProperty("es.logs.cluster_name") + System.getProperty("es.logs.cluster_name")
+ ".log"; + ".log";
final List<String> events = Files.readAllLines(PathUtils.get(path)); final List<String> events = Files.readAllLines(PathUtils.get(path));
assertThat(events.size(), equalTo(5)); assertThat(events, hasSize(5));
final String location = "org.elasticsearch.common.logging.EvilLoggerTests.testLocationInfoTest"; final String location = "org.elasticsearch.common.logging.EvilLoggerTests.testLocationInfoTest";
// the first message is a warning for unsupported configuration files // the first message is a warning for unsupported configuration files
assertLogLine(events.get(0), Level.ERROR, location, "This is an error message"); assertLogLine(events.get(0), Level.ERROR, location, ".*This is an error message");
assertLogLine(events.get(1), Level.WARN, location, "This is a warning message"); assertLogLine(events.get(1), Level.WARN, location, ".*This is a warning message");
assertLogLine(events.get(2), Level.INFO, location, "This is an info message"); assertLogLine(events.get(2), Level.INFO, location, ".*This is an info message");
assertLogLine(events.get(3), Level.DEBUG, location, "This is a debug message"); assertLogLine(events.get(3), Level.DEBUG, location, ".*This is a debug message");
assertLogLine(events.get(4), Level.TRACE, location, "This is a trace message"); assertLogLine(events.get(4), Level.TRACE, location, ".*This is a trace message");
} }
public void testConcurrentDeprecationLogger() throws IOException, BrokenBarrierException, InterruptedException { public void testConcurrentDeprecationLogger() throws IOException, BrokenBarrierException, InterruptedException {
@ -166,14 +167,14 @@ public class EvilLoggerTests extends ESTestCase {
matcher.matches(); matcher.matches();
return Integer.parseInt(matcher.group(1)); return Integer.parseInt(matcher.group(1));
})); }));
assertThat(deprecationEvents.size(), equalTo(128)); assertThat(deprecationEvents, hasSize(128));
for (int i = 0; i < 128; i++) { for (int i = 0; i < 128; i++) {
assertLogLine( assertLogLine(
deprecationEvents.get(i), deprecationEvents.get(i),
DeprecationLogger.CRITICAL, DeprecationLogger.CRITICAL,
"org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0", "org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0",
"This is a maybe logged deprecation message" + i ".*This is a maybe logged deprecation message" + i + ".*"
); );
} }
@ -201,12 +202,12 @@ public class EvilLoggerTests extends ESTestCase {
+ "_deprecation.log"; + "_deprecation.log";
final List<String> deprecationEvents = Files.readAllLines(PathUtils.get(deprecationPath)); final List<String> deprecationEvents = Files.readAllLines(PathUtils.get(deprecationPath));
if (iterations > 0) { if (iterations > 0) {
assertThat(deprecationEvents.size(), equalTo(1)); assertThat(deprecationEvents, hasSize(1));
assertLogLine( assertLogLine(
deprecationEvents.get(0), deprecationEvents.get(0),
DeprecationLogger.CRITICAL, DeprecationLogger.CRITICAL,
"org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0", "org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0",
"\\[deprecated.foo\\] setting was deprecated in Elasticsearch and will be removed in a future release." ".*\\[deprecated.foo\\] setting was deprecated in Elasticsearch and will be removed in a future release..*"
); );
} }
} }
@ -246,7 +247,7 @@ public class EvilLoggerTests extends ESTestCase {
e.printStackTrace(pw); e.printStackTrace(pw);
final int stackTraceLength = sw.toString().split(System.getProperty("line.separator")).length; final int stackTraceLength = sw.toString().split(System.getProperty("line.separator")).length;
final int expectedLogLines = 3; final int expectedLogLines = 3;
assertThat(events.size(), equalTo(expectedLogLines + stackTraceLength)); assertThat(events, hasSize(expectedLogLines + stackTraceLength));
for (int i = 0; i < expectedLogLines; i++) { for (int i = 0; i < expectedLogLines; i++) {
assertThat("Contents of [" + path + "] are wrong", events.get(i), startsWith("[" + getTestName() + "]" + prefix + " test")); assertThat("Contents of [" + path + "] are wrong", events.get(i), startsWith("[" + getTestName() + "]" + prefix + " test"));
} }
@ -287,8 +288,8 @@ public class EvilLoggerTests extends ESTestCase {
+ System.getProperty("es.logs.cluster_name") + System.getProperty("es.logs.cluster_name")
+ ".log"; + ".log";
final List<String> events = Files.readAllLines(PathUtils.get(path)); final List<String> events = Files.readAllLines(PathUtils.get(path));
assertThat(events.size(), equalTo(2)); assertThat(events, hasSize(2));
final String location = "org.elasticsearch.common.logging.LogConfigurator"; final String location = "org.elasticsearch.common.logging.LogConfigurator.*";
// the first message is a warning for unsupported configuration files // the first message is a warning for unsupported configuration files
assertLogLine( assertLogLine(
events.get(0), events.get(0),
@ -324,12 +325,14 @@ public class EvilLoggerTests extends ESTestCase {
LogConfigurator.configure(environment, true); LogConfigurator.configure(environment, true);
} }
private static final Pattern LOG_LINE = Pattern.compile("\\[(.*)]\\[(.*)\\(.*\\)] (.*)");
private void assertLogLine(final String logLine, final Level level, final String location, final String message) { private void assertLogLine(final String logLine, final Level level, final String location, final String message) {
final Matcher matcher = Pattern.compile("\\[(.*)\\]\\[(.*)\\(.*\\)\\] (.*)").matcher(logLine); Matcher matcher = LOG_LINE.matcher(logLine);
assertTrue(logLine, matcher.matches()); assertTrue(logLine, matcher.matches());
assertThat(matcher.group(1), equalTo(level.toString())); assertThat(matcher.group(1), equalTo(level.toString()));
assertThat(matcher.group(2), RegexMatcher.matches(location)); assertThat(matcher.group(2), matchesRegex(location));
assertThat(matcher.group(3), RegexMatcher.matches(message)); assertThat(matcher.group(3), matchesRegex(message));
} }
} }

View file

@ -8,7 +8,6 @@
package org.elasticsearch.common.logging; package org.elasticsearch.common.logging;
import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.ESRestTestCase;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
@ -22,6 +21,8 @@ import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.matchesRegex;
/** /**
* This test verifies that Elasticsearch can startup successfully with a custom logging config using variables introduced in * This test verifies that Elasticsearch can startup successfully with a custom logging config using variables introduced in
* <code>ESJsonLayout</code> * <code>ESJsonLayout</code>
@ -35,14 +36,14 @@ public class CustomLoggingConfigIT extends ESRestTestCase {
public void testSuccessfulStartupWithCustomConfig() throws Exception { public void testSuccessfulStartupWithCustomConfig() throws Exception {
assertBusy(() -> { assertBusy(() -> {
List<String> lines = readAllLines(getPlaintextLogFile()); List<String> lines = readAllLines(getPlaintextLogFile());
assertThat(lines, Matchers.hasItem(RegexMatcher.matches(NODE_STARTED))); assertThat(lines, Matchers.hasItem(matchesRegex(NODE_STARTED)));
}); });
} }
public void testParseAllV7JsonLines() throws Exception { public void testParseAllV7JsonLines() throws Exception {
assertBusy(() -> { assertBusy(() -> {
List<String> lines = readAllLines(getJSONLogFile()); List<String> lines = readAllLines(getJSONLogFile());
assertThat(lines, Matchers.hasItem(RegexMatcher.matches(NODE_STARTED))); assertThat(lines, Matchers.hasItem(matchesRegex(NODE_STARTED)));
}); });
} }

View file

@ -19,7 +19,6 @@ import org.elasticsearch.telemetry.TestTelemetryPlugin;
import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo; import java.lang.management.ThreadInfo;
@ -36,6 +35,7 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFa
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.in; import static org.hamcrest.Matchers.in;
import static org.hamcrest.Matchers.matchesRegex;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0) @ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0)
public class SimpleThreadPoolIT extends ESIntegTestCase { public class SimpleThreadPoolIT extends ESIntegTestCase {
@ -107,7 +107,7 @@ public class SimpleThreadPoolIT extends ESIntegTestCase {
+ "|" + "|"
+ Pattern.quote(ESIntegTestCase.TEST_CLUSTER_NODE_PREFIX) + Pattern.quote(ESIntegTestCase.TEST_CLUSTER_NODE_PREFIX)
+ ")"; + ")";
assertThat(threadName, RegexMatcher.matches("\\[" + nodePrefix + "\\d+\\]")); assertThat(threadName, matchesRegex("elasticsearch\\[" + nodePrefix + "\\d+\\].*"));
} }
} }

View file

@ -12,7 +12,6 @@ import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import org.hamcrest.core.IsSame; import org.hamcrest.core.IsSame;
import java.io.IOException; import java.io.IOException;
@ -26,10 +25,10 @@ import java.util.regex.Matcher;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static org.elasticsearch.common.logging.HeaderWarning.WARNING_HEADER_PATTERN; import static org.elasticsearch.common.logging.HeaderWarning.WARNING_HEADER_PATTERN;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
/** /**
@ -37,7 +36,7 @@ import static org.hamcrest.Matchers.not;
*/ */
public class HeaderWarningTests extends ESTestCase { public class HeaderWarningTests extends ESTestCase {
private static final RegexMatcher warningValueMatcher = matches(WARNING_HEADER_PATTERN.pattern()); private static final org.hamcrest.Matcher<String> warningValueMatcher = matchesRegex(WARNING_HEADER_PATTERN);
private final HeaderWarning logger = new HeaderWarning(); private final HeaderWarning logger = new HeaderWarning();

View file

@ -178,7 +178,6 @@ import static org.elasticsearch.cluster.routing.TestShardRouting.shardRoutingBui
import static org.elasticsearch.common.lucene.Lucene.cleanLuceneIndex; import static org.elasticsearch.common.lucene.Lucene.cleanLuceneIndex;
import static org.elasticsearch.index.IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING; import static org.elasticsearch.index.IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.elasticsearch.xcontent.ToXContent.EMPTY_PARAMS; import static org.elasticsearch.xcontent.ToXContent.EMPTY_PARAMS;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder;
@ -195,6 +194,7 @@ import static org.hamcrest.Matchers.in;
import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
@ -1431,7 +1431,7 @@ public class IndexShardTests extends IndexShardTestCase {
* the race, then the other thread lost the race and only one operation should have been executed. * the race, then the other thread lost the race and only one operation should have been executed.
*/ */
assertThat(e, instanceOf(IllegalStateException.class)); assertThat(e, instanceOf(IllegalStateException.class));
assertThat(e, hasToString(matches("operation primary term \\[\\d+\\] is too old"))); assertThat(e, hasToString(matchesRegex(".*operation primary term \\[\\d+\\] is too old.*")));
assertThat(counter.get(), equalTo(1L)); assertThat(counter.get(), equalTo(1L));
} else { } else {
assertThat(counter.get(), equalTo(2L)); assertThat(counter.get(), equalTo(2L));

View file

@ -61,7 +61,6 @@ import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.internal.AliasFilter; import org.elasticsearch.search.internal.AliasFilter;
import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.test.IndexSettingsModule; import org.elasticsearch.test.IndexSettingsModule;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -89,6 +88,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -606,7 +606,7 @@ public class IndicesServiceTests extends ESSingleNodeTestCase {
); );
final String pattern = final String pattern =
".*multiple engine factories provided for \\[foobar/.*\\]: \\[.*FooEngineFactory\\],\\[.*BarEngineFactory\\].*"; ".*multiple engine factories provided for \\[foobar/.*\\]: \\[.*FooEngineFactory\\],\\[.*BarEngineFactory\\].*";
assertThat(e, hasToString(new RegexMatcher(pattern))); assertThat(e, hasToString(matchesRegex(pattern)));
} }
public void testBuildAliasFilter() { public void testBuildAliasFilter() {

View file

@ -21,9 +21,9 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.matchesRegex;
public class IndexStorePluginTests extends ESTestCase { public class IndexStorePluginTests extends ESTestCase {
@ -112,7 +112,7 @@ public class IndexStorePluginTests extends ESTestCase {
assertThat( assertThat(
e, e,
hasToString( hasToString(
matches( matchesRegex(
"java.lang.IllegalStateException: Duplicate key store \\(attempted merging values " "java.lang.IllegalStateException: Duplicate key store \\(attempted merging values "
+ "org.elasticsearch.index.store.FsDirectoryFactory@[\\w\\d]+ " + "org.elasticsearch.index.store.FsDirectoryFactory@[\\w\\d]+ "
+ "and org.elasticsearch.index.store.FsDirectoryFactory@[\\w\\d]+\\)" + "and org.elasticsearch.index.store.FsDirectoryFactory@[\\w\\d]+\\)"

View file

@ -50,7 +50,7 @@ import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toCollection; import static java.util.stream.Collectors.toCollection;
import static org.elasticsearch.core.Tuple.tuple; import static org.elasticsearch.core.Tuple.tuple;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches; import static org.elasticsearch.test.rest.yaml.section.RegexMatcher.matches;
import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo;

View file

@ -21,7 +21,7 @@ import java.util.regex.Pattern;
import static org.elasticsearch.test.ListMatcher.matchesList; import static org.elasticsearch.test.ListMatcher.matchesList;
import static org.elasticsearch.test.MapMatcher.assertMap; import static org.elasticsearch.test.MapMatcher.assertMap;
import static org.elasticsearch.test.MapMatcher.matchesMap; import static org.elasticsearch.test.MapMatcher.matchesMap;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches; import static org.elasticsearch.test.rest.yaml.section.RegexMatcher.matches;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;

View file

@ -6,7 +6,7 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
package org.elasticsearch.test.hamcrest; package org.elasticsearch.test.rest.yaml.section;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher; import org.hamcrest.TypeSafeMatcher;
@ -16,17 +16,17 @@ import java.util.regex.Pattern;
/** /**
* Matcher that supports regular expression and allows to provide optional flags * Matcher that supports regular expression and allows to provide optional flags
*/ */
public class RegexMatcher extends TypeSafeMatcher<String> { class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex; private final String regex;
private final Pattern pattern; private final Pattern pattern;
public RegexMatcher(String regex) { RegexMatcher(String regex) {
this.regex = regex; this.regex = regex;
this.pattern = Pattern.compile(regex); this.pattern = Pattern.compile(regex);
} }
public RegexMatcher(String regex, int flag) { RegexMatcher(String regex, int flag) {
this.regex = regex; this.regex = regex;
this.pattern = Pattern.compile(regex, flag); this.pattern = Pattern.compile(regex, flag);
} }

View file

@ -46,7 +46,6 @@ import java.util.stream.Collectors;
import static org.elasticsearch.common.logging.DeprecatedMessage.KEY_FIELD_NAME; import static org.elasticsearch.common.logging.DeprecatedMessage.KEY_FIELD_NAME;
import static org.elasticsearch.common.logging.DeprecatedMessage.X_OPAQUE_ID_FIELD_NAME; import static org.elasticsearch.common.logging.DeprecatedMessage.X_OPAQUE_ID_FIELD_NAME;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
@ -56,6 +55,7 @@ import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesRegex;
/** /**
* Tests that deprecation message are returned via response headers, and can be indexed into a data stream. * Tests that deprecation message are returned via response headers, and can be indexed into a data stream.
@ -152,7 +152,7 @@ public class DeprecationHttpIT extends ESRestTestCase {
final Response response = client().performRequest(request); final Response response = client().performRequest(request);
final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders()); final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders());
assertThat(deprecatedWarnings, everyItem(matches(HeaderWarning.WARNING_HEADER_PATTERN.pattern()))); assertThat(deprecatedWarnings, everyItem(matchesRegex(HeaderWarning.WARNING_HEADER_PATTERN)));
final List<String> actualWarningValues = deprecatedWarnings.stream() final List<String> actualWarningValues = deprecatedWarnings.stream()
.map(s -> HeaderWarning.extractWarningValueFromWarningHeader(s, true)) .map(s -> HeaderWarning.extractWarningValueFromWarningHeader(s, true))
@ -295,7 +295,7 @@ public class DeprecationHttpIT extends ESRestTestCase {
headerMatchers.add(equalTo(TestDeprecationHeaderRestAction.DEPRECATED_USAGE)); headerMatchers.add(equalTo(TestDeprecationHeaderRestAction.DEPRECATED_USAGE));
} }
assertThat(deprecatedWarnings, everyItem(matches(HeaderWarning.WARNING_HEADER_PATTERN.pattern()))); assertThat(deprecatedWarnings, everyItem(matchesRegex(HeaderWarning.WARNING_HEADER_PATTERN)));
final List<String> actualWarningValues = deprecatedWarnings.stream() final List<String> actualWarningValues = deprecatedWarnings.stream()
.map(s -> HeaderWarning.extractWarningValueFromWarningHeader(s, true)) .map(s -> HeaderWarning.extractWarningValueFromWarningHeader(s, true))
.collect(Collectors.toList()); .collect(Collectors.toList());

View file

@ -6,20 +6,19 @@
*/ */
package org.elasticsearch.xpack.sql.qa.cli; package org.elasticsearch.xpack.sql.qa.cli;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.matchesRegex;
public abstract class LenientTestCase extends CliIntegrationTestCase { public abstract class LenientTestCase extends CliIntegrationTestCase {
public void testLenientCommand() throws IOException { public void testLenientCommand() throws IOException {
index("test", body -> body.field("name", "foo").field("tags", new String[] { "bar", "bar" })); index("test", body -> body.field("name", "foo").field("tags", new String[] { "bar", "bar" }));
assertEquals("[?1l>[?1000l[?2004llenient set to [90mtrue[0m", command("lenient = true")); assertEquals("[?1l>[?1000l[?2004llenient set to [90mtrue[0m", command("lenient = true"));
assertThat(command("SELECT * FROM test"), RegexMatcher.matches("\\s*name\\s*\\|\\s*tags\\s*")); assertThat(command("SELECT * FROM test"), matchesRegex(".*\\s*name\\s*\\|\\s*tags\\s*.*"));
assertThat(readLine(), containsString("----------")); assertThat(readLine(), containsString("----------"));
assertThat(readLine(), RegexMatcher.matches("\\s*foo\\s*\\|\\s*bar\\s*")); assertThat(readLine(), matchesRegex(".*\\s*foo\\s*\\|\\s*bar\\s*.*"));
assertEquals("", readLine()); assertEquals("", readLine());
} }

View file

@ -6,11 +6,10 @@
*/ */
package org.elasticsearch.xpack.sql.qa.cli; package org.elasticsearch.xpack.sql.qa.cli;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.matchesRegex;
public abstract class SelectTestCase extends CliIntegrationTestCase { public abstract class SelectTestCase extends CliIntegrationTestCase {
public void testSelect() throws IOException { public void testSelect() throws IOException {
@ -32,9 +31,9 @@ public abstract class SelectTestCase extends CliIntegrationTestCase {
public void testSelectWithWhere() throws IOException { public void testSelectWithWhere() throws IOException {
index("test", body -> body.field("test_field", "test_value1").field("i", 1)); index("test", body -> body.field("test_field", "test_value1").field("i", 1));
index("test", body -> body.field("test_field", "test_value2").field("i", 2)); index("test", body -> body.field("test_field", "test_value2").field("i", 2));
assertThat(command("SELECT * FROM test WHERE i = 2"), RegexMatcher.matches("\\s*i\\s*\\|\\s*test_field\\s*")); assertThat(command("SELECT * FROM test WHERE i = 2"), matchesRegex(".*\\s*i\\s*\\|\\s*test_field\\s*.*"));
assertThat(readLine(), containsString("----------")); assertThat(readLine(), containsString("----------"));
assertThat(readLine(), RegexMatcher.matches("\\s*2\\s*\\|\\s*test_value2\\s*")); assertThat(readLine(), matchesRegex(".*\\s*2\\s*\\|\\s*test_value2\\s*.*"));
assertEquals("", readLine()); assertEquals("", readLine());
} }
} }

View file

@ -6,12 +6,13 @@
*/ */
package org.elasticsearch.xpack.sql.qa.cli; package org.elasticsearch.xpack.sql.qa.cli;
import org.elasticsearch.test.hamcrest.RegexMatcher;
import java.io.IOException; import java.io.IOException;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.matchesRegex;
public abstract class ShowTestCase extends CliIntegrationTestCase { public abstract class ShowTestCase extends CliIntegrationTestCase {
@ -20,24 +21,24 @@ public abstract class ShowTestCase extends CliIntegrationTestCase {
public void testShowTables() throws IOException { public void testShowTables() throws IOException {
index("test1", body -> body.field("test_field", "test_value")); index("test1", body -> body.field("test_field", "test_value"));
index("test2", body -> body.field("test_field", "test_value")); index("test2", body -> body.field("test_field", "test_value"));
assertThat(command("SHOW TABLES"), RegexMatcher.matches("\\s*name\\s*")); assertThat(command("SHOW TABLES"), matchesRegex(".*\\s*name\\s*.*"));
assertThat(readLine(), containsString(HEADER_SEPARATOR)); assertThat(readLine(), containsString(HEADER_SEPARATOR));
assertThat(readLine(), RegexMatcher.matches("\\s*test[12]\\s*")); assertThat(readLine(), matchesRegex(".*\\s*test[12]\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*test[12]\\s*")); assertThat(readLine(), matchesRegex(".*\\s*test[12]\\s*.*"));
assertEquals("", readLine()); assertThat(readLine(), is(emptyString()));
} }
public void testShowFunctions() throws IOException { public void testShowFunctions() throws IOException {
assertThat(command("SHOW FUNCTIONS"), RegexMatcher.matches("\\s*name\\s*\\|\\s*type\\s*")); assertThat(command("SHOW FUNCTIONS"), matchesRegex(".*\\s*name\\s*\\|\\s*type\\s*.*"));
assertThat(readLine(), containsString(HEADER_SEPARATOR)); assertThat(readLine(), containsString(HEADER_SEPARATOR));
assertThat(readLine(), RegexMatcher.matches("\\s*AVG\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*AVG\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*COUNT\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*COUNT\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*FIRST\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*FIRST\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*FIRST_VALUE\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*FIRST_VALUE\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LAST\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LAST\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LAST_VALUE\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LAST_VALUE\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*MAX\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*MAX\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*MIN\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*MIN\\s*\\|\\s*AGGREGATE\\s*.*"));
String line = readLine(); String line = readLine();
Pattern aggregateFunction = Pattern.compile("\\s*[A-Z0-9_~]+\\s*\\|\\s*AGGREGATE\\s*"); Pattern aggregateFunction = Pattern.compile("\\s*[A-Z0-9_~]+\\s*\\|\\s*AGGREGATE\\s*");
while (aggregateFunction.matcher(line).matches()) { while (aggregateFunction.matcher(line).matches()) {
@ -56,43 +57,43 @@ public abstract class ShowTestCase extends CliIntegrationTestCase {
line = readLine(); line = readLine();
} }
assertThat(line, RegexMatcher.matches("\\s*SCORE\\s*\\|\\s*SCORE\\s*")); assertThat(line, matchesRegex(".*\\s*SCORE\\s*\\|\\s*SCORE\\s*.*"));
assertEquals("", readLine()); assertThat(readLine(), is(emptyString()));
} }
public void testShowFunctionsLikePrefix() throws IOException { public void testShowFunctionsLikePrefix() throws IOException {
assertThat(command("SHOW FUNCTIONS LIKE 'L%'"), RegexMatcher.matches("\\s*name\\s*\\|\\s*type\\s*")); assertThat(command("SHOW FUNCTIONS LIKE 'L%'"), matchesRegex(".*\\s*name\\s*\\|\\s*type\\s*.*"));
assertThat(readLine(), containsString(HEADER_SEPARATOR)); assertThat(readLine(), containsString(HEADER_SEPARATOR));
assertThat(readLine(), RegexMatcher.matches("\\s*LAST\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LAST\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LAST_VALUE\\s*\\|\\s*AGGREGATE\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LAST_VALUE\\s*\\|\\s*AGGREGATE\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LEAST\\s*\\|\\s*CONDITIONAL\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LEAST\\s*\\|\\s*CONDITIONAL\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LOG\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LOG\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LOG10\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LOG10\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LCASE\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LCASE\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LEFT\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LEFT\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LENGTH\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LENGTH\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LOCATE\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LOCATE\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*LTRIM\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*LTRIM\\s*\\|\\s*SCALAR\\s*.*"));
assertEquals("", readLine()); assertThat(readLine(), is(emptyString()));
} }
public void testShowFunctionsLikeInfix() throws IOException { public void testShowFunctionsLikeInfix() throws IOException {
assertThat(command("SHOW FUNCTIONS LIKE '%DAY%'"), RegexMatcher.matches("\\s*name\\s*\\|\\s*type\\s*")); assertThat(command("SHOW FUNCTIONS LIKE '%DAY%'"), matchesRegex(".*\\s*name\\s*\\|\\s*type\\s*.*"));
assertThat(readLine(), containsString(HEADER_SEPARATOR)); assertThat(readLine(), containsString(HEADER_SEPARATOR));
assertThat(readLine(), RegexMatcher.matches("\\s*DAY\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAY\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAYNAME\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAYNAME\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAYOFMONTH\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAYOFMONTH\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAYOFWEEK\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAYOFWEEK\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAYOFYEAR\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAYOFYEAR\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAY_NAME\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAY_NAME\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAY_OF_MONTH\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAY_OF_MONTH\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAY_OF_WEEK\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAY_OF_WEEK\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*DAY_OF_YEAR\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*DAY_OF_YEAR\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*HOUR_OF_DAY\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*HOUR_OF_DAY\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*ISODAYOFWEEK\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*ISODAYOFWEEK\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*ISO_DAY_OF_WEEK\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*ISO_DAY_OF_WEEK\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*MINUTE_OF_DAY\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*MINUTE_OF_DAY\\s*\\|\\s*SCALAR\\s*.*"));
assertThat(readLine(), RegexMatcher.matches("\\s*TODAY\\s*\\|\\s*SCALAR\\s*")); assertThat(readLine(), matchesRegex(".*\\s*TODAY\\s*\\|\\s*SCALAR\\s*.*"));
assertEquals("", readLine()); assertThat(readLine(), is(emptyString()));
} }
} }