How to unify GPIO output value for raspberry pi in Python

I am making a Raspberry Pi program using python. I want to write unittest my Python code. How to get GPIO output status?

test target class is given below. I want to check the outputs after calling stop, braking, clockwise rotation and turning clockwise control.

 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" 
+5
source share
1 answer

If you trust the RPi.GPIO library, I think this is a good formulation, you can patch it within unittest.mock , patch RPi.GPIO.output give you the opportunity to break the dependency on HW and feel the calls of this function.

It could be your test class.

 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) 

A few notes:

  • In python-2.7, use the mock available by pip instead of unittest.mock
  • I use autospec=True almost every test, if you are wondering why look at this
  • My tests should cause almost 1 error in your code: typo in brake method
+2
source

Source: https://habr.com/ru/post/1214315/


All Articles