A library that computes the ephemerides.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

68 lines
2.4 KiB

  1. #!/usr/bin/env python3
  2. # Kosmorrolib - The Library To Compute Your Ephemerides
  3. # Copyright (C) 2021 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import functools
  18. from unittest import mock
  19. def expect_assertions(assert_fun, num=1):
  20. """Asserts that an assertion function is called as expected.
  21. This is very useful when the assertions are in loops.
  22. To use it, create a nested function in the the tests function.
  23. The nested function will receive as parameter the mocked assertion function to use in place of the original one.
  24. Finally, run the nested function.
  25. Example of use:
  26. >>> # the function we tests:
  27. >>> def my_sum_function(n, m):
  28. >>> # some code here
  29. >>> pass
  30. >>> # The unit tests:
  31. >>> def test_sum(self):
  32. >>> @expect_assertions(self.assertEqual, num=10):
  33. >>> def make_assertions(assert_equal):
  34. >>> for i in range (-5, 5):
  35. >>> for j in range(-5, 5):
  36. >>> assert_equal(i + j, my_sum_function(i, j)
  37. >>>
  38. >>> make_assertions() # You don't need to give any parameter, the decorator does it for you.
  39. :param assert_fun: the assertion function to tests
  40. :param num: the number of times the assertion function is expected to be called
  41. """
  42. assert_fun_mock = mock.Mock(side_effect=assert_fun)
  43. def fun_decorator(fun):
  44. @functools.wraps(fun)
  45. def sniff_function():
  46. fun(assert_fun_mock)
  47. count = assert_fun_mock.call_count
  48. if count != num:
  49. raise AssertionError(
  50. "Expected %d call(s) to function %s but called %d time(s)."
  51. % (num, assert_fun.__name__, count)
  52. )
  53. return sniff_function
  54. return fun_decorator