test_testing.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # -*- coding: utf-8 -*-
  2. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  3. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  4. """Tests that our test infrastructure is really working!"""
  5. import datetime
  6. import os
  7. import sys
  8. import coverage
  9. from coverage.backunittest import TestCase
  10. from coverage.files import actual_path
  11. from tests.coveragetest import CoverageTest
  12. class TestingTest(TestCase):
  13. """Tests of helper methods on `backunittest.TestCase`."""
  14. def test_assert_count_equal(self):
  15. self.assertCountEqual(set(), set())
  16. self.assertCountEqual(set([1,2,3]), set([3,1,2]))
  17. with self.assertRaises(AssertionError):
  18. self.assertCountEqual(set([1,2,3]), set())
  19. with self.assertRaises(AssertionError):
  20. self.assertCountEqual(set([1,2,3]), set([4,5,6]))
  21. class CoverageTestTest(CoverageTest):
  22. """Test the methods in `CoverageTest`."""
  23. def test_arcz_to_arcs(self):
  24. self.assertEqual(self.arcz_to_arcs(".1 12 2."), [(-1, 1), (1, 2), (2, -1)])
  25. self.assertEqual(self.arcz_to_arcs("-11 12 2-5"), [(-1, 1), (1, 2), (2, -5)])
  26. self.assertEqual(
  27. self.arcz_to_arcs("-QA CB IT Z-A"),
  28. [(-26, 10), (12, 11), (18, 29), (35, -10)]
  29. )
  30. def test_file_exists(self):
  31. self.make_file("whoville.txt", "We are here!")
  32. self.assert_exists("whoville.txt")
  33. self.assert_doesnt_exist("shadow.txt")
  34. with self.assertRaises(AssertionError):
  35. self.assert_doesnt_exist("whoville.txt")
  36. with self.assertRaises(AssertionError):
  37. self.assert_exists("shadow.txt")
  38. def test_assert_startwith(self):
  39. self.assert_starts_with("xyzzy", "xy")
  40. self.assert_starts_with("xyz\nabc", "xy")
  41. self.assert_starts_with("xyzzy", ("x", "z"))
  42. with self.assertRaises(AssertionError):
  43. self.assert_starts_with("xyz", "a")
  44. with self.assertRaises(AssertionError):
  45. self.assert_starts_with("xyz\nabc", "a")
  46. def test_assert_recent_datetime(self):
  47. def now_delta(seconds):
  48. """Make a datetime `seconds` seconds from now."""
  49. return datetime.datetime.now() + datetime.timedelta(seconds=seconds)
  50. # Default delta is 10 seconds.
  51. self.assert_recent_datetime(now_delta(0))
  52. self.assert_recent_datetime(now_delta(-9))
  53. with self.assertRaises(AssertionError):
  54. self.assert_recent_datetime(now_delta(-11))
  55. with self.assertRaises(AssertionError):
  56. self.assert_recent_datetime(now_delta(1))
  57. # Delta is settable.
  58. self.assert_recent_datetime(now_delta(0), seconds=120)
  59. self.assert_recent_datetime(now_delta(-100), seconds=120)
  60. with self.assertRaises(AssertionError):
  61. self.assert_recent_datetime(now_delta(-1000), seconds=120)
  62. with self.assertRaises(AssertionError):
  63. self.assert_recent_datetime(now_delta(1), seconds=120)
  64. def test_assert_warnings(self):
  65. cov = coverage.Coverage()
  66. # Make a warning, it should catch it properly.
  67. with self.assert_warnings(cov, ["Hello there!"]):
  68. cov._warn("Hello there!")
  69. # The expected warnings are regexes.
  70. with self.assert_warnings(cov, ["Hello.*!"]):
  71. cov._warn("Hello there!")
  72. # There can be a bunch of actual warnings.
  73. with self.assert_warnings(cov, ["Hello.*!"]):
  74. cov._warn("You there?")
  75. cov._warn("Hello there!")
  76. # There can be a bunch of expected warnings.
  77. with self.assert_warnings(cov, ["Hello.*!", "You"]):
  78. cov._warn("You there?")
  79. cov._warn("Hello there!")
  80. # But if there are a bunch of expected warnings, they have to all happen.
  81. warn_regex = r"Didn't find warning 'You' in \['Hello there!'\]"
  82. with self.assertRaisesRegex(AssertionError, warn_regex):
  83. with self.assert_warnings(cov, ["Hello.*!", "You"]):
  84. cov._warn("Hello there!")
  85. # Make a different warning than expected, it should raise an assertion.
  86. warn_regex = r"Didn't find warning 'Not me' in \['Hello there!'\]"
  87. with self.assertRaisesRegex(AssertionError, warn_regex):
  88. with self.assert_warnings(cov, ["Not me"]):
  89. cov._warn("Hello there!")
  90. # assert_warnings shouldn't hide a real exception.
  91. with self.assertRaises(ZeroDivisionError):
  92. with self.assert_warnings(cov, ["Hello there!"]):
  93. raise ZeroDivisionError("oops")
  94. def test_sub_python_is_this_python(self):
  95. # Try it with a Python command.
  96. os.environ['COV_FOOBAR'] = 'XYZZY'
  97. self.make_file("showme.py", """\
  98. import os, sys
  99. print(sys.executable)
  100. print(os.__file__)
  101. print(os.environ['COV_FOOBAR'])
  102. """)
  103. out = self.run_command("python showme.py").splitlines()
  104. self.assertEqual(actual_path(out[0]), actual_path(sys.executable))
  105. self.assertEqual(out[1], os.__file__)
  106. self.assertEqual(out[2], 'XYZZY')
  107. # Try it with a "coverage debug sys" command.
  108. out = self.run_command("coverage debug sys").splitlines()
  109. # "environment: COV_FOOBAR = XYZZY" or "COV_FOOBAR = XYZZY"
  110. executable = next(l for l in out if "executable:" in l) # pragma: part covered
  111. executable = executable.split(":", 1)[1].strip()
  112. self.assertTrue(same_python_executable(executable, sys.executable))
  113. environ = next(l for l in out if "COV_FOOBAR" in l) # pragma: part covered
  114. _, _, environ = environ.rpartition(":")
  115. self.assertEqual(environ.strip(), "COV_FOOBAR = XYZZY")
  116. def same_python_executable(e1, e2):
  117. """Determine if `e1` and `e2` refer to the same Python executable.
  118. Either path could include symbolic links. The two paths might not refer
  119. to the exact same file, but if they are in the same directory and their
  120. numeric suffixes aren't different, they are the same executable.
  121. """
  122. e1 = os.path.abspath(os.path.realpath(e1))
  123. e2 = os.path.abspath(os.path.realpath(e2))
  124. if os.path.dirname(e1) != os.path.dirname(e2):
  125. return False # pragma: only failure
  126. e1 = os.path.basename(e1)
  127. e2 = os.path.basename(e2)
  128. if e1 == "python" or e2 == "python" or e1 == e2:
  129. # Python and Python2.3: OK
  130. # Python2.3 and Python: OK
  131. # Python and Python: OK
  132. # Python2.3 and Python2.3: OK
  133. return True
  134. return False # pragma: only failure