简体   繁体   中英

Create authenticated user for django tests

The reason I am asking is I have the fields username , password and otp_token . The otp_token is challenging to create, therefore I was wondering if there is a way create an authenticated user at the beginning of the test file to carry out the rest of the django tests as an authenticated user?

For example, how to pass a logged in user to the following

def some_test(self):
    login = self.client.login(username='testUser', password='testPassword')

    response = self.client.get(reverse('page1:conent1'))
    self.assertEqual(response.status_code, 200)

related question

Not sure how are you generating that token, but I think you can use some dummy data in test

from django.test import TestCase, Client

def setUp(self):
    self.user = User.objects.create(username='<USERNAME>',
                                    email='<EMAIL>', otp_token='<YOUR_VALUE>')
    self.user.set_password(<PASSWORD>)
    self.user.save()
    self.client = Client()

def some_test(self):
    login = self.client.login(username='<USERNAME>', password='<PASSWORD>')
...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM