-3

I am trying to write a test case for my post end point, but I seriously do not know what I am doing wrong.

views.py

The user can post a product by typing the name, the price and category I have hard coded:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

products = [] 


class Product(Resource):

    def post(self, name):
        if next(filter(lambda x: x['name'] == name, products), None):
            return {'message':
                    "A product with name '{}' already exists."
                    .format(name)}, 400  
        data = request.get_json()
        product = {'id': len(products) + 1,
                   'name': name, 'price': data['price'],
                   'category': data['category']}
        products.append(product)
        return product, 201 

When I run it I get the JSON data with a 201 OK response.

{
    "price": 50,
    "category": "stationery",
    "name": "pencil",
    "id": 2
}

But when I test it:

test_product.py

import unittest
import json
from app import create_app


class ProductTestCase(unittest.TestCase):
    """This is the class for product test cases"""

    def setUp(self):
        self.app = create_app('testing')
        self.client = self.app.test_client

def test_to_add_product(self):
    """Test method to add product"""
     """Is this how the json payload is passed"""
    add_product = self.client().post('/api/v1/product/pencil', 
        data={
        "price": 50,
        "name": "pencil",
        "category": "stationery"
   },
        content_type='application/json')
    self.assertEqual(add_product.status_code, 201)

I get the following error:

E       AssertionError: 400 != 201

app/tests/v1/test_product.py:22: AssertionError

What does this mean, and how can I fix it?

EDIT

folowing this answer,How to send requests with JSONs in unit tests, this worked for me:

def test_to_add_product(self):
    """Test method to add product"""
    add_product = self.client().post('/api/v1/product/pencil',
                                     data=json.dumps(
                                         dict(category='category',
                                              price='price')),
                                     content_type='application/json')
    self.assertEqual(add_product.status_code, 201)
Olal
  • 162
  • 1
  • 2
  • 12

1 Answers1

0

HTTP 400 means "bad request". It indicates that the request you're sending to your API endpoint is somehow invalid.

I don't see where you're passing any JSON data to your endpoint in your test. If JSON data is required (it appears to be since you have data = request.get_json() in your code) that would explain the bad request response.

If you include a valid JSON payload in your test you should see the response you expect.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257