A library that computes the ephemerides.
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

testutils.py 1.6 KiB

hace 3 años
hace 3 años
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 tests 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 tests:
  11. >>> def my_sum_function(n, m):
  12. >>> # some code here
  13. >>> pass
  14. >>> # The unit tests:
  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 tests
  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(
  34. "Expected %d call(s) to function %s but called %d time(s)."
  35. % (num, assert_fun.__name__, count)
  36. )
  37. return sniff_function
  38. return fun_decorator