I'm populating my test db via a fixture, and everything loads fine. However, I'm unable to get either login
or force_login
to work. User is also in the fixture.
When I try to test the first view, it redirects to the login page.
class TestUnauthUser(TestCase):
fixtures = ['project.json']
@classmethod
def setUpTestData(cls):
cls.client = Client()
# Get User and Login
cls.unauth_user = User.objects.get(username='unauth_user')
print(cls.unauth_user.pk)
#cls.login = cls.client.login(username=cls.unauth_user.username, password=cls.unauth_user.password)
cls.client.force_login(cls.unauth_user)
# Get Project
cls.project = Project.objects.get(slug='test-project')
cls.slug_dict = {'slug': cls.project.slug}
# Get Task
cls.task = Task.objects.get(slug='test-task')
def test_login(self):
self.assertTrue(self.unauth_user.login)
def test_project_view(self):
# Project Main
response = self.client.get(reverse('customerportal:project', kwargs=self.slug_dict))
self.assertEqual(response.status_code, 403)
I'm able to verify that I have the correct user object with: print(cls.unauth_user.pk)
. So the User exists and is being obtained. But, it's still not logging-in successfully.
I found the problem. force_login()
must be run prior to every test. So doing the following solves the issue:
def setUp(self):
self.client.force_login(self.unauth_user)
However, this seems to run contrary to the purpose of setUpTestData
. It was my understanding that anything set under setUpTestData
is supposed to last for the duration of the class. So I'm unsure as to why force_login
must be run repeatedly even when set from there. If anyone could provide further context that would be highly appreciated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.