Reputation: 365
I'm testing my Django application with Selenium in Docker. I encounter a peculiar thing related to cookies availability (I use cookies to authenticate in my tests).
Here is the code that works:
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from users.models import CustomUser
class SomeTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
cls.host = "web" # Docker service name
super().setUpClass()
CustomUser.objects.create_user(username="user", password="password")
def setUp(self):
self.browser = webdriver.Remote("http://selenium:4444/wd/hub", DesiredCapabilities.FIREFOX)
def tearDown(self):
self.browser.quit()
def test2(self):
self.client.login(username="user", password="password")
cookie = self.client.cookies["sessionid"]
...
However, when I insert there another test case before test2
, let it be something as simple as
def test1(self):
pass
then the code crashes with the following error:
Traceback (most recent call last):
File "/home/mysite/functional_tests/test.py", line 28, in test2
cookie = self.client.cookies["sessionid"]
KeyError: 'sessionid'
So the only difference between the working and not-working code is a dummy test function, but what does it change? As far as I know the setUp
and tearDown
methods make sure that the "environment" is the same for every test case, no matter what happens in other test methods and here it clearly depends on the (non-)existence of other test cases before running my test... Is there something I misunderstand? Or is it some kind of a bug?
Any help will be appreciated.
My setup:
Django==2.2.5
selenium==3.141.0
Docker version - 19.03.5
Upvotes: 0
Views: 583
Reputation: 365
I've solved it and I'm posting the answer here in case anyone else encounters similar issues.
So the problem here was not with test case order, Docker, Selenium, or anything within the code itself but with my lack of understanding of how class StaticLiveServerTestCase
behaves. Namely, this class inherits from LiveServerTestCase
which in turn inherits from TransactionTestCase
which tears down the database after each test case (and sets it up before another test case) - more on this can be found in Django docs. And as I was creating the user in setUpClass
- which is run once per all the test cases in the class - it was indeed created but removed (together with the whole database) after any first test case. Sowhen I was doing self.client.login(username="user", password="password")
it was not a problem with cookies or authentication per se but with the fact that the user simply didn't exist.
:-)
Upvotes: 1