首页 > 解决方案 > 根据条件跳过函数执行

问题描述

您能否为第 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模拟,但看起来装饰器在类级语句中是不允许的。

标签: pythonunit-testingclassdecorator

解决方案


您可以使用标准库中的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)


推荐阅读