Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. # in example.py
  2.  
  3. def inner_func(x=None):
  4. if x is None:
  5. return 1
  6.  
  7. return x + 1
  8.  
  9.  
  10. def big_func():
  11. a = inner_func()
  12. b = inner_func(a)
  13. c = inner_func(b)
  14.  
  15. return c
  16.  
  17.  
  18. # in mocks.py
  19. from unittest.mock import Mock
  20.  
  21. class MyMock(Mock):
  22. def __call__(self, *args, **kwargs):
  23. if isinstance(self.return_values, MyMock):
  24. """
  25. By default, when you try to access a property of a Mock which is not set
  26. you will get a Mock object from the same type (in this case MyMock).
  27.  
  28. Because of the way unittest treats our mocks, we cannot use neither the self.__class__
  29. nor type(self) in the if-condition.
  30. """
  31. raise ValueError('Provide `return_values` to the mock')
  32.  
  33. super().__call__(*args, **kwargs)
  34.  
  35. call = self.call_count - 1
  36. if (len(self.return_values) >= call):
  37. return self.return_values[-1]
  38.  
  39. return self.return_values[call]
  40.  
  41. # in tests.py
  42.  
  43. from unittest.mock import patch
  44. from unittest import TestCase
  45.  
  46. from .example import big_func
  47. from .mocks import MyMock
  48.  
  49. class BigFuncTests(TestCase):
  50. @patch('<path_to_inner_func>.inner_func', new_callable=MyMock)
  51. def test_mega_shano_use_case(self, inner_mock):
  52. inner_mock.return_values = [1, 2, 10]
  53. res = big_func()
  54.  
  55. self.assertEqual(res, 10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement