I am trying to write unit-test
to my create function
in Django project. This is my first experience creating of unit-tests. Why I cant create new data? From error I understand that there is no articles in test database. Where I did mistake?
tests.py:
class ArticleViewTestCase(TestCase):
def setUp(self):
self.user = User.objects.create(
username='user',
email='[email protected]',
password='password'
)
self.client = Client()
def test_article_create(self):
self.assertTrue(self.user)
self.client.login(username='user', password='password')
response = self.client.get('/article/create/')
self.assertEquals(response.status_code, 200)
with open('/home/nurzhan/Downloads/planet.jpg', 'rb') as image:
imageStringIO = StringIO(image.read()) # <-- ERROR HERE
response = self.client.post(
'/article/create/',
content_type='multipart/form-data',
data={
'head': 'TEST',
'opt_head': 'TEST',
'body': 'TEST',
'location': 1,
'public': True,
'idx': 0,
'image': (imageStringIO, 'image.jpg')
},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Article.objects.all().count(), 1)
ERROR:
Traceback (most recent call last):
File "/home/nurzhan/CA/article/tests.py", line 26, in test_article_create
imageStringIO = StringIO(image.read())
TypeError: 'module' object is not callable
You can override form_invalid
and check it data in your test
class ArticleCreateView(CreateView):
# YOUR code here
def form_invalid(self, form):
data = {'status': False, 'errors': form.errors}
return JsonResponse(data, , status=500)
in test method:
with open('/home/nurzhan/Downloads/planet.jpg', 'rb') as image:
response = self.client.post('/article/create/',
data={
'head': 'TEST',
'opt_head': 'TEST',
'body': 'TEST',
'location': 1,
'public': True,
'idx': 0,
'image': image
},
follow=True, format='multipart'
)