python - 从 python 调用任务运行 unittest.main()

标签 python python-unittest pyinvoke

我正在尝试通过Python Invoke library运行一些单元测试。 ,但我对 Python 的了解不够,所以无法这样做。

这是我的示例代码:

my_tests.py

import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

def main():
    unittest.main()

if __name__ == '__main__':
    main()

任务.py

from invoke import task

@task
def tests(ctx):
    main()

@task
def other_task(ctx):
    print("This is fine")

def main():
    import my_tests
    import unittest
    unittest.main(module='my_tests')

if __name__ == '__main__':
    main()

这就是我得到的:

C:\ittle_projects\invoke_unittest>python my_tests.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK

C:\ittle_projects\invoke_unittest>python tasks.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

C:\ittle_projects\invoke_unittest>inv tests
E
======================================================================
ERROR: tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module 'my_tests' has no attribute 'tests'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

测试从my_tests.py 和tasks.py 运行良好,但是当我使用invoke stuff 时会中断。 我怎样才能让它发挥作用,或者下一步应该去哪里?

最佳答案

您遇到的问题是 unittest.main() 使用调用程序时使用的命令行参数来确定要运行哪些测试。由于您的程序作为inv测试执行,因此程序的第一个参数是tests,因此unittest正在尝试为模块运行测试名称 tests 不存在。

您可以通过从 system arguments list 中弹出最后一个参数(tests)来解决这个问题。 :

import sys

from invoke import task

@task
def tests(ctx):
    # Pop "tests" off the end of the system arguments
    sys.argv.pop()
    main()

@task
def other_task(ctx):
    print("This is fine")

def main():
    import my_tests
    import unittest
    unittest.main(module='my_tests')

if __name__ == '__main__':
    main()

关于python - 从 python 调用任务运行 unittest.main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248892/

相关文章:

python - 命名元组与字典

python - 如何更改模拟对象的返回值?

python - 我如何让 pyinvoke 使用 python3?

python - 修改 Invoke 的 Config 类

python - 用平均值估算多列 NaN 值的最佳方法

Python:不完整的 URL 正则表达式输出

python - Magento 的 pyUnit 单元测试是个好主意吗?

python - Django 测试运行器在 Ubuntu 上的 virtualenv 中失败

Python Windows 服务到守护进程服务