Python Unit Testing

Enable Javascript to display Table of Contents.

Unit Testing

For unit testing, the code to test shall be separated in a own class. The class will be written in a file, which can be executed for the unit tests. For the tests, simply every class gets a test class, which is derived from unittest.TestCase. All methods there which start with test_ will be executed as test.
import unittest

class TextFormatter:
	def __init__(self, upperCase=False):
		self.upperCase = upperCase

	def do_format(self, text):
		return text.lower()


class Test_TextFormatter(unittest.TestCase):
	def setUp(self):
		pass;

	def test_do_format_lowercase(self):
		formatter = TextFormatter(False)
		self.assertEqual(formatter.do_format("Abc"), "abc")

	def test_do_format_uppercase(self):
		formatter = TextFormatter(True)
		self.assertEqual(formatter.do_format("Abc"), "ABC")

if __name__ == '__main__':
	unittest.main()
The output is straight forward:
$ python3 formatter.py
.F
======================================================================
FAIL: test_do_format_uppercase (__main__.Test_TextFormatter)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/charly/Projects/python_test/formatter.py", line 21, in test_do_format_uppercase
    self.assertEqual(formatter.do_format("Abc"), "ABC")
AssertionError: 'abc' != 'ABC'
- abc
+ ABC


----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)
$
Source: python.org

Mocking

With mocking there are two ways to go:
from unittest.mock import MagicMock
import mock

class Test_Connection(unittest.TestCase):
    def setUp(self):
        self.__testDevice = MagicMock()
        self.__testDevice.query_str = MagicMock()
        self.__testDevice.query_str.return_value = "0, no Error"
        self.__testDevice.write_str = MagicMock()
        self.__testDevice.open = MagicMock()
        self.__testDevice.close = MagicMock()

    @mock.patch.object(RsInstrumentConnection, '_create_connection')
    def test_write(self, create_connection_mock):
        create_connection_mock.return_value = self.__testDevice
        with RsInstrumentConnection("TestDevice") as visa:
            visa.write("TestCommand")
            create_connection_mock.assert_called_once_with('TCPIP::TESTDEVICE::HISLIP0')
            self.__testDevice.write_str.assume_called_once_with("TestCommand") # pylint: disable=no-member
        self.__testDevice.close.assume_called_once()