[Django]-Testing Django view requiring user authentication with Factory Boy

10👍

Actually, you receive a 404 error because the self.client.login call fails.

When you’re passing password=self.user.password, you’re sending the hash of the password, not the password itself.

When you call UserFactory(), the steps taken by factory_boy in your factory are:

  1. Create an object with {'username': "<random>", 'is_active': True, 'is_staff': True, 'email': "<fuzzed>@email.com"}
  2. save() it
  3. Call user.set_password('my_secret')
  4. Call user.save() again

By then, user.password is the result of set_password('my_secret'), not 'my_secret'.

I’d go for (in your test):

pwd = 'my_super_secret'
self.user = UserFactory(password=pwd)
self.client = Client()
self.assertTrue(self.client.login(username=self.user.username, password=pwd))

By the way, the declaration of your email field won’t work as you expect it: when you write fuzzy.FuzzyText(...).fuzz().lower(), this gets executed only once, when the UserFactory class is declared.

You should instead use factory.fuzzy.FuzzyText(chars='abcdefghijklmnopqrstuvwxyz', length=12, suffix='@example.com').

👤Xelnor

0👍

An alternative way than using the client, I have found it is helpful to instantiate the view and directly pass it the request.

self.request.user = UserFactory()
view = ReleaseView.as_view()
response = view(self.request)

And then you can

self.assertEqual(response.status_code, desired_status_code)

And even render the response if you so desire.

👤C.B.

Leave a comment