Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import functools
  2. from unittest import mock
  3. def expect_assertions(assert_fun, num=1):
  4. """Asserts that an assertion function is called as expected.
  5. This is very useful when the assertions are in loops.
  6. To use it, create a nested function in the the test function.
  7. The nested function will receive as parameter the mocked assertion function to use in place of the original one.
  8. Finally, run the nested function.
  9. Example of use:
  10. >>> # the function we test:
  11. >>> def my_sum_function(n, m):
  12. >>> # some code here
  13. >>> pass
  14. >>> # The unit test:
  15. >>> def test_sum(self):
  16. >>> @expect_assertions(self.assertEqual, num=10):
  17. >>> def make_assertions(assert_equal):
  18. >>> for i in range (-5, 5):
  19. >>> for j in range(-5, 5):
  20. >>> assert_equal(i + j, my_sum_function(i, j)
  21. >>>
  22. >>> make_assertions() # You don't need to give any parameter, the decorator does it for you.
  23. :param assert_fun: the assertion function to test
  24. :param num: the number of times the assertion function is expected to be called
  25. """
  26. assert_fun_mock = mock.Mock(side_effect=assert_fun)
  27. def fun_decorator(fun):
  28. @functools.wraps(fun)
  29. def sniff_function():
  30. fun(assert_fun_mock)
  31. count = assert_fun_mock.call_count
  32. if count != num:
  33. raise AssertionError('Expected %d call(s) to function %s but called %d time(s).' % (num,
  34. assert_fun.__name__,
  35. count))
  36. return sniff_function
  37. return fun_decorator