ยปCore Development>Code coverage>Lib/unittest/test/test_program.py

Python code coverage for Lib/unittest/test/test_program.py

#countcontent
1n/aimport io
2n/a
3n/aimport os
4n/aimport sys
5n/afrom test import support
6n/aimport unittest
7n/aimport unittest.test
8n/a
9n/a
10n/aclass Test_TestProgram(unittest.TestCase):
11n/a
12n/a def test_discovery_from_dotted_path(self):
13n/a loader = unittest.TestLoader()
14n/a
15n/a tests = [self]
16n/a expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__))
17n/a
18n/a self.wasRun = False
19n/a def _find_tests(start_dir, pattern):
20n/a self.wasRun = True
21n/a self.assertEqual(start_dir, expectedPath)
22n/a return tests
23n/a loader._find_tests = _find_tests
24n/a suite = loader.discover('unittest.test')
25n/a self.assertTrue(self.wasRun)
26n/a self.assertEqual(suite._tests, tests)
27n/a
28n/a # Horrible white box test
29n/a def testNoExit(self):
30n/a result = object()
31n/a test = object()
32n/a
33n/a class FakeRunner(object):
34n/a def run(self, test):
35n/a self.test = test
36n/a return result
37n/a
38n/a runner = FakeRunner()
39n/a
40n/a oldParseArgs = unittest.TestProgram.parseArgs
41n/a def restoreParseArgs():
42n/a unittest.TestProgram.parseArgs = oldParseArgs
43n/a unittest.TestProgram.parseArgs = lambda *args: None
44n/a self.addCleanup(restoreParseArgs)
45n/a
46n/a def removeTest():
47n/a del unittest.TestProgram.test
48n/a unittest.TestProgram.test = test
49n/a self.addCleanup(removeTest)
50n/a
51n/a program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2)
52n/a
53n/a self.assertEqual(program.result, result)
54n/a self.assertEqual(runner.test, test)
55n/a self.assertEqual(program.verbosity, 2)
56n/a
57n/a class FooBar(unittest.TestCase):
58n/a def testPass(self):
59n/a assert True
60n/a def testFail(self):
61n/a assert False
62n/a
63n/a class FooBarLoader(unittest.TestLoader):
64n/a """Test loader that returns a suite containing FooBar."""
65n/a def loadTestsFromModule(self, module):
66n/a return self.suiteClass(
67n/a [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
68n/a
69n/a def loadTestsFromNames(self, names, module):
70n/a return self.suiteClass(
71n/a [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
72n/a
73n/a def test_defaultTest_with_string(self):
74n/a class FakeRunner(object):
75n/a def run(self, test):
76n/a self.test = test
77n/a return True
78n/a
79n/a old_argv = sys.argv
80n/a sys.argv = ['faketest']
81n/a runner = FakeRunner()
82n/a program = unittest.TestProgram(testRunner=runner, exit=False,
83n/a defaultTest='unittest.test',
84n/a testLoader=self.FooBarLoader())
85n/a sys.argv = old_argv
86n/a self.assertEqual(('unittest.test',), program.testNames)
87n/a
88n/a def test_defaultTest_with_iterable(self):
89n/a class FakeRunner(object):
90n/a def run(self, test):
91n/a self.test = test
92n/a return True
93n/a
94n/a old_argv = sys.argv
95n/a sys.argv = ['faketest']
96n/a runner = FakeRunner()
97n/a program = unittest.TestProgram(
98n/a testRunner=runner, exit=False,
99n/a defaultTest=['unittest.test', 'unittest.test2'],
100n/a testLoader=self.FooBarLoader())
101n/a sys.argv = old_argv
102n/a self.assertEqual(['unittest.test', 'unittest.test2'],
103n/a program.testNames)
104n/a
105n/a def test_NonExit(self):
106n/a program = unittest.main(exit=False,
107n/a argv=["foobar"],
108n/a testRunner=unittest.TextTestRunner(stream=io.StringIO()),
109n/a testLoader=self.FooBarLoader())
110n/a self.assertTrue(hasattr(program, 'result'))
111n/a
112n/a
113n/a def test_Exit(self):
114n/a self.assertRaises(
115n/a SystemExit,
116n/a unittest.main,
117n/a argv=["foobar"],
118n/a testRunner=unittest.TextTestRunner(stream=io.StringIO()),
119n/a exit=True,
120n/a testLoader=self.FooBarLoader())
121n/a
122n/a
123n/a def test_ExitAsDefault(self):
124n/a self.assertRaises(
125n/a SystemExit,
126n/a unittest.main,
127n/a argv=["foobar"],
128n/a testRunner=unittest.TextTestRunner(stream=io.StringIO()),
129n/a testLoader=self.FooBarLoader())
130n/a
131n/a
132n/aclass InitialisableProgram(unittest.TestProgram):
133n/a exit = False
134n/a result = None
135n/a verbosity = 1
136n/a defaultTest = None
137n/a tb_locals = False
138n/a testRunner = None
139n/a testLoader = unittest.defaultTestLoader
140n/a module = '__main__'
141n/a progName = 'test'
142n/a test = 'test'
143n/a def __init__(self, *args):
144n/a pass
145n/a
146n/aRESULT = object()
147n/a
148n/aclass FakeRunner(object):
149n/a initArgs = None
150n/a test = None
151n/a raiseError = 0
152n/a
153n/a def __init__(self, **kwargs):
154n/a FakeRunner.initArgs = kwargs
155n/a if FakeRunner.raiseError:
156n/a FakeRunner.raiseError -= 1
157n/a raise TypeError
158n/a
159n/a def run(self, test):
160n/a FakeRunner.test = test
161n/a return RESULT
162n/a
163n/a
164n/aclass TestCommandLineArgs(unittest.TestCase):
165n/a
166n/a def setUp(self):
167n/a self.program = InitialisableProgram()
168n/a self.program.createTests = lambda: None
169n/a FakeRunner.initArgs = None
170n/a FakeRunner.test = None
171n/a FakeRunner.raiseError = 0
172n/a
173n/a def testVerbosity(self):
174n/a program = self.program
175n/a
176n/a for opt in '-q', '--quiet':
177n/a program.verbosity = 1
178n/a program.parseArgs([None, opt])
179n/a self.assertEqual(program.verbosity, 0)
180n/a
181n/a for opt in '-v', '--verbose':
182n/a program.verbosity = 1
183n/a program.parseArgs([None, opt])
184n/a self.assertEqual(program.verbosity, 2)
185n/a
186n/a def testBufferCatchFailfast(self):
187n/a program = self.program
188n/a for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'),
189n/a ('catch', 'catchbreak')):
190n/a if attr == 'catch' and not hasInstallHandler:
191n/a continue
192n/a
193n/a setattr(program, attr, None)
194n/a program.parseArgs([None])
195n/a self.assertIs(getattr(program, attr), False)
196n/a
197n/a false = []
198n/a setattr(program, attr, false)
199n/a program.parseArgs([None])
200n/a self.assertIs(getattr(program, attr), false)
201n/a
202n/a true = [42]
203n/a setattr(program, attr, true)
204n/a program.parseArgs([None])
205n/a self.assertIs(getattr(program, attr), true)
206n/a
207n/a short_opt = '-%s' % arg[0]
208n/a long_opt = '--%s' % arg
209n/a for opt in short_opt, long_opt:
210n/a setattr(program, attr, None)
211n/a program.parseArgs([None, opt])
212n/a self.assertIs(getattr(program, attr), True)
213n/a
214n/a setattr(program, attr, False)
215n/a with support.captured_stderr() as stderr, \
216n/a self.assertRaises(SystemExit) as cm:
217n/a program.parseArgs([None, opt])
218n/a self.assertEqual(cm.exception.args, (2,))
219n/a
220n/a setattr(program, attr, True)
221n/a with support.captured_stderr() as stderr, \
222n/a self.assertRaises(SystemExit) as cm:
223n/a program.parseArgs([None, opt])
224n/a self.assertEqual(cm.exception.args, (2,))
225n/a
226n/a def testWarning(self):
227n/a """Test the warnings argument"""
228n/a # see #10535
229n/a class FakeTP(unittest.TestProgram):
230n/a def parseArgs(self, *args, **kw): pass
231n/a def runTests(self, *args, **kw): pass
232n/a warnoptions = sys.warnoptions[:]
233n/a try:
234n/a sys.warnoptions[:] = []
235n/a # no warn options, no arg -> default
236n/a self.assertEqual(FakeTP().warnings, 'default')
237n/a # no warn options, w/ arg -> arg value
238n/a self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
239n/a sys.warnoptions[:] = ['somevalue']
240n/a # warn options, no arg -> None
241n/a # warn options, w/ arg -> arg value
242n/a self.assertEqual(FakeTP().warnings, None)
243n/a self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
244n/a finally:
245n/a sys.warnoptions[:] = warnoptions
246n/a
247n/a def testRunTestsRunnerClass(self):
248n/a program = self.program
249n/a
250n/a program.testRunner = FakeRunner
251n/a program.verbosity = 'verbosity'
252n/a program.failfast = 'failfast'
253n/a program.buffer = 'buffer'
254n/a program.warnings = 'warnings'
255n/a
256n/a program.runTests()
257n/a
258n/a self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',
259n/a 'failfast': 'failfast',
260n/a 'buffer': 'buffer',
261n/a 'tb_locals': False,
262n/a 'warnings': 'warnings'})
263n/a self.assertEqual(FakeRunner.test, 'test')
264n/a self.assertIs(program.result, RESULT)
265n/a
266n/a def testRunTestsRunnerInstance(self):
267n/a program = self.program
268n/a
269n/a program.testRunner = FakeRunner()
270n/a FakeRunner.initArgs = None
271n/a
272n/a program.runTests()
273n/a
274n/a # A new FakeRunner should not have been instantiated
275n/a self.assertIsNone(FakeRunner.initArgs)
276n/a
277n/a self.assertEqual(FakeRunner.test, 'test')
278n/a self.assertIs(program.result, RESULT)
279n/a
280n/a def test_locals(self):
281n/a program = self.program
282n/a
283n/a program.testRunner = FakeRunner
284n/a program.parseArgs([None, '--locals'])
285n/a self.assertEqual(True, program.tb_locals)
286n/a program.runTests()
287n/a self.assertEqual(FakeRunner.initArgs, {'buffer': False,
288n/a 'failfast': False,
289n/a 'tb_locals': True,
290n/a 'verbosity': 1,
291n/a 'warnings': None})
292n/a
293n/a def testRunTestsOldRunnerClass(self):
294n/a program = self.program
295n/a
296n/a # Two TypeErrors are needed to fall all the way back to old-style
297n/a # runners - one to fail tb_locals, one to fail buffer etc.
298n/a FakeRunner.raiseError = 2
299n/a program.testRunner = FakeRunner
300n/a program.verbosity = 'verbosity'
301n/a program.failfast = 'failfast'
302n/a program.buffer = 'buffer'
303n/a program.test = 'test'
304n/a
305n/a program.runTests()
306n/a
307n/a # If initialising raises a type error it should be retried
308n/a # without the new keyword arguments
309n/a self.assertEqual(FakeRunner.initArgs, {})
310n/a self.assertEqual(FakeRunner.test, 'test')
311n/a self.assertIs(program.result, RESULT)
312n/a
313n/a def testCatchBreakInstallsHandler(self):
314n/a module = sys.modules['unittest.main']
315n/a original = module.installHandler
316n/a def restore():
317n/a module.installHandler = original
318n/a self.addCleanup(restore)
319n/a
320n/a self.installed = False
321n/a def fakeInstallHandler():
322n/a self.installed = True
323n/a module.installHandler = fakeInstallHandler
324n/a
325n/a program = self.program
326n/a program.catchbreak = True
327n/a
328n/a program.testRunner = FakeRunner
329n/a
330n/a program.runTests()
331n/a self.assertTrue(self.installed)
332n/a
333n/a def _patch_isfile(self, names, exists=True):
334n/a def isfile(path):
335n/a return path in names
336n/a original = os.path.isfile
337n/a os.path.isfile = isfile
338n/a def restore():
339n/a os.path.isfile = original
340n/a self.addCleanup(restore)
341n/a
342n/a
343n/a def testParseArgsFileNames(self):
344n/a # running tests with filenames instead of module names
345n/a program = self.program
346n/a argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt']
347n/a self._patch_isfile(argv)
348n/a
349n/a program.createTests = lambda: None
350n/a program.parseArgs(argv)
351n/a
352n/a # note that 'wing.txt' is not a Python file so the name should
353n/a # *not* be converted to a module name
354n/a expected = ['foo', 'bar', 'baz', 'wing.txt']
355n/a self.assertEqual(program.testNames, expected)
356n/a
357n/a
358n/a def testParseArgsFilePaths(self):
359n/a program = self.program
360n/a argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
361n/a self._patch_isfile(argv)
362n/a
363n/a program.createTests = lambda: None
364n/a program.parseArgs(argv)
365n/a
366n/a expected = ['foo.bar.baz', 'green.red']
367n/a self.assertEqual(program.testNames, expected)
368n/a
369n/a
370n/a def testParseArgsNonExistentFiles(self):
371n/a program = self.program
372n/a argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
373n/a self._patch_isfile([])
374n/a
375n/a program.createTests = lambda: None
376n/a program.parseArgs(argv)
377n/a
378n/a self.assertEqual(program.testNames, argv[1:])
379n/a
380n/a def testParseArgsAbsolutePathsThatCanBeConverted(self):
381n/a cur_dir = os.getcwd()
382n/a program = self.program
383n/a def _join(name):
384n/a return os.path.join(cur_dir, name)
385n/a argv = ['progname', _join('foo/bar/baz.py'), _join('green\\red.py')]
386n/a self._patch_isfile(argv)
387n/a
388n/a program.createTests = lambda: None
389n/a program.parseArgs(argv)
390n/a
391n/a expected = ['foo.bar.baz', 'green.red']
392n/a self.assertEqual(program.testNames, expected)
393n/a
394n/a def testParseArgsAbsolutePathsThatCannotBeConverted(self):
395n/a program = self.program
396n/a # even on Windows '/...' is considered absolute by os.path.abspath
397n/a argv = ['progname', '/foo/bar/baz.py', '/green/red.py']
398n/a self._patch_isfile(argv)
399n/a
400n/a program.createTests = lambda: None
401n/a program.parseArgs(argv)
402n/a
403n/a self.assertEqual(program.testNames, argv[1:])
404n/a
405n/a # it may be better to use platform specific functions to normalise paths
406n/a # rather than accepting '.PY' and '\' as file separator on Linux / Mac
407n/a # it would also be better to check that a filename is a valid module
408n/a # identifier (we have a regex for this in loader.py)
409n/a # for invalid filenames should we raise a useful error rather than
410n/a # leaving the current error message (import of filename fails) in place?
411n/a
412n/a
413n/aif __name__ == '__main__':
414n/a unittest.main()