Created
August 22, 2019 13:06
-
-
Save kuntalchandra/f4c70e72740a18d2bb233b203f1c6399 to your computer and use it in GitHub Desktop.
Python: MagicMock, Patch and Side effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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