简体   繁体   中英

No Post Data - Testing Django View with AJAX Request

I'm currently testing my Django application in order to add some CI/CD to it. However, most of my views contain an AJAX section for requests sent by the frontend. I saw that for testing those I can only just do something like this:

response: HttpResponseBase = self.client.post(
        path=self.my_page_url,
        content_type='application/json',
        HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        data={
            'id': '123456',
            'operation': "Fill Details"
        }
    )

The XMLHttpRequest is making most of the magic here (I think), by simulating the headers that an AJAX request would have. However, in my view I have a section where I do: request.POST['operation'] , but this seems to fail during tests since apparently no data is passed through the POST attribute. Here's the code of the view that I'm using right now:

MyView(request):
   is_ajax: bool = request.headers.get('x-requested-with') == 'XMLHttpRequest'
   if is_ajax:
      operation = request.POST['operation']

I checked and my data is being passed in request.body . I could include an or statement, but it would be ideal if the code for views was not modified because of tests. Is there any way to get the client.post method to pass the data through the POST attribute?

You can simulate ajax like POST using the python requests library.

import requests

headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
}


data = {
            'id': '123456',
            'operation': "Fill Details"
        }

session = requests.Session()
session.post(url, data=data, headers=headers)

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