Search in sources :

Example 1 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class TimeValueTests method testCompareValue.

public void testCompareValue() {
    long firstRandom = randomNonNegativeLong();
    long secondRandom = randomValueOtherThan(firstRandom, OpenSearchTestCase::randomNonNegativeLong);
    TimeUnit unit = randomFrom(TimeUnit.values());
    TimeValue firstValue = new TimeValue(firstRandom, unit);
    TimeValue secondValue = new TimeValue(secondRandom, unit);
    assertEquals(firstRandom > secondRandom, firstValue.compareTo(secondValue) > 0);
    assertEquals(secondRandom > firstRandom, secondValue.compareTo(firstValue) > 0);
}
Also used : OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) TimeUnit(java.util.concurrent.TimeUnit)

Example 2 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class FunctionScoreIT method testMinScoreFunctionScoreBasic.

public void testMinScoreFunctionScoreBasic() throws IOException {
    float score = randomValueOtherThanMany((f) -> Float.compare(f, 0) < 0, OpenSearchTestCase::randomFloat);
    float minScore = randomValueOtherThanMany((f) -> Float.compare(f, 0) < 0, OpenSearchTestCase::randomFloat);
    index(INDEX, TYPE, jsonBuilder().startObject().field("num", 2).field("random_score", // Pass the random score as a document field so that it can be extracted in the script
    score).endObject());
    refresh();
    ensureYellow();
    Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['random_score']", Collections.emptyMap());
    SearchResponse searchResponse = client().search(searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)).setMinScore(minScore)))).actionGet();
    if (score < minScore) {
        assertThat(searchResponse.getHits().getTotalHits().value, is(0L));
    } else {
        assertThat(searchResponse.getHits().getTotalHits().value, is(1L));
    }
    searchResponse = client().search(searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore)))).actionGet();
    if (score < minScore) {
        assertThat(searchResponse.getHits().getTotalHits().value, is(0L));
    } else {
        assertThat(searchResponse.getHits().getTotalHits().value, is(1L));
    }
}
Also used : Script(org.opensearch.script.Script) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) FilterFunctionBuilder(org.opensearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder) OpenSearchAssertions.assertSearchResponse(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder)

Example 3 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class AbstractBulkByScrollRequestTestCase method testForSlice.

public void testForSlice() {
    R original = newRequest();
    extraRandomizationForSlice(original);
    original.setAbortOnVersionConflict(randomBoolean());
    original.setRefresh(randomBoolean());
    original.setTimeout(parseTimeValue(randomPositiveTimeValue(), "timeout"));
    original.setWaitForActiveShards(randomFrom(ActiveShardCount.ALL, ActiveShardCount.NONE, ActiveShardCount.ONE, ActiveShardCount.DEFAULT));
    original.setRetryBackoffInitialTime(parseTimeValue(randomPositiveTimeValue(), "retry_backoff_initial_time"));
    original.setMaxRetries(between(0, 1000));
    original.setRequestsPerSecond(randomBoolean() ? Float.POSITIVE_INFINITY : randomValueOtherThanMany(r -> r < 0, OpenSearchTestCase::randomFloat));
    if (randomBoolean()) {
        if (randomBoolean()) {
            original.setMaxDocs(between(0, Integer.MAX_VALUE));
        } else {
            original.setSize(between(0, Integer.MAX_VALUE));
        }
    }
    // it's not important how many slices there are, we just need a number for forSlice
    int actualSlices = between(2, 1000);
    original.setSlices(randomBoolean() ? actualSlices : AbstractBulkByScrollRequest.AUTO_SLICES);
    TaskId slicingTask = new TaskId(randomAlphaOfLength(5), randomLong());
    SearchRequest sliceRequest = new SearchRequest();
    R forSliced = original.forSlice(slicingTask, sliceRequest, actualSlices);
    assertEquals(original.isAbortOnVersionConflict(), forSliced.isAbortOnVersionConflict());
    assertEquals(original.isRefresh(), forSliced.isRefresh());
    assertEquals(original.getTimeout(), forSliced.getTimeout());
    assertEquals(original.getWaitForActiveShards(), forSliced.getWaitForActiveShards());
    assertEquals(original.getRetryBackoffInitialTime(), forSliced.getRetryBackoffInitialTime());
    assertEquals(original.getMaxRetries(), forSliced.getMaxRetries());
    assertEquals("only the parent task should store results", false, forSliced.getShouldStoreResult());
    assertEquals("slice requests always have a single worker", 1, forSliced.getSlices());
    assertEquals("requests_per_second is split between all workers", original.getRequestsPerSecond() / actualSlices, forSliced.getRequestsPerSecond(), Float.MIN_NORMAL);
    assertEquals("max_docs is split evenly between all workers", original.getMaxDocs() == AbstractBulkByScrollRequest.MAX_DOCS_ALL_MATCHES ? AbstractBulkByScrollRequest.MAX_DOCS_ALL_MATCHES : original.getMaxDocs() / actualSlices, forSliced.getMaxDocs());
    assertEquals(slicingTask, forSliced.getParentTask());
    extraForSliceAssertions(original, forSliced);
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) TaskId(org.opensearch.tasks.TaskId)

