[英]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.