Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why i have the bad request 400?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading