gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:27:32 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com