0

I am writting some tests in a Django project. For example, I want to test an index view in one app fo my Django project. But I am not sure test code below is correct, event if test passed.

User need to be authentified to access this index view.

So, in SetUp, I first create test user and logged in.

And finally, I test I can get index view by testing status_code return.

But if I omit follow=True, it return 302 and test failed. Is my test code correct?

class IndexPageTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_superuser(username='test', password='test', email='test@test.fr')
        self.client.login(username='test', password='test')

    def test_index_page(self):
        response = self.client.get(reverse('ecrf:index'), follow=True)
        self.assertEqual(response.status_code, 200)

Django project architecture

- core
   - urls.py
- ecrf
   - urls.py
   - views.py

core/urls.py

urlpatterns = [
    path('ecrf/', include('ecrf.urls')),
]

ecrf/urls.py

urlpatterns = [
    path("", views.index, name="index"),
]

ecrf/views.py

@login_required
def index(request):
    ...
    return render(request, "ecrf/index.html", context)
Mereva
  • 350
  • 2
  • 14
  • Do you use internationalization? – Nechoj Nov 30 '21 at 14:11
  • Have a look at this post: https://stackoverflow.com/questions/2619102/djangos-self-client-login-does-not-work-in-unit-tests – Nechoj Nov 30 '21 at 14:15
  • I do not use internationalization in this project... why? – Mereva Nov 30 '21 at 14:19
  • If you use internationalization there is always an automatic redirect 302 to the corresponding i18 version of the page – Nechoj Nov 30 '21 at 14:20
  • Have you modified the `USERNAME_FIELD`? – Brian Destura Dec 01 '21 at 00:41
  • @BrianDestura: No I do not – Mereva Dec 01 '21 at 07:22
  • Try to check what the `self.client.login()` call returns. If it's false, then your authentication is failing. In that case can you share your implementation on `create_superuser`? – Brian Destura Dec 01 '21 at 23:20
  • @BrianDestura: ```User.objects.create_superuser(username='test', password='test', email='test@test.fr')``` ; user is created, number of user increased by one, is_superuser = True... but I can not logged in with this newly created user – Mereva Dec 02 '21 at 09:13

1 Answers1

0

I resolve my issue.

I do not know why, but chen creating user with create_user, password is not properly hashed, confirmed by method check_password('test',self.user.password) that return false. But if I create user with create method and set_password 'manually' it works

password correctly hashed for test

cls.user = User.objects.create(username='test', email='test@test.fr')
cls.user.set_password('test')
cls.user.save()

password not properly hashed for test

cls.user = User.objects.create_user(username='test', password='test', email='test@test.fr') 

Mereva
  • 350
  • 2
  • 14