简体   繁体   中英

How should I write view unittest in Django?

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 ?

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.

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