testcontainers / testcontainers-scala

Docker containers for testing in scala
MIT License
634 stars 127 forks source link

Allow to start Kafka and Schema Registry containers in the same Network #266

Open slawomirkania opened 10 months ago

slawomirkania commented 10 months ago

As a Developer I want to be able to start Kafka and Schema Registry in the same network using public interfaces/constructors.

Now it is impossible for two reasons:

  1. starting the Kafka container and invoking its getNetwork method results in a null response
  2. Schema Registry constructor does not allow to provide Network

Example usage

  final case class KafkaConfig(bootstrapServers: String, networkAlias: String)
  final case class SchemaRegistryConfig(schemaUrl: String)

  private def kafka(network: Network) =
    Resource
      .make(IO(KafkaContainer.Def(network).start()))(c => IO(c.stop()))
      .map { kafkaContainer =>
        KafkaConfig(kafkaContainer.bootstrapServers, kafkaContainer.networkAliases.head)
      }

  private def schemaRegistry(network: Network, kafkaConfig: KafkaConfig) =
    Resource
      .make(IO(SchemaRegistryContainer.Def(network, kafkaConfig.networkAlias).start()))(c => IO(c.stop()))
      .map { schemaRegistryContainer =>
        SchemaRegistryConfig(schemaRegistryContainer.schemaUrl)
      }

  def kafkaWithSchemaRegistry: Resource[IO, (KafkaConfig, SchemaRegistryConfig)] =
    for
      network <- Resource.fromAutoCloseable(IO(Network.newNetwork()))
      kafkaConfig <- kafka(network)
      schemaRegistryConfig <- schemaRegistry(network, kafkaConfig)
    yield (kafkaConfig, schemaRegistryConfig)