test_switchbot.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. import unittest.mock
  3. import pytest
  4. import switchbot_mqtt
  5. # pylint: disable=protected-access
  6. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  7. @pytest.mark.parametrize(
  8. "action", [switchbot_mqtt._SwitchbotAction.ON, switchbot_mqtt._SwitchbotAction.OFF]
  9. )
  10. @pytest.mark.parametrize("command_successful", [True, False])
  11. def test__send_command(caplog, mac_address, action, command_successful):
  12. with unittest.mock.patch("switchbot.Switchbot") as switchbot_device_mock:
  13. switchbot_device_mock().turn_on.return_value = command_successful
  14. switchbot_device_mock().turn_off.return_value = command_successful
  15. switchbot_device_mock.reset_mock()
  16. with unittest.mock.patch("switchbot_mqtt._report_state") as report_mock:
  17. with caplog.at_level(logging.INFO):
  18. switchbot_mqtt._send_command(
  19. mqtt_client="dummy",
  20. switchbot_mac_address=mac_address,
  21. action=action,
  22. )
  23. switchbot_device_mock.assert_called_once_with(mac=mac_address)
  24. assert len(caplog.records) == 1
  25. logger, log_level, log_message = caplog.record_tuples[0]
  26. assert logger == "switchbot_mqtt"
  27. if command_successful:
  28. assert log_level == logging.INFO
  29. else:
  30. assert log_level == logging.ERROR
  31. assert "failed" in log_message
  32. assert mac_address in log_message
  33. if action == switchbot_mqtt._SwitchbotAction.ON:
  34. switchbot_device_mock().turn_on.assert_called_once_with()
  35. assert not switchbot_device_mock().turn_off.called
  36. assert "on" in log_message
  37. expected_state = switchbot_mqtt._SwitchbotState.ON
  38. else:
  39. switchbot_device_mock().turn_off.assert_called_once_with()
  40. assert not switchbot_device_mock().turn_on.called
  41. assert "off" in log_message
  42. expected_state = switchbot_mqtt._SwitchbotState.OFF
  43. assert report_mock.called == command_successful
  44. if command_successful:
  45. report_mock.assert_called_once_with(
  46. mqtt_client="dummy",
  47. switchbot_mac_address=mac_address,
  48. switchbot_state=expected_state,
  49. )