【问题标题】:Skip function execution based on a condition根据条件跳过函数执行
【发布时间】: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


【解决方案1】:

您可以使用 unittest 标准库中的 skipIf 功能。你可以定义一些条件,并且必须写一些原因(字符串)。

calc.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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多