python – Django测试全局设置

我有一些用
django进行单元测试的文件:

test1.py

class Test1(unittest.TestCase):
    def setUp(self):
        ...

    def tearDown(self):
        ...

test1.py

class Test1(unittest.TestCase):
    def setUp(self):
       ...

    def tearDown(self):
        ...

testn.py

class Testn(unittest.TestCase):
    def setUp(self):
       ...

    def tearDown(self):
        ...

我想创建一个全局设置来为它进行一些配置测试,有些像:

some_file.py

class GlobalSetUpTest(SomeClass):
    def setup(self): # or any function name
         global_stuff = "whatever"

那可能吗?如果是这样,怎么样?提前致谢.

最佳答案 您可以使用自定义全局setUp方法创建父类,然后让所有其他测试类扩展:

class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.global_stuff = "whatever"


class TestOne(MyTestCase):
    def test_one(self):
        a = self.global_stuff 


class TestTwo(MyTestCase):
    def setUp(self):
        # Other setUp operations here
        super(TestTwo, self).setUp() # this will call MyTestCase.setUp to ensure self.global_stuff is assigned.

    def test_two(self):
        a = self.global_stuff

显然,你可以使用相同的技术来实现’全局’tearDown方法.

点赞