/tests/test_lorapayload.py

https://github.com/jieter/python-lora
Python | 77 lines | 50 code | 22 blank | 5 comment | 10 complexity | c62a10468eb188c099d645c79101b763 MD5 | raw file
  1. from __future__ import print_function
  2. import glob
  3. import os
  4. import unittest
  5. from lora.payload import LoRaPayload
  6. FIXTURES_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "fixtures")
  7. def read(filename):
  8. """Read a file and strip spaces"""
  9. with open(filename) as f:
  10. return f.read().strip()
  11. def fixtures():
  12. for device_path in glob.glob(os.path.join(FIXTURES_PATH, "*")):
  13. if device_path.endswith("README.md"):
  14. continue
  15. # infer dev_addr from fixture path
  16. dev_addr = os.path.split(device_path)[1]
  17. key = read(os.path.join(device_path, "key.hex"))
  18. # text all the files ending in xml in the path we just discovered
  19. for fixture_filename in glob.glob(os.path.join(device_path, "payload*.xml")):
  20. fixture = "/".join(fixture_filename.split("/")[-2:])
  21. if "plaintext" in fixture_filename:
  22. expected = None
  23. else:
  24. expected = read(fixture_filename.replace(".xml", ".txt"))
  25. yield (dev_addr, key, fixture, read(fixture_filename), expected)
  26. class TestLoraPayload(unittest.TestCase):
  27. def test_xmlparsing(self):
  28. xmlfilename = os.path.join(FIXTURES_PATH, "000015E4", "payload_1.xml")
  29. payload = LoRaPayload(read(xmlfilename))
  30. self.assertEquals(payload.DevLrrCnt, "1")
  31. self.assertEquals(payload.FCntUp, "2")
  32. self.assertEquals(payload.Lrr_location(), "SRID=4326;POINT(4.36984 52.014877)")
  33. def test_decrypting_payload(self):
  34. """Check the decrypted plaintext against a list of expected plaintexts"""
  35. for dev_addr, key, fixture_filename, xml, expected in fixtures():
  36. payload = LoRaPayload(xml.encode("UTF-8"))
  37. plaintext_ints = payload.decrypt(key, dev_addr)
  38. decrypted_hex = "".join("{:02x}".format(x) for x in plaintext_ints)
  39. self.assertEquals(
  40. len(decrypted_hex),
  41. len(payload.payload_hex),
  42. "Decryption should not change length of hex string",
  43. )
  44. if expected is None:
  45. # plaintext is in filename, so skip checking the expected outcome
  46. continue
  47. self.assertEquals(
  48. decrypted_hex,
  49. expected,
  50. "Decrypted payload {} not as expected: \npayload_hex: {}\ndecrypted: {}\nexpected: {}".format(
  51. fixture_filename, payload.payload_hex, decrypted_hex, expected
  52. ),
  53. )
  54. if __name__ == "__main__":
  55. unittest.main()