Search code examples
djangoformstestcase

How to get a testing http request in django testcase?


I'm working in a solution with only an GraphQL API, so all my logic are in forms. The save method of one of my forms receives the http request. I use the request to get some data for mailing. So, I'm trying to make a test case of this form but I don't know how to pass the request object.

class SignUpForm(forms.ModelForm):
  ...
  def save(self, request, *args, **kwargs):
    ...

How can I pass the request object to form in a test case?


Solution

  • You can instantiate HttpRequest and use it as a regular request in your test:

        fake_request = HttpRequest()
        fake_request.user = AnonymousUser()
        fake_request.META['SERVER_NAME'] = site.domain
        fake_request.META['SERVER_PORT'] = 80
    
        s = SessionStore()
        s.create()
        fake_request.session = s
    

    In your case you might need to fill more fields