Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created August 22, 2019 13:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuntalchandra/f4c70e72740a18d2bb233b203f1c6399 to your computer and use it in GitHub Desktop.
Save kuntalchandra/f4c70e72740a18d2bb233b203f1c6399 to your computer and use it in GitHub Desktop.
Python: MagicMock, Patch and Side effect
import time
import uuid
class PrintRandom(object):
def execute(self) -> None:
while True:
self.print_number(uuid.uuid1().int)
time.sleep(1)
@staticmethod
def print_number(number: int) -> None:
print("Number is: {}".format(number))
if __name__ == "__main__":
obj = PrintRandom()
obj.execute()
import uuid
from print_random import PrintRandom
import unittest
from unittest.mock import MagicMock, patch
class TestPrintRandom(unittest.TestCase):
def setUp(self) -> None:
pass
def test_print_random(self):
random = PrintRandom()
random.print_number = MagicMock(side_effect=self._side_effect_except())
try:
random.execute()
except StopIteration as e:
self.assertIsInstance(e, StopIteration)
@staticmethod
def _side_effect_except():
return StopIteration
@patch("print_random.PrintRandom.print_number")
def test_print_random_again(self, mocked_print_number):
mocked_print_number.side_effect = self.print_number
random = PrintRandom()
try:
random.execute()
except StopIteration as e:
self.assertIsInstance(e, StopIteration)
@staticmethod
def print_number(number: int) -> None:
print("Printing from patched print: {}".format(number))
raise StopIteration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment