I'm trying to write test for my simple CRUD. But i have a problem with testing post request: There is my test:
def test_post_product(self):
product1 = Product.objects.create(title='Chicken Breast',proteins=24.00,carbs=0.00,fats=3.00,calories=113)
serialized_data = ProductSerializer(product1).data
response = self.client.post(reverse('product-list'), data=serialized_data, content_type='application/json')
print(response)
self.assertEqual(HTTP_201_CREATED, response.status_code)
But in self.assertEqual i have response status code 400 instead of 201. What i'm doing wrong?
It looks like you are creating a product in your database and then trying to post the serialized data for that product to the product-list
endpoint. However, since the product already exists in the database, this will result in a 400 response because you are trying to create a duplicate entry.
Instead of creating the product in the database and then trying to post the serialized data, you can create the data for the product directly and then post that to the endpoint. Here is an example of how you could do that:
def test_post_product(self):
# Create the data for the product you want to post
data = {
'title': 'Chicken Breast',
'proteins': 24.00,
'carbs': 0.00,
'fats': 3.00,
'calories': 113
}
# Post the data to the endpoint
response = self.client.post(reverse('product-list'), data=data, content_type='application/json')
# Assert that the response has a 201 status code
self.assertEqual(HTTP_201_CREATED, response.status_code)
Since the product does not already exist in the database, the endpoint should return a 201 response.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments