1

I want to write a unittest for this method in Django.

def activate(request):
    id = int(request.GET.get('id'))
    user = User.objects.get(id=id)
    user.is_active = True
    user.save()
    return render(request, 'user_authentication/activation.html')

I wrote sth like this:

def test_activate_view(self):
    response = self.client.get('/activation', follow=True)
    self.assertTemplateUsed(response, 'user_authentication/activation.html')

It doesn't work because I get an error:

id = int(request.GET.get('id'))
TypeError: int() argument must be a string or a number, not 'NoneType':

What should I change in my test ?

Jean Jung
  • 1,200
  • 12
  • 29
polix
  • 19
  • 1
  • Well, the test has found a bug: you'll get a 500 error if someone doesn't pass an `id=..` parameter in the GET request. You should probably fix the bug first ;-) – thebjorn Dec 31 '17 at 17:13

1 Answers1

2

Your view reads data from request.GET - you need to pass this data:

response = self.client.get('/activation?id=1', follow=True)

You also fetch this user afterwards from your database. Therefor you need to load some fixture data. Create a fixture using manage.py dumpdata and load it in your unit test like that:

class UserTestCase(TestCase):
    fixtures = ['fixture.json', 'users']

Read the docs about loading fixtures for detailed explanations.

Note regarding your approach

You should not use the users id for this use case. One can easily guess this id and activate accounts.

Someone might register once with a valid email address, receive your link with the id inside and can afterwards create a bunch of accounts without providing a valid email address.

Instead you might generate a unique and random secret (aka token) and associate this token with the user. Your view should accept those tokens and resolve the user based on it. This way one can no longer easily activate.

dahrens
  • 3,879
  • 1
  • 20
  • 38
  • 1
    Django's built-in password reset by email, has all the functionality needed to do this right: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html – thebjorn Dec 31 '17 at 18:31