5.2. Unittest Patch
5.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)
5.2.2. Patch Date in Different Files
class
User
is in themyfile.py
filetests are in the
mytests.py
filecannot
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)
5.2.3. Patch Date in the Same File
class
User
is in themyfile.py
filetests are also in the
myfile.py
filemind additional import inside of a context manager
this is due to the fact, that
date
will be mocked (date.today()
)and
today.return_value
is also adate
object (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)