Previous article As I said, I would like to make a test for a page with a Form. But for some reason I got an error and couldn't test. I thought I should test the Form for the time being, but when I thought about it, I couldn't test the processing after that, so it didn't help. After all, I have to POST and check the context.
The solution is as follows. All I had to do was open it with open, insert the file handler, and POST it.
tests.py
from django.test import TestCase, Client
from django.contrib.auth.models import User
class Test_Model_Create(TestCase):
def setUp(self):
#Create test user
self.user = User.objects.create_user(username='tdd', email='[email protected]', password='test_pass')
self.client=Client()
#Login
self.client.login(username='tdd', password="test_pass")
def test_step1(self):
with open('./path/test.csv') as f:
data = {
"nametest" : "test",
"file_data" : f
}
response = self.client.post('/model_create/form/', data)
self.assertIn('file_data', response.context, "file in context_data not included")
It's okay like this.
The point that was stuck is
--I did POST after closing the file.
--I passed a file instead of a file handler (File (open ('./ path / excel_test.csv'))
)
That was the reason. I also tried using RequestFactory instead of Client, but that was the reason ...
By the way, I have to give two files this time, but in such a case it seems that I can write as below.
tests.py
with open('./path/testA.csv') as fa,open('./path/testB.csv') as fb:
data = {
"name" : "test",
"file_dataA" : fa,
"file_dataB" : fb
}
response = self.client.post('/model_create/form/', data)
The with sentence is really easy. It's amazing.
I'm really wondering why I was so worried. I want to reduce Pokamis.
Recommended Posts