The articles are created by admin. The authenticated user has the right to read them and to Like them or Unlike them. I need to test the view.
The model is:
class Like(models.Model):
reader = models.ForeignKey(User, on_delete = models.CASCADE)
article = models.ForeignKey(Article, on_delete = models.CASCADE)
The view is as follows (the user should not pass any params - he "likes" the article and a new registry is created based on his id and the article id):
class LikeCreate(generics.CreateAPIView):
queryset = Like.objects.all()
serializer_class = LikeSerializer
The test class is:
class TestLikeViews(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.user = User.objects.create_user(
username='Name', email='test@company.com', password='top_secret')
self.article = Article.objects.create(
author='X', title='Title', body='Body content...')
self.like = Like.objects.create(
reader=self.user, article=self.article)
def test_like_post_user(self):
request = self.factory.post('likes/', kwargs={'reader': self.user, 'article': self.article})
request.user = self.user
response = LikeCreate.as_view()(request, reader=self.user, article=self.article)
self.assertEqual(response.status_code, 201,
f'Expected Response Code 201 - CREATED, received {response.status_code} instead.')
I get the following error:
line 105, in test_like_post_user
f'Expected Response Code 201 - CREATED, received {response.status_code} instead.')
AssertionError: 400 != 201 : Expected Response Code 201 - CREATED, received 400 instead.
Line 105 is the line with the f-string - the last line. However, when I start the server and check this endpoint manually - everything works just fine. I suppose the problem lies in the way I formulated the test function.
Thank you!
The problem may rely in the way that you handle the call to the post function, where you have the kwargs sent as named argument. This line instead should be fine, also passing just the PKs and not the whole object:
request = self.factory.post('likes/', {'reader': self.user.pk, 'article': self.article.pk})
That is the usual structure the class APIRequestFactory handles requests.