2024-04-26 18:23:13 发布
网友
我的单元测试文件中有很多单元测试。但是,当从命令行运行单元测试时,我只想跳过其中一个测试。我知道如何总是跳过它(@unittest.skip),但我只想在从命令行运行单元测试文件时跳过它。这可能吗
@unittest.skip
大概是这样的:
test_all_my_tests.py -exclude test_number_five()
谢谢
好问题。 一种想法是命令带有参数,并在参数中指定要跳过哪些测试。 然后在脚本中解析传递的参数并相应地调用测试
您的输入如下所示: test_all_my_tests.py-排除5
在python脚本中,它将检查“-exclude”参数,并接受以下参数
祝你好运
您可以查看@unittest.skipIf(),甚至实现自己的skip-decorator:
@unittest.skipIf()
下面是一个工作示例,我在其中实现了一个自定义装饰器
def skipIfOverCounter(obj):
此装饰器附加到以下所有测试:
@skipIfOverCounter def test_upper(self):
装饰程序递增一个计数,并将其与控制台参数进行比较
实施了3个单元测试:
我称之为python .\unittests.py 0
python .\unittests.py 0
Skipped test 0 Ran 'test_isupper' Ran 'test_split'
参数为1时:python .\unittests.py 1
python .\unittests.py 1
Skipped test 1 Ran 'test_split' Ran 'test_upper'
跳过最后一个测试:python .\unittests.py 2
python .\unittests.py 2
Skipped test 2 Ran 'test_isupper' Ran 'test_upper'
import sys import unittest SKIP_INDEX = 0 COUNTER = 0 if len(sys.argv) > 1: SKIP_INDEX = int(sys.argv.pop()) def skipIfOverCounter(obj): global COUNTER global SKIP_INDEX if SKIP_INDEX == COUNTER: print(f"Skipped test {COUNTER}") COUNTER = COUNTER + 1 return unittest.skip("Skipped test") COUNTER = COUNTER + 1 return obj class TestStringMethods(unittest.TestCase): @skipIfOverCounter def test_upper(self): print("Ran 'test_upper'") self.assertEqual('foo'.upper(), 'FOO') @skipIfOverCounter def test_isupper(self): print("Ran 'test_isupper'") self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) @skipIfOverCounter def test_split(self): print("Ran 'test_split'") 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) if __name__ == '__main__': unittest.main()
您甚至可以通过调整decorator使其仅执行前两个测试或类似的内容来扩展此功能
好问题。 一种想法是命令带有参数,并在参数中指定要跳过哪些测试。 然后在脚本中解析传递的参数并相应地调用测试
您的输入如下所示: test_all_my_tests.py-排除5
在python脚本中,它将检查“-exclude”参数,并接受以下参数
祝你好运
您可以查看
@unittest.skipIf()
,甚至实现自己的skip-decorator:范例
下面是一个工作示例,我在其中实现了一个自定义装饰器
此装饰器附加到以下所有测试:
装饰程序递增一个计数,并将其与控制台参数进行比较
输出
实施了3个单元测试:
我称之为
python .\unittests.py 0
参数为1时:
python .\unittests.py 1
跳过最后一个测试:
python .\unittests.py 2
全工作样品
您甚至可以通过调整decorator使其仅执行前两个测试或类似的内容来扩展此功能
相关问题 更多 >
编程相关推荐