简体   繁体   中英

Mocking django Form cleaned_data field

I have a simple django form like this:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

My view uses it like this:

def my_view(request):
  form = ContactForm(request.POST)
  if form.is_valid():
    data = form.cleaned_data

  ...

I want to test my view and don't care about what the form actually does. This is what my test looks like so far

@patch.object(ContactForm, 'is_valid')
def test_my_view(mock_is_valid):
  is_valid.return_value = True

  ...
  assert response.status_code == 201

However, this doesn't work because form.cleaned_data is not set until form.is_valid() is called. How do I mock out the form.cleaned_data attribute if it doesn't exist in the first place?

You can mock the whole form class instead of just one method:

@patch('myapp.views.ContactForm')
def test_my_view(mock_form_class):
    mock_form_class.return_value.is_valid = True
    mock_form_class.return_value.cleaned_data = {}
    ...
    assert response.status_code == 201

Where myapp.views needs to be replaced with the dotted path to your app's views module. It assumes that you are importing the ContactForm into that module, eg, with from .forms import ContactForm .

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