Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django LiveServerTestCase: User created in in setUpClass method not available in test_method?

I am using Django 1.4's LiveServerTestCase for Selenium testing and am having trouble with the setUpClass class method. As far as I understand MembershipTests.setUpClass is run once before the unit tests are run.

I've put code to add a user to the database in MembershipTests.setUpClass but when I run the MembershipTests.test_signup test no user has been added to the test database. What am I doing incorrectly? I expect the user I created in setUpClass would be available across all unit tests.

If I put the user creation code in MembershipTests.setUp and run MembershipTests.test_signup I can see the user, but don't want this run before every unit test as setUp is. As you can see, I use a custom LiveServerTestCase class to add basic functionality across all of my tests (test_utils.CustomLiveTestCase). I suspect this has something to do with my issue.

Thanks in advance.

test_utils.py:

from selenium.webdriver.firefox.webdriver import WebDriver
from django.test import LiveServerTestCase

class CustomLiveTestCase(LiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        cls.wd = WebDriver()
        super(CustomLiveTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.wd.quit()
        super(CustomLiveTestCase, cls).tearDownClass()

tests.py:

from django.contrib.auth.models import User
from django.test.utils import override_settings
from test_utils import CustomLiveTestCase 
from test_constants import *

@override_settings(STRIPE_SECRET_KEY='xxx', STRIPE_PUBLISHABLE_KEY='xxx')
class MembershipTests(CustomLiveTestCase):

    fixtures = [
        'account_extras/fixtures/test_socialapp_data.json',
        'membership/fixtures/basic/plan.json',
    ]

    def setUp(self):
        pass

    @classmethod
    def setUpClass(cls):
        super(MembershipTests, cls).setUpClass()
        user = User.objects.create_user(
            TEST_USER_USERNAME,
            TEST_USER_EMAIL,
            TEST_USER_PASSWORD
        )

    def test_signup(self):
        print "users: ", User.objects.all()
like image 674
Hakan B. Avatar asked Feb 20 '13 16:02

Hakan B.


2 Answers

Since you're using LiveServerTestCase it's almost same as TransactionTestCase which creates and destroys database (truncates tables) for every testcase ran.

So you really can't do global data with LiveServerTestCase.

like image 77
jtiai Avatar answered Oct 23 '22 12:10

jtiai


The database is torn down and reloaded on every test method, not on the test class. So your user will be lost each time. Do that in setUp not setUpClass.

like image 39
Daniel Roseman Avatar answered Oct 23 '22 11:10

Daniel Roseman