0

I am having an issue mocking some of the behaviours of the Python asyncio_mqtt library. I have issues when mocking certain behaviours which will allow me to test offline.

I have been attempting to write tests for the following code however I cannot for the life of me work out how to perform the mock for the async with client.messages() as messages code. I keep getting the error

>           async with client.messages() as messages:
E           AttributeError: __aenter__

async def connect_to_iot_core():
    """
    Connects to the AWS IoT Core MQTT broker
    """
    tls_params = asyncio_mqtt.TLSParameters(
        ca_certs=AWT_MQTT_CA_PATH,
        certfile=AWS_MQTT_CERT_PATH,
        keyfile=AWS_MQTT_KEY_PATH,
        cert_reqs=ssl.CERT_REQUIRED,
        tls_version=ssl.PROTOCOL_TLSv1_2,
        ciphers=None
    )

    async with asyncio_mqtt.Client(hostname=AWS_MQTT_HOST, port=AWS_MQTT_PORT,
                                   tls_params=tls_params,
                                   client_id=AWS_MQTT_CLIENT_ID, keepalive=5) as client:
        async with client.messages() as messages:
            await client.subscribe("test_topic")
            async for message in messages:
                tracking_processor.receive_packet(msg=message, client=client, userdata=None)

My test is as follows, there are no assertions yet

class TestMain:

    @patch('asyncio_mqtt.Client', new_callable=AsyncContextManagerMock)
    async def test_connect_to_iot_core(self, mock_client):
        await connect_to_iot_core(mock_logger)

Does anyone have any suggestions on how to mock this messages behaviour? Thanks

0 Answers0