Skip to content

Instantly share code, notes, and snippets.

@martyni
Last active May 22, 2019 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martyni/39d82742c792bfd750abaa908e806e93 to your computer and use it in GitHub Desktop.
Save martyni/39d82742c792bfd750abaa908e806e93 to your computer and use it in GitHub Desktop.
example of patch and how it can alter functions for use in tests
from my_other_module import function_4
def function_1():
return 1
def function_2():
return_tuple = (function_1(), function_3(), function_4())
return return_tuple
def function_3():
return 3
def function_4():
return 4
import unittest
import os
from unittest.mock import patch
import my_module
def simple_urandom(length):
return 'f' * length
class TestRandom(unittest.TestCase):
@patch('os.urandom', side_effect=simple_urandom)
def test_urandom(self, urandom_function):
print(os.urandom(5))
assert os.urandom(5) == 'fffff'
@patch('my_module.function_1', return_value=2)
@patch('my_module.function_3', return_value=2)
@patch('my_module.function_4', return_value=2)
def test_method_1(self, *args):
assert my_module.function_2() == (2, 2, 2)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment