Django全局测试设置

9 投票
2 回答
3428 浏览
提问于 2025-04-18 18:12

我有一些用于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"

这样做可能吗?如果可以的话,怎么做呢?提前谢谢!

2 个回答

1

如果你想让它在所有测试中只运行一次,你可以通过在你的某个应用里放一个 management/commands/test.py 来覆盖测试管理命令:

from django.core.management.commands import test

class Command(test.Command):
    def handle(self, *args, **options):
        # Do your magic here
        super(Command, self).handle(*args, **options)

不过,这在PyCharm中效果不好。在PyCharm里,你可以使用“运行前”的任务来代替。

15

你可以创建一个父类,在里面写上你自定义的全局 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 方法。

撰写回答