How to simulate a HTTP Post request from a django view without a template

前端 未结 5 1570
暖寄归人
暖寄归人 2021-02-13 19:11

I am writing views, not so keen to write templates right away.

But I need to test my program by submitting post requests.

How do i simulate HTTP Post from within

相关标签:
5条回答
  • 2021-02-13 19:41

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

    0 讨论(0)
  • 2021-02-13 19:45

    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.

    0 讨论(0)
  • 2021-02-13 19:47

    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.

    0 讨论(0)
  • 2021-02-13 19:49

    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/

    0 讨论(0)
  • 2021-02-13 19:50

    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.

    0 讨论(0)
提交回复
热议问题