Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django views testing , RequestFactory with data

I have this view:

def send_results(request):
    print request
    if request.is_ajax():
        address = request.POST.get('url')
    process_data(address)
    context = get_all_from_database()
    return HttpResponse(json.dumps(context), content_type='application/json')

and I need to test it:

    def test_send_results(self):
        factory = RequestFactory()
        request = factory.get('/views/send_results')
        response = send_results(request)
        self.assertEqual(response.status_code, 200)

But it always stop with error that in my view 'address' value is referensed before asignment. How to pass it some value ?

like image 573
user3156971 Avatar asked Dec 19 '22 18:12

user3156971


1 Answers

If the request.is_ajax() is False then address will not be assigned before process_data(address) is called. If you want to test an AJAX request then you should pass the HTTP_X_REQUESTED_WITH header:

request = factory.get('/views/send_results', HTTP_X_REQUESTED_WITH='XMLHttpRequest')

However you'll still need to fix your view to handle the case when the request is not an AJAX request.

like image 152
Mark Lavin Avatar answered Dec 22 '22 11:12

Mark Lavin