6.2. Unittest Patch — Python
6.2.1. Patch Randint
Code:
>>> from random import randint >>> >>> >>> def throw_dice(): ... return randint(1,6)
Test:
>>> from unittest import TestCase >>> from unittest.mock import patch >>> >>> >>> class MyTest(TestCase): ... def test_age(self): ... with patch('random.randint', return_value=4) as randint: ... result = throw_dice() ... self.assertEqual(result, 4)
6.2.2. Patch Date in Different Files
class
Useris in themyfile.pyfiletests are in the
mytests.pyfilecannot
patch('date.today', return_value=...)because it is immutable
Code in the myfile.py file:
>>> from datetime import date >>> >>> >>> class User: ... def __init__(self, firstname, lastname, birthdate): ... self.firstname = firstname ... self.lastname = lastname ... self.birthdate = date.fromisoformat(birthdate) ... ... def age(self): ... td = date.today() - self.birthdate ... return int(td.days / 365.25)
Tests in the mytests.py file:
>>> from datetime import date >>> from unittest import TestCase >>> from unittest.mock import patch >>> >>> >>> class MyTest(TestCase): ... def test_age(self): ... mark = User('Mark', 'Watney', birthdate='2000-01-02') ... with patch('myfile.date') as d: ... d.today.return_value = date(2024, 1, 2) ... age = mark.get_age() ... self.assertIsInstance(age, int) ... self.assertEqual(age, 24)
6.2.3. Patch Date in the Same File
class
Useris in themyfile.pyfiletests are also in the
myfile.pyfilemind additional import inside of a context manager
this is due to the fact, that
datewill be mocked (date.today())and
today.return_valueis also adateobject (date(2024, 1, 2))
Code and tests in the myfile.py file:
>>> from datetime import date >>> from unittest import TestCase >>> from unittest.mock import patch >>> >>> >>> class User: ... def __init__(self, firstname, lastname, birthdate): ... self.firstname = firstname ... self.lastname = lastname ... self.birthdate = date.fromisoformat(birthdate) ... ... def age(self): ... td = date.today() - self.birthdate ... return int(td.days / 365.25) >>> >>> >>> class MyTest(TestCase): ... def test_age(self): ... mark = User('Mark', 'Watney', birthdate='2000-01-02') ... with patch('myfile.date') as d: ... from datetime import date ... d.today.return_value = date(2024, 1, 2) ... age = mark.age() ... self.assertIsInstance(age, int) ... self.assertEqual(age, 24)