Skip to content

Instantly share code, notes, and snippets.

@FanchenBao
Last active August 15, 2022 18:42
Show Gist options
  • Save FanchenBao/815ef963aa2c320f275b877d6d22115c to your computer and use it in GitHub Desktop.
Save FanchenBao/815ef963aa2c320f275b877d6d22115c to your computer and use it in GitHub Desktop.
Template for using the built-in unit test module in Python3
import unittest
from unittest.mock import MagicMock, patch
class TestFoo(unittest.TestCase):
"""blablabla
To run all the tests in TestFoo, run command
python3 -m unittest tests.test_foo.TestFoo
To run individual test within TestFoo, add the method name to the command.
python3 -m unittest tests.test_foo.TestFoo.test_some_method
To run other test suites, change the class name.
python3 -m unittest tests.test_foo.TestFooBar
To run all the test suites in this file, use the following command.
python3 -m unittest tests.test_foo
"""
@classmethod
def setUp(cls) -> None:
"""Set up stuff before each test.
"""
pass
@patch('some_module.other_module.some_variable', mock_variable)
@patch('some_module.other_module.some_class')
def test_es_state_with_pg_hash(self, mock_some_class):
"""This is an individual test.
mock_some_class is a MagicMock of the original class `some_class`.
`some_variable` has been replaced by `mock_variable`.
NOTE: Read this article for how to use `patch` to patch classmethod/staticmethod and instance method:
https://medium.com/python-pandemonium/python-mocking-you-are-a-tricksy-beast-6c4a1f8d19b2
"""
instance_method_mock = mock_some_class.return_value.instance_method # mock an instance method that requires instantiation of `some_class`
class_or_static_method_mock = mock_some_class.class_or_static_method # mock a class or static method that does not require instantiation of `some_class`
mock_some_class.run()
for arg in instance_method_mock.call_args_list:
self.assertTrue(arg == (1, 2, 3)) # examine the arguments passed to instance method each time it is called
@FanchenBao
Copy link
Author

While I still prefer pytest, if it takes a lot of effort to add a third party library in the tool chain just for unit test, the built-in unittest module is not that bad an alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment