diff --git a/modules/reindex/src/test/java/org/elasticsearch/reindex/ClientScrollableHitSourceTests.java b/modules/reindex/src/test/java/org/elasticsearch/reindex/ClientScrollableHitSourceTests.java index 510da1d80b42e..9c926dd2cd67b 100644 --- a/modules/reindex/src/test/java/org/elasticsearch/reindex/ClientScrollableHitSourceTests.java +++ b/modules/reindex/src/test/java/org/elasticsearch/reindex/ClientScrollableHitSourceTests.java @@ -50,6 +50,7 @@ import java.util.stream.IntStream; import static org.apache.lucene.tests.util.TestUtil.randomSimpleString; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.core.TimeValue.timeValueSeconds; import static org.hamcrest.Matchers.instanceOf; @@ -174,7 +175,7 @@ private SearchResponse createSearchResponse() { private void assertSameHits(List actual, SearchHit[] expected) { assertEquals(actual.size(), expected.length); for (int i = 0; i < actual.size(); ++i) { - assertEquals(actual.get(i).getSource(), expected[i].getSourceRef()); + assertThat(expected[i].getSourceRef(), equalBytes(actual.get(i).getSource())); assertEquals(actual.get(i).getIndex(), expected[i].getIndex()); assertEquals(actual.get(i).getVersion(), expected[i].getVersion()); assertEquals(actual.get(i).getPrimaryTerm(), expected[i].getPrimaryTerm()); diff --git a/modules/reindex/src/test/java/org/elasticsearch/reindex/RoundTripTests.java b/modules/reindex/src/test/java/org/elasticsearch/reindex/RoundTripTests.java index 48856aa4007e1..461e7bb06cc20 100644 --- a/modules/reindex/src/test/java/org/elasticsearch/reindex/RoundTripTests.java +++ b/modules/reindex/src/test/java/org/elasticsearch/reindex/RoundTripTests.java @@ -38,6 +38,7 @@ import java.util.Map; import static org.apache.lucene.tests.util.TestUtil.randomSimpleString; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; /** * Round trip tests for all {@link Writeable} things declared in this plugin. @@ -144,7 +145,7 @@ private void assertRequestEquals(ReindexRequest request, ReindexRequest tripped) assertNotNull(tripped.getRemoteInfo()); assertEquals(request.getRemoteInfo().getScheme(), tripped.getRemoteInfo().getScheme()); assertEquals(request.getRemoteInfo().getHost(), tripped.getRemoteInfo().getHost()); - assertEquals(request.getRemoteInfo().getQuery(), tripped.getRemoteInfo().getQuery()); + assertThat(tripped.getRemoteInfo().getQuery(), equalBytes(request.getRemoteInfo().getQuery())); assertEquals(request.getRemoteInfo().getUsername(), tripped.getRemoteInfo().getUsername()); assertEquals(request.getRemoteInfo().getPassword(), tripped.getRemoteInfo().getPassword()); assertEquals(request.getRemoteInfo().getHeaders(), tripped.getRemoteInfo().getHeaders()); diff --git a/modules/repository-gcs/src/internalClusterTest/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStoreRepositoryTests.java b/modules/repository-gcs/src/internalClusterTest/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStoreRepositoryTests.java index 2532a9212f9e2..de5f4569116db 100644 --- a/modules/repository-gcs/src/internalClusterTest/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStoreRepositoryTests.java +++ b/modules/repository-gcs/src/internalClusterTest/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStoreRepositoryTests.java @@ -59,6 +59,7 @@ import java.util.Collections; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.common.io.Streams.readFully; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.CREDENTIALS_FILE_SETTING; @@ -219,7 +220,7 @@ public void testWriteFileMultipleOfChunkSize() throws IOException { container.writeBlob(randomPurpose(), key, new BytesArray(initialValue), true); BytesReference reference = readFully(container.readBlob(randomPurpose(), key)); - assertEquals(new BytesArray(initialValue), reference); + assertThat(reference, equalBytes(new BytesArray(initialValue))); container.deleteBlobsIgnoringIfNotExists(randomPurpose(), Iterators.single(key)); } diff --git a/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerRetriesTests.java b/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerRetriesTests.java index a09aa8142ad63..832e5149f92b2 100644 --- a/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerRetriesTests.java +++ b/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerRetriesTests.java @@ -79,6 +79,7 @@ import static fixture.gcs.TestUtils.createServiceAccount; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.common.io.Streams.readFully; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose; import static org.elasticsearch.repositories.blobstore.ESBlobStoreRepositoryIntegTestCase.randomBytes; @@ -582,7 +583,7 @@ public void testCompareAndExchangeWhenThrottled() throws IOException { final OptionalBytesReference updateResult = safeAwait( l -> container.compareAndExchangeRegister(randomPurpose(), key, new BytesArray(data), new BytesArray(updatedData), l) ); - assertEquals(new BytesArray(data), updateResult.bytesReference()); + assertThat(updateResult.bytesReference(), equalBytes(new BytesArray(data))); assertEquals(0, requestHandlers.size()); container.delete(randomPurpose()); @@ -601,7 +602,7 @@ public void testContentsChangeWhileStreaming() throws IOException { container.writeBlob(randomPurpose(), key, new BytesArray(initialValue), true); BytesReference reference = readFully(container.readBlob(randomPurpose(), key)); - assertEquals(new BytesArray(initialValue), reference); + assertThat(reference, equalBytes(new BytesArray(initialValue))); try (InputStream inputStream = container.readBlob(randomPurpose(), key)) { // Trigger the first chunk to load diff --git a/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerStatsTests.java b/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerStatsTests.java index 7e2b4348823fd..80bb9ae4f8246 100644 --- a/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerStatsTests.java +++ b/modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerStatsTests.java @@ -50,6 +50,7 @@ import java.util.Map; import java.util.concurrent.TimeUnit; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.APPLICATION_NAME_SETTING; import static org.elasticsearch.repositories.gcs.GoogleCloudStorageClientSettings.CONNECT_TIMEOUT_SETTING; @@ -138,7 +139,7 @@ public void testSingleMultipartWrite() throws Exception { final StatsMap wantStats = new StatsMap(purpose); assertStatsEquals(wantStats.add(INSERT, 1), store.stats()); try (InputStream is = container.readBlob(purpose, blobName)) { - assertEquals(blobContents, Streams.readFully(is)); + assertThat(Streams.readFully(is), equalBytes(blobContents)); } assertStatsEquals(wantStats.add(GET, 1), store.stats()); } @@ -164,7 +165,7 @@ public void testResumableWrite() throws Exception { assertStatsEquals(wantStats.add(INSERT, 1, totalRequests), store.stats()); try (InputStream is = container.readBlob(purpose, blobName)) { - assertEquals(blobContents, Streams.readFully(is)); + assertThat(Streams.readFully(is), equalBytes(blobContents)); } assertStatsEquals(wantStats.add(GET, 1), store.stats()); } diff --git a/modules/repository-s3/qa/third-party/src/test/java/org/elasticsearch/repositories/s3/S3RepositoryThirdPartyTests.java b/modules/repository-s3/qa/third-party/src/test/java/org/elasticsearch/repositories/s3/S3RepositoryThirdPartyTests.java index f6b37b3f34c89..9d9a4302c3819 100644 --- a/modules/repository-s3/qa/third-party/src/test/java/org/elasticsearch/repositories/s3/S3RepositoryThirdPartyTests.java +++ b/modules/repository-s3/qa/third-party/src/test/java/org/elasticsearch/repositories/s3/S3RepositoryThirdPartyTests.java @@ -49,6 +49,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.blankOrNullString; @@ -194,7 +195,7 @@ List listMultipartUploads() { assertTrue(testHarness.tryCompareAndSet(BytesArray.EMPTY, bytes1)); // show we're looking at the right blob - assertEquals(bytes1, testHarness.readRegister()); + assertThat(testHarness.readRegister(), equalBytes(bytes1)); assertArrayEquals( bytes1.array(), client.getObject(GetObjectRequest.builder().bucket(bucketName).key(registerBlobPath).build()).readAllBytes() @@ -217,7 +218,7 @@ List listMultipartUploads() { timeOffsetMillis.addAndGet(blobStore.getCompareAndExchangeTimeToLive().millis() - Math.min(0, age)); assertTrue(testHarness.tryCompareAndSet(bytes1, bytes2)); assertThat(testHarness.listMultipartUploads(), hasSize(0)); - assertEquals(bytes2, testHarness.readRegister()); + assertThat(testHarness.readRegister(), equalBytes(bytes2)); } finally { blobContainer.delete(randomPurpose()); } diff --git a/modules/rest-root/src/test/java/org/elasticsearch/rest/root/RestMainActionTests.java b/modules/rest-root/src/test/java/org/elasticsearch/rest/root/RestMainActionTests.java index a537bf9ef14fe..340b39c34834a 100644 --- a/modules/rest-root/src/test/java/org/elasticsearch/rest/root/RestMainActionTests.java +++ b/modules/rest-root/src/test/java/org/elasticsearch/rest/root/RestMainActionTests.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; @@ -95,6 +96,6 @@ public void testGetResponse() throws Exception { } mainResponse.toXContent(responseBuilder, ToXContent.EMPTY_PARAMS); BytesReference xcontentBytes = BytesReference.bytes(responseBuilder); - assertEquals(xcontentBytes, response.content()); + assertThat(response.content(), equalBytes(xcontentBytes)); } } diff --git a/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpPipeliningHandlerTests.java b/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpPipeliningHandlerTests.java index 21d32f67e4e53..706aa5267e0cd 100644 --- a/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpPipeliningHandlerTests.java +++ b/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpPipeliningHandlerTests.java @@ -72,6 +72,7 @@ import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; @@ -548,7 +549,7 @@ private static void assertChunkedMessageAtIndex(List messagesSeen, int i } private static void assertContentAtIndexEquals(List messagesSeen, int index, BytesReference single) { - assertEquals(Netty4Utils.toBytesReference(((ByteBufHolder) messagesSeen.get(index)).content()), single); + assertThat(single, equalBytes(Netty4Utils.toBytesReference(((ByteBufHolder) messagesSeen.get(index)).content()))); } private static void assertDoneWithClosedChannel(ChannelPromise chunkedWritePromise) { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/search/PointInTimeIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/search/PointInTimeIT.java index 2f5a658c4eca8..6a74dcc685f65 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/search/PointInTimeIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/search/PointInTimeIT.java @@ -54,6 +54,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; @@ -95,7 +96,7 @@ public void testBasic() { refresh("test"); BytesReference pitId = openPointInTime(new String[] { "test" }, TimeValue.timeValueMinutes(2)).getPointInTimeId(); assertResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp1 -> { - assertThat(resp1.pointInTimeId(), equalTo(pitId)); + assertThat(resp1.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp1, numDocs); }); int deletedDocs = 0; @@ -119,7 +120,7 @@ public void testBasic() { prepareSearch().setQuery(new MatchAllQueryBuilder()).setPointInTime(new PointInTimeBuilder(pitId)), resp3 -> { assertHitCount(resp3, numDocs); - assertThat(resp3.pointInTimeId(), equalTo(pitId)); + assertThat(pitId, equalBytes(resp3.pointInTimeId())); } ); } finally { @@ -154,7 +155,7 @@ public void testIndexWithFilteredAlias() { .setSize(0) .setQuery(new MatchAllQueryBuilder()), resp1 -> { - assertThat(resp1.pointInTimeId(), equalTo(pitId)); + assertThat(resp1.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp1, finalCountTagA); } ); @@ -181,7 +182,7 @@ public void testMultipleIndices() { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs); assertNotNull(resp.pointInTimeId()); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); for (int i = 0; i < moreDocs; i++) { String id = "more-" + i; String index = "index-" + randomIntBetween(1, numIndices); @@ -193,7 +194,7 @@ public void testMultipleIndices() { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs); assertNotNull(resp.pointInTimeId()); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); }); } finally { closePointInTime(pitId); @@ -237,7 +238,7 @@ public void testIndexFilter() { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)).setSize(50), resp -> { assertHitCount(resp, numDocs); assertNotNull(resp.pointInTimeId()); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); for (SearchHit hit : resp.getHits()) { assertEquals("index-3", hit.getIndex()); } @@ -261,7 +262,7 @@ public void testRelocation() throws Exception { try { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); }); final Set dataNodes = clusterService().state() .nodes() @@ -281,7 +282,7 @@ public void testRelocation() throws Exception { } assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); }); assertBusy(() -> { final Set assignedNodes = clusterService().state() @@ -294,7 +295,7 @@ public void testRelocation() throws Exception { }, 30, TimeUnit.SECONDS); assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); }); } finally { closePointInTime(pitId); @@ -464,13 +465,13 @@ public void testPartialResults() throws Exception { try { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertHitCount(resp, numDocs1 + numDocs2); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); }); internalCluster().restartNode(assignedNodeForIndex1); assertResponse(prepareSearch().setAllowPartialSearchResults(true).setPointInTime(new PointInTimeBuilder(pitId)), resp -> { assertFailures(resp); - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp, numDocs2); }); } finally { @@ -619,7 +620,7 @@ public void testMissingShardsWithPointInTime() throws Exception { .setPointInTime(new PointInTimeBuilder(pointInTimeResponse.getPointInTimeId())), resp -> { // ensure that al docs are returned - assertThat(resp.pointInTimeId(), equalTo(pointInTimeResponse.getPointInTimeId())); + assertThat(resp.pointInTimeId(), equalBytes(pointInTimeResponse.getPointInTimeId())); assertHitCount(resp, numDocs); } ); @@ -672,7 +673,7 @@ public void testMissingShardsWithPointInTime() throws Exception { resp -> { assertThat(resp.getSuccessfulShards(), equalTo(numShards - shardsRemoved)); assertThat(resp.getFailedShards(), equalTo(shardsRemoved)); - assertThat(resp.pointInTimeId(), equalTo(pointInTimeResponseOneNodeDown.getPointInTimeId())); + assertThat(resp.pointInTimeId(), equalBytes(pointInTimeResponseOneNodeDown.getPointInTimeId())); assertNotNull(resp.getHits().getTotalHits()); assertThat(resp.getHits().getTotalHits().value(), lessThan((long) numDocs)); } @@ -707,7 +708,7 @@ public void testMissingShardsWithPointInTime() throws Exception { prepareSearch().setQuery(new MatchAllQueryBuilder()) .setPointInTime(new PointInTimeBuilder(pointInTimeResponseOneNodeDown.getPointInTimeId())), resp -> { - assertThat(resp.pointInTimeId(), equalTo(pointInTimeResponseOneNodeDown.getPointInTimeId())); + assertThat(resp.pointInTimeId(), equalBytes(pointInTimeResponseOneNodeDown.getPointInTimeId())); assertThat(resp.getTotalShards(), equalTo(numShards)); assertThat(resp.getSuccessfulShards(), equalTo(numShards - shardsRemoved)); assertThat(resp.getFailedShards(), equalTo(shardsRemoved)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/get/GetActionIT.java b/server/src/internalClusterTest/java/org/elasticsearch/get/GetActionIT.java index f06810377771b..027ceb4b6064f 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/get/GetActionIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/get/GetActionIT.java @@ -60,6 +60,7 @@ import java.util.function.UnaryOperator; import static java.util.Collections.singleton; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; @@ -1026,9 +1027,9 @@ public void testRealTimeGetNestedFields() { assertTrue(lucene1.isExists()); assertTrue(lucene2.isExists()); assertTrue(lucene3.isExists()); - assertThat(translog1.getSourceAsBytesRef(), equalTo(lucene1.getSourceAsBytesRef())); - assertThat(translog2.getSourceAsBytesRef(), equalTo(lucene2.getSourceAsBytesRef())); - assertThat(translog3.getSourceAsBytesRef(), equalTo(lucene3.getSourceAsBytesRef())); + assertThat(translog1.getSourceAsBytesRef(), equalBytes(lucene1.getSourceAsBytesRef())); + assertThat(translog2.getSourceAsBytesRef(), equalBytes(lucene2.getSourceAsBytesRef())); + assertThat(translog3.getSourceAsBytesRef(), equalBytes(lucene3.getSourceAsBytesRef())); } private void assertGetFieldsAlwaysWorks(String index, String docId, String[] fields) { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java index bec4e0a2d6970..a91012f7fd532 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java @@ -59,6 +59,7 @@ import static java.util.Collections.singleton; import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.common.util.set.Sets.newHashSet; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -664,7 +665,7 @@ public void testStoredFieldsWithoutSource() throws Exception { assertThat(searchHit.getFields().get("boolean_field").getValue(), equalTo((Object) Boolean.TRUE)); assertThat( searchHit.getFields().get("binary_field").getValue(), - equalTo(new BytesArray("testing text".getBytes(StandardCharsets.UTF_8))) + equalBytes(new BytesArray("testing text".getBytes(StandardCharsets.UTF_8))) ); } ); diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java index 550f8e5843628..3461fa543fccc 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java @@ -22,6 +22,8 @@ import java.util.HashMap; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class GetFieldMappingsResponseTests extends AbstractWireSerializingTestCase { public void testManualSerialization() throws IOException { @@ -36,7 +38,7 @@ public void testManualSerialization() throws IOException { GetFieldMappingsResponse serialized = new GetFieldMappingsResponse(in); FieldMappingMetadata metadata = serialized.fieldMappings("index", "field"); assertNotNull(metadata); - assertEquals(new BytesArray("{}"), metadata.source()); + assertThat(metadata.source(), equalBytes(new BytesArray("{}"))); } } } diff --git a/server/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java b/server/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java index b36b3af1ddb86..4b61fe556b4c4 100644 --- a/server/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java +++ b/server/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java @@ -34,6 +34,7 @@ import java.util.List; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; @@ -52,9 +53,9 @@ public void testSimpleBulk1() throws Exception { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(3)); - assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }"))); + assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalBytes(new BytesArray("{ \"field1\" : \"value1\" }"))); assertThat(bulkRequest.requests().get(1), instanceOf(DeleteRequest.class)); - assertThat(((IndexRequest) bulkRequest.requests().get(2)).source(), equalTo(new BytesArray("{ \"field1\" : \"value3\" }"))); + assertThat(((IndexRequest) bulkRequest.requests().get(2)).source(), equalBytes(new BytesArray("{ \"field1\" : \"value3\" }"))); } public void testSimpleBulkWithCarriageReturn() throws Exception { @@ -65,7 +66,7 @@ public void testSimpleBulkWithCarriageReturn() throws Exception { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(1)); - assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }"))); + assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalBytes(new BytesArray("{ \"field1\" : \"value1\" }"))); Map sourceMap = XContentHelper.convertToMap( ((IndexRequest) bulkRequest.requests().get(0)).source(), false, diff --git a/server/src/test/java/org/elasticsearch/action/index/IndexRequestTests.java b/server/src/test/java/org/elasticsearch/action/index/IndexRequestTests.java index 0373f9975d9df..16b393375f5ab 100644 --- a/server/src/test/java/org/elasticsearch/action/index/IndexRequestTests.java +++ b/server/src/test/java/org/elasticsearch/action/index/IndexRequestTests.java @@ -48,6 +48,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.anEmptyMap; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; @@ -199,7 +200,7 @@ public void testIndexRequestXContentSerialization() throws IOException { StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes); IndexRequest serialized = new IndexRequest(in); assertEquals(XContentType.JSON, serialized.getContentType()); - assertEquals(new BytesArray("{}"), serialized.source()); + assertThat(serialized.source(), equalBytes(new BytesArray("{}"))); assertEquals(isRequireAlias, serialized.isRequireAlias()); assertThat(serialized.getDynamicTemplates(), equalTo(dynamicTemplates)); } diff --git a/server/src/test/java/org/elasticsearch/action/ingest/PutPipelineRequestTests.java b/server/src/test/java/org/elasticsearch/action/ingest/PutPipelineRequestTests.java index f3cc25cbeb5e4..8a4fce28b74e2 100644 --- a/server/src/test/java/org/elasticsearch/action/ingest/PutPipelineRequestTests.java +++ b/server/src/test/java/org/elasticsearch/action/ingest/PutPipelineRequestTests.java @@ -20,6 +20,7 @@ import java.io.IOException; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.ingest.IngestPipelineTestUtils.putJsonPipelineRequest; public class PutPipelineRequestTests extends ESTestCase { @@ -61,6 +62,6 @@ public void testToXContent() throws IOException { ); XContentBuilder requestBuilder = XContentBuilder.builder(xContentType.xContent()); BytesReference actualRequestBody = BytesReference.bytes(request.toXContent(requestBuilder, ToXContent.EMPTY_PARAMS)); - assertEquals(BytesReference.bytes(pipelineBuilder), actualRequestBody); + assertThat(actualRequestBody, equalBytes(BytesReference.bytes(pipelineBuilder))); } } diff --git a/server/src/test/java/org/elasticsearch/action/termvectors/TermVectorsUnitTests.java b/server/src/test/java/org/elasticsearch/action/termvectors/TermVectorsUnitTests.java index 05391c81e6dd1..c34079cf60957 100644 --- a/server/src/test/java/org/elasticsearch/action/termvectors/TermVectorsUnitTests.java +++ b/server/src/test/java/org/elasticsearch/action/termvectors/TermVectorsUnitTests.java @@ -48,6 +48,7 @@ import java.util.HashSet; import java.util.Set; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class TermVectorsUnitTests extends ESTestCase { @@ -239,7 +240,7 @@ public void testStreamRequest() throws IOException { assertThat(request.termStatistics(), equalTo(req2.termStatistics())); assertThat(request.preference(), equalTo(pref)); assertThat(request.routing(), equalTo(null)); - assertEquals(new BytesArray("{}"), request.doc()); + assertThat(request.doc(), equalBytes(new BytesArray("{}"))); assertEquals(XContentType.JSON, request.xContentType()); } } diff --git a/server/src/test/java/org/elasticsearch/common/blobstore/RetryingInputStreamTests.java b/server/src/test/java/org/elasticsearch/common/blobstore/RetryingInputStreamTests.java index 93f7acdb94996..0f6f590005297 100644 --- a/server/src/test/java/org/elasticsearch/common/blobstore/RetryingInputStreamTests.java +++ b/server/src/test/java/org/elasticsearch/common/blobstore/RetryingInputStreamTests.java @@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.empty; public class RetryingInputStreamTests extends ESTestCase { @@ -45,7 +46,7 @@ public RetryingInputStream.SingleAttemptInputStream doGetInputStream(long start, byte[] results = copyToBytes(new RetryingInputStream(services, randomRetryingPurpose()) { }); assertEquals(resourceBytes.length(), results.length); - assertEquals(resourceBytes, new BytesArray(results)); + assertThat(new BytesArray(results), equalBytes(resourceBytes)); assertEquals(retryableFailures + 1, services.getAttempts()); assertEquals(Stream.generate(() -> "read").limit(retryableFailures).toList(), services.getRetryStarted()); } @@ -106,7 +107,7 @@ public RetryingInputStream.SingleAttemptInputStream doGetInputStream(long start, byte[] result = copyToBytes(new RetryingInputStream(services, OperationPurpose.INDICES) { }); - assertEquals(resourceBytes, new BytesArray(result)); + assertThat(new BytesArray(result), equalBytes(resourceBytes)); assertEquals(numberOfFailures + 1, services.getAttempts()); assertEquals(Stream.generate(() -> "read").limit(numberOfFailures).toList(), services.getRetryStarted()); } diff --git a/server/src/test/java/org/elasticsearch/common/blobstore/fs/FsBlobContainerTests.java b/server/src/test/java/org/elasticsearch/common/blobstore/fs/FsBlobContainerTests.java index 9765c2b69e077..e1b48b347783b 100644 --- a/server/src/test/java/org/elasticsearch/common/blobstore/fs/FsBlobContainerTests.java +++ b/server/src/test/java/org/elasticsearch/common/blobstore/fs/FsBlobContainerTests.java @@ -49,6 +49,8 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; +import static org.elasticsearch.common.io.Streams.readFully; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomNonDataPurpose; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomPurpose; import static org.hamcrest.Matchers.containsString; @@ -196,7 +198,7 @@ public void testCompareAndExchange() throws Exception { for (int i = 0; i < 5; i++) { switch (between(1, 4)) { - case 1 -> assertEquals(expectedValue.get(), getBytesAsync(l -> container.getRegister(randomPurpose(), key, l))); + case 1 -> assertThat(getBytesAsync(l -> container.getRegister(randomPurpose(), key, l)), equalBytes(expectedValue.get())); case 2 -> assertFalse( getAsync( l -> container.compareAndSetRegister( @@ -208,8 +210,7 @@ public void testCompareAndExchange() throws Exception { ) ) ); - case 3 -> assertEquals( - expectedValue.get(), + case 3 -> assertThat( getBytesAsync( l -> container.compareAndExchangeRegister( randomPurpose(), @@ -218,7 +219,8 @@ public void testCompareAndExchange() throws Exception { new BytesArray(randomByteArrayOfLength(8)), l ) - ) + ), + equalBytes(expectedValue.get()) ); case 4 -> { /* no-op */ @@ -229,9 +231,9 @@ public void testCompareAndExchange() throws Exception { if (randomBoolean()) { assertTrue(getAsync(l -> container.compareAndSetRegister(randomPurpose(), key, expectedValue.get(), newValue, l))); } else { - assertEquals( - expectedValue.get(), - getBytesAsync(l -> container.compareAndExchangeRegister(randomPurpose(), key, expectedValue.get(), newValue, l)) + assertThat( + getBytesAsync(l -> container.compareAndExchangeRegister(randomPurpose(), key, expectedValue.get(), newValue, l)), + equalBytes(expectedValue.get()) ); } expectedValue.set(newValue); @@ -278,7 +280,7 @@ public void testRegisterContention() throws Exception { l -> container.compareAndExchangeRegister(p, uncontendedKey, startValue, finalValue, l) ); // NB calling .bytesReference() asserts that the result is present, there was no contention - assertEquals(startValue, result.bytesReference()); + assertThat(result.bytesReference(), equalBytes(startValue)); } // other threads try and do contended writes, which may fail and need retrying : () -> { @@ -313,9 +315,9 @@ public void testRegisterContention() throws Exception { } for (var key : new String[] { contendedKey, uncontendedKey }) { - assertEquals( - finalValue, - safeAwait((ActionListener l) -> container.getRegister(p, key, l)).bytesReference() + assertThat( + safeAwait((ActionListener l) -> container.getRegister(p, key, l)).bytesReference(), + equalBytes(finalValue) ); } } @@ -362,7 +364,7 @@ private static void checkAtomicWrite() throws IOException { } else { container.writeBlobAtomic(randomNonDataPurpose(), blobName, blobData.streamInput(), blobData.length(), false); } - assertEquals(blobData, Streams.readFully(container.readBlob(randomPurpose(), blobName))); + assertThat(readFully(container.readBlob(randomPurpose(), blobName)), equalBytes(blobData)); expectThrows( FileAlreadyExistsException.class, () -> container.writeBlobAtomic( @@ -398,8 +400,8 @@ public void testCopy() throws Exception { var sourceContents = Streams.readFully(sourceContainer.readBlob(randomPurpose(), sourceBlobName)); var targetContents = Streams.readFully(destinationContainer.readBlob(randomPurpose(), blobName)); - assertEquals(sourceContents, targetContents); - assertEquals(contents, targetContents); + assertThat(targetContents, equalBytes(sourceContents)); + assertThat(targetContents, equalBytes(contents)); } static class MockFileSystemProvider extends FilterFileSystemProvider { diff --git a/server/src/test/java/org/elasticsearch/common/blobstore/support/BlobContainerUtilsTests.java b/server/src/test/java/org/elasticsearch/common/blobstore/support/BlobContainerUtilsTests.java index 6a7bb92b649b9..12ac9fe6d7445 100644 --- a/server/src/test/java/org/elasticsearch/common/blobstore/support/BlobContainerUtilsTests.java +++ b/server/src/test/java/org/elasticsearch/common/blobstore/support/BlobContainerUtilsTests.java @@ -16,6 +16,7 @@ import static org.elasticsearch.common.blobstore.support.BlobContainerUtils.MAX_REGISTER_CONTENT_LENGTH; import static org.elasticsearch.common.blobstore.support.BlobContainerUtils.ensureValidRegisterContent; import static org.elasticsearch.common.blobstore.support.BlobContainerUtils.getRegisterUsingConsistentRead; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; public class BlobContainerUtilsTests extends ESTestCase { @@ -28,7 +29,7 @@ public void testEnsureValidRegisterContent() { public void testGetRegisterUsingConsistentRead() throws IOException { final var content = randomBytesReference(between(0, MAX_REGISTER_CONTENT_LENGTH)); - assertEquals(content, getRegisterUsingConsistentRead(content.streamInput(), "", "")); + assertThat(getRegisterUsingConsistentRead(content.streamInput(), "", ""), equalBytes(content)); final var invalidContent = randomBytesReference(MAX_REGISTER_CONTENT_LENGTH + 1); expectThrows(IllegalStateException.class, () -> getRegisterUsingConsistentRead(invalidContent.streamInput(), "", "")); diff --git a/server/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java b/server/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java index 1ff86d9b4bfd2..89bf7841a76b8 100644 --- a/server/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java +++ b/server/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class CompositeBytesReferenceTests extends AbstractBytesReferenceTestCase { @@ -98,7 +99,7 @@ public void testCompositeBuffer() throws IOException { int offset = 0; for (BytesReference reference : referenceList) { - assertEquals(reference, ref.slice(offset, reference.length())); + assertThat(ref.slice(offset, reference.length()), equalBytes(reference)); int probes = randomIntBetween(Math.min(10, reference.length()), reference.length()); for (int i = 0; i < probes; i++) { int index = randomIntBetween(0, reference.length() - 1); @@ -108,12 +109,12 @@ public void testCompositeBuffer() throws IOException { } BytesArray array = new BytesArray(builder.toBytesRef()); - assertEquals(array, ref); + assertThat(array, equalBytes(ref)); assertEquals(array.hashCode(), ref.hashCode()); BytesStreamOutput output = new BytesStreamOutput(); ref.writeTo(output); - assertEquals(array, output.bytes()); + assertThat(output.bytes(), equalBytes(array)); } @Override diff --git a/server/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java b/server/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java index 85bb626f6fc5a..da0a70e709717 100644 --- a/server/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java +++ b/server/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java @@ -15,6 +15,8 @@ import java.io.IOException; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase { @Override @@ -121,7 +123,7 @@ public void testEquals() { // get refs & compare BytesReference pbr = BytesReference.fromByteArray(ba1, length); BytesReference pbr2 = BytesReference.fromByteArray(ba2, length); - assertEquals(pbr, pbr2); + assertThat(pbr2, equalBytes(pbr)); int offsetToFlip = randomIntBetween(0, length - 1); int value = ~Byte.toUnsignedInt(ba1.get(offsetToFlip)); ba2.set(offsetToFlip, (byte) value); diff --git a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressTests.java b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressTests.java index 1d213174597fc..709ef5cc5c431 100644 --- a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressTests.java +++ b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressTests.java @@ -26,6 +26,7 @@ import java.util.Random; import java.util.zip.ZipException; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; /** @@ -319,7 +320,7 @@ public void testCompressUncompressWithCorruptions() throws Exception { } } else { var uncompressed = compressor.uncompress(compressed); - assertEquals(original, uncompressed); + assertThat(uncompressed, equalBytes(original)); } } } diff --git a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java index 72f8017950674..1c395a5db4f2d 100644 --- a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java +++ b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java @@ -24,6 +24,7 @@ import java.util.Arrays; import java.util.Random; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; @@ -33,7 +34,7 @@ public class DeflateCompressedXContentTests extends ESTestCase { private void assertEquals(CompressedXContent s1, CompressedXContent s2) { Assert.assertEquals(s1, s2); - assertEquals(s1.uncompressed(), s2.uncompressed()); + assertThat(s2.uncompressed(), equalBytes(s1.uncompressed())); assertEquals(s1.hashCode(), s2.hashCode()); } diff --git a/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamOutputTests.java b/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamOutputTests.java index 32a632bf07572..ed2e86c24cbfb 100644 --- a/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamOutputTests.java +++ b/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamOutputTests.java @@ -15,6 +15,8 @@ import org.elasticsearch.test.ESTestCase; import org.junit.Before; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class BytesStreamOutputTests extends ESTestCase { private BytesStreamOutput stream; @@ -28,7 +30,7 @@ public void setUp() throws Exception { public void testDefaultConstructor() { assertEquals(0, stream.size()); assertEquals(0, stream.position()); - assertEquals(BytesArray.EMPTY, stream.bytes()); + assertThat(stream.bytes(), equalBytes(BytesArray.EMPTY)); } public void testConstructorWithExpectedSize() { diff --git a/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java b/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java index 811f9b692399a..825fe6d5075ea 100644 --- a/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java +++ b/server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java @@ -40,6 +40,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; @@ -327,8 +328,8 @@ public void testSimpleStreams() throws Exception { assertThat(in.readString(), equalTo("goodbye")); assertThat(in.readGenericValue(), equalTo((Object) BytesRefs.toBytesRef("bytesref"))); assertThat(in.readStringArray(), equalTo(new String[] { "a", "b", "cat" })); - assertThat(in.readBytesReference(), equalTo(new BytesArray("test"))); - assertThat(in.readOptionalBytesReference(), equalTo(new BytesArray("test"))); + assertThat(in.readBytesReference(), equalBytes(new BytesArray("test"))); + assertThat(in.readOptionalBytesReference(), equalBytes(new BytesArray("test"))); assertNull(in.readOptionalDouble()); assertThat(in.readOptionalDouble(), closeTo(1.2, 0.0001)); assertEquals(ZoneId.of("CET"), in.readZoneId()); @@ -679,7 +680,7 @@ public void testWriteMapWithConsistentOrder() throws IOException { output.writeMapWithConsistentOrder(map); reverseMapOutput.writeMapWithConsistentOrder(reverseMap); - assertEquals(output.bytes(), reverseMapOutput.bytes()); + assertThat(reverseMapOutput.bytes(), equalBytes(output.bytes())); } } diff --git a/server/src/test/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutputTests.java b/server/src/test/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutputTests.java index e5f985ea3f879..12e5d0ed2f5f3 100644 --- a/server/src/test/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutputTests.java +++ b/server/src/test/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutputTests.java @@ -46,6 +46,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; @@ -368,8 +369,8 @@ public void testSimpleStreams() throws Exception { assertThat(in.readString(), equalTo("goodbye")); assertThat(in.readGenericValue(), equalTo((Object) BytesRefs.toBytesRef("bytesref"))); assertThat(in.readStringArray(), equalTo(new String[] { "a", "b", "cat" })); - assertThat(in.readBytesReference(), equalTo(new BytesArray("test"))); - assertThat(in.readOptionalBytesReference(), equalTo(new BytesArray("test"))); + assertThat(in.readBytesReference(), equalBytes(new BytesArray("test"))); + assertThat(in.readOptionalBytesReference(), equalBytes(new BytesArray("test"))); assertNull(in.readOptionalDouble()); assertThat(in.readOptionalDouble(), closeTo(1.2, 0.0001)); assertEquals(ZoneId.of("CET"), in.readZoneId()); @@ -776,7 +777,7 @@ public void testWriteMapWithConsistentOrder() throws IOException { output.writeMapWithConsistentOrder(map); reverseMapOutput.writeMapWithConsistentOrder(reverseMap); - assertEquals(output.bytes(), reverseMapOutput.bytes()); + assertThat(reverseMapOutput.bytes(), equalBytes(output.bytes())); } } diff --git a/server/src/test/java/org/elasticsearch/common/logging/ChunkedLoggingStreamTests.java b/server/src/test/java/org/elasticsearch/common/logging/ChunkedLoggingStreamTests.java index 5a6caae88b9d7..24af689124deb 100644 --- a/server/src/test/java/org/elasticsearch/common/logging/ChunkedLoggingStreamTests.java +++ b/server/src/test/java/org/elasticsearch/common/logging/ChunkedLoggingStreamTests.java @@ -23,6 +23,8 @@ import java.util.Arrays; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class ChunkedLoggingStreamTests extends ESTestCase { public static final Logger logger = LogManager.getLogger(ChunkedLoggingStreamTests.class); @@ -56,14 +58,11 @@ public void testEncodingRoundTrip() { final var bytes = randomByteArrayOfLength(between(0, 10000)); final var level = randomFrom(Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR); final var referenceDocs = randomFrom(ReferenceDocs.values()); - assertEquals( - new BytesArray(bytes), - ChunkedLoggingStreamTestUtils.getDecodedLoggedBody(logger, level, "prefix", referenceDocs, () -> { - try (var stream = ChunkedLoggingStream.create(logger, level, "prefix", referenceDocs)) { - writeRandomly(stream, bytes); - } - }) - ); + assertThat(ChunkedLoggingStreamTestUtils.getDecodedLoggedBody(logger, level, "prefix", referenceDocs, () -> { + try (var stream = ChunkedLoggingStream.create(logger, level, "prefix", referenceDocs)) { + writeRandomly(stream, bytes); + } + }), equalBytes(new BytesArray(bytes))); } private static void writeRandomly(OutputStream stream, byte[] bytes) throws IOException { diff --git a/server/src/test/java/org/elasticsearch/http/DefaultRestChannelTests.java b/server/src/test/java/org/elasticsearch/http/DefaultRestChannelTests.java index 4af0aa0368a41..93828d8ec312b 100644 --- a/server/src/test/java/org/elasticsearch/http/DefaultRestChannelTests.java +++ b/server/src/test/java/org/elasticsearch/http/DefaultRestChannelTests.java @@ -63,6 +63,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; @@ -106,7 +107,7 @@ public void shutdown() { public void testResponse() { final TestHttpResponse response = executeRequest(Settings.EMPTY, "request-host"); - assertThat(response.content(), equalTo(testRestResponse().content())); + assertThat(response.content(), equalBytes(testRestResponse().content())); } public void testCorsEnabledWithoutAllowOrigins() { @@ -724,15 +725,15 @@ private static void writeContent(OutputStream bso, ChunkedRestResponseBodyPart c ); var responseBody = new BytesArray(randomUnicodeOfLengthBetween(1, 100).getBytes(StandardCharsets.UTF_8)); - assertEquals( - responseBody, + assertThat( ChunkedLoggingStreamTestUtils.getDecodedLoggedBody( LogManager.getLogger(HttpTracerTests.HTTP_BODY_TRACER_LOGGER), Level.TRACE, "[" + request.getRequestId() + "] response body", ReferenceDocs.HTTP_TRACER, () -> channel.sendResponse(new RestResponse(RestStatus.OK, RestResponse.TEXT_CONTENT_TYPE, responseBody)) - ) + ), + equalBytes(responseBody) ); final var parts = new ArrayList(); @@ -787,8 +788,7 @@ public String getResponseContentTypeString() { final var isClosed = new AtomicBoolean(); final var firstPart = new TestBodyPart(responseBody, between(0, 3)); parts.add(firstPart); - assertEquals( - responseBody, + assertThat( ChunkedLoggingStreamTestUtils.getDecodedLoggedBody( LogManager.getLogger(HttpTracerTests.HTTP_BODY_TRACER_LOGGER), Level.TRACE, @@ -801,7 +801,8 @@ public String getResponseContentTypeString() { assertEquals("isLastPart " + i, i == parts.size() - 1, parts.get(i).isLastPart()); } })) - ) + ), + equalBytes(responseBody) ); assertTrue(isClosed.get()); diff --git a/server/src/test/java/org/elasticsearch/http/HttpTracerTests.java b/server/src/test/java/org/elasticsearch/http/HttpTracerTests.java index 017500eb48410..9a21954898553 100644 --- a/server/src/test/java/org/elasticsearch/http/HttpTracerTests.java +++ b/server/src/test/java/org/elasticsearch/http/HttpTracerTests.java @@ -29,6 +29,8 @@ import java.util.List; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class HttpTracerTests extends ESTestCase { // these loggers are named in the docs so must not be changed without due care @@ -96,15 +98,15 @@ public void testBodyLogging() { .withContent(responseBody, null) .build(); - assertEquals( - responseBody, + assertThat( ChunkedLoggingStreamTestUtils.getDecodedLoggedBody( LogManager.getLogger(HTTP_BODY_TRACER_LOGGER), Level.TRACE, "[" + request.getRequestId() + "] request body", ReferenceDocs.HTTP_TRACER, () -> assertNotNull(tracer.maybeLogRequest(request, null)) - ) + ), + equalBytes(responseBody) ); } } diff --git a/server/src/test/java/org/elasticsearch/index/mapper/XContentDataHelperTests.java b/server/src/test/java/org/elasticsearch/index/mapper/XContentDataHelperTests.java index 7d66db422da61..ba094d7211fc4 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/XContentDataHelperTests.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/XContentDataHelperTests.java @@ -34,6 +34,7 @@ import java.util.Set; import java.util.stream.Stream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class XContentDataHelperTests extends ESTestCase { @@ -143,7 +144,7 @@ public void testEmbeddedObject() throws IOException { XContentDataHelper.decodeAndWrite(decoded, encoded); var decodedBytes = BytesReference.bytes(builder); - assertEquals(originalBytes, decodedBytes); + assertThat(decodedBytes, equalBytes(originalBytes)); } public void testObject() throws IOException { diff --git a/server/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java b/server/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java index 53f2d6c6bd680..28a5879c3a587 100644 --- a/server/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java @@ -45,6 +45,7 @@ import java.util.function.Supplier; import static java.util.Collections.emptyList; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; @@ -105,7 +106,7 @@ public void testSerializationOrder() throws Exception { BytesStreamOutput out2 = new BytesStreamOutput(); original.writeTo(out1); deserialized.writeTo(out2); - assertEquals(out1.bytes(), out2.bytes()); + assertThat(out2.bytes(), equalBytes(out1.bytes())); } } diff --git a/server/src/test/java/org/elasticsearch/index/translog/TranslogHeaderWriterTests.java b/server/src/test/java/org/elasticsearch/index/translog/TranslogHeaderWriterTests.java index 9e3f521f21522..3ebf38717785e 100644 --- a/server/src/test/java/org/elasticsearch/index/translog/TranslogHeaderWriterTests.java +++ b/server/src/test/java/org/elasticsearch/index/translog/TranslogHeaderWriterTests.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.util.zip.CRC32; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; /** @@ -206,7 +207,7 @@ private static void serializationMatches( serialized.writeToTranslogBuffer(operationOutput); BytesReference actualWithSize = operationOutput.bytes(); - assertThat(actualWithSize.slice(4 + offset, actualWithSize.length() - offset - 4), equalTo(expectedWithoutSize)); + assertThat(actualWithSize.slice(4 + offset, actualWithSize.length() - offset - 4), equalBytes(expectedWithoutSize)); } private static void operationMatches( diff --git a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java index 62e609c5b9925..0e712d4d9d607 100644 --- a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java +++ b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java @@ -124,6 +124,7 @@ import java.util.stream.LongStream; import java.util.stream.Stream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.common.util.BigArrays.NON_RECYCLING_INSTANCE; import static org.elasticsearch.index.translog.SnapshotMatchers.containsOperationsInAnyOrder; import static org.elasticsearch.index.translog.TranslogOperationsUtils.indexOp; @@ -875,7 +876,7 @@ public void testConcurrentWritesWithVaryingSize() throws Throwable { Translog.Index expIndexOp = (Translog.Index) expectedOp; assertEquals(expIndexOp.uid(), indexOp.uid()); assertEquals(expIndexOp.routing(), indexOp.routing()); - assertEquals(expIndexOp.source(), indexOp.source()); + assertThat(indexOp.source(), equalBytes(expIndexOp.source())); assertEquals(expIndexOp.version(), indexOp.version()); } case DELETE -> { diff --git a/server/src/test/java/org/elasticsearch/rest/ChunkedRestResponseBodyPartTests.java b/server/src/test/java/org/elasticsearch/rest/ChunkedRestResponseBodyPartTests.java index eece90ed94cf9..3e46efba1ee5f 100644 --- a/server/src/test/java/org/elasticsearch/rest/ChunkedRestResponseBodyPartTests.java +++ b/server/src/test/java/org/elasticsearch/rest/ChunkedRestResponseBodyPartTests.java @@ -31,6 +31,8 @@ import java.util.List; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class ChunkedRestResponseBodyPartTests extends ESTestCase { public void testEncodesChunkedXContentCorrectly() throws IOException { @@ -67,7 +69,7 @@ public void testEncodesChunkedXContentCorrectly() throws IOException { } assertTrue(firstBodyPart.isLastPart()); - assertEquals(bytesDirect, CompositeBytesReference.of(refsGenerated.toArray(new BytesReference[0]))); + assertThat(CompositeBytesReference.of(refsGenerated.toArray(new BytesReference[0])), equalBytes(bytesDirect)); } public void testFromTextChunks() throws IOException { @@ -88,7 +90,7 @@ public void testFromTextChunks() throws IOException { writer.write(chunk); } writer.flush(); - assertEquals(new BytesArray(outputStream.toByteArray()), chunkedBytes); + assertThat(chunkedBytes, equalBytes(new BytesArray(outputStream.toByteArray()))); } } } diff --git a/server/src/test/java/org/elasticsearch/rest/RestContentAggregatorTests.java b/server/src/test/java/org/elasticsearch/rest/RestContentAggregatorTests.java index 4ab1ac66a2e4f..022499f74b33e 100644 --- a/server/src/test/java/org/elasticsearch/rest/RestContentAggregatorTests.java +++ b/server/src/test/java/org/elasticsearch/rest/RestContentAggregatorTests.java @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; import static java.util.stream.IntStream.range; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.rest.RestContentAggregator.aggregate; public class RestContentAggregatorTests extends ESTestCase { @@ -78,7 +79,7 @@ public void testAggregateRandomSize() { var aggregated = aggregatedRef.get(); var expectedBytes = CompositeBytesReference.of(streamChunks.toArray(new ReleasableBytesReference[0])); - assertEquals(expectedBytes, aggregated.content()); + assertThat(aggregated.content(), equalBytes(expectedBytes)); aggregated.content().close(); } diff --git a/server/src/test/java/org/elasticsearch/rest/RestRequestTests.java b/server/src/test/java/org/elasticsearch/rest/RestRequestTests.java index 49dc0333624cb..edebbb4b7b549 100644 --- a/server/src/test/java/org/elasticsearch/rest/RestRequestTests.java +++ b/server/src/test/java/org/elasticsearch/rest/RestRequestTests.java @@ -34,6 +34,7 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.rest.RestRequest.OPERATOR_REQUEST; import static org.elasticsearch.rest.RestRequest.SERVERLESS_REQUEST; import static org.hamcrest.Matchers.containsString; @@ -174,16 +175,16 @@ public void testParamAsIntegerWithNonIntegerParameter() { public void testContentOrSourceParam() { Exception e = expectThrows(ElasticsearchParseException.class, () -> contentRestRequest("", emptyMap()).contentOrSourceParam()); assertEquals("request body or source parameter is required", e.getMessage()); - assertEquals(new BytesArray("stuff"), contentRestRequest("stuff", emptyMap()).contentOrSourceParam().v2()); - assertEquals( - new BytesArray("stuff"), - contentRestRequest("stuff", Map.of("source", "stuff2", "source_content_type", "application/json")).contentOrSourceParam().v2() + assertThat(contentRestRequest("stuff", emptyMap()).contentOrSourceParam().v2(), equalBytes(new BytesArray("stuff"))); + assertThat( + contentRestRequest("stuff", Map.of("source", "stuff2", "source_content_type", "application/json")).contentOrSourceParam().v2(), + equalBytes(new BytesArray("stuff2")) ); - assertEquals( - new BytesArray("{\"foo\": \"stuff\"}"), + assertThat( contentRestRequest("", Map.of("source", "{\"foo\": \"stuff\"}", "source_content_type", "application/json")) .contentOrSourceParam() - .v2() + .v2(), + equalBytes(new BytesArray("{\"foo\": \"stuff\"}")) ); e = expectThrows(ValidationException.class, () -> contentRestRequest("", Map.of("source", "stuff2")).contentOrSourceParam()); assertThat(e.getMessage(), containsString("source and source_content_type parameters are required")); @@ -290,10 +291,10 @@ public void testMultipleContentTypeHeaders() { public void testRequiredContent() { Exception e = expectThrows(ElasticsearchParseException.class, () -> contentRestRequest("", emptyMap()).requiredContent()); assertEquals("request body is required", e.getMessage()); - assertEquals(new BytesArray("stuff"), contentRestRequest("stuff", emptyMap()).requiredContent()); - assertEquals( - new BytesArray("stuff"), - contentRestRequest("stuff", Map.of("source", "stuff2", "source_content_type", "application/json")).requiredContent() + assertThat(contentRestRequest("stuff", emptyMap()).requiredContent(), equalBytes(new BytesArray("stuff"))); + assertThat( + contentRestRequest("stuff", Map.of("source", "stuff2", "source_content_type", "application/json")).requiredContent(), + equalBytes(new BytesArray("stuff")) ); e = expectThrows( ElasticsearchParseException.class, diff --git a/server/src/test/java/org/elasticsearch/rest/action/document/RestGetSourceActionTests.java b/server/src/test/java/org/elasticsearch/rest/action/document/RestGetSourceActionTests.java index 7cec10299280e..787a22bd3c8c1 100644 --- a/server/src/test/java/org/elasticsearch/rest/action/document/RestGetSourceActionTests.java +++ b/server/src/test/java/org/elasticsearch/rest/action/document/RestGetSourceActionTests.java @@ -26,6 +26,7 @@ import org.mockito.Mockito; import static java.util.Collections.emptyMap; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; import static org.elasticsearch.rest.RestStatus.OK; import static org.hamcrest.Matchers.equalTo; @@ -63,7 +64,7 @@ public void testRestGetSourceAction() throws Exception { assertThat(restResponse.status(), equalTo(OK)); assertThat(restResponse.contentType(), equalTo("application/json"));// dropping charset as it was not on a request - assertThat(restResponse.content(), equalTo(new BytesArray("{\"foo\": \"bar\"}"))); + assertThat(restResponse.content(), equalBytes(new BytesArray("{\"foo\": \"bar\"}"))); } public void testRestGetSourceActionWithMissingDocument() { diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/DoubleBoundsTests.java b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/DoubleBoundsTests.java index 97e98ae25d6c7..a5b7c3303a6fe 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/DoubleBoundsTests.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/DoubleBoundsTests.java @@ -20,6 +20,7 @@ import java.io.IOException; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class DoubleBoundsTests extends ESTestCase { @@ -66,7 +67,7 @@ public void testTransportRoundTrip() throws IOException { readBytes = out.bytes(); } - assertEquals(origBytes, readBytes); + assertThat(readBytes, equalBytes(origBytes)); } public void testXContentRoundTrip() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/LongBoundsTests.java b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/LongBoundsTests.java index 6f236d611ac24..fa06226c2e322 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/LongBoundsTests.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/LongBoundsTests.java @@ -28,6 +28,7 @@ import static java.lang.Math.max; import static java.lang.Math.min; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class LongBoundsTests extends ESTestCase { @@ -137,7 +138,7 @@ public void testTransportRoundTrip() throws IOException { readBytes = out.bytes(); } - assertEquals(origBytes, readBytes); + assertThat(readBytes, equalBytes(origBytes)); } public void testXContentRoundTrip() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/search/internal/ShardSearchRequestTests.java b/server/src/test/java/org/elasticsearch/search/internal/ShardSearchRequestTests.java index e2207a2d388a3..f7adb2673fb35 100644 --- a/server/src/test/java/org/elasticsearch/search/internal/ShardSearchRequestTests.java +++ b/server/src/test/java/org/elasticsearch/search/internal/ShardSearchRequestTests.java @@ -49,6 +49,7 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.index.query.AbstractQueryBuilder.parseTopLevelQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.Matchers.containsString; @@ -186,7 +187,7 @@ private static void assertEquals(ShardSearchRequest orig, ShardSearchRequest cop assertEquals(orig.searchType(), copy.searchType()); assertEquals(orig.shardId(), copy.shardId()); assertEquals(orig.numberOfShards(), copy.numberOfShards()); - assertEquals(orig.cacheKey(null), copy.cacheKey(null)); + assertThat(copy.cacheKey(null), equalBytes(orig.cacheKey(null))); assertNotSame(orig, copy); assertEquals(orig.getAliasFilter(), copy.getAliasFilter()); assertEquals(orig.indexBoost(), copy.indexBoost(), 0.0f); diff --git a/server/src/test/java/org/elasticsearch/transport/OutboundHandlerTests.java b/server/src/test/java/org/elasticsearch/transport/OutboundHandlerTests.java index e80b88c095f85..9b7c2366b63f1 100644 --- a/server/src/test/java/org/elasticsearch/transport/OutboundHandlerTests.java +++ b/server/src/test/java/org/elasticsearch/transport/OutboundHandlerTests.java @@ -52,6 +52,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -131,7 +132,7 @@ public void testSendRawBytes() { assertSame(e, exception.get()); } - assertEquals(bytesArray, reference); + assertThat(reference, equalBytes(bytesArray)); } public void testSendRequest() throws IOException { diff --git a/test/fixtures/gcs-fixture/src/test/java/fixture/gcs/MultipartUploadTests.java b/test/fixtures/gcs-fixture/src/test/java/fixture/gcs/MultipartUploadTests.java index 6b9b8a201bfb7..4b7fde0e6391c 100644 --- a/test/fixtures/gcs-fixture/src/test/java/fixture/gcs/MultipartUploadTests.java +++ b/test/fixtures/gcs-fixture/src/test/java/fixture/gcs/MultipartUploadTests.java @@ -19,6 +19,7 @@ import java.util.Arrays; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; public class MultipartUploadTests extends ESTestCase { @@ -63,7 +64,7 @@ public void testReadUntilDelimiter() throws IOException { var delimitedContent = DelimitedContent.randomContent(); var inputStream = delimitedContent.toBytesReference().streamInput(); var readBytes = MultipartUpload.readUntilDelimiter(inputStream, delimitedContent.delimiter); - assertEquals(new BytesArray(delimitedContent.before), readBytes); + assertThat(readBytes, equalBytes(new BytesArray(delimitedContent.before))); var readRemaining = inputStream.readAllBytes(); assertArrayEquals(delimitedContent.after, readRemaining); } diff --git a/test/framework/src/main/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java b/test/framework/src/main/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java index 3d576370affd7..88a28e3538238 100644 --- a/test/framework/src/main/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Map; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.greaterThan; public abstract class AbstractBytesReferenceTestCase extends ESTestCase { @@ -508,13 +509,13 @@ public void testEquals() throws IOException { BytesReference copy = bytesReference.slice(0, bytesReference.length()); // get refs & compare - assertEquals(copy, bytesReference); + assertThat(bytesReference, equalBytes(copy)); int sliceFrom = randomIntBetween(0, bytesReference.length()); int sliceLength = randomIntBetween(0, bytesReference.length() - sliceFrom); - assertEquals(copy.slice(sliceFrom, sliceLength), bytesReference.slice(sliceFrom, sliceLength)); + assertThat(bytesReference.slice(sliceFrom, sliceLength), equalBytes(copy.slice(sliceFrom, sliceLength))); BytesRef bytesRef = BytesRef.deepCopyOf(copy.toBytesRef()); - assertEquals(new BytesArray(bytesRef), copy); + assertThat(copy, equalBytes(new BytesArray(bytesRef))); int offsetToFlip = randomIntBetween(0, bytesRef.length - 1); int value = ~Byte.toUnsignedInt(bytesRef.bytes[bytesRef.offset + offsetToFlip]); @@ -625,13 +626,13 @@ public void testBasicEquals() { final BytesArray b1 = new BytesArray(array1, offset1, len); final BytesArray b2 = new BytesArray(array2, offset2, len); - assertEquals(b1, b2); + assertThat(b2, equalBytes(b1)); assertEquals(Arrays.hashCode(BytesReference.toBytes(b1)), b1.hashCode()); assertEquals(Arrays.hashCode(BytesReference.toBytes(b2)), b2.hashCode()); // test same instance - assertEquals(b1, b1); - assertEquals(b2, b2); + assertThat(b1, equalBytes(b1)); + assertThat(b2, equalBytes(b2)); if (len > 0) { // test different length @@ -714,7 +715,7 @@ public void testReadSlices() throws IOException { } boolean sliceRight = randomBoolean(); BytesReference right = sliceRight ? input2.readSlicedBytesReference() : input2.readBytesReference(); - assertEquals(left, right); + assertThat(right, equalBytes(left)); if (sliceRight && bytesReference.hasArray()) { assertSame(right.array(), right.array()); } diff --git a/test/framework/src/main/java/org/elasticsearch/common/bytes/BytesReferenceTestUtils.java b/test/framework/src/main/java/org/elasticsearch/common/bytes/BytesReferenceTestUtils.java new file mode 100644 index 0000000000000..c74726243ea72 --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/common/bytes/BytesReferenceTestUtils.java @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side + * Public License v 1"; you may not use this file except in compliance with, at + * your election, the "Elastic License 2.0", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +package org.elasticsearch.common.bytes; + +import org.apache.lucene.util.BytesRef; +import org.elasticsearch.common.Strings; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; + +import java.io.IOException; +import java.util.Objects; + +public enum BytesReferenceTestUtils { + ; + + /** + * Like {@link Matchers#equalTo} except it reports the contents of the respective {@link BytesReference} instances on mismatch. + */ + public static Matcher equalBytes(BytesReference expected) { + return new BaseMatcher<>() { + @Override + public boolean matches(Object actual) { + return Objects.equals(expected, actual); + } + + @Override + public void describeTo(Description description) { + if (expected == null) { + description.appendValue(null); + } else { + appendBytesReferenceDescription(expected, description); + } + } + + private void appendBytesReferenceDescription(BytesReference bytesReference, Description description) { + final var stringBuilder = new StringBuilder("BytesReference["); + final var iterator = bytesReference.iterator(); + BytesRef bytesRef; + boolean first = true; + try { + while ((bytesRef = iterator.next()) != null) { + for (int i = 0; i <= bytesRef.length; i++) { + if (first) { + first = false; + } else { + stringBuilder.append(' '); + } + stringBuilder.append(Strings.format("%02x", bytesRef.bytes[bytesRef.offset + i])); + } + } + description.appendText(stringBuilder.append(']').toString()); + } catch (IOException e) { + throw new AssertionError("no IO happens here", e); + } + } + + @Override + public void describeMismatch(Object item, Description description) { + description.appendText("was "); + if (item instanceof BytesReference bytesReference) { + appendBytesReferenceDescription(bytesReference, description); + } else { + description.appendValue(item); + } + } + }; + } +} diff --git a/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java index e552bb133add4..0335a63ab6316 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java @@ -142,6 +142,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.shuffle; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.index.engine.Engine.Operation.Origin.PEER_RECOVERY; import static org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY; import static org.elasticsearch.index.engine.Engine.Operation.Origin.REPLICA; @@ -1434,7 +1435,7 @@ public static void assertConsistentHistoryBetweenTranslogAndLuceneIndex(Engine e translogOperationAsserter.assertSameIndexOperation((Translog.Index) luceneOp, (Translog.Index) translogOp) ); } else { - assertThat(((Translog.Index) luceneOp).source(), equalTo(((Translog.Index) translogOp).source())); + assertThat(((Translog.Index) luceneOp).source(), equalBytes(((Translog.Index) translogOp).source())); } } } diff --git a/test/framework/src/main/java/org/elasticsearch/repositories/AbstractThirdPartyRepositoryTestCase.java b/test/framework/src/main/java/org/elasticsearch/repositories/AbstractThirdPartyRepositoryTestCase.java index 8cd3aa1b15dfc..2878159a10f9d 100644 --- a/test/framework/src/main/java/org/elasticsearch/repositories/AbstractThirdPartyRepositoryTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/repositories/AbstractThirdPartyRepositoryTestCase.java @@ -45,6 +45,7 @@ import java.util.concurrent.Executor; import java.util.function.Predicate; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.repositories.blobstore.BlobStoreRepository.METADATA_PREFIX; import static org.elasticsearch.repositories.blobstore.BlobStoreRepository.SNAPSHOT_PREFIX; import static org.elasticsearch.repositories.blobstore.BlobStoreTestUtil.randomNonDataPurpose; @@ -299,7 +300,7 @@ public void testReadFromPositionWithLength() { }); { - assertThat("Exact Range", readBlob(repository, blobName, 0L, blobBytes.length()), equalTo(blobBytes)); + assertThat("Exact Range", readBlob(repository, blobName, 0L, blobBytes.length()), equalBytes(blobBytes)); } { int position = randomIntBetween(0, blobBytes.length() - 1); @@ -307,7 +308,7 @@ public void testReadFromPositionWithLength() { assertThat( "Random Range: " + position + '-' + (position + length), readBlob(repository, blobName, position, length), - equalTo(blobBytes.slice(position, length)) + equalBytes(blobBytes.slice(position, length)) ); } { @@ -316,7 +317,7 @@ public void testReadFromPositionWithLength() { assertThat( "Random Larger Range: " + position + '-' + (position + length), readBlob(repository, blobName, position, length), - equalTo(blobBytes.slice(position, Math.toIntExact(Math.min(length, blobBytes.length() - position)))) + equalBytes(blobBytes.slice(position, Math.toIntExact(Math.min(length, blobBytes.length() - position)))) ); } } @@ -386,7 +387,7 @@ public void testFailIfAlreadyExists() { return null; }); - assertEquals(overwriteBlobBytes, readBlob(repository, blobName, 0, overwriteBlobBytes.length())); + assertThat(readBlob(repository, blobName, 0, overwriteBlobBytes.length()), equalBytes(overwriteBlobBytes)); // throw exception if failIfAlreadyExists is set to true executeOnBlobStore(repository, blobStore -> { diff --git a/test/framework/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTestUtilsTests.java b/test/framework/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTestUtilsTests.java new file mode 100644 index 0000000000000..1644340ebb016 --- /dev/null +++ b/test/framework/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTestUtilsTests.java @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side + * Public License v 1"; you may not use this file except in compliance with, at + * your election, the "Elastic License 2.0", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +package org.elasticsearch.common.bytes; + +import org.elasticsearch.test.ESTestCase; +import org.hamcrest.StringDescription; + +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + +public class BytesReferenceTestUtilsTests extends ESTestCase { + public void testEqualBytes() { + final var expectedBytes = randomBoolean() + ? new BytesArray(new byte[] { 0, 1, 2, 3, 99 }) + : CompositeBytesReference.of(new BytesArray(new byte[] { 0, 1 }), new BytesArray(new byte[] { 2, 3, 99 })); + + final var matcher = equalBytes(expectedBytes); + assertTrue(matcher.matches(expectedBytes)); + assertTrue(matcher.matches(new BytesArray(BytesReference.toBytes(expectedBytes)))); + assertTrue(matcher.matches(CompositeBytesReference.of(expectedBytes.slice(0, 3), expectedBytes.slice(3, 2)))); + assertFalse(matcher.matches(randomBytesReference(5))); + + final var description = new StringDescription(); + matcher.describeTo(description); + assertEquals("BytesReference[00 01 02 03 63]", description.toString()); + + final var nullMismatchDescription = new StringDescription(); + matcher.describeMismatch(null, nullMismatchDescription); + assertEquals("was null", nullMismatchDescription.toString()); + + final var unequalMismatchDescription = new StringDescription(); + matcher.describeMismatch(new BytesArray(new byte[] { 0, 1, 2, 3, 15 }), unequalMismatchDescription); + assertEquals("was BytesReference[00 01 02 03 0f]", unequalMismatchDescription.toString()); + + final var nullMatcher = equalBytes(null); + assertTrue(nullMatcher.matches(null)); + assertFalse(nullMatcher.matches(randomBytesReference(5))); + + final var nullMatcherDescription = new StringDescription(); + nullMatcher.describeTo(nullMatcherDescription); + assertEquals("null", nullMatcherDescription.toString()); + } +} diff --git a/x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/GetAutoscalingCapacityActionResponseTests.java b/x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/GetAutoscalingCapacityActionResponseTests.java index 225ab2a7ba8bb..0858f3ce48bca 100644 --- a/x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/GetAutoscalingCapacityActionResponseTests.java +++ b/x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/action/GetAutoscalingCapacityActionResponseTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.autoscaling.AutoscalingTestCase; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderResults; -import org.hamcrest.Matchers; import java.io.IOException; import java.util.Map; @@ -23,6 +22,8 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; + public class GetAutoscalingCapacityActionResponseTests extends AutoscalingTestCase { public void testToXContent() throws IOException { @@ -50,6 +51,6 @@ public void testToXContent() throws IOException { expected.endObject(); expected.endObject(); BytesReference expectedBytes = BytesReference.bytes(expected); - assertThat(responseBytes, Matchers.equalTo(expectedBytes)); + assertThat(responseBytes, equalBytes(expectedBytes)); } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTests.java index bd7f82501ce13..7e520ae19a1b2 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTests.java @@ -44,6 +44,7 @@ import java.util.stream.Collectors; import static java.util.Map.entry; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.xpack.core.security.authc.Authentication.VERSION_API_KEY_ROLES_AS_BYTES; import static org.elasticsearch.xpack.core.security.authc.AuthenticationTestHelper.randomCloudApiKeyAuthentication; import static org.elasticsearch.xpack.core.security.authc.AuthenticationTestHelper.randomCrossClusterAccessSubjectInfo; @@ -1262,7 +1263,7 @@ public void testMaybeRemoveRemoteIndicesFromRoleDescriptors() { ); // check null value - assertThat(null, equalTo(Authentication.maybeRemoveRemoteIndicesFromRoleDescriptors(null))); + assertThat(null, equalBytes(Authentication.maybeRemoveRemoteIndicesFromRoleDescriptors(null))); // and an empty map final BytesReference empty = randomBoolean() ? new BytesArray(""" diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/SubjectTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/SubjectTests.java index 625feca39cdb5..056b9dca939c4 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/SubjectTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/SubjectTests.java @@ -38,6 +38,7 @@ import java.util.Map; import java.util.Set; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_REALM_NAME; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_REALM_TYPE; @@ -358,7 +359,7 @@ public void testGetFleetApiKeyRoleReferenceBwcBugFix() { final List roleReferences = roleReferenceIntersection.getRoleReferences(); assertThat(roleReferences, contains(isA(ApiKeyRoleReference.class), isA(ApiKeyRoleReference.class))); final ApiKeyRoleReference limitedByRoleReference = (ApiKeyRoleReference) roleReferences.get(1); - assertThat(limitedByRoleReference.getRoleDescriptorsBytes(), equalTo(FLEET_SERVER_ROLE_DESCRIPTOR_BYTES_V_7_14)); + assertThat(limitedByRoleReference.getRoleDescriptorsBytes(), equalBytes(FLEET_SERVER_ROLE_DESCRIPTOR_BYTES_V_7_14)); } private AnonymousUser getAnonymousUser() { diff --git a/x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/search/PITAwareQueryClientTests.java b/x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/search/PITAwareQueryClientTests.java index b004190c0ca43..e6bcceb6071e5 100644 --- a/x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/search/PITAwareQueryClientTests.java +++ b/x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/search/PITAwareQueryClientTests.java @@ -68,6 +68,7 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static org.elasticsearch.action.ActionListener.wrap; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.index.query.QueryBuilders.idsQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; @@ -219,7 +220,7 @@ protected void listener.onResponse((Response) response); } else if (request instanceof ClosePointInTimeRequest closePIT) { assertTrue(openedPIT); - assertEquals(pitId, closePIT.getId()); + assertThat(closePIT.getId(), equalBytes(pitId)); openedPIT = false; ClosePointInTimeResponse response = new ClosePointInTimeResponse(true, 1); @@ -229,7 +230,7 @@ protected void searchRequestsRemainingCount--; assertTrue(searchRequestsRemainingCount >= 0); - assertEquals(pitId, searchRequest.source().pointInTimeBuilder().getEncodedId()); + assertThat(searchRequest.source().pointInTimeBuilder().getEncodedId(), equalBytes(pitId)); assertEquals(0, searchRequest.indices().length); // no indices set in the search request assertEquals(1, searchRequest.source().subSearches().size()); diff --git a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/support/SamlAuthenticationStateTests.java b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/support/SamlAuthenticationStateTests.java index 61018fe77d47e..ff2d143eaefdb 100644 --- a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/support/SamlAuthenticationStateTests.java +++ b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/support/SamlAuthenticationStateTests.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.util.List; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; public class SamlAuthenticationStateTests extends IdpSamlTestCase { @@ -81,7 +82,7 @@ private SamlAuthenticationState assertXContentRoundTrip(SamlAuthenticationState assertThat(obj2, equalTo(obj1)); final BytesReference bytes2 = XContentHelper.toXContent(obj2, xContentType, humanReadable); - assertThat(bytes2, equalTo(bytes1)); + assertThat(bytes2, equalBytes(bytes1)); return obj2; } diff --git a/x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/action/filter/ShardBulkInferenceActionFilterTests.java b/x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/action/filter/ShardBulkInferenceActionFilterTests.java index 04997af32b125..c8e5e50a4b556 100644 --- a/x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/action/filter/ShardBulkInferenceActionFilterTests.java +++ b/x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/action/filter/ShardBulkInferenceActionFilterTests.java @@ -88,6 +88,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.index.IndexingPressure.MAX_COORDINATING_BYTES; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.awaitLatch; @@ -767,7 +768,7 @@ public void testIndexingPressureTripsOnInferenceRequestGeneration() throws Excep IndexRequest doc1IndexRequest = getIndexRequestOrNull(doc1Request.request()); assertThat(doc1IndexRequest, notNullValue()); - assertThat(doc1IndexRequest.source(), equalTo(BytesReference.bytes(doc1Source))); + assertThat(doc1IndexRequest.source(), equalBytes(BytesReference.bytes(doc1Source))); IndexingPressure.Coordinating coordinatingIndexingPressure = indexingPressure.getCoordinating(); assertThat(coordinatingIndexingPressure, notNullValue()); @@ -851,7 +852,7 @@ public void testIndexingPressureTripsOnInferenceResponseHandling() throws Except IndexRequest doc1IndexRequest = getIndexRequestOrNull(doc1Request.request()); assertThat(doc1IndexRequest, notNullValue()); - assertThat(doc1IndexRequest.source(), equalTo(BytesReference.bytes(doc1Source))); + assertThat(doc1IndexRequest.source(), equalBytes(BytesReference.bytes(doc1Source))); IndexingPressure.Coordinating coordinatingIndexingPressure = indexingPressure.getCoordinating(); assertThat(coordinatingIndexingPressure, notNullValue()); @@ -964,7 +965,7 @@ public void testIndexingPressurePartialFailure() throws Exception { IndexRequest doc2IndexRequest = getIndexRequestOrNull(doc2Request.request()); assertThat(doc2IndexRequest, notNullValue()); - assertThat(doc2IndexRequest.source(), equalTo(BytesReference.bytes(doc2Source))); + assertThat(doc2IndexRequest.source(), equalBytes(BytesReference.bytes(doc2Source))); IndexingPressure.Coordinating coordinatingIndexingPressure = indexingPressure.getCoordinating(); assertThat(coordinatingIndexingPressure, notNullValue()); diff --git a/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/ChunkedTrainedModelPersisterIT.java b/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/ChunkedTrainedModelPersisterIT.java index 35bc424f67aff..bdc441cfe54de 100644 --- a/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/ChunkedTrainedModelPersisterIT.java +++ b/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/ChunkedTrainedModelPersisterIT.java @@ -58,6 +58,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.startsWith; @@ -143,7 +144,7 @@ public void testStoreModelViaChunkedPersisterWithNodeInfo() throws IOException { TrainedModelConfig storedConfig = getTrainedModelFuture.actionGet(); - assertThat(storedConfig.getCompressedDefinition(), equalTo(compressedDefinition)); + assertThat(storedConfig.getCompressedDefinition(), equalBytes(compressedDefinition)); assertThat(storedConfig.getEstimatedOperations(), equalTo((long) modelSizeInfo.numOperations())); assertThat(storedConfig.getModelSize(), equalTo(modelSizeInfo.ramBytesUsed())); assertThat(storedConfig.getMetadata(), hasKey("total_feature_importance")); @@ -219,7 +220,7 @@ public void testStoreModelViaChunkedPersisterWithoutNodeInfo() throws IOExceptio trainedModelProvider.getTrainedModel(inferenceModelId, GetTrainedModelsAction.Includes.all(), null, getTrainedModelFuture); TrainedModelConfig storedConfig = getTrainedModelFuture.actionGet(); - assertThat(storedConfig.getCompressedDefinition(), equalTo(compressedDefinition)); + assertThat(storedConfig.getCompressedDefinition(), equalBytes(compressedDefinition)); assertThat(storedConfig.getEstimatedOperations(), equalTo((long) modelSizeInfo.numOperations())); assertThat(storedConfig.getModelSize(), equalTo(modelSizeInfo.ramBytesUsed())); assertThat(storedConfig.getMetadata(), hasKey("total_feature_importance")); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java index 1d52f278323dd..0dcbf4873d328 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java @@ -67,6 +67,7 @@ import java.util.Optional; import java.util.function.Supplier; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.xpack.ml.MachineLearning.DELAYED_DATA_CHECK_FREQ; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; @@ -389,7 +390,7 @@ public void testRealtimeRun() throws Exception { IndexRequest indexRequest = (IndexRequest) bulkRequest.requests().get(0); assertThat(indexRequest.index(), equalTo(AnnotationIndex.WRITE_ALIAS_NAME)); assertThat(indexRequest.id(), equalTo(annotationDocId)); - assertThat(indexRequest.source(), equalTo(expectedSource)); + assertThat(indexRequest.source(), equalBytes(expectedSource)); assertThat(indexRequest.opType(), equalTo(DocWriteRequest.OpType.INDEX)); } diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkDocTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkDocTests.java index 9cd98ff4636cb..82644ce81d5a1 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkDocTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkDocTests.java @@ -23,6 +23,7 @@ import java.util.List; import static java.util.Collections.emptyList; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; import static org.elasticsearch.xpack.monitoring.MonitoringTestUtils.randomMonitoringBulkDoc; import static org.hamcrest.Matchers.equalTo; @@ -74,7 +75,7 @@ public void testConstructor() { assertThat(document.getId(), equalTo(id)); assertThat(document.getTimestamp(), equalTo(timestamp)); assertThat(document.getIntervalMillis(), equalTo(interval)); - assertThat(document.getSource(), equalTo(source)); + assertThat(document.getSource(), equalBytes(source)); assertThat(document.getXContentType(), equalTo(xContentType)); } diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkRequestTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkRequestTests.java index e7357672bbeda..5db1971ba57af 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkRequestTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkRequestTests.java @@ -26,6 +26,7 @@ import java.util.Collection; import java.util.List; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; @@ -134,7 +135,7 @@ public void testAddRequestContent() throws IOException { assertThat(bulkDoc.getId(), equalTo(ids[count])); assertThat(bulkDoc.getTimestamp(), equalTo(timestamp)); assertThat(bulkDoc.getIntervalMillis(), equalTo(interval)); - assertThat(bulkDoc.getSource(), equalTo(sources[count])); + assertThat(bulkDoc.getSource(), equalBytes(sources[count])); assertThat(bulkDoc.getXContentType(), equalTo(xContentType)); ++count; } diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/BytesReferenceMonitoringDocTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/BytesReferenceMonitoringDocTests.java index dd0dc68da0cb7..fd39a5818219d 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/BytesReferenceMonitoringDocTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/BytesReferenceMonitoringDocTests.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.List; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; import static org.elasticsearch.xpack.core.monitoring.MonitoredSystem.KIBANA; import static org.hamcrest.Matchers.equalTo; @@ -62,7 +63,7 @@ protected void assertMonitoringDoc(final BytesReferenceMonitoringDoc document) { assertThat(document.getId(), equalTo(id)); assertThat(document.getXContentType(), equalTo(xContentType)); - assertThat(document.getSource(), equalTo(source)); + assertThat(document.getSource(), equalBytes(source)); } public void testConstructorMonitoredSystemMustNotBeNull() { diff --git a/x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/RetrySearchIntegTests.java b/x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/RetrySearchIntegTests.java index e983d955a191c..0ee6160149f81 100644 --- a/x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/RetrySearchIntegTests.java +++ b/x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/RetrySearchIntegTests.java @@ -38,6 +38,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicLong; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailuresAndResponse; @@ -139,7 +140,7 @@ public void testRetryPointInTime() throws Exception { SetOnce updatedPit = new SetOnce<>(); try { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp, docCount); }); final Set allocatedNodes = internalCluster().nodesInclude(indexName); @@ -176,7 +177,7 @@ public void testRetryPointInTime() throws Exception { .setAllowPartialSearchResults(randomBoolean()) // partial results should not matter here .setPointInTime(new PointInTimeBuilder(updatedPit.get()).setKeepAlive(TimeValue.timeValueMinutes(2))), resp -> { - assertThat(resp.pointInTimeId(), equalTo(updatedPit.get())); + assertThat(resp.pointInTimeId(), equalBytes(updatedPit.get())); assertHitCount(resp, docCount); } ); @@ -208,7 +209,7 @@ public void testRetryRemovedPointInTime() throws Exception { try { assertNoFailuresAndResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)), resp -> { - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp, docCount); }); @@ -226,7 +227,7 @@ public void testRetryRemovedPointInTime() throws Exception { .setAllowPartialSearchResults(true) .setPointInTime(new PointInTimeBuilder(pitId)), resp -> { - assertThat(resp.pointInTimeId(), equalTo(pitId)); + assertThat(resp.pointInTimeId(), equalBytes(pitId)); assertHitCount(resp, docCount); } ); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java index a453b21b402ea..35607e13139b8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java @@ -162,6 +162,7 @@ import java.util.stream.IntStream; import java.util.stream.LongStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; 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.ActionListenerUtils.anyActionListener; @@ -1277,10 +1278,13 @@ public void testValidateApiKey() throws Exception { assertThat(result.getValue().email(), is("test@user.com")); assertThat(result.getValue().roles(), is(emptyArray())); assertThat(result.getValue().metadata(), is(Collections.emptyMap())); - assertThat(result.getMetadata().get(AuthenticationField.API_KEY_ROLE_DESCRIPTORS_KEY), equalTo(apiKeyDoc.roleDescriptorsBytes)); assertThat( - result.getMetadata().get(AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY), - equalTo(apiKeyDoc.limitedByRoleDescriptorsBytes) + asInstanceOf(BytesReference.class, result.getMetadata().get(AuthenticationField.API_KEY_ROLE_DESCRIPTORS_KEY)), + equalBytes(apiKeyDoc.roleDescriptorsBytes) + ); + assertThat( + asInstanceOf(BytesReference.class, result.getMetadata().get(AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY)), + equalBytes(apiKeyDoc.limitedByRoleDescriptorsBytes) ); assertThat(result.getMetadata().get(AuthenticationField.API_KEY_CREATOR_REALM_NAME), is("realm1")); assertThat(result.getMetadata().get(API_KEY_TYPE_KEY), is(apiKeyDoc.type.value())); @@ -1302,10 +1306,13 @@ public void testValidateApiKey() throws Exception { assertThat(result.getValue().email(), is("test@user.com")); assertThat(result.getValue().roles(), is(emptyArray())); assertThat(result.getValue().metadata(), is(Collections.emptyMap())); - assertThat(result.getMetadata().get(AuthenticationField.API_KEY_ROLE_DESCRIPTORS_KEY), equalTo(apiKeyDoc.roleDescriptorsBytes)); assertThat( - result.getMetadata().get(AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY), - equalTo(apiKeyDoc.limitedByRoleDescriptorsBytes) + asInstanceOf(BytesReference.class, result.getMetadata().get(AuthenticationField.API_KEY_ROLE_DESCRIPTORS_KEY)), + equalBytes(apiKeyDoc.roleDescriptorsBytes) + ); + assertThat( + asInstanceOf(BytesReference.class, result.getMetadata().get(AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY)), + equalBytes(apiKeyDoc.limitedByRoleDescriptorsBytes) ); assertThat(result.getMetadata().get(AuthenticationField.API_KEY_CREATOR_REALM_NAME), is("realm1")); assertThat(result.getMetadata().get(API_KEY_TYPE_KEY), is(apiKeyDoc.type.value())); @@ -2150,7 +2157,7 @@ public void testApiKeyDocCache() throws IOException, ExecutionException, Interru if (metadata == null) { assertNull(cachedApiKeyDoc.metadataFlattened); } else { - assertThat(cachedApiKeyDoc.metadataFlattened, equalTo(XContentTestUtils.convertToXContent(metadata, XContentType.JSON))); + assertThat(cachedApiKeyDoc.metadataFlattened, equalBytes(XContentTestUtils.convertToXContent(metadata, XContentType.JSON))); } assertThat(cachedApiKeyDoc.type, is(type)); @@ -2181,7 +2188,7 @@ public void testApiKeyDocCache() throws IOException, ExecutionException, Interru if (metadata2 == null) { assertNull(cachedApiKeyDoc2.metadataFlattened); } else { - assertThat(cachedApiKeyDoc2.metadataFlattened, equalTo(XContentTestUtils.convertToXContent(metadata2, XContentType.JSON))); + assertThat(cachedApiKeyDoc2.metadataFlattened, equalBytes(XContentTestUtils.convertToXContent(metadata2, XContentType.JSON))); } assertThat(cachedApiKeyDoc2.type, is(type)); @@ -2223,7 +2230,7 @@ public void testApiKeyDocCache() throws IOException, ExecutionException, Interru if (metadata3 == null) { assertNull(cachedApiKeyDoc3.metadataFlattened); } else { - assertThat(cachedApiKeyDoc3.metadataFlattened, equalTo(XContentTestUtils.convertToXContent(metadata3, XContentType.JSON))); + assertThat(cachedApiKeyDoc3.metadataFlattened, equalBytes(XContentTestUtils.convertToXContent(metadata3, XContentType.JSON))); } assertThat(cachedApiKeyDoc3.type, is(type)); @@ -2255,7 +2262,7 @@ public void testApiKeyDocCache() throws IOException, ExecutionException, Interru if (metadata31 == null) { assertNull(cachedApiKeyDoc31.metadataFlattened); } else { - assertThat(cachedApiKeyDoc31.metadataFlattened, equalTo(XContentTestUtils.convertToXContent(metadata31, XContentType.JSON))); + assertThat(cachedApiKeyDoc31.metadataFlattened, equalBytes(XContentTestUtils.convertToXContent(metadata31, XContentType.JSON))); } assertThat(service.getRoleDescriptorsBytesCache().get(cachedApiKeyDoc31.roleDescriptorsHash), sameInstance(roleDescriptorsBytes3)); assertThat(cachedApiKeyDoc31.type, is(ApiKey.Type.CROSS_CLUSTER)); @@ -2675,10 +2682,10 @@ public void testApiKeyDocDeserialization() throws IOException { assertEquals("{PBKDF2}10000$abc", apiKeyDoc.hash); assertEquals("key-1", apiKeyDoc.name); assertEquals(7000099, apiKeyDoc.version); - assertEquals(new BytesArray(""" - {"a":{"cluster":["all"]}}"""), apiKeyDoc.roleDescriptorsBytes); - assertEquals(new BytesArray(""" - {"limited_by":{"cluster":["all"],"metadata":{"_reserved":true},"type":"role"}}"""), apiKeyDoc.limitedByRoleDescriptorsBytes); + assertThat(apiKeyDoc.roleDescriptorsBytes, equalBytes(new BytesArray(""" + {"a":{"cluster":["all"]}}"""))); + assertThat(apiKeyDoc.limitedByRoleDescriptorsBytes, equalBytes(new BytesArray(""" + {"limited_by":{"cluster":["all"],"metadata":{"_reserved":true},"type":"role"}}"""))); final Map creator = apiKeyDoc.creator; assertEquals("admin", creator.get("principal")); @@ -2877,7 +2884,7 @@ public void testMaybeBuildUpdatedDocument() throws IOException { assertEquals(new HashSet<>(newKeyRoles), new HashSet<>(actualKeyRoles)); } if (changeMetadata == false) { - assertEquals(oldApiKeyDoc.metadataFlattened, updatedApiKeyDoc.metadataFlattened); + assertThat(updatedApiKeyDoc.metadataFlattened, equalBytes(oldApiKeyDoc.metadataFlattened)); } else { assertEquals(newMetadata, XContentHelper.convertToMap(updatedApiKeyDoc.metadataFlattened, true, XContentType.JSON).v2()); } @@ -2938,7 +2945,7 @@ public void testApiKeyDocDeserializationWithNullValues() throws IOException { ); assertEquals(-1L, apiKeyDoc.expirationTime); assertNull(apiKeyDoc.name); - assertEquals(new BytesArray("{}"), apiKeyDoc.roleDescriptorsBytes); + assertThat(apiKeyDoc.roleDescriptorsBytes, equalBytes(new BytesArray("{}"))); } public void testGetApiKeyMetadata() throws IOException { @@ -3713,8 +3720,8 @@ private void checkAuthApiKeyMetadata(Object metadata, AuthenticationResult assertThat(authResult1.getMetadata().containsKey(API_KEY_METADATA_KEY), is(false)); } else { assertThat( - authResult1.getMetadata().get(API_KEY_METADATA_KEY), - equalTo(XContentTestUtils.convertToXContent((Map) metadata, XContentType.JSON)) + asInstanceOf(BytesReference.class, authResult1.getMetadata().get(API_KEY_METADATA_KEY)), + equalBytes(XContentTestUtils.convertToXContent((Map) metadata, XContentType.JSON)) ); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java index 14ceadfa97611..1c089efdae7b8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java @@ -85,6 +85,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.common.util.set.Sets.newHashSet; import static org.elasticsearch.search.SearchService.ALLOW_EXPENSIVE_QUERIES; import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; @@ -702,7 +703,7 @@ public void testPutPrivileges() throws Exception { assertThat(request.indices(), arrayContaining(SecuritySystemIndices.SECURITY_MAIN_ALIAS)); assertThat(request.id(), equalTo("application-privilege_" + privilege.getApplication() + ":" + privilege.getName())); final XContentBuilder builder = privilege.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), true); - assertThat(request.source(), equalTo(BytesReference.bytes(builder))); + assertThat(request.source(), equalBytes(BytesReference.bytes(builder))); final boolean created = privilege.getName().equals("user") == false; responses[i] = BulkItemResponse.success( i, diff --git a/x-pack/plugin/snapshot-repo-test-kit/src/internalClusterTest/java/org/elasticsearch/repositories/blobstore/testkit/analyze/RepositoryAnalysisSuccessIT.java b/x-pack/plugin/snapshot-repo-test-kit/src/internalClusterTest/java/org/elasticsearch/repositories/blobstore/testkit/analyze/RepositoryAnalysisSuccessIT.java index f93c4018b6232..fcccf2dafb760 100644 --- a/x-pack/plugin/snapshot-repo-test-kit/src/internalClusterTest/java/org/elasticsearch/repositories/blobstore/testkit/analyze/RepositoryAnalysisSuccessIT.java +++ b/x-pack/plugin/snapshot-repo-test-kit/src/internalClusterTest/java/org/elasticsearch/repositories/blobstore/testkit/analyze/RepositoryAnalysisSuccessIT.java @@ -61,6 +61,7 @@ import java.util.function.Consumer; import java.util.stream.Collectors; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.elasticsearch.indices.recovery.RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING; import static org.elasticsearch.repositories.blobstore.BlobStoreRepository.MAX_RESTORE_BYTES_PER_SEC; import static org.elasticsearch.repositories.blobstore.BlobStoreRepository.MAX_SNAPSHOT_BYTES_PER_SEC; @@ -594,7 +595,7 @@ public void compareAndExchangeRegister( contendedRegisterValue = updatedValue; } } else { - assertEquals(expected, witness); // uncontended writes always succeed + assertThat(witness, equalBytes(expected)); // uncontended writes always succeed assertNotEquals(expected, updated); // uncontended register sees only updates if (updated.length() != 0) { final var updatedValue = longFromBytes(updated); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/CancellationTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/CancellationTests.java index 9cc888c7f1192..53170d68a5014 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/CancellationTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/CancellationTests.java @@ -52,6 +52,7 @@ import java.util.concurrent.TimeUnit; import static java.util.Collections.singletonMap; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.instanceOf; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -192,7 +193,7 @@ public void testCancellationDuringSearch(String query) throws InterruptedExcepti doAnswer((Answer) invocation -> { @SuppressWarnings("unchecked") SearchRequest request = (SearchRequest) invocation.getArguments()[1]; - assertEquals(pitId, request.pointInTimeBuilder().getEncodedId()); + assertThat(request.pointInTimeBuilder().getEncodedId(), equalBytes(pitId)); TaskId parentTask = request.getParentTask(); assertNotNull(parentTask); assertEquals(task.getId(), parentTask.getId()); @@ -206,7 +207,7 @@ public void testCancellationDuringSearch(String query) throws InterruptedExcepti // Emulation of close pit doAnswer(invocation -> { ClosePointInTimeRequest request = (ClosePointInTimeRequest) invocation.getArguments()[1]; - assertEquals(pitId, request.getId()); + assertThat(request.getId(), equalBytes(pitId)); @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocation.getArguments()[2]; diff --git a/x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/transforms/ClientTransformIndexerTests.java b/x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/transforms/ClientTransformIndexerTests.java index 63462ee32b415..63679c9540fff 100644 --- a/x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/transforms/ClientTransformIndexerTests.java +++ b/x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/transforms/ClientTransformIndexerTests.java @@ -87,6 +87,7 @@ import java.util.function.Consumer; import java.util.stream.IntStream; +import static org.elasticsearch.common.bytes.BytesReferenceTestUtils.equalBytes; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -189,7 +190,7 @@ public void testPitInjection() throws InterruptedException { ); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); }); assertEquals(1L, client.getPitContextCounter()); @@ -202,15 +203,15 @@ public void testPitInjection() throws InterruptedException { assertEquals(0L, client.getPitContextCounter()); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); }); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id++"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id++"))); }); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+++"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+++"))); }); assertEquals(1L, client.getPitContextCounter()); @@ -219,7 +220,7 @@ public void testPitInjection() throws InterruptedException { assertEquals(0L, client.getPitContextCounter()); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); }); var paceCounter = new AtomicInteger(0); @@ -229,15 +230,15 @@ public void testPitInjection() throws InterruptedException { assertEquals(0L, client.getPitContextCounter()); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); }); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id++"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id++"))); }); this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { - assertEquals(new BytesArray("the_pit_id+++"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+++"))); }); assertEquals(1L, client.getPitContextCounter()); @@ -380,7 +381,7 @@ public void testDisablePit() throws InterruptedException { this.assertAsync(listener -> indexer.doNextSearch(0, listener), response -> { if (pitEnabled) { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); } else { assertNull(response.pointInTimeId()); } @@ -393,7 +394,7 @@ public void testDisablePit() throws InterruptedException { if (pitEnabled) { assertNull(response.pointInTimeId()); } else { - assertEquals(new BytesArray("the_pit_id+"), response.pointInTimeId()); + assertThat(response.pointInTimeId(), equalBytes(new BytesArray("the_pit_id+"))); } }); }