pytest-mqtt supports testing systems based on MQTT

mqtt, pytest, testing, mosquitto, paho, mqtt-broker, mqtt-client, mqtt-test, mqtt-testing, pytest-plugin, python-qa, python-testing
pip install pytest-mqtt==0.4.0



CI outcome Test suite code coverage Project license PyPI downloads per month Supported Python versions Project status (alpha, beta, stable) Package version on PyPI


pytest-mqtt supports testing systems based on MQTT by providing test fixtures for pytest. It has been conceived for the fine terkin-datalogger and mqttwarn programs.

capmqtt fixture

Capture MQTT messages, using the Paho MQTT Python Client, in the spirit of caplog and capsys. It can also be used to publish MQTT messages.

MQTT server host and port are configurable via pytest cli arguments: --mqtt-host and --mqtt-port. Default values are localhost/1883.

mosquitto fixture

Provide the Mosquitto MQTT broker as a session-scoped fixture to your test cases.


from pytest_mqtt.model import MqttMessage

def test_mqtt_send_receive(mosquitto, capmqtt):
    Basic send/receive roundtrip, using text payload (`str`).

    By using the `capmqtt_decode_utf8` marker, the message payloads
    will be recorded as `str`, after decoding them from `utf-8`.
    Otherwise, message payloads would be recorded as `bytes`.

    # Submit a basic MQTT message.
    capmqtt.publish(topic="foo", payload="bar")

    # Demonstrate the "messages" property.
    # It returns a list of "MqttMessage" objects.
    assert capmqtt.messages == [
        MqttMessage(topic="foo", payload="bar", userdata=None),

    # Demonstrate the "records" property.
    # It returns tuples of "(topic, payload, userdata)".
    assert capmqtt.records == [
        ("foo", "bar", None),

The capmqtt_decode_utf8 setting can be enabled in three ways.

  1. Session-wide, per pytestconfig option, for example within

    @pytest.fixture(scope="session", autouse=True)
    def configure_capmqtt_decode_utf8(pytestconfig):
        pytestconfig.option.capmqtt_decode_utf8 = True
  2. On the module level, just say capmqtt_decode_utf8 = True on top of your file.
  3. On individual test cases as a test case marker, using @pytest.mark.capmqtt_decode_utf8.


  • The mosquitto fixture currently does not support either authentication or encryption.
  • capmqtt should be able to capture messages only from specified topics.


git clone
cd pytest-mqtt
python3 -m venv .venv
source .venv/bin/activate
pip install --editable=.[test,develop]
poe test

Project information


Every kind of contribution, feedback, or patch, is much welcome. Create an issue or submit a patch if you think we should include a new feature, or to report or fix a bug.



The project is licensed under the terms of the MIT license, see LICENSE.