Search code examples
selenium-webdriverdjango-testing

Persistant login during django selenium tests


Here the snippet I'm using for my end-to-end tests using selenium (i'm totally new in selenium django testing) ;

from django.contrib.auth.models import User
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.chrome.webdriver import WebDriver

class MyTest(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super(DashboardTest, cls).setUpClass()

        cls.selenium = WebDriver()
        cls.user = User.objects.create_superuser(username=...,
                                                 password=...,
                                                 email=...)
        time.sleep(1)
        cls._login()

    @classmethod
    def _login(cls):
        cls.selenium.get(
            '%s%s' % (cls.live_server_url, '/admin/login/?next=/'))
        ...

    def test_login(self):
        self.selenium.implicitly_wait(10)
        self.assertIn(self.username,
                      self.selenium.find_element_by_class_name("fixtop").text)

    def test_go_to_dashboard(self):
        query_json, saved_entry = self._create_entry()
        self.selenium.get(
            '%s%s' % (
                self.live_server_url, '/dashboard/%d/' % saved_entry.id))
        # assert on displayed values

    def self._create_entry():
        # create an entry using form  and returns it

    def test_create(self):
        self.maxDiff = None
        query_json, saved_entry = self._create_entry()
        ... assert on displayed values

I'm noticed that between each test the login is not persistant. So i can use _login in the setUp but make my tests slower.

So how to keep persistant login between test ? What are the best practices for testing those tests (djnago selenium tests) ?


Solution

  • kevinharvey pointed me to the solution! Finally found out a way to reduce time of testing and keeping track of all tests:

    I have renamed all methods starting with test.. to _test_.. and added a main method that calls each _test_ method:

    def test_main(self):
        for attr in dir(self):
            # call each test and avoid recursive call
            if attr.startswith('_test_') and attr != self.test_main.__name__:
                with self.subTest("subtest %s " % attr):
                    self.selenium.get(self.live_server_url)
                    getattr(self, attr)()
    

    This way, I can test (debug) individually each method :)