test_cmdline.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. """Test cmdline.py for coverage.py."""
  4. import pprint
  5. import re
  6. import shlex
  7. import sys
  8. import textwrap
  9. import mock
  10. import coverage
  11. import coverage.cmdline
  12. from coverage import env
  13. from coverage.config import CoverageConfig
  14. from coverage.data import CoverageData, CoverageDataFiles
  15. from coverage.misc import ExceptionDuringRun
  16. from tests.coveragetest import CoverageTest, OK, ERR
  17. class BaseCmdLineTest(CoverageTest):
  18. """Tests of execution paths through the command line interpreter."""
  19. run_in_temp_dir = False
  20. # Make a dict mapping function names to the default values that cmdline.py
  21. # uses when calling the function.
  22. defaults = mock.Mock()
  23. defaults.coverage(
  24. cover_pylib=None, data_suffix=None, timid=None, branch=None,
  25. config_file=True, source=None, include=None, omit=None, debug=None,
  26. concurrency=None,
  27. )
  28. defaults.annotate(
  29. directory=None, ignore_errors=None, include=None, omit=None, morfs=[],
  30. )
  31. defaults.html_report(
  32. directory=None, ignore_errors=None, include=None, omit=None, morfs=[],
  33. title=None,
  34. )
  35. defaults.report(
  36. ignore_errors=None, include=None, omit=None, morfs=[],
  37. show_missing=None, skip_covered=None
  38. )
  39. defaults.xml_report(
  40. ignore_errors=None, include=None, omit=None, morfs=[], outfile=None,
  41. )
  42. DEFAULT_KWARGS = dict((name, kw) for name, _, kw in defaults.mock_calls)
  43. def model_object(self):
  44. """Return a Mock suitable for use in CoverageScript."""
  45. mk = mock.Mock()
  46. # We'll invoke .coverage as the constructor, and then keep using the
  47. # same object as the resulting coverage object.
  48. mk.coverage.return_value = mk
  49. # The mock needs to get options, but shouldn't need to set them.
  50. config = CoverageConfig()
  51. mk.get_option = config.get_option
  52. return mk
  53. def mock_command_line(self, args, path_exists=None):
  54. """Run `args` through the command line, with a Mock.
  55. Returns the Mock it used and the status code returned.
  56. """
  57. m = self.model_object()
  58. m.path_exists.return_value = path_exists
  59. ret = coverage.cmdline.CoverageScript(
  60. _covpkg=m, _run_python_file=m.run_python_file,
  61. _run_python_module=m.run_python_module, _help_fn=m.help_fn,
  62. _path_exists=m.path_exists,
  63. ).command_line(shlex.split(args))
  64. return m, ret
  65. def cmd_executes(self, args, code, ret=OK, path_exists=None):
  66. """Assert that the `args` end up executing the sequence in `code`."""
  67. m1, r1 = self.mock_command_line(args, path_exists=path_exists)
  68. self.assertEqual(r1, ret, "Wrong status: got %r, wanted %r" % (r1, ret))
  69. # Remove all indentation, and change ".foo()" to "m2.foo()".
  70. code = re.sub(r"(?m)^\s+", "", code)
  71. code = re.sub(r"(?m)^\.", "m2.", code)
  72. m2 = self.model_object()
  73. m2.path_exists.return_value = path_exists
  74. code_obj = compile(code, "<code>", "exec")
  75. eval(code_obj, globals(), {'m2': m2}) # pylint: disable=eval-used
  76. # Many of our functions take a lot of arguments, and cmdline.py
  77. # calls them with many. But most of them are just the defaults, which
  78. # we don't want to have to repeat in all tests. For each call, apply
  79. # the defaults. This lets the tests just mention the interesting ones.
  80. for name, args, kwargs in m2.method_calls:
  81. for k, v in self.DEFAULT_KWARGS.get(name, {}).items():
  82. if k not in kwargs:
  83. kwargs[k] = v
  84. self.assert_same_method_calls(m1, m2)
  85. def cmd_executes_same(self, args1, args2):
  86. """Assert that the `args1` executes the same as `args2`."""
  87. m1, r1 = self.mock_command_line(args1)
  88. m2, r2 = self.mock_command_line(args2)
  89. self.assertEqual(r1, r2)
  90. self.assert_same_method_calls(m1, m2)
  91. def assert_same_method_calls(self, m1, m2):
  92. """Assert that `m1.method_calls` and `m2.method_calls` are the same."""
  93. # Use a real equality comparison, but if it fails, use a nicer assert
  94. # so we can tell what's going on. We have to use the real == first due
  95. # to CmdOptionParser.__eq__
  96. if m1.method_calls != m2.method_calls:
  97. pp1 = pprint.pformat(m1.method_calls)
  98. pp2 = pprint.pformat(m2.method_calls)
  99. self.assertMultiLineEqual(pp1+'\n', pp2+'\n')
  100. def cmd_help(self, args, help_msg=None, topic=None, ret=ERR):
  101. """Run a command line, and check that it prints the right help.
  102. Only the last function call in the mock is checked, which should be the
  103. help message that we want to see.
  104. """
  105. m, r = self.mock_command_line(args)
  106. self.assertEqual(r, ret, "Wrong status: got %s, wanted %s" % (r, ret))
  107. if help_msg:
  108. self.assertEqual(m.method_calls[-1], ('help_fn', (help_msg,), {}))
  109. else:
  110. self.assertEqual(m.method_calls[-1], ('help_fn', (), {'topic': topic}))
  111. class BaseCmdLineTestTest(BaseCmdLineTest):
  112. """Tests that our BaseCmdLineTest helpers work."""
  113. def test_assert_same_method_calls(self):
  114. # All the other tests here use self.cmd_executes_same in successful
  115. # ways, so here we just check that it fails.
  116. with self.assertRaises(AssertionError):
  117. self.cmd_executes_same("run", "debug")
  118. class CmdLineTest(BaseCmdLineTest):
  119. """Tests of the coverage.py command line."""
  120. def test_annotate(self):
  121. # coverage annotate [-d DIR] [-i] [--omit DIR,...] [FILE1 FILE2 ...]
  122. self.cmd_executes("annotate", """\
  123. .coverage()
  124. .load()
  125. .annotate()
  126. """)
  127. self.cmd_executes("annotate -d dir1", """\
  128. .coverage()
  129. .load()
  130. .annotate(directory="dir1")
  131. """)
  132. self.cmd_executes("annotate -i", """\
  133. .coverage()
  134. .load()
  135. .annotate(ignore_errors=True)
  136. """)
  137. self.cmd_executes("annotate --omit fooey", """\
  138. .coverage(omit=["fooey"])
  139. .load()
  140. .annotate(omit=["fooey"])
  141. """)
  142. self.cmd_executes("annotate --omit fooey,booey", """\
  143. .coverage(omit=["fooey", "booey"])
  144. .load()
  145. .annotate(omit=["fooey", "booey"])
  146. """)
  147. self.cmd_executes("annotate mod1", """\
  148. .coverage()
  149. .load()
  150. .annotate(morfs=["mod1"])
  151. """)
  152. self.cmd_executes("annotate mod1 mod2 mod3", """\
  153. .coverage()
  154. .load()
  155. .annotate(morfs=["mod1", "mod2", "mod3"])
  156. """)
  157. def test_combine(self):
  158. # coverage combine with args
  159. self.cmd_executes("combine datadir1", """\
  160. .coverage()
  161. .combine(["datadir1"])
  162. .save()
  163. """)
  164. # coverage combine, appending
  165. self.cmd_executes("combine --append datadir1", """\
  166. .coverage()
  167. .load()
  168. .combine(["datadir1"])
  169. .save()
  170. """)
  171. # coverage combine without args
  172. self.cmd_executes("combine", """\
  173. .coverage()
  174. .combine(None)
  175. .save()
  176. """)
  177. def test_combine_doesnt_confuse_options_with_args(self):
  178. # https://bitbucket.org/ned/coveragepy/issues/385/coverage-combine-doesnt-work-with-rcfile
  179. self.cmd_executes("combine --rcfile cov.ini", """\
  180. .coverage(config_file='cov.ini')
  181. .combine(None)
  182. .save()
  183. """)
  184. self.cmd_executes("combine --rcfile cov.ini data1 data2/more", """\
  185. .coverage(config_file='cov.ini')
  186. .combine(["data1", "data2/more"])
  187. .save()
  188. """)
  189. def test_debug(self):
  190. self.cmd_help("debug", "What information would you like: config, data, sys?")
  191. self.cmd_help("debug foo", "Don't know what you mean by 'foo'")
  192. def test_debug_sys(self):
  193. self.command_line("debug sys")
  194. out = self.stdout()
  195. self.assertIn("version:", out)
  196. self.assertIn("data_path:", out)
  197. def test_debug_config(self):
  198. self.command_line("debug config")
  199. out = self.stdout()
  200. self.assertIn("cover_pylib:", out)
  201. self.assertIn("skip_covered:", out)
  202. def test_erase(self):
  203. # coverage erase
  204. self.cmd_executes("erase", """\
  205. .coverage()
  206. .erase()
  207. """)
  208. def test_version(self):
  209. # coverage --version
  210. self.cmd_help("--version", topic="version", ret=OK)
  211. def test_help_option(self):
  212. # coverage -h
  213. self.cmd_help("-h", topic="help", ret=OK)
  214. self.cmd_help("--help", topic="help", ret=OK)
  215. def test_help_command(self):
  216. self.cmd_executes("help", ".help_fn(topic='help')")
  217. def test_cmd_help(self):
  218. self.cmd_executes("run --help", ".help_fn(parser='<CmdOptionParser:run>')")
  219. self.cmd_executes_same("help run", "run --help")
  220. def test_html(self):
  221. # coverage html -d DIR [-i] [--omit DIR,...] [FILE1 FILE2 ...]
  222. self.cmd_executes("html", """\
  223. .coverage()
  224. .load()
  225. .html_report()
  226. """)
  227. self.cmd_executes("html -d dir1", """\
  228. .coverage()
  229. .load()
  230. .html_report(directory="dir1")
  231. """)
  232. self.cmd_executes("html -i", """\
  233. .coverage()
  234. .load()
  235. .html_report(ignore_errors=True)
  236. """)
  237. self.cmd_executes("html --omit fooey", """\
  238. .coverage(omit=["fooey"])
  239. .load()
  240. .html_report(omit=["fooey"])
  241. """)
  242. self.cmd_executes("html --omit fooey,booey", """\
  243. .coverage(omit=["fooey", "booey"])
  244. .load()
  245. .html_report(omit=["fooey", "booey"])
  246. """)
  247. self.cmd_executes("html mod1", """\
  248. .coverage()
  249. .load()
  250. .html_report(morfs=["mod1"])
  251. """)
  252. self.cmd_executes("html mod1 mod2 mod3", """\
  253. .coverage()
  254. .load()
  255. .html_report(morfs=["mod1", "mod2", "mod3"])
  256. """)
  257. self.cmd_executes("html --title=Hello_there", """\
  258. .coverage()
  259. .load()
  260. .html_report(title='Hello_there')
  261. """)
  262. def test_report(self):
  263. # coverage report [-m] [-i] [-o DIR,...] [FILE1 FILE2 ...]
  264. self.cmd_executes("report", """\
  265. .coverage()
  266. .load()
  267. .report(show_missing=None)
  268. """)
  269. self.cmd_executes("report -i", """\
  270. .coverage()
  271. .load()
  272. .report(ignore_errors=True)
  273. """)
  274. self.cmd_executes("report -m", """\
  275. .coverage()
  276. .load()
  277. .report(show_missing=True)
  278. """)
  279. self.cmd_executes("report --omit fooey", """\
  280. .coverage(omit=["fooey"])
  281. .load()
  282. .report(omit=["fooey"])
  283. """)
  284. self.cmd_executes("report --omit fooey,booey", """\
  285. .coverage(omit=["fooey", "booey"])
  286. .load()
  287. .report(omit=["fooey", "booey"])
  288. """)
  289. self.cmd_executes("report mod1", """\
  290. .coverage()
  291. .load()
  292. .report(morfs=["mod1"])
  293. """)
  294. self.cmd_executes("report mod1 mod2 mod3", """\
  295. .coverage()
  296. .load()
  297. .report(morfs=["mod1", "mod2", "mod3"])
  298. """)
  299. self.cmd_executes("report --skip-covered", """\
  300. .coverage()
  301. .load()
  302. .report(skip_covered=True)
  303. """)
  304. def test_run(self):
  305. # coverage run [-p] [-L] [--timid] MODULE.py [ARG1 ARG2 ...]
  306. # run calls coverage.erase first.
  307. self.cmd_executes("run foo.py", """\
  308. .coverage()
  309. .erase()
  310. .start()
  311. .run_python_file('foo.py', ['foo.py'])
  312. .stop()
  313. .save()
  314. """)
  315. # run -a combines with an existing data file before saving.
  316. self.cmd_executes("run -a foo.py", """\
  317. .coverage()
  318. .start()
  319. .run_python_file('foo.py', ['foo.py'])
  320. .stop()
  321. .path_exists('.coverage')
  322. .combine(data_paths=['.coverage'])
  323. .save()
  324. """, path_exists=True)
  325. # run -a doesn't combine anything if the data file doesn't exist.
  326. self.cmd_executes("run -a foo.py", """\
  327. .coverage()
  328. .start()
  329. .run_python_file('foo.py', ['foo.py'])
  330. .stop()
  331. .path_exists('.coverage')
  332. .save()
  333. """, path_exists=False)
  334. # --timid sets a flag, and program arguments get passed through.
  335. self.cmd_executes("run --timid foo.py abc 123", """\
  336. .coverage(timid=True)
  337. .erase()
  338. .start()
  339. .run_python_file('foo.py', ['foo.py', 'abc', '123'])
  340. .stop()
  341. .save()
  342. """)
  343. # -L sets a flag, and flags for the program don't confuse us.
  344. self.cmd_executes("run -p -L foo.py -a -b", """\
  345. .coverage(cover_pylib=True, data_suffix=True)
  346. .erase()
  347. .start()
  348. .run_python_file('foo.py', ['foo.py', '-a', '-b'])
  349. .stop()
  350. .save()
  351. """)
  352. self.cmd_executes("run --branch foo.py", """\
  353. .coverage(branch=True)
  354. .erase()
  355. .start()
  356. .run_python_file('foo.py', ['foo.py'])
  357. .stop()
  358. .save()
  359. """)
  360. self.cmd_executes("run --rcfile=myrc.rc foo.py", """\
  361. .coverage(config_file="myrc.rc")
  362. .erase()
  363. .start()
  364. .run_python_file('foo.py', ['foo.py'])
  365. .stop()
  366. .save()
  367. """)
  368. self.cmd_executes("run --include=pre1,pre2 foo.py", """\
  369. .coverage(include=["pre1", "pre2"])
  370. .erase()
  371. .start()
  372. .run_python_file('foo.py', ['foo.py'])
  373. .stop()
  374. .save()
  375. """)
  376. self.cmd_executes("run --omit=opre1,opre2 foo.py", """\
  377. .coverage(omit=["opre1", "opre2"])
  378. .erase()
  379. .start()
  380. .run_python_file('foo.py', ['foo.py'])
  381. .stop()
  382. .save()
  383. """)
  384. self.cmd_executes("run --include=pre1,pre2 --omit=opre1,opre2 foo.py", """\
  385. .coverage(include=["pre1", "pre2"], omit=["opre1", "opre2"])
  386. .erase()
  387. .start()
  388. .run_python_file('foo.py', ['foo.py'])
  389. .stop()
  390. .save()
  391. """)
  392. self.cmd_executes("run --source=quux,hi.there,/home/bar foo.py", """\
  393. .coverage(source=["quux", "hi.there", "/home/bar"])
  394. .erase()
  395. .start()
  396. .run_python_file('foo.py', ['foo.py'])
  397. .stop()
  398. .save()
  399. """)
  400. self.cmd_executes("run --concurrency=gevent foo.py", """\
  401. .coverage(concurrency='gevent')
  402. .erase()
  403. .start()
  404. .run_python_file('foo.py', ['foo.py'])
  405. .stop()
  406. .save()
  407. """)
  408. self.cmd_executes("run --concurrency=multiprocessing foo.py", """\
  409. .coverage(concurrency='multiprocessing')
  410. .erase()
  411. .start()
  412. .run_python_file('foo.py', ['foo.py'])
  413. .stop()
  414. .save()
  415. """)
  416. def test_bad_concurrency(self):
  417. self.command_line("run --concurrency=nothing", ret=ERR)
  418. out = self.stdout()
  419. self.assertIn("option --concurrency: invalid choice: 'nothing'", out)
  420. def test_no_multiple_concurrency(self):
  421. # You can't use multiple concurrency values on the command line.
  422. # I would like to have a better message about not allowing multiple
  423. # values for this option, but optparse is not that flexible.
  424. self.command_line("run --concurrency=multiprocessing,gevent foo.py", ret=ERR)
  425. out = self.stdout()
  426. self.assertIn("option --concurrency: invalid choice: 'multiprocessing,gevent'", out)
  427. def test_multiprocessing_needs_config_file(self):
  428. # You can't use command-line args to add options to multiprocessing
  429. # runs, since they won't make it to the subprocesses. You need to use a
  430. # config file.
  431. self.command_line("run --concurrency=multiprocessing --branch foo.py", ret=ERR)
  432. self.assertIn(
  433. "Options affecting multiprocessing must be specified in a configuration file.",
  434. self.stdout()
  435. )
  436. def test_run_debug(self):
  437. self.cmd_executes("run --debug=opt1 foo.py", """\
  438. .coverage(debug=["opt1"])
  439. .erase()
  440. .start()
  441. .run_python_file('foo.py', ['foo.py'])
  442. .stop()
  443. .save()
  444. """)
  445. self.cmd_executes("run --debug=opt1,opt2 foo.py", """\
  446. .coverage(debug=["opt1","opt2"])
  447. .erase()
  448. .start()
  449. .run_python_file('foo.py', ['foo.py'])
  450. .stop()
  451. .save()
  452. """)
  453. def test_run_module(self):
  454. self.cmd_executes("run -m mymodule", """\
  455. .coverage()
  456. .erase()
  457. .start()
  458. .run_python_module('mymodule', ['mymodule'])
  459. .stop()
  460. .save()
  461. """)
  462. self.cmd_executes("run -m mymodule -qq arg1 arg2", """\
  463. .coverage()
  464. .erase()
  465. .start()
  466. .run_python_module('mymodule', ['mymodule', '-qq', 'arg1', 'arg2'])
  467. .stop()
  468. .save()
  469. """)
  470. self.cmd_executes("run --branch -m mymodule", """\
  471. .coverage(branch=True)
  472. .erase()
  473. .start()
  474. .run_python_module('mymodule', ['mymodule'])
  475. .stop()
  476. .save()
  477. """)
  478. self.cmd_executes_same("run -m mymodule", "run --module mymodule")
  479. def test_run_nothing(self):
  480. self.command_line("run", ret=ERR)
  481. self.assertIn("Nothing to do", self.stdout())
  482. def test_cant_append_parallel(self):
  483. self.command_line("run --append --parallel-mode foo.py", ret=ERR)
  484. self.assertIn("Can't append to data files in parallel mode.", self.stdout())
  485. def test_xml(self):
  486. # coverage xml [-i] [--omit DIR,...] [FILE1 FILE2 ...]
  487. self.cmd_executes("xml", """\
  488. .coverage()
  489. .load()
  490. .xml_report()
  491. """)
  492. self.cmd_executes("xml -i", """\
  493. .coverage()
  494. .load()
  495. .xml_report(ignore_errors=True)
  496. """)
  497. self.cmd_executes("xml -o myxml.foo", """\
  498. .coverage()
  499. .load()
  500. .xml_report(outfile="myxml.foo")
  501. """)
  502. self.cmd_executes("xml -o -", """\
  503. .coverage()
  504. .load()
  505. .xml_report(outfile="-")
  506. """)
  507. self.cmd_executes("xml --omit fooey", """\
  508. .coverage(omit=["fooey"])
  509. .load()
  510. .xml_report(omit=["fooey"])
  511. """)
  512. self.cmd_executes("xml --omit fooey,booey", """\
  513. .coverage(omit=["fooey", "booey"])
  514. .load()
  515. .xml_report(omit=["fooey", "booey"])
  516. """)
  517. self.cmd_executes("xml mod1", """\
  518. .coverage()
  519. .load()
  520. .xml_report(morfs=["mod1"])
  521. """)
  522. self.cmd_executes("xml mod1 mod2 mod3", """\
  523. .coverage()
  524. .load()
  525. .xml_report(morfs=["mod1", "mod2", "mod3"])
  526. """)
  527. def test_no_arguments_at_all(self):
  528. self.cmd_help("", topic="minimum_help", ret=OK)
  529. def test_bad_command(self):
  530. self.cmd_help("xyzzy", "Unknown command: 'xyzzy'")
  531. class CmdLineWithFilesTest(BaseCmdLineTest):
  532. """Test the command line in ways that need temp files."""
  533. run_in_temp_dir = True
  534. no_files_in_temp_dir = True
  535. def test_debug_data(self):
  536. data = CoverageData()
  537. data.add_lines({
  538. "file1.py": dict.fromkeys(range(1, 18)),
  539. "file2.py": dict.fromkeys(range(1, 24)),
  540. })
  541. data.add_file_tracers({"file1.py": "a_plugin"})
  542. data_files = CoverageDataFiles()
  543. data_files.write(data)
  544. self.command_line("debug data")
  545. self.assertMultiLineEqual(self.stdout(), textwrap.dedent("""\
  546. -- data ------------------------------------------------------
  547. path: FILENAME
  548. has_arcs: False
  549. 2 files:
  550. file1.py: 17 lines [a_plugin]
  551. file2.py: 23 lines
  552. """).replace("FILENAME", data_files.filename))
  553. def test_debug_data_with_no_data(self):
  554. data_files = CoverageDataFiles()
  555. self.command_line("debug data")
  556. self.assertMultiLineEqual(self.stdout(), textwrap.dedent("""\
  557. -- data ------------------------------------------------------
  558. path: FILENAME
  559. No data collected
  560. """).replace("FILENAME", data_files.filename))
  561. class CmdLineStdoutTest(BaseCmdLineTest):
  562. """Test the command line with real stdout output."""
  563. def test_minimum_help(self):
  564. self.command_line("")
  565. out = self.stdout()
  566. self.assertIn("Code coverage for Python.", out)
  567. self.assertLess(out.count("\n"), 4)
  568. def test_version(self):
  569. self.command_line("--version")
  570. out = self.stdout()
  571. self.assertIn("ersion ", out)
  572. if env.C_TRACER:
  573. self.assertIn("with C extension", out)
  574. else:
  575. self.assertIn("without C extension", out)
  576. self.assertLess(out.count("\n"), 4)
  577. def test_help(self):
  578. self.command_line("help")
  579. out = self.stdout()
  580. self.assertIn("readthedocs.io", out)
  581. self.assertGreater(out.count("\n"), 10)
  582. def test_cmd_help(self):
  583. self.command_line("help run")
  584. out = self.stdout()
  585. self.assertIn("<pyfile>", out)
  586. self.assertIn("--timid", out)
  587. self.assertGreater(out.count("\n"), 10)
  588. def test_unknown_topic(self):
  589. # Should probably be an ERR return, but meh.
  590. self.command_line("help foobar")
  591. self.assertEqual(self.stdout(), "Don't know topic 'foobar'\n")
  592. def test_error(self):
  593. self.command_line("fooey kablooey", ret=ERR)
  594. out = self.stdout()
  595. self.assertIn("fooey", out)
  596. self.assertIn("help", out)
  597. class CmdMainTest(CoverageTest):
  598. """Tests of coverage.cmdline.main(), using mocking for isolation."""
  599. run_in_temp_dir = False
  600. class CoverageScriptStub(object):
  601. """A stub for coverage.cmdline.CoverageScript, used by CmdMainTest."""
  602. def command_line(self, argv):
  603. """Stub for command_line, the arg determines what it will do."""
  604. if argv[0] == 'hello':
  605. print("Hello, world!")
  606. elif argv[0] == 'raise':
  607. try:
  608. raise Exception("oh noes!")
  609. except:
  610. raise ExceptionDuringRun(*sys.exc_info())
  611. elif argv[0] == 'internalraise':
  612. raise ValueError("coverage is broken")
  613. elif argv[0] == 'exit':
  614. sys.exit(23)
  615. else:
  616. raise AssertionError("Bad CoverageScriptStub: %r" % (argv,))
  617. return 0
  618. def setUp(self):
  619. super(CmdMainTest, self).setUp()
  620. self.old_CoverageScript = coverage.cmdline.CoverageScript
  621. coverage.cmdline.CoverageScript = self.CoverageScriptStub
  622. self.addCleanup(self.cleanup_coverage_script)
  623. def cleanup_coverage_script(self):
  624. """Restore CoverageScript when the test is done."""
  625. coverage.cmdline.CoverageScript = self.old_CoverageScript
  626. def test_normal(self):
  627. ret = coverage.cmdline.main(['hello'])
  628. self.assertEqual(ret, 0)
  629. self.assertEqual(self.stdout(), "Hello, world!\n")
  630. def test_raise(self):
  631. ret = coverage.cmdline.main(['raise'])
  632. self.assertEqual(ret, 1)
  633. self.assertEqual(self.stdout(), "")
  634. err = self.stderr().split('\n')
  635. self.assertEqual(err[0], 'Traceback (most recent call last):')
  636. self.assertEqual(err[-3], ' raise Exception("oh noes!")')
  637. self.assertEqual(err[-2], 'Exception: oh noes!')
  638. def test_internalraise(self):
  639. with self.assertRaisesRegex(ValueError, "coverage is broken"):
  640. coverage.cmdline.main(['internalraise'])
  641. def test_exit(self):
  642. ret = coverage.cmdline.main(['exit'])
  643. self.assertEqual(ret, 23)