Python—如何在运行时屏蔽在unittest中执行的类
请参阅下面的代码。我试图为我的项目实现一个测试套件Python—如何在运行时屏蔽在unittest中执行的类,python,python-unittest,django-unittest,Python,Python Unittest,Django Unittest,请参阅下面的代码。我试图为我的项目实现一个测试套件 import unittest class TestClass1(unittest.TestCase): def test_1_first(self): print("First test case") def test_2_second(self): print("Second test case") class TestClass2(unittest.TestCase): def
import unittest
class TestClass1(unittest.TestCase):
def test_1_first(self):
print("First test case")
def test_2_second(self):
print("Second test case")
class TestClass2(unittest.TestCase):
def test_3_third(self):
print("Third test case")
def test_4_fourth(self):
print("Fourth test case")
if __name__ == "__main__":
# val = 1 <-- getting from user
# if val == 1:
# Execute test cases in TestClass2
# else
# Execute test cases in TestClass1\
unittest.main()
导入单元测试
类TestClass1(unittest.TestCase):
def测试_1_优先(自):
打印(“第一个测试用例”)
def测试2秒(自身):
打印(“第二个测试用例”)
类TestClass2(unittest.TestCase):
def测试_3_第三(自):
打印(“第三个测试用例”)
def测试4第四(自我):
打印(“第四个测试用例”)
如果名称=“\uuuuu main\uuuuuuuu”:
#val=1unittest.main()
已经解析了sys.argv
以允许运行特定类或单个测试
例如,如果您的脚本名为test.py
,则可以运行以下命令以仅运行TestClass1
:
python test.py __main__.TestClass1
或者只运行下面的TestClass1.test\u 1\u first
:
python test.py __main__.TestClass1.test_1_first
如果希望在脚本中执行此操作,可以将要运行的测试名称作为defaultTest
参数传递:
unittest.main(defaultTest='__main__.TestClass1')
unittest.main()
已解析sys.argv
以允许运行特定类或单个测试
例如,如果您的脚本名为test.py
,则可以运行以下命令以仅运行TestClass1
:
python test.py __main__.TestClass1
或者只运行下面的TestClass1.test\u 1\u first
:
python test.py __main__.TestClass1.test_1_first
如果希望在脚本中执行此操作,可以将要运行的测试名称作为defaultTest
参数传递:
unittest.main(defaultTest='__main__.TestClass1')
已经是这样了。您可以通过以下命令运行特定类:
python -m unittest test_module.TestClass1
如果确实需要在scpript中执行此操作,则可以将类传递到unittest.TestLoader().loadTestsFromName
,然后使用unittest.TextTestRunner()运行测试套件。运行(套件)
。它看起来像这样:
test_suite = unittest.TestLoader().loadTestsFromName('__main__.TestClass1')
unittest.TextTestRunner().run(test_suite)
已经是这样了。您可以通过以下命令运行特定类:
python -m unittest test_module.TestClass1
如果确实需要在scpript中执行此操作,则可以将类传递到unittest.TestLoader().loadTestsFromName
,然后使用unittest.TextTestRunner()运行测试套件。运行(套件)
。它看起来像这样:
test_suite = unittest.TestLoader().loadTestsFromName('__main__.TestClass1')
unittest.TextTestRunner().run(test_suite)
你能举个例子说明你希望它如何工作吗?@Cyphall,完成。现在清楚了吗?你能举个例子说明你希望它如何工作吗?@Cyphall,完成了。现在清楚了吗?非常感谢。这就是我要找的。非常感谢。这就是我要找的。