Search in sources :

Example 1 with ClientYamlSuiteRestSpec

use of org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec in project OpenSearch by opensearch-project.

the class RestHighLevelClientTests method testApiNamingConventions.

public void testApiNamingConventions() throws Exception {
    // this list should be empty once the high-level client is feature complete
    String[] notYetSupportedApi = new String[] { "create", "get_script_context", "get_script_languages", "indices.exists_type", "indices.get_upgrade", "indices.put_alias", "render_search_template", "scripts_painless_execute", "indices.simulate_template", "indices.resolve_index", "indices.add_block" };
    // These API are not required for high-level client feature completeness
    String[] notRequiredApi = new String[] { "cluster.allocation_explain", "cluster.pending_tasks", "cluster.reroute", "cluster.state", "cluster.stats", "cluster.post_voting_config_exclusions", "cluster.delete_voting_config_exclusions", "dangling_indices.delete_dangling_index", "dangling_indices.import_dangling_index", "dangling_indices.list_dangling_indices", "indices.shard_stores", "indices.upgrade", "indices.recovery", "indices.segments", "indices.stats", "ingest.processor_grok", "nodes.info", "nodes.stats", "nodes.hot_threads", "nodes.usage", "nodes.reload_secure_settings", "search_shards" };
    List<String> booleanReturnMethods = Arrays.asList("security.enable_user", "security.disable_user", "security.change_password");
    Set<String> deprecatedMethods = new HashSet<>();
    deprecatedMethods.add("indices.force_merge");
    deprecatedMethods.add("multi_get");
    deprecatedMethods.add("multi_search");
    deprecatedMethods.add("search_scroll");
    ClientYamlSuiteRestSpec restSpec = ClientYamlSuiteRestSpec.load("/rest-api-spec/api");
    Set<String> apiSpec = restSpec.getApis().stream().map(ClientYamlSuiteRestApi::getName).collect(Collectors.toSet());
    Set<String> apiUnsupported = new HashSet<>(apiSpec);
    Set<String> apiNotFound = new HashSet<>();
    Set<String> topLevelMethodsExclusions = new HashSet<>();
    topLevelMethodsExclusions.add("getLowLevelClient");
    topLevelMethodsExclusions.add("close");
    Map<String, Set<Method>> methods = Arrays.stream(RestHighLevelClient.class.getMethods()).filter(method -> method.getDeclaringClass().equals(RestHighLevelClient.class) && topLevelMethodsExclusions.contains(method.getName()) == false).map(method -> Tuple.tuple(toSnakeCase(method.getName()), method)).flatMap(tuple -> tuple.v2().getReturnType().getName().endsWith("Client") ? getSubClientMethods(tuple.v1(), tuple.v2().getReturnType()) : Stream.of(tuple)).filter(tuple -> tuple.v2().getAnnotation(Deprecated.class) == null).collect(Collectors.groupingBy(Tuple::v1, Collectors.mapping(Tuple::v2, Collectors.toSet())));
    // TODO remove in 8.0 - we will undeprecate indices.get_template because the current getIndexTemplate
    // impl will replace the existing getTemplate method.
    // The above general-purpose code ignores all deprecated methods which in this case leaves `getTemplate`
    // looking like it doesn't have a valid implementatation when it does.
    apiUnsupported.remove("indices.get_template");
    // Synced flush is deprecated
    apiUnsupported.remove("indices.flush_synced");
    for (Map.Entry<String, Set<Method>> entry : methods.entrySet()) {
        String apiName = entry.getKey();
        for (Method method : entry.getValue()) {
            assertTrue("method [" + apiName + "] is not final", Modifier.isFinal(method.getClass().getModifiers()) || Modifier.isFinal(method.getModifiers()));
            assertTrue("method [" + method + "] should be public", Modifier.isPublic(method.getModifiers()));
            // we convert all the method names to snake case, hence we need to look for the '_async' suffix rather than 'Async'
            if (apiName.endsWith("_async")) {
                assertAsyncMethod(methods, method, apiName);
            } else if (isSubmitTaskMethod(apiName)) {
                assertSubmitTaskMethod(methods, method, apiName, restSpec);
            } else {
                assertSyncMethod(method, apiName, booleanReturnMethods);
                apiUnsupported.remove(apiName);
                if (apiSpec.contains(apiName) == false) {
                    if (deprecatedMethods.contains(apiName)) {
                        assertTrue("method [" + method.getName() + "], api [" + apiName + "] should be deprecated", method.isAnnotationPresent(Deprecated.class));
                    } else {
                        if (// can get rid of 7.0's deprecated "getTemplate"
                        apiName.equals("indices.get_index_template") == false) {
                            apiNotFound.add(apiName);
                        }
                    }
                }
            }
        }
    }
    assertThat("Some client method doesn't match a corresponding API defined in the REST spec: " + apiNotFound, apiNotFound.size(), equalTo(0));
    // we decided not to support cat API in the high-level REST client, they are supposed to be used from a low-level client
    apiUnsupported.removeIf(api -> api.startsWith("cat."));
    Stream.concat(Arrays.stream(notYetSupportedApi), Arrays.stream(notRequiredApi)).forEach(api -> assertTrue(api + " API is either not defined in the spec or already supported by the high-level client", apiUnsupported.remove(api)));
    assertThat("Some API are not supported but they should be: " + apiUnsupported, apiUnsupported.size(), equalTo(0));
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) Arrays(java.util.Arrays) Aggregation(org.opensearch.search.aggregations.Aggregation) MainResponse(org.opensearch.client.core.MainResponse) ToXContentFragment(org.opensearch.common.xcontent.ToXContentFragment) CheckedFunction(org.opensearch.common.CheckedFunction) ToXContent(org.opensearch.common.xcontent.ToXContent) CoreMatchers.endsWith(org.hamcrest.CoreMatchers.endsWith) ChildrenAggregationBuilder(org.opensearch.join.aggregations.ChildrenAggregationBuilder) ActionRequest(org.opensearch.action.ActionRequest) OpenSearchException(org.opensearch.OpenSearchException) StatusLine(org.apache.http.StatusLine) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) EvaluationMetric(org.opensearch.index.rankeval.EvaluationMetric) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Map(java.util.Map) NStringEntity(org.apache.http.nio.entity.NStringEntity) ActionListener(org.opensearch.action.ActionListener) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Method(java.lang.reflect.Method) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) MetricDetail(org.opensearch.index.rankeval.MetricDetail) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) RecallAtK(org.opensearch.index.rankeval.RecallAtK) List(java.util.List) Stream(java.util.stream.Stream) HttpGet(org.apache.http.client.methods.HttpGet) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) MeanReciprocalRank(org.opensearch.index.rankeval.MeanReciprocalRank) Mockito.any(org.mockito.Mockito.any) SmileXContent(org.opensearch.common.xcontent.smile.SmileXContent) Mockito.mock(org.mockito.Mockito.mock) BytesReference(org.opensearch.common.bytes.BytesReference) BasicStatusLine(org.apache.http.message.BasicStatusLine) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CborXContent(org.opensearch.common.xcontent.cbor.CborXContent) ExpectedReciprocalRank(org.opensearch.index.rankeval.ExpectedReciprocalRank) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) XContentHelper.toXContent(org.opensearch.common.xcontent.XContentHelper.toXContent) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) SocketTimeoutException(java.net.SocketTimeoutException) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ClientYamlSuiteRestApi(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) MainRequest(org.opensearch.client.core.MainRequest) Before(org.junit.Before) MatrixStatsAggregationBuilder(org.opensearch.search.aggregations.matrix.stats.MatrixStatsAggregationBuilder) BasicRequestLine(org.apache.http.message.BasicRequestLine) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) DiscountedCumulativeGain(org.opensearch.index.rankeval.DiscountedCumulativeGain) ProtocolVersion(org.apache.http.ProtocolVersion) Sets(org.opensearch.common.util.set.Sets) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Suggest(org.opensearch.search.suggest.Suggest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) Set(java.util.Set) HashSet(java.util.HashSet) Method(java.lang.reflect.Method) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) Map(java.util.Map) HashMap(java.util.HashMap) Tuple(org.opensearch.common.collect.Tuple) HashSet(java.util.HashSet)

