如何在Python中统一测试raspberry pi的GPIO输出值

2024-10-01 17:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作Raspberry Pi程序。 我想写我的python代码的unittest。 如何获得GPIO的输出状态?在

测试目标类如下。我想在调用stop、brake、rotateClockwise和rotateCounterClockwise后检查输出。在

import RPi.GPIO as GPIO
# moter management class, with like TA7291P
class MoterManager:
    def __init__(self, in1Pin, in2Pin):
        self.__in1Pin = in1Pin
        self.__in2Pin = in2Pin

    def stop(self):
        self.__offIn1()
        self.__offIn2()

    def brake(self):
        elf.__onIn1()
        self.__onIn2()

    def rotateClockwise(self):
        self.__onIn1()
        self.__offIn2()

    def rotateCounterClockwise(self):
        self.__offIn1()
        self.__onIn2()

    def __onIn1(self):
        GPIO.output( self.__in1Pin, True)
        print "In1 on"

    def __onIn2(self):
        GPIO.output( self.__in2Pin, True)
        print "In2 on"

    def __offIn1(self):
        GPIO.output( self.__in1Pin, False )
        print "In1 off"

    def __offIn2(self):
        GPIO.output( self.__in2Pin, False )
        print "In2 off"

Tags: selfoutputgpiodefstopprintbrakerotatecounterclockwise
1条回答
网友
1楼 · 发布于 2024-10-01 17:39:20

如果您信任RPi.GPIO库,我认为这是一个很好的声明点,您可以^{} it by ^{} frameworkpatchRPi.GPIO.output使您能够从HW中断依赖关系并感知对该函数的调用。在

那可能是你的测试课

import unittest
from unittest.mock import patch, call
from my_module import MoterManager

@patch("RPi.GPIO.output", autospec=True)
class TestMoterManager(unittest.TestClass):
    in1Pin=67
    in2Pin=68

    def test_init(self, mock_output):
        """If you would MoterManager() stop motor when you build it your test looks like follow code"""
        mm = MoterManager(self.in1Pin,self.in1Pin)
        mock_output.assert_has_calls([call(self.in1Pin, False),call(self.in2Pin, False)],any_order=True)

    def test_stop(self, mock_output):
        mm = MoterManager(self.in1Pin,self.in1Pin)
        mock_output.reset_mock
        mm.stop()
        mock_output.assert_has_calls([call(self.in1Pin, False),call(self.in2Pin, False)],any_order=True)

    def test_brake(self, mock_output):
        mm = MoterManager(self.in1Pin,self.in1Pin)
        mock_output.reset_mock
        mm.stop()
        mock_output.assert_has_calls([call(self.in1Pin, True),call(self.in2Pin, True)],any_order=True)

    def test_rotateClockwise(self, mock_output):
        mm = MoterManager(self.in1Pin,self.in1Pin)
        mock_output.reset_mock
        mm.stop()
        mock_output.assert_has_calls([call(self.in1Pin, True),call(self.in2Pin, False)],any_order=True)

    def test_rotateCounterClockwise(self, mock_output):
        mm = MoterManager(self.in1Pin,self.in1Pin)
        mock_output.reset_mock
        mm.stop()
        mock_output.assert_has_calls([call(self.in1Pin, False),call(self.in2Pin, True)],any_order=True)

注意事项:

  • 在python-2.7中,使用pip提供的mock,而不是{}
  • 如果您想知道为什么要查看this,我几乎在每个测试中都使用autospec=True
  • 我的测试应该会在你的代码中引发1个错误:在brake方法中输入错误

相关问题 更多 >

    热门问题