xiaohongshu
xiaohongshu
kafka-integration-testing
Write integration tests for Kafka producers and consumers using testcontainers. Use when testing producer/consumer workflows, verifying message ordering, testing error scenarios, and validating exactly-once semantics. Creates test Kafka brokers and validates end-to-end streaming behavior without ...
Full skill instructions
Write production-grade integration tests for Kafka producers and consumers using testcontainers. Covers setting up temporary test brokers, testing producer/consumer workflows, verifying message ordering guarantees, testing error scenarios, and validating delivery semantics without mocking external services.
Use when testing Kafka producer/consumer workflows end-to-end with "test Kafka integration", "verify message ordering", "test Kafka roundtrip", or "validate exactly-once semantics".
Do NOT use for unit testing with mocked Kafka (use pytest-adapter-integration-testing), implementing producers/consumers (use respective kafka-*-implementation skills), or schema validation (use kafka-schema-management).
Create a producer/consumer round-trip test in 3 steps:
pip install testcontainers[kafka]>=4.0.0
import pytest
from testcontainers.kafka import KafkaContainer
from app.extraction.adapters.kafka.producer import OrderEventPublisher
from app.storage.adapters.kafka.consumer import OrderEventConsumer
@pytest.fixture
def kafka_container():
with KafkaContainer() as kafka:
yield kafka
def test_producer_consumer_roundtrip(kafka_container):
brokers = [kafka_container.get_bootstrap_server()]
# Produce
publisher = OrderEventPublisher(brokers, "test-orders")
event = OrderEventMessage(order_id="test_123", ...)
publisher.publish_order(event)
publisher.flush()
# Consume
consumer = OrderEventConsumer(brokers, "test-orders", "test-group")
message = consumer.consume(timeout=5.0)
assert message is not None
assert message.order_id == "test_123"
pytest tests/integration/test_kafka_roundtrip.py -v
Configure pytest fixtures for Kafka container management:
# tests/integration/conftest.py
import pytest
from testcontainers.kafka import KafkaContainer
@pytest.fixture(scope="function")
def kafka_container() -> KafkaContainer:
"""Start isolated Kafka container for each test."""
container = KafkaContainer()
container.start()
try:
import time
time.sleep(2) # Give broker time to become ready
yield container
finally:
container.stop()
@pytest.fixture
def kafka_brokers(kafka_container: KafkaContainer) -> list[str]:
"""Get broker addresses."""
return [kafka_container.get_bootstrap_server()]
def test_publisher_publishes_message_to_kafka(kafka_brokers: list[str]) -> None:
"""Test publisher successfully publishes message."""
publisher = OrderEventPublisher(brokers=kafka_brokers, topic="orders")
event = OrderEventMessage(order_id="order_123", ...)
publisher.publish_order(event)
publisher.flush()
def test_consumer_receives_published_message(kafka_brokers: list[str]) -> None:
"""Test consumer receives published message."""
topic = "test-orders"
# Publish
publisher = OrderEventPublisher(brokers=kafka_brokers, topic=topic)
publisher.publish_order(event)
publisher.flush()
# Consume
consumer = OrderEventConsumer(brokers=kafka_brokers, topic=topic, group_id="test-group")
message = consumer.consume(timeout=5.0)
assert message is not None
assert message.order_id == "order_123"
consumer.close()
def test_consumer_handles_malformed_message(kafka_brokers: list[str]) -> None:
"""Test consumer raises error on malformed JSON."""
from confluent_kafka import Producer
producer = Producer({"bootstrap.servers": ",".join(kafka_brokers)})
producer.produce("test-orders", key=b"bad", value=b"not valid json")
producer.flush()
consumer = OrderEventConsumer(brokers=kafka_brokers, topic="test-orders", group_id="test-group")
with pytest.raises(KafkaConsumerException):
consumer.consume(timeout=5.0)
def test_messages_ordered_within_partition(kafka_brokers: list[str]) -> None:
"""Test messages with same key maintain order."""
publisher = OrderEventPublisher(brokers=kafka_brokers, topic="ordered-orders")
order_id = "order_123"
# Publish 5 messages with same order_id (same partition key)
for i in range(5):
event = OrderEventMessage(order_id=order_id, created_at=f"2024-01-01T12:00:{i:02d}Z", ...)
publisher.publish_order(event)
publisher.flush()
# Consume and verify order
consumer = OrderEventConsumer(brokers=kafka_brokers, topic="ordered-orders", group_id="test-group")
for i in range(5):
message = consumer.consume(timeout=5.0)
assert message is not None
assert message.created_at == f"2024-01-01T12:00:{i:02d}Z"
testcontainers>=4.0.0 - Container managementtestcontainers[kafka]>=4.0.0 - Kafka container supportconfluent-kafka>=2.3.0 - Kafka clientmsgspec>=0.18.6 - Message serializationpytest>=7.4.3 - Test frameworkpytest-asyncio>=0.21.1 - Async test support# All integration tests
pytest tests/integration/ -v
# Specific test class
pytest tests/integration/test_kafka_producer_integration.py::TestOrderEventPublisherIntegration -v
# With coverage
pytest tests/integration/ --cov=app.extraction.adapters.kafka --cov=app.storage.adapters.kafka
Container logs:
docker logs <container_id>
Verbose output:
pytest tests/integration/test_kafka.py::test_name -vv -s
Container fails to start: Check Docker is running and has available resources.
Test hangs on consume(): Verify publisher called flush() before consuming.
Malformed message exceptions: Check message schema matches expected structure.
Port already in use: Testcontainers uses random ports, conflicts are rare.
Intermittent failures: Add 2s sleep after container start for broker readiness.
See examples/examples.md for comprehensive examples:
See references/reference.md for detailed troubleshooting:
kafka-producer-implementation skill - Producer implementationkafka-consumer-implementation skill - Consumer implementationkafka-schema-management skill - Schema designexamples/examples.md - Complete test examplesreferences/reference.md - Troubleshooting guidexiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience