I need some unit tests to check if a user after successful login can open profile editing page, how am I supposed to do this?
I tried this code, but it shows an error. Do I have to use my own view to register a user then to log in or there are some unit test modules for that?
class UserProfilePage(TestCase):
def setUp(self):
self.credentials = {
'username': 'test_user',
'password': 'secret'}
user = User.objects.create_user(**self.credentials)
self.user_profile = {
'user': user,
'first_name': 'Test_1',
'surname': 'test_surname',
'about_me': 'some_info',
'email': '[email protected]',
}
UserProfile.objects.create(**self.user_profile).save()
self.user_id = UserProfile.objects.get(user=user.id)
def test_profile_page_and_current_template(self):
response = self.client.get('/blog/user/profile/', self.user_id)
self.assertEqual(response.status_code, 200)
ValueError: Cannot query "Test_1": Must be "User" instance.
CodePudding user response:
The client API allows you to login a user like so:
self.client.force_login(user)
Just run that before accessing the profile page in your test.
There also is an error in your code.
...
self.user_id = UserProfile.objects.get(user=user)
...
Here you are assigning the profile object to user_id
and later trying to pass user_id
as parameter in the request, instead of the user ID. I am guessing that is why you get the error.
I would suggest to only set the user
as object property; you do not need anything else. Then access it with self.user.id
in your test.
See also: https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.Client.force_login