[Solved]-Global set up in django test framework?


You don’t need to “re-write the whole test runner framework” but you will need to create a custom test_runner (you can just copy the existing one and modify it to include your global setup code). It’s about 100 lines of code. Then set the TEST_RUNNER setting to point to your custom runner and away you go.


This is partially addressed in newer versions of python/django by setUpClass() which will at least allow me to run class level setup.


What about a class with static variables ?
Something like :

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')
        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)

Leave a comment