0

I've seen the documentation and other questions, but I am having trouble.

my code file: index.py from paho.mqtt,client import Client

mqtt_connected = False
mqtt_client = Client("my-client") 
TOPIC = "topic"

def _send_message(msg, client):
    client.on_connect = on_connect
    print(f"Here in send message with client {mqtt_client}")
    client.connect("test.mosquitto.org",1883, 60)      
    response = client.publish(TOPIC, msg)
    return response.is_published

test_mqtt.py from unittest.mock import patch

class Test_Mqtt:

    msg = "My message"        

    def test_send(self):
        from fsas_lambda import index

        with patch('fsas_lambda.index.Client' ) as mock_client:
           # mock_client.return_value = index.Client()
           index._send_message(DBirth(self.event), mock_client)

           print(f"Mock client = {mock_client}")
           print(f" Client methos calls: {mock_client.method_calls}")
    
           mock_client.publish.assert_called()
           assert False

When run as pytest this fails with AssertionError: Expected 'publish' to have been called.

The only prints are from pytest:

Mock client = <MagicMock name='Client' id='1443899989344'>
 Client methos calls: []

When run from pytest <path>/test_mqtt.py it gets all the way to the assert False

I also get prints from the code under test:

Here in send message with client <MagicMock name='Client' id='2589477813456'>
Mock client = <MagicMock name='Client' id='2589477813456'>
Client methos calls: [call.connect('test.mosquitto.org', 1883, 60),
call.publish('topic', 'My message')]

I get the same results with or without this line
# mock_client.return_value = index.Client()

Also tried this patch with no change: with patch('paho.mqtt.client.Client' ) as mock_client:

MikeF
  • 764
  • 9
  • 26

0 Answers0