PageRenderTime 32ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/igor.py

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