igor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. """Helper for building, testing, and linting coverage.py.
  5. To get portability, all these operations are written in Python here instead
  6. of in shell scripts, batch files, or Makefiles.
  7. """
  8. import contextlib
  9. import fnmatch
  10. import glob
  11. import inspect
  12. import os
  13. import platform
  14. import sys
  15. import textwrap
  16. import warnings
  17. import zipfile
  18. # We want to see all warnings while we are running tests. But we also need to
  19. # disable warnings for some of the more complex setting up of tests.
  20. warnings.simplefilter("default")
  21. @contextlib.contextmanager
  22. def ignore_warnings():
  23. """Context manager to ignore warning within the with statement."""
  24. with warnings.catch_warnings():
  25. warnings.simplefilter("ignore")
  26. yield
  27. # Functions named do_* are executable from the command line: do_blah is run
  28. # by "python igor.py blah".
  29. def do_show_env():
  30. """Show the environment variables."""
  31. print("Environment:")
  32. for env in sorted(os.environ):
  33. print(" %s = %r" % (env, os.environ[env]))
  34. def do_remove_extension():
  35. """Remove the compiled C extension, no matter what its name."""
  36. so_patterns = """
  37. tracer.so
  38. tracer.*.so
  39. tracer.pyd
  40. tracer.*.pyd
  41. """.split()
  42. for pattern in so_patterns:
  43. pattern = os.path.join("coverage", pattern)
  44. for filename in glob.glob(pattern):
  45. try:
  46. os.remove(filename)
  47. except OSError:
  48. pass
  49. def label_for_tracer(tracer):
  50. """Get the label for these tests."""
  51. if tracer == "py":
  52. label = "with Python tracer"
  53. else:
  54. label = "with C tracer"
  55. return label
  56. def should_skip(tracer):
  57. """Is there a reason to skip these tests?"""
  58. if tracer == "py":
  59. skipper = os.environ.get("COVERAGE_NO_PYTRACER")
  60. else:
  61. skipper = (
  62. os.environ.get("COVERAGE_NO_EXTENSION") or
  63. os.environ.get("COVERAGE_NO_CTRACER")
  64. )
  65. if skipper:
  66. msg = "Skipping tests " + label_for_tracer(tracer)
  67. if len(skipper) > 1:
  68. msg += ": " + skipper
  69. else:
  70. msg = ""
  71. return msg
  72. def run_tests(tracer, *nose_args):
  73. """The actual running of tests."""
  74. with ignore_warnings():
  75. import nose.core
  76. if 'COVERAGE_TESTING' not in os.environ:
  77. os.environ['COVERAGE_TESTING'] = "True"
  78. print_banner(label_for_tracer(tracer))
  79. nose_args = ["nosetests"] + list(nose_args)
  80. nose.core.main(argv=nose_args)
  81. def run_tests_with_coverage(tracer, *nose_args):
  82. """Run tests, but with coverage."""
  83. # Need to define this early enough that the first import of env.py sees it.
  84. os.environ['COVERAGE_TESTING'] = "True"
  85. os.environ['COVERAGE_PROCESS_START'] = os.path.abspath('metacov.ini')
  86. os.environ['COVERAGE_HOME'] = os.getcwd()
  87. # Create the .pth file that will let us measure coverage in sub-processes.
  88. # The .pth file seems to have to be alphabetically after easy-install.pth
  89. # or the sys.path entries aren't created right?
  90. import nose
  91. pth_dir = os.path.dirname(os.path.dirname(nose.__file__))
  92. pth_path = os.path.join(pth_dir, "zzz_metacov.pth")
  93. with open(pth_path, "w") as pth_file:
  94. pth_file.write("import coverage; coverage.process_startup()\n")
  95. # Make names for the data files that keep all the test runs distinct.
  96. impl = platform.python_implementation().lower()
  97. version = "%s%s" % sys.version_info[:2]
  98. if '__pypy__' in sys.builtin_module_names:
  99. version += "_%s%s" % sys.pypy_version_info[:2]
  100. suffix = "%s%s_%s_%s" % (impl, version, tracer, platform.platform())
  101. os.environ['COVERAGE_METAFILE'] = os.path.abspath(".metacov."+suffix)
  102. import coverage
  103. cov = coverage.Coverage(config_file="metacov.ini", data_suffix=False)
  104. # Cheap trick: the coverage.py code itself is excluded from measurement,
  105. # but if we clobber the cover_prefix in the coverage object, we can defeat
  106. # the self-detection.
  107. cov.cover_prefix = "Please measure coverage.py!"
  108. cov._warn_unimported_source = False
  109. cov.start()
  110. try:
  111. # Re-import coverage to get it coverage tested! I don't understand all
  112. # the mechanics here, but if I don't carry over the imported modules
  113. # (in covmods), then things go haywire (os == None, eventually).
  114. covmods = {}
  115. covdir = os.path.split(coverage.__file__)[0]
  116. # We have to make a list since we'll be deleting in the loop.
  117. modules = list(sys.modules.items())
  118. for name, mod in modules:
  119. if name.startswith('coverage'):
  120. if getattr(mod, '__file__', "??").startswith(covdir):
  121. covmods[name] = mod
  122. del sys.modules[name]
  123. import coverage # pylint: disable=reimported
  124. sys.modules.update(covmods)
  125. # Run nosetests, with the arguments from our command line.
  126. try:
  127. run_tests(tracer, *nose_args)
  128. except SystemExit:
  129. # nose3 seems to raise SystemExit, not sure why?
  130. pass
  131. finally:
  132. cov.stop()
  133. os.remove(pth_path)
  134. cov.combine()
  135. cov.save()
  136. def do_combine_html():
  137. """Combine data from a meta-coverage run, and make the HTML and XML reports."""
  138. import coverage
  139. os.environ['COVERAGE_HOME'] = os.getcwd()
  140. os.environ['COVERAGE_METAFILE'] = os.path.abspath(".metacov")
  141. cov = coverage.Coverage(config_file="metacov.ini")
  142. cov.load()
  143. cov.combine()
  144. cov.save()
  145. cov.html_report()
  146. cov.xml_report()
  147. def do_test_with_tracer(tracer, *noseargs):
  148. """Run nosetests with a particular tracer."""
  149. # If we should skip these tests, skip them.
  150. skip_msg = should_skip(tracer)
  151. if skip_msg:
  152. print(skip_msg)
  153. return
  154. os.environ["COVERAGE_TEST_TRACER"] = tracer
  155. if os.environ.get("COVERAGE_COVERAGE", ""):
  156. return run_tests_with_coverage(tracer, *noseargs)
  157. else:
  158. return run_tests(tracer, *noseargs)
  159. def do_zip_mods():
  160. """Build the zipmods.zip file."""
  161. zf = zipfile.ZipFile("tests/zipmods.zip", "w")
  162. # Take one file from disk.
  163. zf.write("tests/covmodzip1.py", "covmodzip1.py")
  164. # The others will be various encodings.
  165. source = textwrap.dedent(u"""\
  166. # coding: {encoding}
  167. text = u"{text}"
  168. ords = {ords}
  169. assert [ord(c) for c in text] == ords
  170. print(u"All OK with {encoding}")
  171. """)
  172. # These encodings should match the list in tests/test_python.py
  173. details = [
  174. (u'utf8', u'ⓗⓔⓛⓛⓞ, ⓦⓞⓡⓛⓓ'),
  175. (u'gb2312', u'你好,世界'),
  176. (u'hebrew', u'שלום, עולם'),
  177. (u'shift_jis', u'こんにちは世界'),
  178. (u'cp1252', u'“hi”'),
  179. ]
  180. for encoding, text in details:
  181. filename = 'encoded_{0}.py'.format(encoding)
  182. ords = [ord(c) for c in text]
  183. source_text = source.format(encoding=encoding, text=text, ords=ords)
  184. zf.writestr(filename, source_text.encode(encoding))
  185. zf.close()
  186. def do_install_egg():
  187. """Install the egg1 egg for tests."""
  188. # I am pretty certain there are easier ways to install eggs...
  189. # pylint: disable=import-error,no-name-in-module
  190. cur_dir = os.getcwd()
  191. os.chdir("tests/eggsrc")
  192. with ignore_warnings():
  193. import distutils.core
  194. distutils.core.run_setup("setup.py", ["--quiet", "bdist_egg"])
  195. egg = glob.glob("dist/*.egg")[0]
  196. distutils.core.run_setup(
  197. "setup.py", ["--quiet", "easy_install", "--no-deps", "--zip-ok", egg]
  198. )
  199. os.chdir(cur_dir)
  200. def do_check_eol():
  201. """Check files for incorrect newlines and trailing whitespace."""
  202. ignore_dirs = [
  203. '.svn', '.hg', '.git',
  204. '.tox*',
  205. '*.egg-info',
  206. '_build',
  207. ]
  208. checked = set()
  209. def check_file(fname, crlf=True, trail_white=True):
  210. """Check a single file for whitespace abuse."""
  211. fname = os.path.relpath(fname)
  212. if fname in checked:
  213. return
  214. checked.add(fname)
  215. line = None
  216. with open(fname, "rb") as f:
  217. for n, line in enumerate(f, start=1):
  218. if crlf:
  219. if "\r" in line:
  220. print("%s@%d: CR found" % (fname, n))
  221. return
  222. if trail_white:
  223. line = line[:-1]
  224. if not crlf:
  225. line = line.rstrip('\r')
  226. if line.rstrip() != line:
  227. print("%s@%d: trailing whitespace found" % (fname, n))
  228. return
  229. if line is not None and not line.strip():
  230. print("%s: final blank line" % (fname,))
  231. def check_files(root, patterns, **kwargs):
  232. """Check a number of files for whitespace abuse."""
  233. for root, dirs, files in os.walk(root):
  234. for f in files:
  235. fname = os.path.join(root, f)
  236. for p in patterns:
  237. if fnmatch.fnmatch(fname, p):
  238. check_file(fname, **kwargs)
  239. break
  240. for ignore_dir in ignore_dirs:
  241. ignored = []
  242. for dir_name in dirs:
  243. if fnmatch.fnmatch(dir_name, ignore_dir):
  244. ignored.append(dir_name)
  245. for dir_name in ignored:
  246. dirs.remove(dir_name)
  247. check_files("coverage", ["*.py"])
  248. check_files("coverage/ctracer", ["*.c", "*.h"])
  249. check_files("coverage/htmlfiles", ["*.html", "*.css", "*.js"])
  250. check_file("tests/farm/html/src/bom.py", crlf=False)
  251. check_files("tests", ["*.py"])
  252. check_files("tests", ["*,cover"], trail_white=False)
  253. check_files("tests/js", ["*.js", "*.html"])
  254. check_file("setup.py")
  255. check_file("igor.py")
  256. check_file("Makefile")
  257. check_file(".hgignore")
  258. check_file(".travis.yml")
  259. check_files(".", ["*.rst", "*.txt"])
  260. check_files(".", ["*.pip"])
  261. def print_banner(label):
  262. """Print the version of Python."""
  263. try:
  264. impl = platform.python_implementation()
  265. except AttributeError:
  266. impl = "Python"
  267. version = platform.python_version()
  268. if '__pypy__' in sys.builtin_module_names:
  269. version += " (pypy %s)" % ".".join(str(v) for v in sys.pypy_version_info)
  270. try:
  271. which_python = os.path.relpath(sys.executable)
  272. except ValueError:
  273. # On Windows having a python executable on a different drives
  274. # than the sources cannot be relative.
  275. which_python = sys.executable
  276. print('=== %s %s %s (%s) ===' % (impl, version, label, which_python))
  277. sys.stdout.flush()
  278. def do_help():
  279. """List the available commands"""
  280. items = list(globals().items())
  281. items.sort()
  282. for name, value in items:
  283. if name.startswith('do_'):
  284. print("%-20s%s" % (name[3:], value.__doc__))
  285. def analyze_args(function):
  286. """What kind of args does `function` expect?
  287. Returns:
  288. star, num_pos:
  289. star(boolean): Does `function` accept *args?
  290. num_args(int): How many positional arguments does `function` have?
  291. """
  292. try:
  293. getargspec = inspect.getfullargspec
  294. except AttributeError:
  295. getargspec = inspect.getargspec
  296. argspec = getargspec(function)
  297. return bool(argspec[1]), len(argspec[0])
  298. def main(args):
  299. """Main command-line execution for igor.
  300. Verbs are taken from the command line, and extra words taken as directed
  301. by the arguments needed by the handler.
  302. """
  303. while args:
  304. verb = args.pop(0)
  305. handler = globals().get('do_'+verb)
  306. if handler is None:
  307. print("*** No handler for %r" % verb)
  308. return 1
  309. star, num_args = analyze_args(handler)
  310. if star:
  311. # Handler has *args, give it all the rest of the command line.
  312. handler_args = args
  313. args = []
  314. else:
  315. # Handler has specific arguments, give it only what it needs.
  316. handler_args = args[:num_args]
  317. args = args[num_args:]
  318. ret = handler(*handler_args)
  319. # If a handler returns a failure-like value, stop.
  320. if ret:
  321. return ret
  322. if __name__ == '__main__':
  323. sys.exit(main(sys.argv[1:]))