Example 2 with ClientYamlSuiteRestSpec

use of org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec in project OpenSearch by opensearch-project.

the class OpenSearchClientYamlSuiteTestCase method initAndResetContext.

@Before
public void initAndResetContext() throws Exception {
    if (restTestExecutionContext == null) {
        assert adminExecutionContext == null;
        assert denylistPathMatchers == null;
        final ClientYamlSuiteRestSpec restSpec = ClientYamlSuiteRestSpec.load(SPEC_PATH);
        validateSpec(restSpec);
        final List<HttpHost> hosts = getClusterHosts();
        Tuple<Version, Version> versionVersionTuple = readVersionsFromCatNodes(adminClient());
        final Version esVersion = versionVersionTuple.v1();
        final Version masterVersion = versionVersionTuple.v2();
        logger.info("initializing client, minimum es version [{}], master version, [{}], hosts {}", esVersion, masterVersion, hosts);
        clientYamlTestClient = initClientYamlTestClient(restSpec, client(), hosts, esVersion, masterVersion);
        restTestExecutionContext = new ClientYamlTestExecutionContext(clientYamlTestClient, randomizeContentType());
        adminExecutionContext = new ClientYamlTestExecutionContext(clientYamlTestClient, false);
        final String[] denylist = resolvePathsProperty(REST_TESTS_BLACKLIST, null);
        denylistPathMatchers = new ArrayList<>();
        for (final String entry : denylist) {
            denylistPathMatchers.add(new BlacklistedPathPatternMatcher(entry));
        }
        final String[] denylistAdditions = resolvePathsProperty(REST_TESTS_BLACKLIST_ADDITIONS, null);
        for (final String entry : denylistAdditions) {
            denylistPathMatchers.add(new BlacklistedPathPatternMatcher(entry));
        }
    }
    assert restTestExecutionContext != null;
    assert adminExecutionContext != null;
    assert denylistPathMatchers != null;
    // admin context must be available for @After always, regardless of whether the test was denylisted
    adminExecutionContext.clear();
    restTestExecutionContext.clear();
}
Also used : Version(org.opensearch.Version) HttpHost(org.apache.http.HttpHost) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) Before(org.junit.Before)

Aggregations

HttpHost (org.apache.http.HttpHost)2 Before (org.junit.Before)2 JsonParseException (com.fasterxml.jackson.core.JsonParseException)1 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 Modifier (java.lang.reflect.Modifier)1 SocketTimeoutException (java.net.SocketTimeoutException)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Set (java.util.Set)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1