【发布时间】:2021-07-16 21:54:55
【问题描述】:
您能否为第 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 模拟,但看起来装饰器在类级语句中是不允许的。
【问题讨论】:
-
请解释一下你的目标是什么。不清楚
read_argument做了什么。 -
你想解决什么问题?为什么行为要根据是否
__name__ == "__main__"而改变?如果这段代码代表测试运行程序要使用的测试用例,那么为什么会您将它作为主脚本运行? -
实际上 ignorethistestcase 是一个装饰器,意味着忽略测试用例 - 甚至不让它进入 unittest 管道(不像跳过),所以它在 setupclass 被调用之前被评估
标签: python unit-testing class decorator