简体   繁体   English

如何测试 Django CreateView 和 form_valid

[英]How to test Django CreateView and form_valid

This maybe very basic but I still fail to understand how to test a Django CreateView which has a form_valid(self, form) method ?这可能非常基本,但我仍然无法理解如何测试具有form_valid(self, form)方法的 Django CreateView

Here's my code:这是我的代码:

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)`

I'm using pytest and I simply fail to understand how to test this one.我正在使用 pytest,我只是不明白如何测试这个。 I would be really grateful for a short example how this could be tested ... Thanks!我真的很感激一个简短的例子,如何测试它......谢谢!

Here once again is the class you have:这里再次是你所拥有的课程:

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)

We can test the form validation by using a 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

    

I believe you'd have to create the post data and such in the setUp of your test.我相信,你必须在创建后的数据和这样setUp您的测试。

class NewPatientFormTest(TestCase):

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

In your setUp make sure the rest of your data is setup appropriately.在你setUp确保您的数据的其余部分的设置适当。 Then use your test - probably something like this:然后使用您的测试 - 可能是这样的:

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

Obviously this is super simplified - but should get you on in the right direction on getting this tested.显然,这是超级简化的 - 但应该让您在进行此测试时朝着正确的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用测试客户端测试 django (3.0) CreateView 的“form_valid”方法和参数? - How to test django (3.0) CreateView's 'form_valid' method and parameters with a test client? Django form_valid 未将参数传递给 CreateView - Django form_valid not passing params to CreateView 未调用CreateView中的Django form_valid()和form_invalid() - Django form_valid() and form_invalid() in CreateView not called Django:CreateView中的transaction.atomic,form_valid() - Django: transaction.atomic in CreateView, form_valid() Django CreateView form_valid方法中的访问请求变量 - Access request variable in Django CreateView form_valid method Django - CreateView form_valid() 如何访问外键对象 - Django - CreateView form_valid() how can I access foreign key objects 如何在 CreateView 的 form_valid 方法中引发错误 - How to raise a error inside form_valid method of a CreateView 有人可以解释为什么我们在 django 的 CreateView 中的 form_valid 方法中返回 super().form_valid(form) 吗? - could someone explain why we return super().form_valid(form) in form_valid method in CreateView in django? form_Valid function 如何在 django 中工作? - How the form_Valid function works in django? 尝试创建新菜时,CreateView 中的 Django form_valid() 未执行 object - Django form_valid() in CreateView not executing when trying to create a new dish object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM