如何测试Django CreateView和form_valid

时间:2018-10-24 20:16:53

标签: python django testing django-forms

这可能是非常基本的,但是我仍然不明白如何测试具有CreateView方法的Django form_valid(self, form)

这是我的代码:

class NewPatientFormView(LoginRequiredMixin, CreateView):
    model = Patient
    fields = ['name', 'surname', 'phone', 'email', 'PESEL', 'age',
          'patient_agreement']

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.created_by_user = self.request.user
        self.object.save()
        return super().form_valid(form)`

我正在使用pytest,但是我根本不明白如何测试这一点。我将不胜感激,举一个简短的示例,可以对其进行测试...谢谢!

2 个答案:

答案 0 :(得分:0)

我相信您必须在测试的setUp中创建帖子数据等。

class NewPatientFormTest(TestCase):

    def setUp(self):
        self.form_data = {
            'name': 'Billy',
            'surname': 'Masters',
            'phone': '123-358-2382',
            *...the rest of your form data...*
        }

请确保您的setUp中的其余数据已正确设置。然后使用您的测试-可能是这样的:

def test_new_patient_form_is_valid(self):
    form = NewPatientForm(data=self.form_data)
    self.assertTrue(form.is_valid())

显然,这是超级简化的方法-但应在正确的方向进行测试。

答案 1 :(得分:0)

这又是您上的课:

class NewPatientFormView(LoginRequiredMixin, CreateView):
    model = Patient
    fields = ['name', 'surname', 'phone', 'email', 'PESEL', 'age',
      'patient_agreement']
    

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.created_by_user = self.request.user
        self.object.save()
        return super().form_valid(form)

我们可以使用Request Factory测试表单验证:

import pytest
from django.test import RequestFactory
from django.contrib.auth.models import User    

factory = RequestFactory()

@pytest.mark.django_db
def test_form_valid_on_create_view():
    # Arrange
    data = {
       'name': 'Billy',
       'surname': 'Masters',
       'phone': '123-358-2382',
       # other fields
    } 
  
    user = User.objects.create_user(
        username='jacob', email='jacob@…', password='top_secret')

    request = factory.post( '/[Path to new Patient Form]/', data=data)
    request.user = user
   
    # Act
    response = NewPatientFormView.as_view()(request) # this will submit the form and run the form_valid.  

    # Assert
    
    Assert True