Skip to content

Unittest Notes

# file test_my_module.py
from unittest import TestCase
from unittest.mock import patch
from testfixtures import compare
from tempfile import NamedTemporaryFile
from my_module import add_function
class TestMyModule(TestCase):
def test_add_function(self):
expected = 7 # Arrange
result = add_function(2, 5) # Act
compare(result, expected) # Assert
def test_tmp_file(self):
tmp_file_content = "7"
with NamedTemporaryFile() as tmp:
tmp.write(content)
tmp_path = tmp.name
# automatically erased on cleanup
@patch("distro.id", return_value="rhel")
def test_mock(self, mock_id):
# now will be mocked out inside this test function
def test_assert_logs(self):
with self.assertLogs(level="ERROR") as log:
# make logs generate
self.assertEqual(len(log.output), 1)
self.assertEqual(len(log.records), 1)
self.assertIn('Log message', log.output[0])