# tests/test_mqtt.py import pytest import socket from tools.mqtt import MQTT def test_mqtt_ip_resolution_success(mocker): # Force socket.gethostbyname to simulate a working DNS mocker.patch("socket.gethostbyname", return_value="10.11.0.33") mqtt_client = MQTT() assert mqtt_client.IP == "10.11.0.33" def test_mqtt_ip_resolution_fallback(mocker, caplog): # Simulate a DNS timeout (like what happened to you earlier!) mocker.patch("socket.gethostbyname", side_effect=socket.timeout("DNS down")) mqtt_client = MQTT() # Assert it fell back to the static IP from your .env / constants assert mqtt_client.IP == "10.11.0.33" assert "Falling back to static IP" in caplog.text def test_mqtt_send_error_handling(mocker, caplog): # Mock the actual publish function to throw a connection error mocker.patch( "tools.mqtt.mqtt_publish", side_effect=ConnectionRefusedError("Broker offline") ) mqtt_client = MQTT() mqtt_client.send({"temp": 20}) # Assert it didn't crash, and logged the error assert "MQTT data couldn't be sent" in caplog.text