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

Python code coverage for Lib/unittest/main.py

#countcontent
1n/a"""Unittest main program"""
2n/a
3n/aimport sys
4n/aimport argparse
5n/aimport os
6n/a
7n/afrom . import loader, runner
8n/afrom .signals import installHandler
9n/a
10n/a__unittest = True
11n/a
12n/aMAIN_EXAMPLES = """\
13n/aExamples:
14n/a %(prog)s test_module - run tests from test_module
15n/a %(prog)s module.TestClass - run tests from module.TestClass
16n/a %(prog)s module.Class.test_method - run specified test method
17n/a"""
18n/a
19n/aMODULE_EXAMPLES = """\
20n/aExamples:
21n/a %(prog)s - run default set of tests
22n/a %(prog)s MyTestSuite - run suite 'MyTestSuite'
23n/a %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething
24n/a %(prog)s MyTestCase - run all 'test*' test methods
25n/a in MyTestCase
26n/a"""
27n/a
28n/adef _convert_name(name):
29n/a # on Linux / Mac OS X 'foo.PY' is not importable, but on
30n/a # Windows it is. Simpler to do a case insensitive match
31n/a # a better check would be to check that the name is a
32n/a # valid Python module name.
33n/a if os.path.isfile(name) and name.lower().endswith('.py'):
34n/a if os.path.isabs(name):
35n/a rel_path = os.path.relpath(name, os.getcwd())
36n/a if os.path.isabs(rel_path) or rel_path.startswith(os.pardir):
37n/a return name
38n/a name = rel_path
39n/a # on Windows both '\' and '/' are used as path
40n/a # separators. Better to replace both than rely on os.path.sep
41n/a return name[:-3].replace('\\', '.').replace('/', '.')
42n/a return name
43n/a
44n/adef _convert_names(names):
45n/a return [_convert_name(name) for name in names]
46n/a
47n/a
48n/aclass TestProgram(object):
49n/a """A command-line program that runs a set of tests; this is primarily
50n/a for making test modules conveniently executable.
51n/a """
52n/a # defaults for testing
53n/a module=None
54n/a verbosity = 1
55n/a failfast = catchbreak = buffer = progName = warnings = None
56n/a _discovery_parser = None
57n/a
58n/a def __init__(self, module='__main__', defaultTest=None, argv=None,
59n/a testRunner=None, testLoader=loader.defaultTestLoader,
60n/a exit=True, verbosity=1, failfast=None, catchbreak=None,
61n/a buffer=None, warnings=None, *, tb_locals=False):
62n/a if isinstance(module, str):
63n/a self.module = __import__(module)
64n/a for part in module.split('.')[1:]:
65n/a self.module = getattr(self.module, part)
66n/a else:
67n/a self.module = module
68n/a if argv is None:
69n/a argv = sys.argv
70n/a
71n/a self.exit = exit
72n/a self.failfast = failfast
73n/a self.catchbreak = catchbreak
74n/a self.verbosity = verbosity
75n/a self.buffer = buffer
76n/a self.tb_locals = tb_locals
77n/a if warnings is None and not sys.warnoptions:
78n/a # even if DeprecationWarnings are ignored by default
79n/a # print them anyway unless other warnings settings are
80n/a # specified by the warnings arg or the -W python flag
81n/a self.warnings = 'default'
82n/a else:
83n/a # here self.warnings is set either to the value passed
84n/a # to the warnings args or to None.
85n/a # If the user didn't pass a value self.warnings will
86n/a # be None. This means that the behavior is unchanged
87n/a # and depends on the values passed to -W.
88n/a self.warnings = warnings
89n/a self.defaultTest = defaultTest
90n/a self.testRunner = testRunner
91n/a self.testLoader = testLoader
92n/a self.progName = os.path.basename(argv[0])
93n/a self.parseArgs(argv)
94n/a self.runTests()
95n/a
96n/a def usageExit(self, msg=None):
97n/a if msg:
98n/a print(msg)
99n/a if self._discovery_parser is None:
100n/a self._initArgParsers()
101n/a self._print_help()
102n/a sys.exit(2)
103n/a
104n/a def _print_help(self, *args, **kwargs):
105n/a if self.module is None:
106n/a print(self._main_parser.format_help())
107n/a print(MAIN_EXAMPLES % {'prog': self.progName})
108n/a self._discovery_parser.print_help()
109n/a else:
110n/a print(self._main_parser.format_help())
111n/a print(MODULE_EXAMPLES % {'prog': self.progName})
112n/a
113n/a def parseArgs(self, argv):
114n/a self._initArgParsers()
115n/a if self.module is None:
116n/a if len(argv) > 1 and argv[1].lower() == 'discover':
117n/a self._do_discovery(argv[2:])
118n/a return
119n/a self._main_parser.parse_args(argv[1:], self)
120n/a if not self.tests:
121n/a # this allows "python -m unittest -v" to still work for
122n/a # test discovery.
123n/a self._do_discovery([])
124n/a return
125n/a else:
126n/a self._main_parser.parse_args(argv[1:], self)
127n/a
128n/a if self.tests:
129n/a self.testNames = _convert_names(self.tests)
130n/a if __name__ == '__main__':
131n/a # to support python -m unittest ...
132n/a self.module = None
133n/a elif self.defaultTest is None:
134n/a # createTests will load tests from self.module
135n/a self.testNames = None
136n/a elif isinstance(self.defaultTest, str):
137n/a self.testNames = (self.defaultTest,)
138n/a else:
139n/a self.testNames = list(self.defaultTest)
140n/a self.createTests()
141n/a
142n/a def createTests(self):
143n/a if self.testNames is None:
144n/a self.test = self.testLoader.loadTestsFromModule(self.module)
145n/a else:
146n/a self.test = self.testLoader.loadTestsFromNames(self.testNames,
147n/a self.module)
148n/a
149n/a def _initArgParsers(self):
150n/a parent_parser = self._getParentArgParser()
151n/a self._main_parser = self._getMainArgParser(parent_parser)
152n/a self._discovery_parser = self._getDiscoveryArgParser(parent_parser)
153n/a
154n/a def _getParentArgParser(self):
155n/a parser = argparse.ArgumentParser(add_help=False)
156n/a
157n/a parser.add_argument('-v', '--verbose', dest='verbosity',
158n/a action='store_const', const=2,
159n/a help='Verbose output')
160n/a parser.add_argument('-q', '--quiet', dest='verbosity',
161n/a action='store_const', const=0,
162n/a help='Quiet output')
163n/a parser.add_argument('--locals', dest='tb_locals',
164n/a action='store_true',
165n/a help='Show local variables in tracebacks')
166n/a if self.failfast is None:
167n/a parser.add_argument('-f', '--failfast', dest='failfast',
168n/a action='store_true',
169n/a help='Stop on first fail or error')
170n/a self.failfast = False
171n/a if self.catchbreak is None:
172n/a parser.add_argument('-c', '--catch', dest='catchbreak',
173n/a action='store_true',
174n/a help='Catch Ctrl-C and display results so far')
175n/a self.catchbreak = False
176n/a if self.buffer is None:
177n/a parser.add_argument('-b', '--buffer', dest='buffer',
178n/a action='store_true',
179n/a help='Buffer stdout and stderr during tests')
180n/a self.buffer = False
181n/a
182n/a return parser
183n/a
184n/a def _getMainArgParser(self, parent):
185n/a parser = argparse.ArgumentParser(parents=[parent])
186n/a parser.prog = self.progName
187n/a parser.print_help = self._print_help
188n/a
189n/a parser.add_argument('tests', nargs='*',
190n/a help='a list of any number of test modules, '
191n/a 'classes and test methods.')
192n/a
193n/a return parser
194n/a
195n/a def _getDiscoveryArgParser(self, parent):
196n/a parser = argparse.ArgumentParser(parents=[parent])
197n/a parser.prog = '%s discover' % self.progName
198n/a parser.epilog = ('For test discovery all test modules must be '
199n/a 'importable from the top level directory of the '
200n/a 'project.')
201n/a
202n/a parser.add_argument('-s', '--start-directory', dest='start',
203n/a help="Directory to start discovery ('.' default)")
204n/a parser.add_argument('-p', '--pattern', dest='pattern',
205n/a help="Pattern to match tests ('test*.py' default)")
206n/a parser.add_argument('-t', '--top-level-directory', dest='top',
207n/a help='Top level directory of project (defaults to '
208n/a 'start directory)')
209n/a for arg in ('start', 'pattern', 'top'):
210n/a parser.add_argument(arg, nargs='?',
211n/a default=argparse.SUPPRESS,
212n/a help=argparse.SUPPRESS)
213n/a
214n/a return parser
215n/a
216n/a def _do_discovery(self, argv, Loader=None):
217n/a self.start = '.'
218n/a self.pattern = 'test*.py'
219n/a self.top = None
220n/a if argv is not None:
221n/a # handle command line args for test discovery
222n/a if self._discovery_parser is None:
223n/a # for testing
224n/a self._initArgParsers()
225n/a self._discovery_parser.parse_args(argv, self)
226n/a
227n/a loader = self.testLoader if Loader is None else Loader()
228n/a self.test = loader.discover(self.start, self.pattern, self.top)
229n/a
230n/a def runTests(self):
231n/a if self.catchbreak:
232n/a installHandler()
233n/a if self.testRunner is None:
234n/a self.testRunner = runner.TextTestRunner
235n/a if isinstance(self.testRunner, type):
236n/a try:
237n/a try:
238n/a testRunner = self.testRunner(verbosity=self.verbosity,
239n/a failfast=self.failfast,
240n/a buffer=self.buffer,
241n/a warnings=self.warnings,
242n/a tb_locals=self.tb_locals)
243n/a except TypeError:
244n/a # didn't accept the tb_locals argument
245n/a testRunner = self.testRunner(verbosity=self.verbosity,
246n/a failfast=self.failfast,
247n/a buffer=self.buffer,
248n/a warnings=self.warnings)
249n/a except TypeError:
250n/a # didn't accept the verbosity, buffer or failfast arguments
251n/a testRunner = self.testRunner()
252n/a else:
253n/a # it is assumed to be a TestRunner instance
254n/a testRunner = self.testRunner
255n/a self.result = testRunner.run(self.test)
256n/a if self.exit:
257n/a sys.exit(not self.result.wasSuccessful())
258n/a
259n/amain = TestProgram