Search in sources :

Example 21 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class RequestValidatorTest method shouldThrowIfServiceContextIsNotSandbox.

@Test
public void shouldThrowIfServiceContextIsNotSandbox() {
    // Given:
    serviceContext = mock(ServiceContext.class);
    givenRequestValidator(ImmutableMap.of());
    // When:
    final Exception e = assertThrows(IllegalArgumentException.class, () -> validator.validate(serviceContext, ImmutableList.of(), sessionProperties, "sql"));
    // Then:
    assertThat(e.getMessage(), containsString("Expected sandbox"));
}
Also used : ServiceContext(io.confluent.ksql.services.ServiceContext) TestServiceContext(io.confluent.ksql.services.TestServiceContext) SandboxedServiceContext(io.confluent.ksql.services.SandboxedServiceContext) KsqlException(io.confluent.ksql.util.KsqlException) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) Test(org.junit.Test)

Example 22 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class ListSourceExecutorTest method shouldAddWarningsOnClientExceptionForTopicListing.

@Test
public void shouldAddWarningsOnClientExceptionForTopicListing() {
    // Given:
    final KsqlTable<?> table1 = engine.givenSource(DataSourceType.KTABLE, "table1");
    final KsqlTable<?> table2 = engine.givenSource(DataSourceType.KTABLE, "table2");
    final ServiceContext serviceContext = engine.getServiceContext();
    serviceContext.getTopicClient().deleteTopics(ImmutableList.of("table1", "table2"));
    // When:
    final KsqlEntity entity = CUSTOM_EXECUTORS.listTables().execute((ConfiguredStatement<ListTables>) engine.configure("SHOW TABLES EXTENDED;"), SESSION_PROPERTIES, engine.getEngine(), serviceContext).getEntity().orElseThrow(IllegalStateException::new);
    // Then:
    assertSourceListWithWarning(entity, table1, table2);
}
Also used : ServiceContext(io.confluent.ksql.services.ServiceContext) TestServiceContext(io.confluent.ksql.services.TestServiceContext) ListTables(io.confluent.ksql.parser.tree.ListTables) KsqlEntity(io.confluent.ksql.rest.entity.KsqlEntity) Test(org.junit.Test)

Example 23 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class ListSourceExecutorTest method shouldAddWarningOnClientExceptionForDescription.

@Test
public void shouldAddWarningOnClientExceptionForDescription() {
    // Given:
    final KsqlStream<?> stream1 = engine.givenSource(DataSourceType.KSTREAM, "STREAM1");
    final ServiceContext serviceContext = engine.getServiceContext();
    serviceContext.getTopicClient().deleteTopics(ImmutableList.of("STREAM1"));
    // When:
    final KsqlEntity entity = CUSTOM_EXECUTORS.showColumns().execute((ConfiguredStatement<ShowColumns>) engine.configure("DESCRIBE STREAM1 EXTENDED;"), SESSION_PROPERTIES, engine.getEngine(), serviceContext).getEntity().orElseThrow(IllegalStateException::new);
    // Then:
    assertThat(entity, instanceOf(SourceDescriptionEntity.class));
    final SourceDescriptionEntity description = (SourceDescriptionEntity) entity;
    assertThat(description.getSourceDescription(), equalTo(SourceDescriptionFactory.create(stream1, true, ImmutableList.of(), ImmutableList.of(), Optional.empty(), ImmutableList.of(), ImmutableList.of(), new MetricCollectors())));
    assertThat(description.getWarnings(), contains(new KsqlWarning("Error from Kafka: unknown topic: STREAM1")));
}
Also used : ServiceContext(io.confluent.ksql.services.ServiceContext) TestServiceContext(io.confluent.ksql.services.TestServiceContext) ShowColumns(io.confluent.ksql.parser.tree.ShowColumns) SourceDescriptionEntity(io.confluent.ksql.rest.entity.SourceDescriptionEntity) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) KsqlWarning(io.confluent.ksql.rest.entity.KsqlWarning) KsqlEntity(io.confluent.ksql.rest.entity.KsqlEntity) Test(org.junit.Test)

