002-message.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import pathlib
  2. test_file = pathlib.Path(__file__)
  3. test_dir = test_file.parent
  4. project_dir = test_dir.parent
  5. import sys
  6. sys.path.append(str(project_dir.absolute()))
  7. import source as communication
  8. class sample_message(communication.message):
  9. _type = 0x0010
  10. def __init__(self) -> None:
  11. super().__init__()
  12. self._add_field(communication.field("x_axis", int, 2))
  13. self._add_field(communication.field("y_axis", int, 2))
  14. self._add_field(communication.field("z_axis", int, 2))
  15. def main():
  16. print("Starting test.")
  17. print("Sample message size: " + str(sample_message().size))
  18. print("Setting test message.")
  19. testing = sample_message()
  20. testing.set_x_axis(10)
  21. testing.set_y_axis(20)
  22. testing.set_z_axis(30)
  23. print("Encoding.")
  24. encoded = testing.encoder().code()
  25. print("Encoded lenght: " + str(len(encoded)))
  26. print("Encoded: " + str(encoded))
  27. print("Decoding.")
  28. decoded = communication.message_decoder(encoded).build(sample_message)
  29. print("Checking.")
  30. try:
  31. if decoded.get_x_axis() != 10:
  32. raise ValueError("X asis not validated.")
  33. if decoded.get_y_axis() != 20:
  34. raise ValueError("Y asis not validated.")
  35. if decoded.get_z_axis() != 30:
  36. raise ValueError("Z asis not validated.")
  37. print("Validated property.")
  38. except ValueError as error:
  39. print("Not validated, error: " + str(error))
  40. print("Checking decoder validation.")
  41. print("Adding errors to coded message.")
  42. too_long = encoded + bytes(10)
  43. with_bad_id = int(2).to_bytes(2) + encoded[2:]
  44. broken_message = encoded[0:5] + int(2).to_bytes(1) + encoded[6:]
  45. try:
  46. print("Testing too long message.")
  47. communication.message_decoder(too_long).build(sample_message)
  48. except Exception as error:
  49. print("Work, raised: " + str(error))
  50. try:
  51. print("Testing message with bad id.")
  52. communication.message_decoder(with_bad_id).build(sample_message)
  53. except Exception as error:
  54. print("Work, raised: " + str(error))
  55. try:
  56. print("Testing message with broken content")
  57. communication.message_decoder(broken_message).build(sample_message)
  58. except Exception as error:
  59. print("Work, raised: " + str(error))
  60. if __name__ == "__main__":
  61. main()