Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(301)

Side by Side Diff: tools/telemetry/third_party/coverage/tests/test_execfile.py

Issue 1366913004: Add coverage Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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
4 """Tests for coverage.execfile"""
5
6 import compileall
7 import json
8 import os
9 import os.path
10 import re
11 import sys
12
13 from coverage.backward import binary_bytes
14 from coverage.execfile import run_python_file, run_python_module
15 from coverage.misc import NoCode, NoSource
16
17 from tests.coveragetest import CoverageTest
18
19 HERE = os.path.dirname(__file__)
20
21
22 class RunFileTest(CoverageTest):
23 """Test cases for `run_python_file`."""
24
25 def test_run_python_file(self):
26 tryfile = os.path.join(HERE, "try_execfile.py")
27 run_python_file(tryfile, [tryfile, "arg1", "arg2"])
28 mod_globs = json.loads(self.stdout())
29
30 # The file should think it is __main__
31 self.assertEqual(mod_globs['__name__'], "__main__")
32
33 # It should seem to come from a file named try_execfile.py
34 dunder_file = os.path.basename(mod_globs['__file__'])
35 self.assertEqual(dunder_file, "try_execfile.py")
36
37 # It should have its correct module data.
38 self.assertEqual(mod_globs['__doc__'].splitlines()[0],
39 "Test file for run_python_file.")
40 self.assertEqual(mod_globs['DATA'], "xyzzy")
41 self.assertEqual(mod_globs['FN_VAL'], "my_fn('fooey')")
42
43 # It must be self-importable as __main__.
44 self.assertEqual(mod_globs['__main__.DATA'], "xyzzy")
45
46 # Argv should have the proper values.
47 self.assertEqual(mod_globs['argv'], [tryfile, "arg1", "arg2"])
48
49 # __builtins__ should have the right values, like open().
50 self.assertEqual(mod_globs['__builtins__.has_open'], True)
51
52 def test_no_extra_file(self):
53 # Make sure that running a file doesn't create an extra compiled file.
54 self.make_file("xxx", """\
55 desc = "a non-.py file!"
56 """)
57
58 self.assertEqual(os.listdir("."), ["xxx"])
59 run_python_file("xxx", ["xxx"])
60 self.assertEqual(os.listdir("."), ["xxx"])
61
62 def test_universal_newlines(self):
63 # Make sure we can read any sort of line ending.
64 pylines = """# try newlines|print('Hello, world!')|""".split('|')
65 for nl in ('\n', '\r\n', '\r'):
66 with open('nl.py', 'wb') as fpy:
67 fpy.write(nl.join(pylines).encode('utf-8'))
68 run_python_file('nl.py', ['nl.py'])
69 self.assertEqual(self.stdout(), "Hello, world!\n"*3)
70
71 def test_missing_final_newline(self):
72 # Make sure we can deal with a Python file with no final newline.
73 self.make_file("abrupt.py", """\
74 if 1:
75 a = 1
76 print("a is %r" % a)
77 #""")
78 with open("abrupt.py") as f:
79 abrupt = f.read()
80 self.assertEqual(abrupt[-1], '#')
81 run_python_file("abrupt.py", ["abrupt.py"])
82 self.assertEqual(self.stdout(), "a is 1\n")
83
84 def test_no_such_file(self):
85 with self.assertRaises(NoSource):
86 run_python_file("xyzzy.py", [])
87
88 def test_directory_with_main(self):
89 self.make_file("with_main/__main__.py", """\
90 print("I am __main__")
91 """)
92 run_python_file("with_main", ["with_main"])
93 self.assertEqual(self.stdout(), "I am __main__\n")
94
95 def test_directory_without_main(self):
96 self.make_file("without_main/__init__.py", "")
97 with self.assertRaisesRegex(NoSource, "Can't find '__main__' module in ' without_main'"):
98 run_python_file("without_main", ["without_main"])
99
100
101 class RunPycFileTest(CoverageTest):
102 """Test cases for `run_python_file`."""
103
104 def make_pyc(self):
105 """Create a .pyc file, and return the relative path to it."""
106 self.make_file("compiled.py", """\
107 def doit():
108 print("I am here!")
109
110 doit()
111 """)
112 compileall.compile_dir(".", quiet=True)
113 os.remove("compiled.py")
114
115 # Find the .pyc file!
116 for there, _, files in os.walk("."): # pragma: part covered
117 for f in files:
118 if f.endswith(".pyc"): # pragma: part covered
119 return os.path.join(there, f)
120
121 def test_running_pyc(self):
122 pycfile = self.make_pyc()
123 run_python_file(pycfile, [pycfile])
124 self.assertEqual(self.stdout(), "I am here!\n")
125
126 def test_running_pyo(self):
127 pycfile = self.make_pyc()
128 pyofile = re.sub(r"[.]pyc$", ".pyo", pycfile)
129 self.assertNotEqual(pycfile, pyofile)
130 os.rename(pycfile, pyofile)
131 run_python_file(pyofile, [pyofile])
132 self.assertEqual(self.stdout(), "I am here!\n")
133
134 def test_running_pyc_from_wrong_python(self):
135 pycfile = self.make_pyc()
136
137 # Jam Python 2.1 magic number into the .pyc file.
138 with open(pycfile, "r+b") as fpyc:
139 fpyc.seek(0)
140 fpyc.write(binary_bytes([0x2a, 0xeb, 0x0d, 0x0a]))
141
142 with self.assertRaisesRegex(NoCode, "Bad magic number in .pyc file"):
143 run_python_file(pycfile, [pycfile])
144
145 def test_no_such_pyc_file(self):
146 with self.assertRaisesRegex(NoCode, "No file to run: 'xyzzy.pyc'"):
147 run_python_file("xyzzy.pyc", [])
148
149
150 class RunModuleTest(CoverageTest):
151 """Test run_python_module."""
152
153 run_in_temp_dir = False
154
155 def setUp(self):
156 super(RunModuleTest, self).setUp()
157 # Parent class saves and restores sys.path, we can just modify it.
158 sys.path.append(self.nice_file(os.path.dirname(__file__), 'modules'))
159
160 def test_runmod1(self):
161 run_python_module("runmod1", ["runmod1", "hello"])
162 self.assertEqual(self.stderr(), "")
163 self.assertEqual(self.stdout(), "runmod1: passed hello\n")
164
165 def test_runmod2(self):
166 run_python_module("pkg1.runmod2", ["runmod2", "hello"])
167 self.assertEqual(self.stderr(), "")
168 self.assertEqual(self.stdout(), "runmod2: passed hello\n")
169
170 def test_runmod3(self):
171 run_python_module("pkg1.sub.runmod3", ["runmod3", "hello"])
172 self.assertEqual(self.stderr(), "")
173 self.assertEqual(self.stdout(), "runmod3: passed hello\n")
174
175 def test_pkg1_main(self):
176 run_python_module("pkg1", ["pkg1", "hello"])
177 self.assertEqual(self.stderr(), "")
178 self.assertEqual(self.stdout(), "pkg1.__main__: passed hello\n")
179
180 def test_pkg1_sub_main(self):
181 run_python_module("pkg1.sub", ["pkg1.sub", "hello"])
182 self.assertEqual(self.stderr(), "")
183 self.assertEqual(self.stdout(), "pkg1.sub.__main__: passed hello\n")
184
185 def test_no_such_module(self):
186 with self.assertRaises(NoSource):
187 run_python_module("i_dont_exist", [])
188 with self.assertRaises(NoSource):
189 run_python_module("i.dont_exist", [])
190 with self.assertRaises(NoSource):
191 run_python_module("i.dont.exist", [])
192
193 def test_no_main(self):
194 with self.assertRaises(NoSource):
195 run_python_module("pkg2", ["pkg2", "hi"])
OLDNEW
« no previous file with comments | « tools/telemetry/third_party/coverage/tests/test_debug.py ('k') | tools/telemetry/third_party/coverage/tests/test_farm.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698