Django测试框架中的全局设置?

2024-10-03 21:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法(使用标准Django.test.TestCaseframework)对某些变量执行全局初始化,使其只发生一次。在

put things setUp()使变量在每次测试之前初始化,当设置涉及到昂贵的操作时,这会降低性能。我想运行一次设置类型特性,然后让这里初始化的变量对我所有的测试都可见。在

我不希望重写testrunner框架。在

我在想类似于Ruby/RSpec世界中的before(:all)。在

-S型


Tags: djangotest框架类型标准putsetup特性
3条回答

在python/django的较新版本中,setUpClass()部分解决了这一问题,它至少允许我运行类级别的设置。在

有静态变量的类呢? 比如:

class InitialSetup(object):
    GEOLOCATOR = GeoLocator()
    DEFAULT_LOCATION = GEOLOCATOR.get_geocode_object(settings.DEFAULT_ADDRESS, with_country=True)

    def setUp(self):
        self.geolocator = InitialSetup.GEOLOCATOR
        self.default_location = InitialSetup.DEFAULT_LOCATION
        p = Page.objects.create(site_id=settings.SITE_ID, template='home_page.html')
        p.publish()
        self.client = Client()


class AccessTest(InitialSetup, Testcase):  # Diamond inheritance issue! inheritance order matters
    def setUp(self):
        super(AccessTest, self).setUp()


    def test_access(self):
        # Issue a GET request.
        response = self.client.get('/')

        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

您不需要“重新编写整个testrunner框架”,但您需要创建一个自定义的测试运行程序(您只需copy the existing one并对其进行修改以包含全局设置代码)。大约有100行代码。然后设置TEST_RUNNER设置以指向您的自定义跑步者,然后离开。在

相关问题 更多 >