I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
self.assertEqual(response.status_code, 200) # we get our page back with an error
The page always returns a response of 200 whether there's an form error or not. How can I check that my Form failed and that the particular field (soemthing
) had an error?
To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...
Django comes with a small set of its own tools for writing tests, notably a test client and four provided test case classes. These classes rely on Python's unittest module and TestCase base class. The Django test client can be used to act like a dummy web browser and check views.
There is a very easy solution to this: use django-crispy-forms and regain all control of what your form looks like frontend. There is good documentation which includes parts on how to make your forms use bootstrap. i am wondering why i should use it and what it would save me.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:
from django.test import TestCase
from myapp.forms import MyForm
class MyTests(TestCase):
def test_forms(self):
form_data = {'something': 'something'}
form = MyForm(data=form_data)
self.assertTrue(form.is_valid())
... # other tests relating forms, for example checking the form data
https://docs.djangoproject.com/en/stable/topics/testing/tools/#django.test.SimpleTestCase.assertFormError
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
self.assertFormError(response, 'form', 'something', 'This field is required.')
Where "form" is the context variable name for your form, "something" is the field name, and "This field is required." is the exact text of the expected validation error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With