python - 根据条件跳过函数执行
问题描述
您能否为第 10-11 行编写的代码建议一种更好的方法,因为这不是if __name__ == "__main__":
在同一个文件中包含多个块的好方法。
我也可以将代码保留在read_argument()
内部setupClass
,但我不想这样做,因为这样做第 29 行的代码ignoreThisTestCase
只会变得无效(在setUpClass
调用之前对装饰器进行评估 - 使用调试检查)
read_argument() - This is a method using argparser for initializing the value of env
代码块:
1 import unittest
2 from utils import read_argument, ignoreThisTestCase
3 from unittest import TestCase
4 env = ''
5 option_list = ['dev', 'prod', 'stage']
6 class TestMethods(TestCase):
7 """
8 A basic simple test class using only unittest
9 """
10 if __name__ == "__main__":
11 read_argument(dev_options=option_list)
12 @classmethod
13 def setUpClass(cls):
14 print("setUpClass")
15
16 @classmethod
17 def tearDownClass(cls):
18 print("tearDownClass")
19
20 def test_001_upper(self):
21 """This is explanation of the Test case no 1
22 and it works fine
23
24 """
25
26 print(f'\t\t\texec : {self._testMethodName}')
27 self.assertEqual('bar'.upper(), 'BAR')
28
29 @ignoreThisTestCase(env == 'stage', "will work in staging")
30 def test_002_isupper(self):
31 """This is explanation of the Test case no 2
32 and it works fine
33
34 """
35 print(f'\t\t\tRunning test: {self._testMethodName}')
36 self.assertTrue('FOO'.isupper())
37 self.assertFalse('Foo'.isupper())
38
39 if __name__ == '__main__':
40
41 unittest.main()
我已经尝试过编写装饰器和unitttest
模拟,但看起来装饰器在类级语句中是不允许的。
解决方案
您可以使用标准库中的skipIf
功能。unittest
您可以定义一些条件并且必须写一些原因(字符串)。
计算.py
def plus(a, b):
return a + b
test_calc.py
import unittest
from calc import plus
env = 'dev'
class TestPlusMethod(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("setUpClass")
@classmethod
def tearDownClass(cls):
print("tearDownClass")
def test_positive_numbers(self):
self.assertEquals(plus(1, 1), 2)
@unittest.skipIf(env == 'dev', 'Some reason...')
def test_negative_numbers(self):
self.assertEqual(plus(-1, -1), -2)
if __name__ == '__main__':
unittest.main()
这应该是结果
/ # python test_app.py
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK (skipped=1)
推荐阅读
- spring - Spring 5可以在没有控制器的情况下允许在jsp中进行POST吗?
- eclipse - Eclipse CDT 为 Docker 容器构建和启动应用程序
- node.js - 弹性搜索响应 JSON 清理
- matlab - 盈透证券和 MATLAB 连接
- r - 在shinyapp中带有来自网络的图像的LaTeX PDF
- c# - 使用 LINQ 查询 Azure MobileServiceSyncTable
- python - 网络上的 Diffie-Hellman 密钥交换或任何其他密钥交换
- java - REST 控制器中的存储库捕获错误“找不到构造函数的参数 1
- jquery - 如何在多选中获取所有选定的值?
- python - 在特殊字符 Python RegEx 之后获取字符串