Example 4 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class UpdateRequestTests method testUpdateScript.

public void testUpdateScript() throws Exception {
    ShardId shardId = new ShardId("test", "", 0);
    GetResult getResult = new GetResult("test", "1", 0, 1, 0, true, new BytesArray("{\"body\": \"bar\"}"), null, null);
    UpdateRequest request = new UpdateRequest("test", "1").script(mockInlineScript("ctx._source.body = \"foo\""));
    UpdateHelper.Result result = updateHelper.prepareUpdateScriptRequest(shardId, request, getResult, OpenSearchTestCase::randomNonNegativeLong);
    assertThat(result.action(), instanceOf(IndexRequest.class));
    assertThat(result.getResponseResult(), equalTo(DocWriteResponse.Result.UPDATED));
    assertThat(result.updatedSourceAsMap().get("body").toString(), equalTo("foo"));
    // Now where the script changes the op to "delete"
    request = new UpdateRequest("test", "1").script(mockInlineScript("ctx.op = delete"));
    result = updateHelper.prepareUpdateScriptRequest(shardId, request, getResult, OpenSearchTestCase::randomNonNegativeLong);
    assertThat(result.action(), instanceOf(DeleteRequest.class));
    assertThat(result.getResponseResult(), equalTo(DocWriteResponse.Result.DELETED));
    // We treat everything else as a No-op
    boolean goodNoop = randomBoolean();
    if (goodNoop) {
        request = new UpdateRequest("test", "1").script(mockInlineScript("ctx.op = none"));
    } else {
        request = new UpdateRequest("test", "1").script(mockInlineScript("ctx.op = bad"));
    }
    result = updateHelper.prepareUpdateScriptRequest(shardId, request, getResult, OpenSearchTestCase::randomNonNegativeLong);
    assertThat(result.action(), instanceOf(UpdateResponse.class));
    assertThat(result.getResponseResult(), equalTo(DocWriteResponse.Result.NOOP));
}
Also used : ShardId(org.opensearch.index.shard.ShardId) BytesArray(org.opensearch.common.bytes.BytesArray) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) GetResult(org.opensearch.index.get.GetResult) IndexRequest(org.opensearch.action.index.IndexRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest)

Example 5 with OpenSearchTestCase

use of org.opensearch.test.OpenSearchTestCase in project OpenSearch by opensearch-project.

the class CoordinationMetadataTests method testCoordinationMetadataSerializationEqualsHashCode.

public void testCoordinationMetadataSerializationEqualsHashCode() {
    CoordinationMetadata initialMetadata = new CoordinationMetadata(randomNonNegativeLong(), randomVotingConfig(), randomVotingConfig(), randomVotingTombstones());
    // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type
    EqualsHashCodeTestUtils.checkEqualsAndHashCode(initialMetadata, (CopyFunction<CoordinationMetadata>) orig -> OpenSearchTestCase.copyWriteable(orig, new NamedWriteableRegistry(Collections.emptyList()), CoordinationMetadata::new), meta -> {
        CoordinationMetadata.Builder builder = CoordinationMetadata.builder(meta);
        switch(randomInt(3)) {
            case 0:
                builder.term(randomValueOtherThan(meta.term(), OpenSearchTestCase::randomNonNegativeLong));
                break;
            case 1:
                builder.lastCommittedConfiguration(randomlyChangeVotingConfiguration(meta.getLastCommittedConfiguration()));
                break;
            case 2:
                builder.lastAcceptedConfiguration(randomlyChangeVotingConfiguration(meta.getLastAcceptedConfiguration()));
                break;
            case 3:
                if (meta.getVotingConfigExclusions().isEmpty() == false && randomBoolean()) {
                    builder.clearVotingConfigExclusions();
                } else {
                    randomVotingTombstones().forEach(dn -> builder.addVotingConfigExclusion(dn));
                }
                break;
        }
        return builder.build();
    });
}
Also used : VotingConfigExclusion(org.opensearch.cluster.coordination.CoordinationMetadata.VotingConfigExclusion) VotingConfiguration(org.opensearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) BytesReference(org.opensearch.common.bytes.BytesReference) ToXContent(org.opensearch.common.xcontent.ToXContent) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) IOException(java.io.IOException) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentParser(org.opensearch.common.xcontent.XContentParser) HashSet(java.util.HashSet) Sets(org.opensearch.common.util.set.Sets) Matchers.equalTo(org.hamcrest.Matchers.equalTo) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) EqualsHashCodeTestUtils(org.opensearch.test.EqualsHashCodeTestUtils) CopyFunction(org.opensearch.test.EqualsHashCodeTestUtils.CopyFunction) Collections(java.util.Collections) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry)

Aggregations

OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)10 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 EqualsHashCodeTestUtils (org.opensearch.test.EqualsHashCodeTestUtils)2 CopyFunction (org.opensearch.test.EqualsHashCodeTestUtils.CopyFunction)2 ParametersFactory (com.carrotsearch.randomizedtesting.annotations.ParametersFactory)1 Configuration (com.google.common.jimfs.Configuration)1 Jimfs (com.google.common.jimfs.Jimfs)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 StringReader (java.io.StringReader)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URL (java.net.URL)1