【发布时间】:2019-03-19 21:28:49
【问题描述】:
我正在尝试为我的帖子端点编写一个测试用例,但我真的不知道我做错了什么。
views.py
用户可以通过输入name、price 和category 来发布产品,我已经硬编码:
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)
【问题讨论】:
-
如果您将 content_type 指定为 json,您不需要传递有效负载吗?
标签: python flask python-unittest