我有一条仅用于 POST 请求的路由,如果满足条件,它会返回 json 响应。是这样的:
@app.route('/panel', methods=['POST'])
def post_panel():
# Check for conditions and database operations
return jsonify({"message": "Panel added to database!"
"success": 1})
我正在使用flask-sslify将 http 请求强制发送到 https。
我正在使用 Flask 测试客户端和 unittest 测试这条路线。测试功能类似如下:
class TestAPI2_0(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
create_fake_data(db)
self.client = self.app.test_client()
def tearDown(self):
....
def test_post_panel_with_good_data(self):
# data
r = self.client.post('/panel',
data=json.dumps(data),
follow_redirects=True)
print(r.data)
self.assertEqual(r.status_code, 200)
输出正好在下面:
test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n'
======================================================================
FAIL: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/tanjibpa/work/craftr-master/tests/test_api_2_0.py", line 110, in test_post_panel_with_good_data
self.assertEqual(r.status_code, 200)
AssertionError: 405 != 200
我收到一个错误,即 Method is not allowed in that route。如果我将 GET 指定methods=['GET', 'POST']
为路由测试的方法 ( ) 似乎有效。但是为什么测试客户端发出 GET 请求呢?除了为路由指定 GET 请求之外,有什么办法吗?
更新:
如果这样做:
@app.route('/panel', methods=['GET', 'POST'])
def post_panel():
if request.method == 'POST':
# Check for conditions and database operations
return jsonify({"message": "Panel added to database!"
"success": 1})
return jsonify({"message": "GET request"})
我得到这样的输出:
test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'{\n "message": "GET request"\n}\n'