返回教程正文

配套源码

test_single_motor_brick.py

app/tests/test_single_motor_brick.py
zdt-x57s-can-test:封装单电机 Brick 并组合验证四台电机app/tests/test_single_motor_brick.py
Python96 行
  1. import unittest
  2. from unittest import mock
  3. from zdt_x57s_can import ZdtX57SCan, ZdtX57SCanError
  4. class SingleMotorBrickTests(unittest.TestCase):
  5. """
  6. @description : 验证每个Brick对象只绑定并操作一台ZDT X57S电机
  7. @param : unittest自动创建
  8. @return : 无
  9. """
  10. def create_motor(self, motor_id):
  11. """
  12. @description : 创建不连接真实网关的单电机测试对象
  13. @param motor_id : 测试电机地址
  14. @return : ZdtX57SCan对象
  15. """
  16. return ZdtX57SCan(
  17. motor_id=motor_id,
  18. host="127.0.0.1",
  19. port=8766,
  20. token="unit-test-token",
  21. timeout_s=0.5,
  22. )
  23. def test_four_objects_keep_independent_ids(self):
  24. """
  25. @description : 校验同一Brick类可创建四个地址互不影响的对象
  26. @param : 无
  27. @return : 无
  28. """
  29. motors = [self.create_motor(motor_id) for motor_id in range(1, 5)]
  30. self.assertEqual([motor.motor_id for motor in motors], [1, 2, 3, 4])
  31. def test_read_speed_uses_bound_motor_id(self):
  32. """
  33. @description : 校验读取速度请求自动携带对象绑定地址
  34. @param : 无
  35. @return : 无
  36. """
  37. motor = self.create_motor(7)
  38. with mock.patch.object(
  39. motor,
  40. "_call",
  41. return_value={"motor_id": 7, "speed_rpm": -20},
  42. ) as gateway_call:
  43. self.assertEqual(motor.read_speed(), -20)
  44. gateway_call.assert_called_once_with(
  45. "read_speed", {"motor_id": 7}
  46. )
  47. def test_motion_call_uses_bound_motor_id(self):
  48. """
  49. @description : 校验速度控制请求不能覆盖对象绑定地址
  50. @param : 无
  51. @return : 无
  52. """
  53. motor = self.create_motor(9)
  54. with mock.patch.object(
  55. motor,
  56. "_call",
  57. return_value={"motor_id": 9, "accepted": True},
  58. ) as gateway_call:
  59. motor.set_speed(
  60. rpm=20,
  61. acceleration_level=10,
  62. confirmation="RUN_ZDT_X57S_V1_0",
  63. )
  64. gateway_call.assert_called_once_with(
  65. "set_speed",
  66. {
  67. "rpm": 20,
  68. "acceleration_level": 10,
  69. "motor_id": 9,
  70. "confirmation": "RUN_ZDT_X57S_V1_0",
  71. },
  72. timeout_s=None,
  73. )
  74. def test_rejects_invalid_object_motor_id(self):
  75. """
  76. @description : 校验对象构造时拒绝0、256、布尔值和字符串地址
  77. @param : 无
  78. @return : 无
  79. """
  80. for motor_id in (0, 256, True, "1"):
  81. with self.subTest(motor_id=motor_id):
  82. with self.assertRaises(ZdtX57SCanError):
  83. self.create_motor(motor_id)
  84. if __name__ == "__main__":
  85. unittest.main()