python - 在模块中编写单元测试的正确方法?

标签 python unit-testing module

我想为主文件 calc.py 编写测试,并在模块文件 MyTests.py 中进行单元测试。

这是我的主要 python 文件,calc.py:

import myTests

def first(x):
    return x**2

def second(x):
    return x**3

def main():
    one = first(5)
    two = second(5)

if __name__ == "__main__":
    main()
    try:
        myTests.unittest.main()
    except SystemExit:
        pass

这是我的 MyTests.py 文件:

import unittest
import calc

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.testInput = 10

    def test_first(self):
        output = calc.first(self.testInput)
        correct = 100
        assert(output == correct)

    def test_second(self):
        output = calc.second(self.testInput)
        correct = 1000
        assert(output == correct)

当我运行 calc.py 时,我得到以下输出:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

为什么单元测试会打印“Ran 0 test”?
在模块中编写单元测试的正确方法是什么?

最佳答案

unittests.main() 在当前模块中查找 TestCase 实例。你的模块没有这样的测试用例;它只有一个 myTests 全局变量。

最佳实践是自行运行测试。。将 __main__ 部分添加到 myTests.py 文件中:

import unittest
import calc

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.testInput = 10

    def test_first(self):
        output = calc.first(self.testInput)
        correct = 100
        assert(output == correct)

    def test_second(self):
        output = calc.second(self.testInput)
        correct = 1000
        assert(output == correct)

if __name__ == '__main__':
    unittest.main()

并运行python myTests.py

或者,将导入的 myTests 模块传递到 unittest.main() 中。您可能希望将 import myTests向下移动到 __main__ 中,因为您也有循环导入。对于您的情况来说,这很好,myTests 不会在测试用例之外使用 calc 中的任何全局变量,但最好明确说明这一点。

if __name__ == "__main__":
    main()
    try:
        import myTests
        myTests.unittest.main(myTests)
    except SystemExit:
        pass

关于python - 在模块中编写单元测试的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452340/

相关文章:

python - 如何在 python 中生成声音输出..?

python - 使用 python 通过网络抓取来提取表

python - 我试图从 clrs 书中实现队列,但它没有按预期工作?我的代码有什么问题

java - 有什么办法可以代替动态方法吗?

javascript - 配置一个从单元测试中的延迟返回 promise 的 stub 工厂?

python - 即使没有必要,我是否应该始终使用 'else:'?

unit-testing - 使用协程进行测试时检测到使用不同的调度程序

python - 查找项目中所有python包

c++ - 将声明和实现压缩到一个 HPP 文件中

python - 在没有 Internet 访问的情况下安装 Python 模块