Because of CSRF, even if I send a file by POST, an error is returned! I thought, but I knew I should test the form. ~~ I really wanted to test the context to POST and come back, but I didn't know. There may be a way, so I will add it when I understand it. ~~
Since it has been resolved, it is summarized in this article.
Let's say you want to test the Form below.
forms.py
from django import forms
class FormTest(forms.Form):
table_name=forms.CharField(max_length=30)
file_data= forms.FileField()
The file upload test for this is written as below.
tests.py
from django.core.files import File
from ..forms import DocumentForm
class Test_Model_Create(TestCase):
def setUp(self):
self.file_data=File(open('./path/test.csv'))
def test_step1_form(self):
data = {
"table_name":"name_test"
}
files={
"file_data":self.file_data
}
form = DocumentForm(data,files)
self.assertTrue(form.is_valid())
If you throw the correct data, ʻis_valid ()` will return True.
As I wrote at the beginning, I couldn't POST the file correctly, probably because of CSRF. After that, I changed it as above, but it didn't go through easily. In conclusion ** Custom validation was bad. ** ** Well, it worked fine rather than bad, but the data I wrote in the test didn't match it. To avoid being like yourself, please make sure that you show validation errors when testing your form.
tests.py
print(form.errors)
Now you can see the contents of the validation error. Please check if the error is as expected.
Recommended Posts