【问题标题】:Run unittest.main() from a python invoke task从 python 调用任务运行 unittest.main()
【发布时间】:2018-10-19 07:22:37
【问题描述】:

我正在尝试通过 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()

tasks.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 中运行良好,但是当我使用调用时会中断。 我怎样才能让它发挥作用,或者我接下来应该去哪里?

【问题讨论】:

    标签: python python-unittest pyinvoke


    【解决方案1】:

    您遇到的问题是unittest.main() 使用调用您的程序的命令行参数来确定要运行哪些测试。由于您的程序以inv tests 执行,因此程序的第一个参数是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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多