Skip to content

Commit

Permalink
Expand uses of matchers for Optionals (#104123)
Browse files Browse the repository at this point in the history
Also add variants to assert for specific values
  • Loading branch information
thecoop committed Jan 9, 2024
1 parent dcb019d commit 0d53be3
Show file tree
Hide file tree
Showing 24 changed files with 231 additions and 153 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import static org.elasticsearch.test.hamcrest.ModuleDescriptorMatchers.exportsOf;
import static org.elasticsearch.test.hamcrest.ModuleDescriptorMatchers.opensOf;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isEmpty;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresent;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
Expand All @@ -51,16 +51,13 @@ public void testVersion() {
assertThat(over, isEmpty());

over = EmbeddedModulePath.version("foo-1.2.jar");
assertThat(over, isPresent());
assertThat(over.get(), is(Version.parse("1.2")));
assertThat(over, isPresentWith(Version.parse("1.2")));

over = EmbeddedModulePath.version("foo-bar-1.2.3-SNAPSHOT.jar");
assertThat(over, isPresent());
assertThat(over.get(), is(Version.parse("1.2.3-SNAPSHOT")));
assertThat(over, isPresentWith(Version.parse("1.2.3-SNAPSHOT")));

over = EmbeddedModulePath.version("elasticsearch-8.3.0-SNAPSHOT.jar");
assertThat(over, isPresent());
assertThat(over.get(), is(Version.parse("8.3.0-SNAPSHOT")));
assertThat(over, isPresentWith(Version.parse("8.3.0-SNAPSHOT")));

expectThrows(IAE, () -> EmbeddedModulePath.version(""));
expectThrows(IAE, () -> EmbeddedModulePath.version("foo"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
import static org.elasticsearch.test.hamcrest.ModuleDescriptorMatchers.providesOf;
import static org.elasticsearch.test.hamcrest.ModuleDescriptorMatchers.requiresOf;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresent;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.iterableWithSize;
import static org.hamcrest.Matchers.not;

public class InMemoryModuleFinderTests extends ESTestCase {
Expand All @@ -45,7 +47,7 @@ public void testOfModuleDescriptor() {
ModuleDescriptor fooMd = ModuleDescriptor.newModule("foo").build();
ModuleDescriptor barMd = ModuleDescriptor.newModule("bar").build();
var finder = InMemoryModuleFinder.of(fooMd, barMd);
assertThat(finder.findAll().size(), is(2));
assertThat(finder.findAll(), hasSize(2));
var fooMod = finder.find("foo");
var barMod = finder.find("bar");
assertThat(fooMod, isPresent());
Expand Down Expand Up @@ -79,7 +81,7 @@ public void testAutoModuleEmbeddedJar() throws Exception {

// automatic module, and no filtering
var finder = InMemoryModuleFinder.of(Set.of(), fooRoot);
assertThat(finder.findAll().size(), is(1));
assertThat(finder.findAll(), hasSize(1));
var mod = finder.find("foo");
assertThat(mod, isPresent());
assertThat(mod.get().descriptor().isAutomatic(), is(true));
Expand Down Expand Up @@ -135,7 +137,7 @@ private void testExplicitModuleEmbeddedJarVersionSpecific(int version) throws Ex
try (FileSystem fileSystem = FileSystems.newFileSystem(outerJar, Map.of(), InMemoryModuleFinderTests.class.getClassLoader())) {
Path mRoot = fileSystem.getPath("/a/b/m.jar");
var finder = InMemoryModuleFinder.of(Set.of(), mRoot);
assertThat(finder.findAll().size(), is(1));
assertThat(finder.findAll(), hasSize(1));
var mref = finder.find("m");
assertThat(mref, isPresent());
assertThat(mref.get().descriptor().isAutomatic(), is(false));
Expand All @@ -161,7 +163,7 @@ public void testAutoModuleExplodedPath() throws Exception {

// automatic module, and no filtering
var finder = InMemoryModuleFinder.of(Set.of(), fooRoot);
assertThat(finder.findAll().size(), is(1));
assertThat(finder.findAll(), hasSize(1));
var mod = finder.find("foo");
assertThat(mod, isPresent());
assertThat(mod.get().descriptor().isAutomatic(), is(true));
Expand Down Expand Up @@ -218,8 +220,7 @@ public void testFilterRequiresBasic() {
{ // filter the bar module
var md = InMemoryModuleFinder.filterRequires(initialMd, Set.of("bar"));
assertThat(md.name(), is("foo"));
assertThat(md.version(), isPresent());
assertThat(md.version().get(), is(Version.parse("1.0")));
assertThat(md.version(), isPresentWith(Version.parse("1.0")));
assertThat(md.requires(), hasItem(requiresOf("baz")));
assertThat(md.requires(), not(hasItem(requiresOf("bar"))));
assertThat(md.exports(), containsInAnyOrder(exportsOf("p"), exportsOf("q", Set.of("baz"))));
Expand All @@ -240,8 +241,8 @@ public void testFilterRequiresOpenModule() {
assertThat(md.isOpen(), is(true));
assertThat(md.name(), equalTo("openMod"));
assertThat(md.requires(), not(hasItem(requiresOf("bar"))));
assertThat(md.exports(), iterableWithSize(0));
assertThat(md.opens(), iterableWithSize(0));
assertThat(md.exports(), empty());
assertThat(md.opens(), empty());
}

public void testFilterRequiresAutoModule() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose;
import static org.elasticsearch.repositories.blobstore.ESBlobStoreRepositoryIntegTestCase.randomBytes;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
Expand Down Expand Up @@ -133,8 +134,7 @@ public void testReadRangeBlobWithRetries() throws Exception {
final int rangeStart = getRangeStart(exchange);
assertThat(rangeStart, lessThan(bytes.length));
final Optional<Integer> rangeEnd = getRangeEnd(exchange);
assertThat(rangeEnd.isPresent(), is(true));
assertThat(rangeEnd.get(), greaterThanOrEqualTo(rangeStart));
assertThat(rangeEnd, isPresentWith(greaterThanOrEqualTo(rangeStart)));
final int length = (rangeEnd.get() - rangeStart) + 1;
assertThat(length, lessThanOrEqualTo(bytes.length - rangeStart));
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.ENDPOINT_SETTING;
import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.READ_TIMEOUT_SETTING;
import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.TOKEN_URI_SETTING;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresent;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
Expand Down Expand Up @@ -203,7 +204,7 @@ public void testWriteBlobWithRetries() throws Exception {
assertThat(exchange.getRequestURI().getQuery(), containsString("uploadType=multipart"));
if (countDown.countDown()) {
Optional<Tuple<String, BytesReference>> content = parseMultipartRequestBody(exchange.getRequestBody());
assertThat(content.isPresent(), is(true));
assertThat(content, isPresent());
assertThat(content.get().v1(), equalTo(blobContainer.path().buildAsString() + "write_blob_max_retries"));
if (Objects.deepEquals(bytes, BytesReference.toBytes(content.get().v2()))) {
byte[] response = Strings.format("""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;

import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
Expand Down Expand Up @@ -110,12 +112,16 @@ public void testOnNodeStartedSuccess() {

public void testOnNodeStartedFailure() {
final int rc = randomIntBetween(Integer.MIN_VALUE, -1);
runTestOnNodeStarted(Boolean.TRUE.toString(), rc, (maybe, plugin) -> {
assertThat(maybe, OptionalMatchers.isPresent());
// noinspection OptionalGetWithoutIsPresent
assertThat(maybe.get(), instanceOf(RuntimeException.class));
assertThat(maybe.get(), hasToString(containsString("sd_notify returned error [" + rc + "]")));
});
runTestOnNodeStarted(
Boolean.TRUE.toString(),
rc,
(maybe, plugin) -> assertThat(
maybe,
isPresentWith(
allOf(instanceOf(RuntimeException.class), hasToString(containsString("sd_notify returned error [" + rc + "]")))
)
)
);
}

public void testOnNodeStartedNotEnabled() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.hamcrest.OptionalMatchers;
import org.hamcrest.Matchers;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.elasticsearch.test.LambdaMatchers.transformedMatch;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isEmpty;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresent;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.arrayWithSize;

public class RequestValidatorsTests extends ESTestCase {

private final RequestValidators.RequestValidator<PutMappingRequest> EMPTY = (request, state, indices) -> Optional.empty();
Expand All @@ -32,17 +36,17 @@ public void testValidates() {
validators.add(EMPTY);
}
final RequestValidators<PutMappingRequest> requestValidators = new RequestValidators<>(validators);
assertThat(requestValidators.validateRequest(null, null, null), OptionalMatchers.isEmpty());
assertThat(requestValidators.validateRequest(null, null, null), isEmpty());
}

public void testFailure() {
final RequestValidators<PutMappingRequest> validators = new RequestValidators<>(List.of(FAIL));
assertThat(validators.validateRequest(null, null, null), OptionalMatchers.isPresent());
assertThat(validators.validateRequest(null, null, null), isPresent());
}

public void testValidatesAfterFailure() {
final RequestValidators<PutMappingRequest> validators = new RequestValidators<>(List.of(FAIL, EMPTY));
assertThat(validators.validateRequest(null, null, null), OptionalMatchers.isPresent());
assertThat(validators.validateRequest(null, null, null), isPresent());
}

public void testMultipleFailures() {
Expand All @@ -53,9 +57,7 @@ public void testMultipleFailures() {
}
final RequestValidators<PutMappingRequest> requestValidators = new RequestValidators<>(validators);
final Optional<Exception> e = requestValidators.validateRequest(null, null, null);
assertThat(e, OptionalMatchers.isPresent());
// noinspection OptionalGetWithoutIsPresent
assertThat(e.get().getSuppressed(), Matchers.arrayWithSize(numberOfFailures - 1));
assertThat(e, isPresentWith(transformedMatch(Exception::getSuppressed, arrayWithSize(numberOfFailures - 1))));
}

public void testRandom() {
Expand All @@ -74,11 +76,9 @@ public void testRandom() {
final RequestValidators<PutMappingRequest> requestValidators = new RequestValidators<>(validators);
final Optional<Exception> e = requestValidators.validateRequest(null, null, null);
if (numberOfFailures == 0) {
assertThat(e, OptionalMatchers.isEmpty());
assertThat(e, isEmpty());
} else {
assertThat(e, OptionalMatchers.isPresent());
// noinspection OptionalGetWithoutIsPresent
assertThat(e.get().getSuppressed(), Matchers.arrayWithSize(numberOfFailures - 1));
assertThat(e, isPresentWith(transformedMatch(Exception::getSuppressed, arrayWithSize(numberOfFailures - 1))));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
package org.elasticsearch.common.network;

import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.hamcrest.OptionalMatchers;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.List;
import java.util.Optional;

import static org.elasticsearch.common.network.NetworkUtils.getInterfaces;
import static org.elasticsearch.test.LambdaMatchers.transformedMatch;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

Expand Down Expand Up @@ -80,8 +81,7 @@ public void testMaybeGetInterfaceByName() throws Exception {
networkInterfaces,
netIf.getName()
);
assertThat(maybeNetworkInterface, OptionalMatchers.isPresent());
assertThat(maybeNetworkInterface.get().getName(), equalTo(netIf.getName()));
assertThat(maybeNetworkInterface, isPresentWith(transformedMatch(NetworkInterface::getName, equalTo(netIf.getName()))));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@
import static org.elasticsearch.index.seqno.SequenceNumbers.NO_OPS_PERFORMED;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresent;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.contains;
Expand Down Expand Up @@ -7719,7 +7720,7 @@ private static void assertCommitGenerations(List<IndexCommit> commits, List<Long

private static void releaseCommitRef(Map<IndexCommit, Engine.IndexCommitRef> commits, long generation) {
var releasable = commits.keySet().stream().filter(c -> c.getGeneration() == generation).findFirst();
assertThat(releasable.isPresent(), is(true));
assertThat(releasable, isPresent());
Engine.IndexCommitRef indexCommitRef = commits.get(releasable.get());
try {
indexCommitRef.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
import java.util.Optional;
import java.util.ServiceLoader;

import static org.elasticsearch.test.hamcrest.OptionalMatchers.isEmpty;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

Expand Down Expand Up @@ -72,7 +72,7 @@ public int getValue() {

public void testNoProvider() {
Optional<TestService> service = ExtensionLoader.loadSingleton(ServiceLoader.load(TestService.class));
assertThat(service.isEmpty(), is(true));
assertThat(service, isEmpty());
}

public void testOneProvider() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.Map;
import java.util.function.Consumer;

import static org.elasticsearch.test.hamcrest.OptionalMatchers.isEmpty;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
Expand Down Expand Up @@ -183,14 +184,14 @@ public void testReadFromPropertiesJvmMissingClassname() throws Exception {

public void testReadFromPropertiesModulenameFallback() throws Exception {
PluginDescriptor info = mockInternalDescriptor("modulename", null);
assertThat(info.getModuleName().isPresent(), is(false));
assertThat(info.getModuleName(), isEmpty());
assertThat(info.isModular(), is(false));
assertThat(info.getExtendedPlugins(), empty());
}

public void testReadFromPropertiesModulenameEmpty() throws Exception {
PluginDescriptor info = mockInternalDescriptor("modulename", " ");
assertThat(info.getModuleName().isPresent(), is(false));
assertThat(info.getModuleName(), isEmpty());
assertThat(info.isModular(), is(false));
assertThat(info.getExtendedPlugins(), empty());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
import java.util.Set;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.test.hamcrest.OptionalMatchers.isPresentWith;
import static org.elasticsearch.transport.RemoteClusterService.REMOTE_CLUSTER_HANDSHAKE_ACTION_NAME;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
Expand Down Expand Up @@ -166,8 +166,7 @@ public void testWrapAndResolveConnectionRoundTrip() {
final Optional<RemoteConnectionManager.RemoteClusterAliasWithCredentials> actual = RemoteConnectionManager
.resolveRemoteClusterAliasWithCredentials(wrappedConnection);

assertThat(actual.isPresent(), is(true));
assertThat(actual.get(), equalTo(new RemoteConnectionManager.RemoteClusterAliasWithCredentials(clusterAlias, credentials)));
assertThat(actual, isPresentWith(new RemoteConnectionManager.RemoteClusterAliasWithCredentials(clusterAlias, credentials)));
}

private static class TestRemoteConnection extends CloseableConnection {
Expand Down

0 comments on commit 0d53be3

Please sign in to comment.