如何将doctests与unittest的测试发现集成?

blu*_*e13 16 python doctest unit-testing code-coverage

我写了一个python脚本来自动为我做所有的测试,并生成一个HTML报告.前discover几天我发现了单元测试,它允许我在给定目录中运行所有单元测试而不明确地命名它们,我真的希望能够以相同的方式进行我的doctests,而不是必须明确地导入每个模块.

我在https://docs.python.org/2/library/doctest.html上找到了一些关于如何执行此操作的信息,但实际上并没有得到它.你可以帮助我使用discover我的doctests吗?

Python测试发现与doctests,coverage和parallelism是相关的,但仍然没有回答我的问题.

coverage_module

import coverage
import doctest
import unittest
import os

# import test_module 
import my_module

cov = coverage.Coverage()
cov.start()

# running doctest by explicity naming the module
doctest.testmod(my_module)

# running unittests by just specifying the folder to look into
testLoad = unittest.TestLoader()
testSuite = testLoad.discover(start_dir=os.getcwd())
runner = unittest.TextTestRunner()
runner.run(testSuite)

cov.stop()
cov.save()
cov.html_report()
print "tests completed"
Run Code Online (Sandbox Code Playgroud)

test_module

import unittest
import doctest

from my_module import My_Class


class My_Class_Tests(unittest.TestCase):
    def setUp(self):
        # setup variables

    def test_1(self):
        # test code

# The bit that should load up the doctests? What's loader, tests, and ignore though? 
# Is this in the right place?
def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(module_with_doctests))
    return tests

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

ffe*_*ast 7

让我们弄清楚那里发生了什么

1)unittest.discovery

它没有doctests的线索,因为doctests是一个不同的框架.所以unittest不应该发现开箱即用的doctests.这意味着你需要手工将它们粘在一起

2)doctest

它本质上是一个单独的框架,虽然它有一些粘合类可以将doctests转换为类似单元测试的TestCases. https://docs.python.org/2.7/library/doctest.html#doctest.DocTestSuite

3)发现

没想到discover你的意思,我想是的

python -m unittest discover
Run Code Online (Sandbox Code Playgroud)

如果没有,你正在谈论https://pypi.python.org/pypi/discover然后忘记它 - 它是早期版本的python的后端

4)该怎么做

要么load_tests在你的代码中散布很多钩子,如https://docs.python.org/2.7/library/doctest.html#unittest-api所述,要么编写一个方法来收集你在一个地方拥有的所有模块并转换它们到DocTestSuite [s] https://docs.python.org/2.7/library/doctest.html#doctest.DocTestSuite

但老实说,现在这两种方法都没有任何意义,因为它归结为:

$ py.test --doctest-modules
Run Code Online (Sandbox Code Playgroud)

要么

$ nosetests --with-doctest
Run Code Online (Sandbox Code Playgroud)

当然coverage,这些框架也提供了许多花里胡哨的东西,你可能会继续坚持使用unittest.TestCase,你甚至不需要创建一个coverage_module,所以我会深入研究其中一个而不是试图想出来你自己的解决方案

  • 我很遗憾没有提出使用标准库的解决方案,首先是原则上的,但最实际的是因为我在一个规范受限的环境中工作,无论好坏,我都不允许安装第三方库(甚至是 pytest !)。 (2认同)