Example 24 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class KsqlEngineTest method shouldHandleMultipleStatements.

@SuppressWarnings("unchecked")
@Test
public void shouldHandleMultipleStatements() {
    // Given:
    final String sql = "" + "-- single line comment\n" + "/*\n" + "   Multi-line comment\n" + "*/\n" + "CREATE STREAM S0 (a INT, b VARCHAR) " + "      WITH (kafka_topic='s0_topic', value_format='DELIMITED', key_format='KAFKA');\n" + "\n" + "CREATE TABLE T1 (f0 BIGINT PRIMARY KEY, f1 DOUBLE) " + "     WITH (kafka_topic='t1_topic', value_format='JSON', key_format='KAFKA');\n" + "\n" + "CREATE STREAM S1 AS SELECT * FROM S0;\n" + "\n" + "CREATE STREAM S2 AS SELECT * FROM S0;\n" + "\n" + "DROP TABLE T1;";
    givenTopicsExist("s0_topic", "t1_topic");
    final List<QueryMetadata> queries = new ArrayList<>();
    // When:
    final List<PreparedStatement<?>> preparedStatements = ksqlEngine.parse(sql).stream().map(stmt -> {
        final PreparedStatement<?> prepared = ksqlEngine.prepare(stmt);
        final ExecuteResult result = ksqlEngine.execute(serviceContext, ConfiguredStatement.of(prepared, SessionConfig.of(ksqlConfig, new HashMap<>())));
        result.getQuery().ifPresent(queries::add);
        return prepared;
    }).collect(Collectors.toList());
    // Then:
    final List<?> statements = preparedStatements.stream().map(PreparedStatement::getStatement).collect(Collectors.toList());
    assertThat(statements, contains(instanceOf(CreateStream.class), instanceOf(CreateTable.class), instanceOf(CreateStreamAsSelect.class), instanceOf(CreateStreamAsSelect.class), instanceOf(DropTable.class)));
    assertThat(queries, hasSize(2));
}
Also used : Query(io.confluent.ksql.parser.tree.Query) Arrays(java.util.Arrays) InternalFunctionRegistry(io.confluent.ksql.function.InternalFunctionRegistry) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) SourceName(io.confluent.ksql.name.SourceName) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Matchers.not(org.hamcrest.Matchers.not) ServiceContext(io.confluent.ksql.services.ServiceContext) KsqlExceptionMatcher.statementText(io.confluent.ksql.util.KsqlExceptionMatcher.statementText) SandboxedTransientQueryMetadata(io.confluent.ksql.util.SandboxedTransientQueryMetadata) MutableMetaStore(io.confluent.ksql.metastore.MutableMetaStore) Matchers.hasItems(org.hamcrest.Matchers.hasItems) TransientQueryMetadata(io.confluent.ksql.util.TransientQueryMetadata) QueryCleanupTask(io.confluent.ksql.engine.QueryCleanupService.QueryCleanupTask) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) CreateTable(io.confluent.ksql.parser.tree.CreateTable) KsqlEngineTestUtil.execute(io.confluent.ksql.engine.KsqlEngineTestUtil.execute) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Map(java.util.Map) After(org.junit.After) Spy(org.mockito.Spy) SandboxedPersistentQueryMetadataImpl(io.confluent.ksql.util.SandboxedPersistentQueryMetadataImpl) Assert.fail(org.junit.Assert.fail) RestClientException(io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException) QueryId(io.confluent.ksql.query.QueryId) FakeKafkaTopicClient(io.confluent.ksql.services.FakeKafkaTopicClient) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata) QueryMetadata(io.confluent.ksql.util.QueryMetadata) MockSchemaRegistryClient(io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient) FakeKafkaConsumerGroupClient(io.confluent.ksql.services.FakeKafkaConsumerGroupClient) SystemColumns(io.confluent.ksql.schema.ksql.SystemColumns) Schema(org.apache.avro.Schema) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) KsqlConfig(io.confluent.ksql.util.KsqlConfig) MetaStoreFixture(io.confluent.ksql.util.MetaStoreFixture) Collectors(java.util.stream.Collectors) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) TestServiceContext(io.confluent.ksql.services.TestServiceContext) List(java.util.List) ParseFailedException(io.confluent.ksql.parser.exception.ParseFailedException) Matchers.contains(org.hamcrest.Matchers.contains) KsqlExecutionContext(io.confluent.ksql.KsqlExecutionContext) Matchers.equalTo(org.hamcrest.Matchers.equalTo) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) KsqlConstants(io.confluent.ksql.util.KsqlConstants) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Mockito.mock(org.mockito.Mockito.mock) KsqlExceptionMatcher.rawMessage(io.confluent.ksql.util.KsqlExceptionMatcher.rawMessage) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) StreamsConfig(org.apache.kafka.streams.StreamsConfig) Iterables(com.google.common.collect.Iterables) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) CreateStreamAsSelect(io.confluent.ksql.parser.tree.CreateStreamAsSelect) ReservedInternalTopics(io.confluent.ksql.util.ReservedInternalTopics) Supplier(java.util.function.Supplier) AvroSchema(io.confluent.kafka.schemaregistry.avro.AvroSchema) ArrayList(java.util.ArrayList) SessionConfig(io.confluent.ksql.config.SessionConfig) CreateStream(io.confluent.ksql.parser.tree.CreateStream) ParsedStatement(io.confluent.ksql.parser.KsqlParser.ParsedStatement) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) DropTable(io.confluent.ksql.parser.tree.DropTable) Matchers.empty(org.hamcrest.Matchers.empty) Assert.assertTrue(org.junit.Assert.assertTrue) FieldMatchers.hasFullName(io.confluent.ksql.metastore.model.MetaStoreMatchers.FieldMatchers.hasFullName) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) SandboxedBinPackedPersistentQueryMetadataImpl(io.confluent.ksql.util.SandboxedBinPackedPersistentQueryMetadataImpl) ConfigException(org.apache.kafka.common.config.ConfigException) Mockito.verify(org.mockito.Mockito.verify) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) SchemaBuilder(org.apache.avro.SchemaBuilder) KsqlConfigTestUtil(io.confluent.ksql.KsqlConfigTestUtil) Mockito.never(org.mockito.Mockito.never) Matchers.hasItem(org.hamcrest.Matchers.hasItem) KafkaStreams(org.apache.kafka.streams.KafkaStreams) Assert(org.junit.Assert) Collections(java.util.Collections) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) SandboxedTransientQueryMetadata(io.confluent.ksql.util.SandboxedTransientQueryMetadata) TransientQueryMetadata(io.confluent.ksql.util.TransientQueryMetadata) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata) QueryMetadata(io.confluent.ksql.util.QueryMetadata) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) Matchers.containsString(org.hamcrest.Matchers.containsString) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) Test(org.junit.Test)

