coveragetest.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Base test case class for coverage.py testing."""
  4. import contextlib
  5. import datetime
  6. import glob
  7. import os
  8. import random
  9. import re
  10. import shlex
  11. import shutil
  12. import sys
  13. from unittest_mixins import (
  14. EnvironmentAwareMixin, StdStreamCapturingMixin, TempDirMixin,
  15. DelayedAssertionMixin,
  16. )
  17. import coverage
  18. from coverage.backunittest import TestCase
  19. from coverage.backward import StringIO, import_local_file, string_class, shlex_quote
  20. from coverage.cmdline import CoverageScript
  21. from coverage.debug import _TEST_NAME_FILE, DebugControl
  22. from tests.helpers import run_command
  23. # Status returns for the command line.
  24. OK, ERR = 0, 1
  25. class CoverageTest(
  26. EnvironmentAwareMixin,
  27. StdStreamCapturingMixin,
  28. TempDirMixin,
  29. DelayedAssertionMixin,
  30. TestCase
  31. ):
  32. """A base class for coverage.py test cases."""
  33. # Standard unittest setting: show me diffs even if they are very long.
  34. maxDiff = None
  35. # Tell newer unittest implementations to print long helpful messages.
  36. longMessage = True
  37. def setUp(self):
  38. super(CoverageTest, self).setUp()
  39. # Attributes for getting info about what happened.
  40. self.last_command_status = None
  41. self.last_command_output = None
  42. self.last_module_name = None
  43. if _TEST_NAME_FILE: # pragma: debugging
  44. with open(_TEST_NAME_FILE, "w") as f:
  45. f.write("%s_%s" % (
  46. self.__class__.__name__, self._testMethodName,
  47. ))
  48. def clean_local_file_imports(self):
  49. """Clean up the results of calls to `import_local_file`.
  50. Use this if you need to `import_local_file` the same file twice in
  51. one test.
  52. """
  53. # So that we can re-import files, clean them out first.
  54. self.cleanup_modules()
  55. # Also have to clean out the .pyc file, since the timestamp
  56. # resolution is only one second, a changed file might not be
  57. # picked up.
  58. for pyc in glob.glob('*.pyc'):
  59. os.remove(pyc)
  60. if os.path.exists("__pycache__"):
  61. shutil.rmtree("__pycache__")
  62. def import_local_file(self, modname, modfile=None):
  63. """Import a local file as a module.
  64. Opens a file in the current directory named `modname`.py, imports it
  65. as `modname`, and returns the module object. `modfile` is the file to
  66. import if it isn't in the current directory.
  67. """
  68. return import_local_file(modname, modfile)
  69. def start_import_stop(self, cov, modname, modfile=None):
  70. """Start coverage, import a file, then stop coverage.
  71. `cov` is started and stopped, with an `import_local_file` of
  72. `modname` in the middle. `modfile` is the file to import as `modname`
  73. if it isn't in the current directory.
  74. The imported module is returned.
  75. """
  76. cov.start()
  77. try: # pragma: nested
  78. # Import the Python file, executing it.
  79. mod = self.import_local_file(modname, modfile)
  80. finally: # pragma: nested
  81. # Stop coverage.py.
  82. cov.stop()
  83. return mod
  84. def get_module_name(self):
  85. """Return a random module name to use for this test run."""
  86. self.last_module_name = 'coverage_test_' + str(random.random())[2:]
  87. return self.last_module_name
  88. # Map chars to numbers for arcz_to_arcs
  89. _arcz_map = {'.': -1}
  90. _arcz_map.update(dict((c, ord(c) - ord('0')) for c in '123456789'))
  91. _arcz_map.update(dict(
  92. (c, 10 + ord(c) - ord('A')) for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  93. ))
  94. def arcz_to_arcs(self, arcz):
  95. """Convert a compact textual representation of arcs to a list of pairs.
  96. The text has space-separated pairs of letters. Period is -1, 1-9 are
  97. 1-9, A-Z are 10 through 36. The resulting list is sorted regardless of
  98. the order of the input pairs.
  99. ".1 12 2." --> [(-1,1), (1,2), (2,-1)]
  100. Minus signs can be included in the pairs:
  101. "-11, 12, 2-5" --> [(-1,1), (1,2), (2,-5)]
  102. """
  103. arcs = []
  104. for pair in arcz.split():
  105. asgn = bsgn = 1
  106. if len(pair) == 2:
  107. a, b = pair
  108. else:
  109. assert len(pair) == 3
  110. if pair[0] == '-':
  111. _, a, b = pair
  112. asgn = -1
  113. else:
  114. assert pair[1] == '-'
  115. a, _, b = pair
  116. bsgn = -1
  117. arcs.append((asgn * self._arcz_map[a], bsgn * self._arcz_map[b]))
  118. return sorted(arcs)
  119. def assert_equal_args(self, a1, a2, msg=None):
  120. """Assert that the arc lists `a1` and `a2` are equal."""
  121. # Make them into multi-line strings so we can see what's going wrong.
  122. s1 = "\n".join(repr(a) for a in a1) + "\n"
  123. s2 = "\n".join(repr(a) for a in a2) + "\n"
  124. self.assertMultiLineEqual(s1, s2, msg)
  125. def check_coverage(
  126. self, text, lines=None, missing="", report="",
  127. excludes=None, partials="",
  128. arcz=None, arcz_missing="", arcz_unpredicted="",
  129. arcs=None, arcs_missing=None, arcs_unpredicted=None,
  130. ):
  131. """Check the coverage measurement of `text`.
  132. The source `text` is run and measured. `lines` are the line numbers
  133. that are executable, or a list of possible line numbers, any of which
  134. could match. `missing` are the lines not executed, `excludes` are
  135. regexes to match against for excluding lines, and `report` is the text
  136. of the measurement report.
  137. For arc measurement, `arcz` is a string that can be decoded into arcs
  138. in the code (see `arcz_to_arcs` for the encoding scheme).
  139. `arcz_missing` are the arcs that are not executed, and
  140. `arcz_unpredicted` are the arcs executed in the code, but not deducible
  141. from the code. These last two default to "", meaning we explicitly
  142. check that there are no missing or unpredicted arcs.
  143. Returns the Coverage object, in case you want to poke at it some more.
  144. """
  145. # We write the code into a file so that we can import it.
  146. # Coverage.py wants to deal with things as modules with file names.
  147. modname = self.get_module_name()
  148. self.make_file(modname + ".py", text)
  149. if arcs is None and arcz is not None:
  150. arcs = self.arcz_to_arcs(arcz)
  151. if arcs_missing is None:
  152. arcs_missing = self.arcz_to_arcs(arcz_missing)
  153. if arcs_unpredicted is None:
  154. arcs_unpredicted = self.arcz_to_arcs(arcz_unpredicted)
  155. # Start up coverage.py.
  156. cov = coverage.Coverage(branch=True)
  157. cov.erase()
  158. for exc in excludes or []:
  159. cov.exclude(exc)
  160. for par in partials or []:
  161. cov.exclude(par, which='partial')
  162. mod = self.start_import_stop(cov, modname)
  163. # Clean up our side effects
  164. del sys.modules[modname]
  165. # Get the analysis results, and check that they are right.
  166. analysis = cov._analyze(mod)
  167. statements = sorted(analysis.statements)
  168. if lines is not None:
  169. if isinstance(lines[0], int):
  170. # lines is just a list of numbers, it must match the statements
  171. # found in the code.
  172. self.assertEqual(statements, lines)
  173. else:
  174. # lines is a list of possible line number lists, one of them
  175. # must match.
  176. for line_list in lines:
  177. if statements == line_list:
  178. break
  179. else:
  180. self.fail("None of the lines choices matched %r" % statements)
  181. missing_formatted = analysis.missing_formatted()
  182. if isinstance(missing, string_class):
  183. self.assertEqual(missing_formatted, missing)
  184. else:
  185. for missing_list in missing:
  186. if missing_formatted == missing_list:
  187. break
  188. else:
  189. self.fail("None of the missing choices matched %r" % missing_formatted)
  190. if arcs is not None:
  191. with self.delayed_assertions():
  192. self.assert_equal_args(
  193. analysis.arc_possibilities(), arcs,
  194. "Possible arcs differ",
  195. )
  196. self.assert_equal_args(
  197. analysis.arcs_missing(), arcs_missing,
  198. "Missing arcs differ"
  199. )
  200. self.assert_equal_args(
  201. analysis.arcs_unpredicted(), arcs_unpredicted,
  202. "Unpredicted arcs differ"
  203. )
  204. if report:
  205. frep = StringIO()
  206. cov.report(mod, file=frep, show_missing=True)
  207. rep = " ".join(frep.getvalue().split("\n")[2].split()[1:])
  208. self.assertEqual(report, rep)
  209. return cov
  210. @contextlib.contextmanager
  211. def assert_warnings(self, cov, warnings):
  212. """A context manager to check that particular warnings happened in `cov`."""
  213. saved_warnings = []
  214. def capture_warning(msg):
  215. """A fake implementation of Coverage._warn, to capture warnings."""
  216. saved_warnings.append(msg)
  217. original_warn = cov._warn
  218. cov._warn = capture_warning
  219. try:
  220. yield
  221. except:
  222. raise
  223. else:
  224. for warning_regex in warnings:
  225. for saved in saved_warnings:
  226. if re.search(warning_regex, saved):
  227. break
  228. else:
  229. self.fail("Didn't find warning %r in %r" % (warning_regex, saved_warnings))
  230. cov._warn = original_warn
  231. def nice_file(self, *fparts):
  232. """Canonicalize the file name composed of the parts in `fparts`."""
  233. fname = os.path.join(*fparts)
  234. return os.path.normcase(os.path.abspath(os.path.realpath(fname)))
  235. def assert_same_files(self, flist1, flist2):
  236. """Assert that `flist1` and `flist2` are the same set of file names."""
  237. flist1_nice = [self.nice_file(f) for f in flist1]
  238. flist2_nice = [self.nice_file(f) for f in flist2]
  239. self.assertCountEqual(flist1_nice, flist2_nice)
  240. def assert_exists(self, fname):
  241. """Assert that `fname` is a file that exists."""
  242. msg = "File %r should exist" % fname
  243. self.assertTrue(os.path.exists(fname), msg)
  244. def assert_doesnt_exist(self, fname):
  245. """Assert that `fname` is a file that doesn't exist."""
  246. msg = "File %r shouldn't exist" % fname
  247. self.assertTrue(not os.path.exists(fname), msg)
  248. def assert_starts_with(self, s, prefix, msg=None):
  249. """Assert that `s` starts with `prefix`."""
  250. if not s.startswith(prefix):
  251. self.fail(msg or ("%r doesn't start with %r" % (s, prefix)))
  252. def assert_recent_datetime(self, dt, seconds=10, msg=None):
  253. """Assert that `dt` marks a time at most `seconds` seconds ago."""
  254. age = datetime.datetime.now() - dt
  255. # Python2.6 doesn't have total_seconds :(
  256. self.assertEqual(age.days, 0, msg)
  257. self.assertGreaterEqual(age.seconds, 0, msg)
  258. self.assertLessEqual(age.seconds, seconds, msg)
  259. def command_line(self, args, ret=OK, _covpkg=None):
  260. """Run `args` through the command line.
  261. Use this when you want to run the full coverage machinery, but in the
  262. current process. Exceptions may be thrown from deep in the code.
  263. Asserts that `ret` is returned by `CoverageScript.command_line`.
  264. Compare with `run_command`.
  265. Returns None.
  266. """
  267. script = CoverageScript(_covpkg=_covpkg)
  268. ret_actual = script.command_line(shlex.split(args))
  269. self.assertEqual(ret_actual, ret)
  270. coverage_command = "coverage"
  271. def run_command(self, cmd):
  272. """Run the command-line `cmd` in a sub-process.
  273. `cmd` is the command line to invoke in a sub-process. Returns the
  274. combined content of `stdout` and `stderr` output streams from the
  275. sub-process.
  276. Use this when you need to test the process behavior of coverage.
  277. Compare with `command_line`.
  278. Handles the following command name specially:
  279. * "python" is replaced with the command name of the current
  280. Python interpreter.
  281. * "coverage" is replaced with the command name for the main
  282. Coverage.py program.
  283. """
  284. split_commandline = cmd.split(" ", 1)
  285. command_name = split_commandline[0]
  286. command_args = split_commandline[1:]
  287. if command_name == "python":
  288. # Running a Python interpreter in a sub-processes can be tricky.
  289. # Use the real name of our own executable. So "python foo.py" might
  290. # get executed as "python3.3 foo.py". This is important because
  291. # Python 3.x doesn't install as "python", so you might get a Python
  292. # 2 executable instead if you don't use the executable's basename.
  293. command_name = os.path.basename(sys.executable)
  294. if command_name == "coverage":
  295. # The invocation requests the Coverage.py program. Substitute the
  296. # actual Coverage.py main command name.
  297. command_name = self.coverage_command
  298. full_commandline = " ".join([shlex_quote(command_name)] + command_args)
  299. _, output = self.run_command_status(full_commandline)
  300. return output
  301. def run_command_status(self, cmd):
  302. """Run the command-line `cmd` in a sub-process, and print its output.
  303. Use this when you need to test the process behavior of coverage.
  304. Compare with `command_line`.
  305. Returns a pair: the process' exit status and stdout text, which are
  306. also stored as self.last_command_status and self.last_command_output.
  307. """
  308. # Add our test modules directory to PYTHONPATH. I'm sure there's too
  309. # much path munging here, but...
  310. here = os.path.dirname(self.nice_file(coverage.__file__, ".."))
  311. testmods = self.nice_file(here, 'tests/modules')
  312. zipfile = self.nice_file(here, 'tests/zipmods.zip')
  313. pypath = os.getenv('PYTHONPATH', '')
  314. if pypath:
  315. pypath += os.pathsep
  316. pypath += testmods + os.pathsep + zipfile
  317. self.set_environ('PYTHONPATH', pypath)
  318. self.last_command_status, self.last_command_output = run_command(cmd)
  319. print(self.last_command_output)
  320. return self.last_command_status, self.last_command_output
  321. def report_from_command(self, cmd):
  322. """Return the report from the `cmd`, with some convenience added."""
  323. report = self.run_command(cmd).replace('\\', '/')
  324. self.assertNotIn("error", report.lower())
  325. return report
  326. def report_lines(self, report):
  327. """Return the lines of the report, as a list."""
  328. lines = report.split('\n')
  329. self.assertEqual(lines[-1], "")
  330. return lines[:-1]
  331. def line_count(self, report):
  332. """How many lines are in `report`?"""
  333. return len(self.report_lines(report))
  334. def squeezed_lines(self, report):
  335. """Return a list of the lines in report, with the spaces squeezed."""
  336. lines = self.report_lines(report)
  337. return [re.sub(r"\s+", " ", l.strip()) for l in lines]
  338. def last_line_squeezed(self, report):
  339. """Return the last line of `report` with the spaces squeezed down."""
  340. return self.squeezed_lines(report)[-1]
  341. class DebugControlString(DebugControl):
  342. """A `DebugControl` that writes to a StringIO, for testing."""
  343. def __init__(self, options):
  344. super(DebugControlString, self).__init__(options, StringIO())
  345. def get_output(self):
  346. """Get the output text from the `DebugControl`."""
  347. return self.output.getvalue()