[Fixed]-How to use django serializer in unit test

1👍

to do this I simply had to “mock” a request using APIRequestFactory.

So I wrote this method as well:

# call response
def r(self, method, status_code, url, data=None, *args, **kwargs):
    kwargs['data'] = data
    kwargs['format'] = kwargs.get('format', 'json')


    r = getattr(self.c, method)(url, *args, **kwargs)
    self.assertEqual(r.status_code, status_code,
        'Expected status %d, got %d.\n%s\n%s' % (
            status_code, r.status_code, url, pformat(getattr(r, 'data', None))) )
    return r

# return both request and response
def rq(self, method, status_code, url, data=None, *args, **kwargs):
    kwargs['data'] = data
    kwargs['format'] = kwargs.get('format', 'json')

    request = getattr(self.f, method)(url, *args, **kwargs)

    return request, self.r(method, status_code, url, data)

and then this is how I called it:

    rq, rs = self.rq('post', 201, data)
    rs0 = rs

    requestor_superior_id = rs0.data['extra']['next_employees'][0]
    superior_emp = Employee.objects.get(pk=requestor_superior_id)

    self.attach_user_to_request(rq, self.username)

    employee_serializer = EmployeeSerializer(superior_emp, context={'request': rq})
    employee_serializer.data  # works

note: i also had to “attach” a user to the request like so

def attach_user_to_request(self, request, username, password=None):
    try:
        user = User.objects.get(email=username+'@test.test')
    except User.DoesNotExist:
        raise Exception('No Such User')
    if not user.check_password(None, password or 'test'):
        raise Exception('Bad Password')
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    request.user = user
    return True

this is discussed under Forcing authentication here

👤abbood

Leave a comment