test_plugins.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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 plugins."""
  4. import os.path
  5. import coverage
  6. from coverage import env
  7. from coverage.backward import StringIO
  8. from coverage.control import Plugins
  9. from coverage.misc import CoverageException
  10. import coverage.plugin
  11. from tests.coveragetest import CoverageTest
  12. from tests.helpers import CheckUniqueFilenames
  13. class FakeConfig(object):
  14. """A fake config for use in tests."""
  15. def __init__(self, plugin, options):
  16. self.plugin = plugin
  17. self.options = options
  18. self.asked_for = []
  19. def get_plugin_options(self, module):
  20. """Just return the options for `module` if this is the right module."""
  21. self.asked_for.append(module)
  22. if module == self.plugin:
  23. return self.options
  24. else:
  25. return {}
  26. class LoadPluginsTest(CoverageTest):
  27. """Test Plugins.load_plugins directly."""
  28. def test_implicit_boolean(self):
  29. self.make_file("plugin1.py", """\
  30. from coverage import CoveragePlugin
  31. class Plugin(CoveragePlugin):
  32. pass
  33. def coverage_init(reg, options):
  34. reg.add_file_tracer(Plugin())
  35. """)
  36. config = FakeConfig("plugin1", {})
  37. plugins = Plugins.load_plugins([], config)
  38. self.assertFalse(plugins)
  39. plugins = Plugins.load_plugins(["plugin1"], config)
  40. self.assertTrue(plugins)
  41. def test_importing_and_configuring(self):
  42. self.make_file("plugin1.py", """\
  43. from coverage import CoveragePlugin
  44. class Plugin(CoveragePlugin):
  45. def __init__(self, options):
  46. self.options = options
  47. self.this_is = "me"
  48. def coverage_init(reg, options):
  49. reg.add_file_tracer(Plugin(options))
  50. """)
  51. config = FakeConfig("plugin1", {'a': 'hello'})
  52. plugins = list(Plugins.load_plugins(["plugin1"], config))
  53. self.assertEqual(len(plugins), 1)
  54. self.assertEqual(plugins[0].this_is, "me")
  55. self.assertEqual(plugins[0].options, {'a': 'hello'})
  56. self.assertEqual(config.asked_for, ['plugin1'])
  57. def test_importing_and_configuring_more_than_one(self):
  58. self.make_file("plugin1.py", """\
  59. from coverage import CoveragePlugin
  60. class Plugin(CoveragePlugin):
  61. def __init__(self, options):
  62. self.options = options
  63. self.this_is = "me"
  64. def coverage_init(reg, options):
  65. reg.add_file_tracer(Plugin(options))
  66. """)
  67. self.make_file("plugin2.py", """\
  68. from coverage import CoveragePlugin
  69. class Plugin(CoveragePlugin):
  70. def __init__(self, options):
  71. self.options = options
  72. def coverage_init(reg, options):
  73. reg.add_file_tracer(Plugin(options))
  74. """)
  75. config = FakeConfig("plugin1", {'a': 'hello'})
  76. plugins = list(Plugins.load_plugins(["plugin1", "plugin2"], config))
  77. self.assertEqual(len(plugins), 2)
  78. self.assertEqual(plugins[0].this_is, "me")
  79. self.assertEqual(plugins[0].options, {'a': 'hello'})
  80. self.assertEqual(plugins[1].options, {})
  81. self.assertEqual(config.asked_for, ['plugin1', 'plugin2'])
  82. # The order matters...
  83. config = FakeConfig("plugin1", {'a': 'second'})
  84. plugins = list(Plugins.load_plugins(["plugin2", "plugin1"], config))
  85. self.assertEqual(len(plugins), 2)
  86. self.assertEqual(plugins[0].options, {})
  87. self.assertEqual(plugins[1].this_is, "me")
  88. self.assertEqual(plugins[1].options, {'a': 'second'})
  89. def test_cant_import(self):
  90. with self.assertRaises(ImportError):
  91. _ = Plugins.load_plugins(["plugin_not_there"], None)
  92. def test_plugin_must_define_coverage_init(self):
  93. self.make_file("no_plugin.py", """\
  94. from coverage import CoveragePlugin
  95. Nothing = 0
  96. """)
  97. msg_pat = "Plugin module 'no_plugin' didn't define a coverage_init function"
  98. with self.assertRaisesRegex(CoverageException, msg_pat):
  99. list(Plugins.load_plugins(["no_plugin"], None))
  100. class PluginTest(CoverageTest):
  101. """Test plugins through the Coverage class."""
  102. def test_plugin_imported(self):
  103. # Prove that a plugin will be imported.
  104. self.make_file("my_plugin.py", """\
  105. from coverage import CoveragePlugin
  106. class Plugin(CoveragePlugin):
  107. pass
  108. def coverage_init(reg, options):
  109. reg.add_noop(Plugin())
  110. with open("evidence.out", "w") as f:
  111. f.write("we are here!")
  112. """)
  113. self.assert_doesnt_exist("evidence.out")
  114. cov = coverage.Coverage()
  115. cov.set_option("run:plugins", ["my_plugin"])
  116. cov.start()
  117. cov.stop() # pragma: nested
  118. with open("evidence.out") as f:
  119. self.assertEqual(f.read(), "we are here!")
  120. def test_missing_plugin_raises_import_error(self):
  121. # Prove that a missing plugin will raise an ImportError.
  122. with self.assertRaises(ImportError):
  123. cov = coverage.Coverage()
  124. cov.set_option("run:plugins", ["does_not_exist_woijwoicweo"])
  125. cov.start()
  126. cov.stop()
  127. def test_bad_plugin_isnt_hidden(self):
  128. # Prove that a plugin with an error in it will raise the error.
  129. self.make_file("plugin_over_zero.py", """\
  130. 1/0
  131. """)
  132. with self.assertRaises(ZeroDivisionError):
  133. cov = coverage.Coverage()
  134. cov.set_option("run:plugins", ["plugin_over_zero"])
  135. cov.start()
  136. cov.stop()
  137. def test_plugin_sys_info(self):
  138. self.make_file("plugin_sys_info.py", """\
  139. import coverage
  140. class Plugin(coverage.CoveragePlugin):
  141. def sys_info(self):
  142. return [("hello", "world")]
  143. def coverage_init(reg, options):
  144. reg.add_noop(Plugin())
  145. """)
  146. debug_out = StringIO()
  147. cov = coverage.Coverage(debug=["sys"])
  148. cov._debug_file = debug_out
  149. cov.set_option("run:plugins", ["plugin_sys_info"])
  150. cov.load()
  151. out_lines = debug_out.getvalue().splitlines()
  152. expected_end = [
  153. "-- sys: plugin_sys_info.Plugin -------------------------------",
  154. " hello: world",
  155. "-- end -------------------------------------------------------",
  156. ]
  157. self.assertEqual(expected_end, out_lines[-len(expected_end):])
  158. def test_plugin_with_no_sys_info(self):
  159. self.make_file("plugin_no_sys_info.py", """\
  160. import coverage
  161. class Plugin(coverage.CoveragePlugin):
  162. pass
  163. def coverage_init(reg, options):
  164. reg.add_noop(Plugin())
  165. """)
  166. debug_out = StringIO()
  167. cov = coverage.Coverage(debug=["sys"])
  168. cov._debug_file = debug_out
  169. cov.set_option("run:plugins", ["plugin_no_sys_info"])
  170. cov.load()
  171. out_lines = debug_out.getvalue().splitlines()
  172. expected_end = [
  173. "-- sys: plugin_no_sys_info.Plugin ----------------------------",
  174. "-- end -------------------------------------------------------",
  175. ]
  176. self.assertEqual(expected_end, out_lines[-len(expected_end):])
  177. def test_local_files_are_importable(self):
  178. self.make_file("importing_plugin.py", """\
  179. from coverage import CoveragePlugin
  180. import local_module
  181. class MyPlugin(CoveragePlugin):
  182. pass
  183. def coverage_init(reg, options):
  184. reg.add_noop(MyPlugin())
  185. """)
  186. self.make_file("local_module.py", "CONST = 1")
  187. self.make_file(".coveragerc", """\
  188. [run]
  189. plugins = importing_plugin
  190. """)
  191. self.make_file("main_file.py", "print('MAIN')")
  192. out = self.run_command("coverage run main_file.py")
  193. self.assertEqual(out, "MAIN\n")
  194. out = self.run_command("coverage html")
  195. self.assertEqual(out, "")
  196. class PluginWarningOnPyTracer(CoverageTest):
  197. """Test that we get a controlled exception with plugins on PyTracer."""
  198. def test_exception_if_plugins_on_pytracer(self):
  199. if env.C_TRACER:
  200. self.skipTest("This test is only about PyTracer.")
  201. self.make_file("simple.py", """a = 1""")
  202. cov = coverage.Coverage()
  203. cov.set_option("run:plugins", ["tests.plugin1"])
  204. expected_warnings = [
  205. r"Plugin file tracers \(tests.plugin1.Plugin\) aren't supported with PyTracer",
  206. ]
  207. with self.assert_warnings(cov, expected_warnings):
  208. self.start_import_stop(cov, "simple")
  209. class FileTracerTest(CoverageTest):
  210. """Tests of plugins that implement file_tracer."""
  211. def setUp(self):
  212. super(FileTracerTest, self).setUp()
  213. if not env.C_TRACER:
  214. self.skipTest("Plugins are only supported with the C tracer.")
  215. class GoodPluginTest(FileTracerTest):
  216. """Tests of plugin happy paths."""
  217. def test_plugin1(self):
  218. self.make_file("simple.py", """\
  219. import try_xyz
  220. a = 1
  221. b = 2
  222. """)
  223. self.make_file("try_xyz.py", """\
  224. c = 3
  225. d = 4
  226. """)
  227. cov = coverage.Coverage()
  228. CheckUniqueFilenames.hook(cov, '_should_trace')
  229. CheckUniqueFilenames.hook(cov, '_check_include_omit_etc')
  230. cov.set_option("run:plugins", ["tests.plugin1"])
  231. # Import the Python file, executing it.
  232. self.start_import_stop(cov, "simple")
  233. _, statements, missing, _ = cov.analysis("simple.py")
  234. self.assertEqual(statements, [1, 2, 3])
  235. self.assertEqual(missing, [])
  236. zzfile = os.path.abspath(os.path.join("/src", "try_ABC.zz"))
  237. _, statements, _, _ = cov.analysis(zzfile)
  238. self.assertEqual(statements, [105, 106, 107, 205, 206, 207])
  239. def make_render_and_caller(self):
  240. """Make the render.py and caller.py files we need."""
  241. # plugin2 emulates a dynamic tracing plugin: the caller's locals
  242. # are examined to determine the source file and line number.
  243. # The plugin is in tests/plugin2.py.
  244. self.make_file("render.py", """\
  245. def render(filename, linenum):
  246. # This function emulates a template renderer. The plugin
  247. # will examine the `filename` and `linenum` locals to
  248. # determine the source file and line number.
  249. fiddle_around = 1 # not used, just chaff.
  250. return "[{0} @ {1}]".format(filename, linenum)
  251. def helper(x):
  252. # This function is here just to show that not all code in
  253. # this file will be part of the dynamic tracing.
  254. return x+1
  255. """)
  256. self.make_file("caller.py", """\
  257. import sys
  258. from render import helper, render
  259. assert render("foo_7.html", 4) == "[foo_7.html @ 4]"
  260. # Render foo_7.html again to try the CheckUniqueFilenames asserts.
  261. render("foo_7.html", 4)
  262. assert helper(42) == 43
  263. assert render("bar_4.html", 2) == "[bar_4.html @ 2]"
  264. assert helper(76) == 77
  265. # quux_5.html will be omitted from the results.
  266. assert render("quux_5.html", 3) == "[quux_5.html @ 3]"
  267. # In Python 2, either kind of string should be OK.
  268. if sys.version_info[0] == 2:
  269. assert render(u"uni_3.html", 2) == "[uni_3.html @ 2]"
  270. """)
  271. # will try to read the actual source files, so make some
  272. # source files.
  273. def lines(n):
  274. """Make a string with n lines of text."""
  275. return "".join("line %d\n" % i for i in range(n))
  276. self.make_file("bar_4.html", lines(4))
  277. self.make_file("foo_7.html", lines(7))
  278. def test_plugin2(self):
  279. self.make_render_and_caller()
  280. cov = coverage.Coverage(omit=["*quux*"])
  281. CheckUniqueFilenames.hook(cov, '_should_trace')
  282. CheckUniqueFilenames.hook(cov, '_check_include_omit_etc')
  283. cov.set_option("run:plugins", ["tests.plugin2"])
  284. self.start_import_stop(cov, "caller")
  285. # The way plugin2 works, a file named foo_7.html will be claimed to
  286. # have 7 lines in it. If render() was called with line number 4,
  287. # then the plugin will claim that lines 4 and 5 were executed.
  288. _, statements, missing, _ = cov.analysis("foo_7.html")
  289. self.assertEqual(statements, [1, 2, 3, 4, 5, 6, 7])
  290. self.assertEqual(missing, [1, 2, 3, 6, 7])
  291. self.assertIn("foo_7.html", cov.data.line_counts())
  292. _, statements, missing, _ = cov.analysis("bar_4.html")
  293. self.assertEqual(statements, [1, 2, 3, 4])
  294. self.assertEqual(missing, [1, 4])
  295. self.assertIn("bar_4.html", cov.data.line_counts())
  296. self.assertNotIn("quux_5.html", cov.data.line_counts())
  297. if env.PY2:
  298. _, statements, missing, _ = cov.analysis("uni_3.html")
  299. self.assertEqual(statements, [1, 2, 3])
  300. self.assertEqual(missing, [1])
  301. self.assertIn("uni_3.html", cov.data.line_counts())
  302. def test_plugin2_with_branch(self):
  303. self.make_render_and_caller()
  304. cov = coverage.Coverage(branch=True, omit=["*quux*"])
  305. CheckUniqueFilenames.hook(cov, '_should_trace')
  306. CheckUniqueFilenames.hook(cov, '_check_include_omit_etc')
  307. cov.set_option("run:plugins", ["tests.plugin2"])
  308. self.start_import_stop(cov, "caller")
  309. # The way plugin2 works, a file named foo_7.html will be claimed to
  310. # have 7 lines in it. If render() was called with line number 4,
  311. # then the plugin will claim that lines 4 and 5 were executed.
  312. analysis = cov._analyze("foo_7.html")
  313. self.assertEqual(analysis.statements, set([1, 2, 3, 4, 5, 6, 7]))
  314. # Plugins don't do branch coverage yet.
  315. self.assertEqual(analysis.has_arcs(), True)
  316. self.assertEqual(analysis.arc_possibilities(), [])
  317. self.assertEqual(analysis.missing, set([1, 2, 3, 6, 7]))
  318. def test_plugin2_with_text_report(self):
  319. self.make_render_and_caller()
  320. cov = coverage.Coverage(branch=True, omit=["*quux*"])
  321. cov.set_option("run:plugins", ["tests.plugin2"])
  322. self.start_import_stop(cov, "caller")
  323. repout = StringIO()
  324. total = cov.report(file=repout, include=["*.html"], omit=["uni*.html"], show_missing=True)
  325. report = repout.getvalue().splitlines()
  326. expected = [
  327. 'Name Stmts Miss Branch BrPart Cover Missing',
  328. '--------------------------------------------------------',
  329. 'bar_4.html 4 2 0 0 50% 1, 4',
  330. 'foo_7.html 7 5 0 0 29% 1-3, 6-7',
  331. '--------------------------------------------------------',
  332. 'TOTAL 11 7 0 0 36%',
  333. ]
  334. self.assertEqual(report, expected)
  335. self.assertAlmostEqual(total, 36.36, places=2)
  336. def test_plugin2_with_html_report(self):
  337. self.make_render_and_caller()
  338. cov = coverage.Coverage(branch=True, omit=["*quux*"])
  339. cov.set_option("run:plugins", ["tests.plugin2"])
  340. self.start_import_stop(cov, "caller")
  341. total = cov.html_report(include=["*.html"], omit=["uni*.html"])
  342. self.assertAlmostEqual(total, 36.36, places=2)
  343. self.assert_exists("htmlcov/index.html")
  344. self.assert_exists("htmlcov/bar_4_html.html")
  345. self.assert_exists("htmlcov/foo_7_html.html")
  346. def test_plugin2_with_xml_report(self):
  347. self.make_render_and_caller()
  348. cov = coverage.Coverage(branch=True, omit=["*quux*"])
  349. cov.set_option("run:plugins", ["tests.plugin2"])
  350. self.start_import_stop(cov, "caller")
  351. total = cov.xml_report(include=["*.html"], omit=["uni*.html"])
  352. self.assertAlmostEqual(total, 36.36, places=2)
  353. with open("coverage.xml") as fxml:
  354. xml = fxml.read()
  355. for snip in [
  356. 'filename="bar_4.html" line-rate="0.5" name="bar_4.html"',
  357. 'filename="foo_7.html" line-rate="0.2857" name="foo_7.html"',
  358. ]:
  359. self.assertIn(snip, xml)
  360. def test_defer_to_python(self):
  361. # A plugin that measures, but then wants built-in python reporting.
  362. self.make_file("fairly_odd_plugin.py", """\
  363. # A plugin that claims all the odd lines are executed, and none of
  364. # the even lines, and then punts reporting off to the built-in
  365. # Python reporting.
  366. import coverage.plugin
  367. class Plugin(coverage.CoveragePlugin):
  368. def file_tracer(self, filename):
  369. return OddTracer(filename)
  370. def file_reporter(self, filename):
  371. return "python"
  372. class OddTracer(coverage.plugin.FileTracer):
  373. def __init__(self, filename):
  374. self.filename = filename
  375. def source_filename(self):
  376. return self.filename
  377. def line_number_range(self, frame):
  378. lineno = frame.f_lineno
  379. if lineno % 2:
  380. return (lineno, lineno)
  381. else:
  382. return (-1, -1)
  383. def coverage_init(reg, options):
  384. reg.add_file_tracer(Plugin())
  385. """)
  386. self.make_file("unsuspecting.py", """\
  387. a = 1
  388. b = 2
  389. c = 3
  390. d = 4
  391. e = 5
  392. f = 6
  393. """)
  394. cov = coverage.Coverage(include=["unsuspecting.py"])
  395. cov.set_option("run:plugins", ["fairly_odd_plugin"])
  396. self.start_import_stop(cov, "unsuspecting")
  397. repout = StringIO()
  398. total = cov.report(file=repout, show_missing=True)
  399. report = repout.getvalue().splitlines()
  400. expected = [
  401. 'Name Stmts Miss Cover Missing',
  402. '-----------------------------------------------',
  403. 'unsuspecting.py 6 3 50% 2, 4, 6',
  404. ]
  405. self.assertEqual(report, expected)
  406. self.assertEqual(total, 50)
  407. class BadPluginTest(FileTracerTest):
  408. """Test error handling around plugins."""
  409. def run_plugin(self, module_name):
  410. """Run a plugin with the given module_name.
  411. Uses a few fixed Python files.
  412. Returns the Coverage object.
  413. """
  414. self.make_file("simple.py", """\
  415. import other, another
  416. a = other.f(2)
  417. b = other.f(3)
  418. c = another.g(4)
  419. d = another.g(5)
  420. """)
  421. # The names of these files are important: some plugins apply themselves
  422. # to "*other.py".
  423. self.make_file("other.py", """\
  424. def f(x):
  425. return x+1
  426. """)
  427. self.make_file("another.py", """\
  428. def g(x):
  429. return x-1
  430. """)
  431. cov = coverage.Coverage()
  432. cov.set_option("run:plugins", [module_name])
  433. self.start_import_stop(cov, "simple")
  434. return cov
  435. def run_bad_plugin(self, module_name, plugin_name, our_error=True, excmsg=None):
  436. """Run a file, and see that the plugin failed.
  437. `module_name` and `plugin_name` is the module and name of the plugin to
  438. use.
  439. `our_error` is True if the error reported to the user will be an
  440. explicit error in our test code, marked with an '# Oh noes!' comment.
  441. `excmsg`, if provided, is text that should appear in the stderr.
  442. The plugin will be disabled, and we check that a warning is output
  443. explaining why.
  444. """
  445. self.run_plugin(module_name)
  446. stderr = self.stderr()
  447. print(stderr) # for diagnosing test failures.
  448. if our_error:
  449. errors = stderr.count("# Oh noes!")
  450. # The exception we're causing should only appear once.
  451. self.assertEqual(errors, 1)
  452. # There should be a warning explaining what's happening, but only one.
  453. # The message can be in two forms:
  454. # Disabling plugin '...' due to previous exception
  455. # or:
  456. # Disabling plugin '...' due to an exception:
  457. msg = "Disabling plugin '%s.%s' due to " % (module_name, plugin_name)
  458. warnings = stderr.count(msg)
  459. self.assertEqual(warnings, 1)
  460. if excmsg:
  461. self.assertIn(excmsg, stderr)
  462. def test_file_tracer_has_no_file_tracer_method(self):
  463. self.make_file("bad_plugin.py", """\
  464. class Plugin(object):
  465. pass
  466. def coverage_init(reg, options):
  467. reg.add_file_tracer(Plugin())
  468. """)
  469. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)
  470. def test_file_tracer_has_inherited_sourcefilename_method(self):
  471. self.make_file("bad_plugin.py", """\
  472. import coverage
  473. class Plugin(coverage.CoveragePlugin):
  474. def file_tracer(self, filename):
  475. # Just grab everything.
  476. return FileTracer()
  477. class FileTracer(coverage.FileTracer):
  478. pass
  479. def coverage_init(reg, options):
  480. reg.add_file_tracer(Plugin())
  481. """)
  482. self.run_bad_plugin(
  483. "bad_plugin", "Plugin", our_error=False,
  484. excmsg="Class 'bad_plugin.FileTracer' needs to implement source_filename()",
  485. )
  486. def test_plugin_has_inherited_filereporter_method(self):
  487. self.make_file("bad_plugin.py", """\
  488. import coverage
  489. class Plugin(coverage.CoveragePlugin):
  490. def file_tracer(self, filename):
  491. # Just grab everything.
  492. return FileTracer()
  493. class FileTracer(coverage.FileTracer):
  494. def source_filename(self):
  495. return "foo.xxx"
  496. def coverage_init(reg, options):
  497. reg.add_file_tracer(Plugin())
  498. """)
  499. cov = self.run_plugin("bad_plugin")
  500. expected_msg = "Plugin 'bad_plugin.Plugin' needs to implement file_reporter()"
  501. with self.assertRaisesRegex(NotImplementedError, expected_msg):
  502. cov.report()
  503. def test_file_tracer_fails(self):
  504. self.make_file("bad_plugin.py", """\
  505. import coverage.plugin
  506. class Plugin(coverage.plugin.CoveragePlugin):
  507. def file_tracer(self, filename):
  508. 17/0 # Oh noes!
  509. def coverage_init(reg, options):
  510. reg.add_file_tracer(Plugin())
  511. """)
  512. self.run_bad_plugin("bad_plugin", "Plugin")
  513. def test_file_tracer_returns_wrong(self):
  514. self.make_file("bad_plugin.py", """\
  515. import coverage.plugin
  516. class Plugin(coverage.plugin.CoveragePlugin):
  517. def file_tracer(self, filename):
  518. return 3.14159
  519. def coverage_init(reg, options):
  520. reg.add_file_tracer(Plugin())
  521. """)
  522. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)
  523. def test_has_dynamic_source_filename_fails(self):
  524. self.make_file("bad_plugin.py", """\
  525. import coverage.plugin
  526. class Plugin(coverage.plugin.CoveragePlugin):
  527. def file_tracer(self, filename):
  528. return BadFileTracer()
  529. class BadFileTracer(coverage.plugin.FileTracer):
  530. def has_dynamic_source_filename(self):
  531. 23/0 # Oh noes!
  532. def coverage_init(reg, options):
  533. reg.add_file_tracer(Plugin())
  534. """)
  535. self.run_bad_plugin("bad_plugin", "Plugin")
  536. def test_source_filename_fails(self):
  537. self.make_file("bad_plugin.py", """\
  538. import coverage.plugin
  539. class Plugin(coverage.plugin.CoveragePlugin):
  540. def file_tracer(self, filename):
  541. return BadFileTracer()
  542. class BadFileTracer(coverage.plugin.FileTracer):
  543. def source_filename(self):
  544. 42/0 # Oh noes!
  545. def coverage_init(reg, options):
  546. reg.add_file_tracer(Plugin())
  547. """)
  548. self.run_bad_plugin("bad_plugin", "Plugin")
  549. def test_source_filename_returns_wrong(self):
  550. self.make_file("bad_plugin.py", """\
  551. import coverage.plugin
  552. class Plugin(coverage.plugin.CoveragePlugin):
  553. def file_tracer(self, filename):
  554. return BadFileTracer()
  555. class BadFileTracer(coverage.plugin.FileTracer):
  556. def source_filename(self):
  557. return 17.3
  558. def coverage_init(reg, options):
  559. reg.add_file_tracer(Plugin())
  560. """)
  561. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)
  562. def test_dynamic_source_filename_fails(self):
  563. self.make_file("bad_plugin.py", """\
  564. import coverage.plugin
  565. class Plugin(coverage.plugin.CoveragePlugin):
  566. def file_tracer(self, filename):
  567. if filename.endswith("other.py"):
  568. return BadFileTracer()
  569. class BadFileTracer(coverage.plugin.FileTracer):
  570. def has_dynamic_source_filename(self):
  571. return True
  572. def dynamic_source_filename(self, filename, frame):
  573. 101/0 # Oh noes!
  574. def coverage_init(reg, options):
  575. reg.add_file_tracer(Plugin())
  576. """)
  577. self.run_bad_plugin("bad_plugin", "Plugin")
  578. def test_line_number_range_returns_non_tuple(self):
  579. self.make_file("bad_plugin.py", """\
  580. import coverage.plugin
  581. class Plugin(coverage.plugin.CoveragePlugin):
  582. def file_tracer(self, filename):
  583. if filename.endswith("other.py"):
  584. return BadFileTracer()
  585. class BadFileTracer(coverage.plugin.FileTracer):
  586. def source_filename(self):
  587. return "something.foo"
  588. def line_number_range(self, frame):
  589. return 42.23
  590. def coverage_init(reg, options):
  591. reg.add_file_tracer(Plugin())
  592. """)
  593. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)
  594. def test_line_number_range_returns_triple(self):
  595. self.make_file("bad_plugin.py", """\
  596. import coverage.plugin
  597. class Plugin(coverage.plugin.CoveragePlugin):
  598. def file_tracer(self, filename):
  599. if filename.endswith("other.py"):
  600. return BadFileTracer()
  601. class BadFileTracer(coverage.plugin.FileTracer):
  602. def source_filename(self):
  603. return "something.foo"
  604. def line_number_range(self, frame):
  605. return (1, 2, 3)
  606. def coverage_init(reg, options):
  607. reg.add_file_tracer(Plugin())
  608. """)
  609. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)
  610. def test_line_number_range_returns_pair_of_strings(self):
  611. self.make_file("bad_plugin.py", """\
  612. import coverage.plugin
  613. class Plugin(coverage.plugin.CoveragePlugin):
  614. def file_tracer(self, filename):
  615. if filename.endswith("other.py"):
  616. return BadFileTracer()
  617. class BadFileTracer(coverage.plugin.FileTracer):
  618. def source_filename(self):
  619. return "something.foo"
  620. def line_number_range(self, frame):
  621. return ("5", "7")
  622. def coverage_init(reg, options):
  623. reg.add_file_tracer(Plugin())
  624. """)
  625. self.run_bad_plugin("bad_plugin", "Plugin", our_error=False)