Skip to content

Instantly share code, notes, and snippets.

@python012
Last active April 14, 2018 00:56
Show Gist options
  • Save python012/3fca87520cf8067b424c7989ae340324 to your computer and use it in GitHub Desktop.
Save python012/3fca87520cf8067b424c7989ae340324 to your computer and use it in GitHub Desktop.
Try patch and mock functions in unit test
#!/usr/bin/env python3
from unittest import TestCase
from unittest.mock import patch
from unittest import main
class Person(object):
def __init__(self, name):
self.name = name
def print_name(self):
print('My name is ' + self.name)
def print_parents(self):
mother = input("Enter mother's name: ")
father = input("Enter father's name: ")
print("{}'s parents are {} and {}.".format(self.name, mother, father))
self.fake_func()
def fake_func():
pass
class FuncTest(TestCase):
def test_print_parents(self):
john = Person('John')
with patch('builtins.input') as mocked_input:
mocked_input.side_effect = ('Jo', 'Lee')
with patch('builtins.print') as mocked_print:
with patch.object("Person.fake_func") as mocked_fake_func:
john.print_parents()
mocked_print.assert_called_with("John's parents are Jo and Lee.")
mocked_fake_func.assert_called_once()
if __name__ == '__main__':
main()
@python012
Copy link
Author

python012 commented Apr 13, 2018

rx:garrulous_py_practice reed$ python3 py_unittest_02.py
.
--------------------------------
Ran 1 test in 0.001s

OK

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