Flask AssertionError:400!= 201

时间:2018-10-15 12:36:53

标签: python flask python-unittest

我正在尝试为我的发布端点编写一个测试用例,但我真的不知道自己在做什么错。

views.py

用户可以通过键入我已经硬编码的namepricecategory发布产品:

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 

当我运行它时,我得到了201 OK响应的JSON数据。

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

但是当我测试时:

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)

我收到以下错误:

E       AssertionError: 400 != 201

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

这是什么意思,我该如何解决?

编辑

遵循这个答案How to send requests with JSONs in unit tests,这对我有用:

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)

1 个答案:

答案 0 :(得分:0)

HTTP 400表示“错误请求”。这表明您发送到API端点的请求在某种程度上无效。

我看不到要在测试中将任何JSON数据传递到端点的位置。如果需要JSON数据(这似乎是因为您的代码中包含data = request.get_json(),则可以解释错误的请求响应。

如果您在测试中包含有效的JSON有效负载,您应该会看到期望的响应。

相关问题