test_execfile.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. """Tests for coverage.execfile"""
  4. import compileall
  5. import json
  6. import os
  7. import os.path
  8. import re
  9. import sys
  10. from coverage.backward import binary_bytes
  11. from coverage.execfile import run_python_file, run_python_module
  12. from coverage.misc import NoCode, NoSource
  13. from tests.coveragetest import CoverageTest
  14. TRY_EXECFILE = os.path.join(os.path.dirname(__file__), "modules/process_test/try_execfile.py")
  15. class RunFileTest(CoverageTest):
  16. """Test cases for `run_python_file`."""
  17. def test_run_python_file(self):
  18. run_python_file(TRY_EXECFILE, [TRY_EXECFILE, "arg1", "arg2"])
  19. mod_globs = json.loads(self.stdout())
  20. # The file should think it is __main__
  21. self.assertEqual(mod_globs['__name__'], "__main__")
  22. # It should seem to come from a file named try_execfile.py
  23. dunder_file = os.path.basename(mod_globs['__file__'])
  24. self.assertEqual(dunder_file, "try_execfile.py")
  25. # It should have its correct module data.
  26. self.assertEqual(mod_globs['__doc__'].splitlines()[0],
  27. "Test file for run_python_file.")
  28. self.assertEqual(mod_globs['DATA'], "xyzzy")
  29. self.assertEqual(mod_globs['FN_VAL'], "my_fn('fooey')")
  30. # It must be self-importable as __main__.
  31. self.assertEqual(mod_globs['__main__.DATA'], "xyzzy")
  32. # Argv should have the proper values.
  33. self.assertEqual(mod_globs['argv'], [TRY_EXECFILE, "arg1", "arg2"])
  34. # __builtins__ should have the right values, like open().
  35. self.assertEqual(mod_globs['__builtins__.has_open'], True)
  36. def test_no_extra_file(self):
  37. # Make sure that running a file doesn't create an extra compiled file.
  38. self.make_file("xxx", """\
  39. desc = "a non-.py file!"
  40. """)
  41. self.assertEqual(os.listdir("."), ["xxx"])
  42. run_python_file("xxx", ["xxx"])
  43. self.assertEqual(os.listdir("."), ["xxx"])
  44. def test_universal_newlines(self):
  45. # Make sure we can read any sort of line ending.
  46. pylines = """# try newlines|print('Hello, world!')|""".split('|')
  47. for nl in ('\n', '\r\n', '\r'):
  48. with open('nl.py', 'wb') as fpy:
  49. fpy.write(nl.join(pylines).encode('utf-8'))
  50. run_python_file('nl.py', ['nl.py'])
  51. self.assertEqual(self.stdout(), "Hello, world!\n"*3)
  52. def test_missing_final_newline(self):
  53. # Make sure we can deal with a Python file with no final newline.
  54. self.make_file("abrupt.py", """\
  55. if 1:
  56. a = 1
  57. print("a is %r" % a)
  58. #""")
  59. with open("abrupt.py") as f:
  60. abrupt = f.read()
  61. self.assertEqual(abrupt[-1], '#')
  62. run_python_file("abrupt.py", ["abrupt.py"])
  63. self.assertEqual(self.stdout(), "a is 1\n")
  64. def test_no_such_file(self):
  65. with self.assertRaises(NoSource):
  66. run_python_file("xyzzy.py", [])
  67. def test_directory_with_main(self):
  68. self.make_file("with_main/__main__.py", """\
  69. print("I am __main__")
  70. """)
  71. run_python_file("with_main", ["with_main"])
  72. self.assertEqual(self.stdout(), "I am __main__\n")
  73. def test_directory_without_main(self):
  74. self.make_file("without_main/__init__.py", "")
  75. with self.assertRaisesRegex(NoSource, "Can't find '__main__' module in 'without_main'"):
  76. run_python_file("without_main", ["without_main"])
  77. class RunPycFileTest(CoverageTest):
  78. """Test cases for `run_python_file`."""
  79. def make_pyc(self):
  80. """Create a .pyc file, and return the relative path to it."""
  81. self.make_file("compiled.py", """\
  82. def doit():
  83. print("I am here!")
  84. doit()
  85. """)
  86. compileall.compile_dir(".", quiet=True)
  87. os.remove("compiled.py")
  88. # Find the .pyc file!
  89. for there, _, files in os.walk("."): # pragma: part covered
  90. for f in files:
  91. if f.endswith(".pyc"): # pragma: part covered
  92. return os.path.join(there, f)
  93. def test_running_pyc(self):
  94. pycfile = self.make_pyc()
  95. run_python_file(pycfile, [pycfile])
  96. self.assertEqual(self.stdout(), "I am here!\n")
  97. def test_running_pyo(self):
  98. pycfile = self.make_pyc()
  99. pyofile = re.sub(r"[.]pyc$", ".pyo", pycfile)
  100. self.assertNotEqual(pycfile, pyofile)
  101. os.rename(pycfile, pyofile)
  102. run_python_file(pyofile, [pyofile])
  103. self.assertEqual(self.stdout(), "I am here!\n")
  104. def test_running_pyc_from_wrong_python(self):
  105. pycfile = self.make_pyc()
  106. # Jam Python 2.1 magic number into the .pyc file.
  107. with open(pycfile, "r+b") as fpyc:
  108. fpyc.seek(0)
  109. fpyc.write(binary_bytes([0x2a, 0xeb, 0x0d, 0x0a]))
  110. with self.assertRaisesRegex(NoCode, "Bad magic number in .pyc file"):
  111. run_python_file(pycfile, [pycfile])
  112. def test_no_such_pyc_file(self):
  113. with self.assertRaisesRegex(NoCode, "No file to run: 'xyzzy.pyc'"):
  114. run_python_file("xyzzy.pyc", [])
  115. class RunModuleTest(CoverageTest):
  116. """Test run_python_module."""
  117. run_in_temp_dir = False
  118. def setUp(self):
  119. super(RunModuleTest, self).setUp()
  120. # Parent class saves and restores sys.path, we can just modify it.
  121. sys.path.append(self.nice_file(os.path.dirname(__file__), 'modules'))
  122. def test_runmod1(self):
  123. run_python_module("runmod1", ["runmod1", "hello"])
  124. self.assertEqual(self.stderr(), "")
  125. self.assertEqual(self.stdout(), "runmod1: passed hello\n")
  126. def test_runmod2(self):
  127. run_python_module("pkg1.runmod2", ["runmod2", "hello"])
  128. self.assertEqual(self.stderr(), "")
  129. self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\nrunmod2: passed hello\n")
  130. def test_runmod3(self):
  131. run_python_module("pkg1.sub.runmod3", ["runmod3", "hello"])
  132. self.assertEqual(self.stderr(), "")
  133. self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\nrunmod3: passed hello\n")
  134. def test_pkg1_main(self):
  135. run_python_module("pkg1", ["pkg1", "hello"])
  136. self.assertEqual(self.stderr(), "")
  137. self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.__main__: passed hello\n")
  138. def test_pkg1_sub_main(self):
  139. run_python_module("pkg1.sub", ["pkg1.sub", "hello"])
  140. self.assertEqual(self.stderr(), "")
  141. self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.sub.__main__: passed hello\n")
  142. def test_pkg1_init(self):
  143. run_python_module("pkg1.__init__", ["pkg1.__init__", "wut?"])
  144. self.assertEqual(self.stderr(), "")
  145. self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.__init__: __main__\n")
  146. def test_no_such_module(self):
  147. with self.assertRaises(NoSource):
  148. run_python_module("i_dont_exist", [])
  149. with self.assertRaises(NoSource):
  150. run_python_module("i.dont_exist", [])
  151. with self.assertRaises(NoSource):
  152. run_python_module("i.dont.exist", [])
  153. def test_no_main(self):
  154. with self.assertRaises(NoSource):
  155. run_python_module("pkg2", ["pkg2", "hi"])