Skip to main content
 首页 » 编程设计

python之Django + django-nose 的 PyCharm 代码覆盖率

2025年04月02日31birdshome

当尝试在 PyCharm 中的 Django + django-nose 下运行覆盖率测试时,我似乎无法让覆盖率报告正常工作。我试过使用捆绑的 coverage.py 和不使用。没有捆绑的 coverage.py 我看到:

Traceback (most recent call last): 
  File "/Applications/PyCharm.app/Contents/helpers/coverage_runner/run_coverage.py", line 44, in <module> 
    main() 
  File "/Users/dane/.virtualenvs/dhp/lib/python3.5/site-packages/coverage/cmdline.py", line 741, in main 
    status = CoverageScript().command_line(argv) 
  File "/Users/dane/.virtualenvs/dhp/lib/python3.5/site-packages/coverage/cmdline.py", line 481, in command_line 
    return self.do_run(options, args) 
  File "/Users/dane/.virtualenvs/dhp/lib/python3.5/site-packages/coverage/cmdline.py", line 625, in do_run 
    self.coverage.stop() 
  File "/Users/dane/.virtualenvs/dhp/lib/python3.5/site-packages/coverage/control.py", line 692, in stop 
    self.collector.stop() 
  File "/Users/dane/.virtualenvs/dhp/lib/python3.5/site-packages/coverage/collector.py", line 277, in stop 
    "Expected current collector to be %r, but it's %r" % (self, self._collectors[-1]) 
AssertionError: Expected current collector to be <Collector at 0x10e0cfbe0: CTracer>, but it's <Collector at 0x10fa368d0: CTracer> 

有了它,我看到了:

Traceback (most recent call last): 
  File "/Applications/PyCharm.app/Contents/helpers/coverage_runner/run_coverage.py", line 44, in <module> 
    main() 
  File "/Applications/PyCharm.app/Contents/helpers/coveragepy/coverage/cmdline.py", line 721, in main 
    status = CoverageScript().command_line(argv) 
  File "/Applications/PyCharm.app/Contents/helpers/coveragepy/coverage/cmdline.py", line 438, in command_line 
    self.do_execute(options, args) 
  File "/Applications/PyCharm.app/Contents/helpers/coveragepy/coverage/cmdline.py", line 580, in do_execute 
    self.coverage.stop() 
  File "/Applications/PyCharm.app/Contents/helpers/coveragepy/coverage/control.py", line 410, in stop 
    self.collector.stop() 
  File "/Applications/PyCharm.app/Contents/helpers/coveragepy/coverage/collector.py", line 294, in stop 
    assert self._collectors[-1] is self 
AssertionError 

我的测试和覆盖率报告通过命令行正常工作,即:

$ python manage.py test 

我已经使用 Django 测试模板设置了一个运行配置,据我所知,我没有做任何特别或不寻常的事情。有没有人遇到这个并解决了它?覆盖整合将非常有用!

更新

此问题已通过 JetBrains 打开 here .

请您参考如下方法:

我假设您的配置中有类似的东西:

NOSE_ARGS = [ 
    '--with-coverage', 
    '--cover-package=foo,bar' 
] 

PyCharm 的覆盖范围在配置时会爆炸。我假设它正在运行两个覆盖实例,或者覆盖输出不是它预期解析的内容。无论哪种方式,您目前似乎都无法使用它。

目前的解决方案:

  • 删除 NOSE_ARGS 配置,如果您的任何自动化/持续集成工具需要它,请在命令行上使用覆盖选项运行它们:python manage.py test --with- coverage --cover-package=foo(我选择这个选项是因为 PyCharm 的好处)
  • 不要在 PyCharm 中使用覆盖

注意:我找到了遇到这个问题的其他人 here .