Example 25 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class TestExecutor method buildAndExecuteQuery.

public void buildAndExecuteQuery(final TestCase testCase, final TestExecutionListener listener) {
    topicInfoCache.clear();
    final KsqlConfig ksqlConfig = testCase.applyPersistedProperties(new KsqlConfig(config));
    try {
        System.setProperty(RuntimeBuildContext.KSQL_TEST_TRACK_SERDE_TOPICS, "true");
        final List<TopologyTestDriverContainer> topologyTestDrivers = topologyBuilder.buildStreamsTopologyTestDrivers(testCase, serviceContext, ksqlEngine, ksqlConfig, kafka, listener);
        writeInputIntoTopics(testCase.getInputRecords(), kafka);
        final Set<String> inputTopics = testCase.getInputRecords().stream().map(Record::getTopicName).collect(Collectors.toSet());
        for (final TopologyTestDriverContainer topologyTestDriverContainer : topologyTestDrivers) {
            if (validateResults) {
                verifyTopology(testCase);
            }
            final Set<String> topicsFromInput = topologyTestDriverContainer.getSourceTopicNames().stream().filter(inputTopics::contains).collect(Collectors.toSet());
            final Set<String> topicsFromKafka = topologyTestDriverContainer.getSourceTopicNames().stream().filter(topicName -> !inputTopics.contains(topicName)).collect(Collectors.toSet());
            if (!topicsFromInput.isEmpty()) {
                pipeRecordsFromProvidedInput(testCase, topologyTestDriverContainer);
            }
            for (final String kafkaTopic : topicsFromKafka) {
                pipeRecordsFromKafka(kafkaTopic, topologyTestDriverContainer);
            }
            topologyTestDriverContainer.getTopologyTestDriver().producedTopicNames().forEach(topicInfoCache::get);
        }
        verifyOutput(testCase);
        testCase.expectedException().map(ee -> {
            throw new AssertionError("Expected test to throw" + StringDescription.toString(ee));
        });
        kafka.getAllTopics().stream().map(Topic::getName).forEach(topicInfoCache::get);
        final List<PostTopicNode> knownTopics = topicInfoCache.all().stream().map(ti -> {
            final Topic topic = kafka.getTopic(ti.getTopicName());
            final OptionalInt partitions = topic == null ? OptionalInt.empty() : OptionalInt.of(topic.getNumPartitions());
            final Optional<SchemaMetadata> keyMetadata = SchemaRegistryUtil.getLatestSchema(serviceContext.getSchemaRegistryClient(), ti.getTopicName(), true);
            final Optional<SchemaMetadata> valueMetadata = SchemaRegistryUtil.getLatestSchema(serviceContext.getSchemaRegistryClient(), ti.getTopicName(), false);
            return new PostTopicNode(ti.getTopicName(), ti.getKeyFormat(), ti.getValueFormat(), partitions, fromSchemaMetadata(keyMetadata), fromSchemaMetadata(valueMetadata));
        }).collect(Collectors.toList());
        final List<SourceNode> knownSources = ksqlEngine.getMetaStore().getAllDataSources().values().stream().map(SourceNode::fromDataSource).collect(Collectors.toList());
        if (validateResults) {
            testCase.getPostConditions().verify(ksqlEngine.getMetaStore(), knownTopics);
        }
        listener.runComplete(knownTopics, knownSources);
    } catch (final RuntimeException e) {
        final Optional<Matcher<Throwable>> expectedExceptionMatcher = testCase.expectedException();
        if (!expectedExceptionMatcher.isPresent()) {
            throw e;
        }
        assertThat(e, isThrowable(expectedExceptionMatcher.get()));
    } finally {
        System.clearProperty(RuntimeBuildContext.KSQL_TEST_TRACK_SERDE_TOPICS);
    }
}
Also used : InternalFunctionRegistry(io.confluent.ksql.function.InternalFunctionRegistry) SchemaNode(io.confluent.ksql.test.model.SchemaNode) SequentialQueryIdGenerator(io.confluent.ksql.query.id.SequentialQueryIdGenerator) SourceNode(io.confluent.ksql.test.model.SourceNode) StringDescription(org.hamcrest.StringDescription) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) ServiceContext(io.confluent.ksql.services.ServiceContext) ProcessingLogContext(io.confluent.ksql.logging.processing.ProcessingLogContext) MutableMetaStore(io.confluent.ksql.metastore.MutableMetaStore) ByteBuffer(java.nio.ByteBuffer) DefaultConnectClient(io.confluent.ksql.services.DefaultConnectClient) NullNode(com.fasterxml.jackson.databind.node.NullNode) TestUtils(io.confluent.ksql.test.utils.TestUtils) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) TestRecord(org.apache.kafka.streams.test.TestRecord) CONNECT_REQUEST_TIMEOUT_DEFAULT(io.confluent.ksql.util.KsqlConfig.CONNECT_REQUEST_TIMEOUT_DEFAULT) MockSchemaRegistryClient(io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient) TestHeader(io.confluent.ksql.test.model.TestHeader) DefaultServiceContext(io.confluent.ksql.services.DefaultServiceContext) ImmutableSet(com.google.common.collect.ImmutableSet) RuntimeBuildContext(io.confluent.ksql.execution.runtime.RuntimeBuildContext) ImmutableMap(com.google.common.collect.ImmutableMap) FunctionRegistry(io.confluent.ksql.function.FunctionRegistry) Collection(java.util.Collection) TopicInfo(io.confluent.ksql.test.tools.TopicInfoCache.TopicInfo) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) KsqlConfig(io.confluent.ksql.util.KsqlConfig) Streams(com.google.common.collect.Streams) Collectors(java.util.stream.Collectors) MetaStoreImpl(io.confluent.ksql.metastore.MetaStoreImpl) DisabledKsqlClient(io.confluent.ksql.services.DisabledKsqlClient) List(java.util.List) Header(org.apache.kafka.common.header.Header) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Entry(java.util.Map.Entry) KsqlEngineMetrics(io.confluent.ksql.internal.KsqlEngineMetrics) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) StreamsConfig(org.apache.kafka.streams.StreamsConfig) StubKafkaTopicClient(io.confluent.ksql.test.tools.stubs.StubKafkaTopicClient) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) WindowData(io.confluent.ksql.test.model.WindowData) PostTopicNode(io.confluent.ksql.test.model.PostConditionsNode.PostTopicNode) Headers(org.apache.kafka.common.header.Headers) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) StubKafkaClientSupplier(io.confluent.ksql.test.tools.stubs.StubKafkaClientSupplier) SchemaRegistryUtil(io.confluent.ksql.schema.registry.SchemaRegistryUtil) ImmutableList(com.google.common.collect.ImmutableList) Windowed(org.apache.kafka.streams.kstream.Windowed) Objects.requireNonNull(java.util.Objects.requireNonNull) StubKafkaService(io.confluent.ksql.test.tools.stubs.StubKafkaService) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) ProtobufFormat(io.confluent.ksql.serde.protobuf.ProtobufFormat) TestOutputTopic(org.apache.kafka.streams.TestOutputTopic) Iterator(java.util.Iterator) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) MutableFunctionRegistry(io.confluent.ksql.function.MutableFunctionRegistry) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StubKafkaConsumerGroupClient(io.confluent.ksql.test.tools.stubs.StubKafkaConsumerGroupClient) BytesUtils(io.confluent.ksql.util.BytesUtils) JUnitMatchers.isThrowable(org.junit.matchers.JUnitMatchers.isThrowable) KsqlServerException(io.confluent.ksql.util.KsqlServerException) Closeable(java.io.Closeable) Matcher(org.hamcrest.Matcher) VisibleForTesting(com.google.common.annotations.VisibleForTesting) SchemaMetadata(io.confluent.kafka.schemaregistry.client.SchemaMetadata) Collections(java.util.Collections) UdfLoaderUtil(io.confluent.ksql.function.UdfLoaderUtil) PostTopicNode(io.confluent.ksql.test.model.PostConditionsNode.PostTopicNode) Optional(java.util.Optional) KsqlConfig(io.confluent.ksql.util.KsqlConfig) OptionalInt(java.util.OptionalInt) SourceNode(io.confluent.ksql.test.model.SourceNode) JUnitMatchers.isThrowable(org.junit.matchers.JUnitMatchers.isThrowable) TestOutputTopic(org.apache.kafka.streams.TestOutputTopic)

Aggregations

ServiceContext (io.confluent.ksql.services.ServiceContext)44 Optional (java.util.Optional)25 KsqlConfig (io.confluent.ksql.util.KsqlConfig)23 Collectors (java.util.stream.Collectors)23 List (java.util.List)22 ConfiguredStatement (io.confluent.ksql.statement.ConfiguredStatement)21 KsqlException (io.confluent.ksql.util.KsqlException)21 Map (java.util.Map)21 ImmutableMap (com.google.common.collect.ImmutableMap)18 TestServiceContext (io.confluent.ksql.services.TestServiceContext)15 Collections (java.util.Collections)15 ImmutableList (com.google.common.collect.ImmutableList)13 KsqlExecutionContext (io.confluent.ksql.KsqlExecutionContext)13 LogicalSchema (io.confluent.ksql.schema.ksql.LogicalSchema)13 KsqlEngine (io.confluent.ksql.engine.KsqlEngine)12 KsqlStatementException (io.confluent.ksql.util.KsqlStatementException)12 Test (org.junit.Test)12 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)9