mqtt_basic.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import unittest
  2. import settings
  3. import time
  4. import mosquitto
  5. def on_message(mosq, obj, msg):
  6. obj.message_queue.append(msg)
  7. class mqtt_basic(unittest.TestCase):
  8. message_queue = []
  9. @classmethod
  10. def setUpClass(self):
  11. self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True, obj=self)
  12. self.client.connect(settings.server_ip)
  13. self.client.on_message = on_message
  14. self.client.subscribe("outTopic", 0)
  15. @classmethod
  16. def tearDownClass(self):
  17. self.client.disconnect()
  18. def test_one(self):
  19. i = 30
  20. while len(self.message_queue) == 0 and i > 0:
  21. self.client.loop()
  22. time.sleep(0.5)
  23. i -= 1
  24. self.assertTrue(i > 0, "message receive timed-out")
  25. self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received")
  26. msg = self.message_queue[0]
  27. self.assertEqual(msg.mid, 0, "message id not 0")
  28. self.assertEqual(msg.topic, "outTopic", "message topic incorrect")
  29. self.assertEqual(msg.payload, "hello world")
  30. self.assertEqual(msg.qos, 0, "message qos not 0")
  31. self.assertEqual(msg.retain, False, "message retain flag incorrect")