File tree 2 files changed +41
-3
lines changed
2 files changed +41
-3
lines changed Original file line number Diff line number Diff line change 1
1
import tarfile
2
2
import time
3
+ from dataclasses import dataclass , field
3
4
from io import BytesIO
5
+ from os import environ
4
6
from textwrap import dedent
5
7
6
8
from typing_extensions import Self
14
16
__all__ = [
15
17
"KafkaContainer" ,
16
18
"RedpandaContainer" ,
19
+ "kafka_config" ,
17
20
]
21
+ LIMIT_BROKER_ENV_VAR = "TC_KAFKA_LIMIT_BROKER_TO_FIRST_HOST"
22
+
23
+
24
+ @dataclass
25
+ class _KafkaConfig :
26
+ limit_broker_to_first_host : bool = field (default_factory = lambda : environ .get (LIMIT_BROKER_ENV_VAR ) == "true" )
27
+ """
28
+ This option is useful for a setup with a network,
29
+ see testcontainers/testcontainers-python#637 for more details
30
+ """
31
+
32
+
33
+ kafka_config = _KafkaConfig ()
18
34
19
35
20
36
class KafkaContainer (DockerContainer ):
@@ -136,7 +152,10 @@ def get_bootstrap_server(self) -> str:
136
152
def tc_start (self ) -> None :
137
153
host = self .get_container_host_ip ()
138
154
port = self .get_exposed_port (self .port )
139
- listeners = f"PLAINTEXT://{ host } :{ port } ,BROKER://$(hostname -i):9092"
155
+ if kafka_config .limit_broker_to_first_host :
156
+ listeners = f"PLAINTEXT://{ host } :{ port } ,BROKER://$(hostname -i | cut -d' ' -f1):9092"
157
+ else :
158
+ listeners = f"PLAINTEXT://{ host } :{ port } ,BROKER://$(hostname -i):9092"
140
159
data = (
141
160
dedent (
142
161
f"""
Original file line number Diff line number Diff line change 1
- from kafka import KafkaConsumer , KafkaProducer , TopicPartition
1
+ import pytest
2
+ from kafka import KafkaAdminClient , KafkaConsumer , KafkaProducer , TopicPartition
2
3
3
- from testcontainers .kafka import KafkaContainer
4
+ from testcontainers .core .network import Network
5
+ from testcontainers .kafka import KafkaContainer , kafka_config
4
6
5
7
6
8
def test_kafka_producer_consumer ():
@@ -20,6 +22,23 @@ def test_kafka_producer_consumer_custom_port():
20
22
produce_and_consume_kafka_message (container )
21
23
22
24
25
+ def test_kafka_on_networks (monkeypatch : pytest .MonkeyPatch ):
26
+ """
27
+ this test case comes from testcontainers/testcontainers-python#637
28
+ """
29
+ monkeypatch .setattr (kafka_config , "limit_broker_to_first_host" , True )
30
+
31
+ with Network () as network :
32
+ kafka_ctr = KafkaContainer ()
33
+ kafka_ctr .with_network (network )
34
+ kafka_ctr .with_network_aliases ("kafka" )
35
+
36
+ with kafka_ctr :
37
+ print ("started" ) # Will not reach here and timeout
38
+ admin_client = KafkaAdminClient (bootstrap_servers = [kafka_ctr .get_bootstrap_server ()])
39
+ print (admin_client .describe_cluster ())
40
+
41
+
23
42
def produce_and_consume_kafka_message (container ):
24
43
topic = "test-topic"
25
44
bootstrap_server = container .get_bootstrap_server ()
You can’t perform that action at this time.
0 commit comments