mqtt_publish_in_callback.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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_publish_in_callback(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_connect(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.pop(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")
  32. def test_publish(self):
  33. self.assertEqual(len(self.message_queue), 0, "message queue not empty")
  34. payload = "abcdefghij"
  35. self.client.publish("inTopic", payload)
  36. i = 30
  37. while len(self.message_queue) == 0 and i > 0:
  38. self.client.loop()
  39. time.sleep(0.5)
  40. i -= 1
  41. self.assertTrue(i > 0, "message receive timed-out")
  42. self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received")
  43. msg = self.message_queue.pop(0)
  44. self.assertEqual(msg.mid, 0, "message id not 0")
  45. self.assertEqual(msg.topic, "outTopic", "message topic incorrect")
  46. self.assertEqual(msg.payload, payload)
  47. self.assertEqual(msg.qos, 0, "message qos not 0")
  48. self.assertEqual(msg.retain, False, "message retain flag incorrect")