[Fixed]-How to simulate a HTTP Post request from a django view without a template

12👍

Django has a built in mock Client utility that can mimic requests as if they are coming from a browser. If you don’t need to fully mimic a browser and just want to invoke your views directly from your tests, consider using a RequestFactory instead.

3👍

For such cases I think RequestFactory is ideally suited.

It works just like django’s test client with the difference that it let’s you create a request object that you can use anywhere. So you could just create your own request object and pass it to your view or form for testing.

I like this method of testing more then using the test client, since it comes closer to pure unit testing. That is, testing a single piece of code. If you’re using the test client, there are more layers added before the actual code you’re testing is reached.

2👍

To avoid the pain of creating the request object yourself you can use this tip on Django snippets

1👍

It sounds like you are looking for either a unit test or an acceptance test. Take a look at unittest which is part of the standard library.

For quick ad hoc tests while developing web apps, I like to use curl. It’s a simple command line tool that easily generates all sorts of HTTP requests. You can POST with a command like:

curl -i -d field=value http://localhost:8080/sample/something

Curl is available on a lot of platforms. Check it out at http://curl.haxx.se/

1👍

If you are looking at this from the context of writing unittests, you could consider creating the Request object yourself and just calling the view function directly. You could even mock it, and any other parameters the view might take.

Leave a comment