Skip to main content
Join the official 2020 Python Developers SurveyStart the survey!

Zookeeper, Kafka server, and Kafka consumer fixtures for Pytest

Project description

Pytest fixture factories for Zookeeper, Kafka server and Kafka consumer. Read the API docs.

from pathlib import Path
from pytest_kafka import (
    make_zookeeper_process, make_kafka_server, make_kafka_consumer,

ROOT = Path(__file__).parent
KAFKA_SCRIPTS = ROOT / 'kafka/bin/'

# You can pass a custom teardown function (or parametrise ours). Just don't call it `teardown`
# or Pytest will interpret it as a module-scoped teardown function.
teardown_fn = partial(terminate, signal_fn=Popen.kill)
zookeeper_proc = make_zookeeper_process(ZOOKEEPER_BIN, teardown_fn=teardown_fn)
kafka_server = make_kafka_server(KAFKA_BIN, 'zookeeper_proc', teardown_fn=teardown_fn)
kafka_consumer = make_kafka_consumer(
    'kafka_server', seek_to_beginning=True, kafka_topics=['topic'])

This creates 3 fixtures:

  1. zookeeper_proc - Zookeeper process
  2. kafka_server - Kafka process
  3. kafka_consumer - usable kafka.KafkaConsumer instance

ZOOKEEPER_BIN and KAFKA_BIN are paths to launch scripts in your Kafka distribution. Check this project’s to see a way of installing Kafka for development.

It is advised to pass seek_to_beginning=True because otherwise some messages may not be captured by the consumer. This requires knowing the topics upfront because without topics there’s no partitions to seek.

Kafka server is known to take a couple of seconds to terminate gracefully. You probably don’t need that, so you can pass partial(terminate, signal_fn=Popen.kill) to make it killed with SIGKILL and waited for afterwards.

It’s possible to create multiple Kafka fixtures forming a cluster by passing the same Zookeeper fixture to them. For an example, check the tests.

Session-scoped fixtures are also available. Consult the test suite.

System requirements


Execute ./ develop in a virtualenv. This will take care of:

  • installing dependencies
  • updating pip
  • installing dev dependencies
  • installing Kafka to the project dir (for development only)


The library has been open-sourced from a codebase belonging to Infectious Media.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for pytest-kafka, version 0.4.0
Filename, size File type Python version Upload date Hashes
Filename, size pytest_kafka-0.4.0-py3-none-any.whl (8.8 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size pytest-kafka-0.4.0.tar.gz (9.3 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page