当我在Redis DB中查询一个不存在的键时,我的Flask应用程序期望得到一个404响应状态代码-但却收到了一个200代码

xlpyo6sf  于 7个月前  发布在  Redis
关注(0)|答案(1)|浏览(55)

我在我的Python Flask应用程序中遇到了一个测试失败,当我在Redis数据库中查询一个不存在的键时,我希望得到一个404响应状态代码,但是我总是收到一个200的响应状态代码。我试图写一个Python Flask应用程序来作为一个透明的Redis代理。它的目的是提供一个HTTP Web服务来与Redis DB交互。路由处理程序/代码如下:

from flask import Flask, request, jsonify
import redis 

app = Flask(__name__)

redis_client = redis.StrictRedis(host = 'localhost', port=6379, db=0)
@app.route('/get/<key>', methods= ['GET'])
def get_data(key):
    value = redis_client.get(key)
    if value:
        return jsonify({'key': key, 'value': value.decode('utf-8')})
    else:
        return jsonify({'message': 'Key not found'}, 404)
if __name__ == '__main__':
    app.run()

字符串
我尝试编写一些单元测试来验证它是否正常工作:

import unittest
from flask import Flask, jsonify
import redis

from redis_proxy import app

class RedisProxyTest(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
    def test_get_data(self):
        redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
        redis_client.set('test_key', 'test_value')
        response = self.app.get('/get/test_key')
        self.assertEqual(response.status_code, 200)
        expected_data = {'key': 'test_key', 'value': 'test_value'}
        self.assertEqual(response.get_json(), expected_data)

    def test_get_data_key_not_found(self):
        response = self.app.get('/get/xxx')
        print(response.data)
        print(response.status_code)
        self.assertEqual(response.status_code, 404)
        expected_data = {'message': 'Key not found'}
        self.assertEqual(response.get_json(), expected_data)
if __name__ == '__main__':
    unittest.main()


我还添加了一些print语句来打印数据库中存在键的分支的响应数据和状态代码。
下面是这些测试的输出:

python3 -m unittest redis_proxy_test.py
.b'[{"message":"Key not found"},404]\n'
200
F
======================================================================
FAIL: test_get_data_key_not_found (redis_proxy_test.RedisProxyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/redis-proxy/redis_proxy_test.py", line 26, in test_get_data_key_not_found
    self.assertEqual(response.status_code, 404)
AssertionError: 200 != 404

----------------------------------------------------------------------
Ran 2 tests in 0.006s

FAILED (failures=1)


另外-关键字'xxx'不存在于数据库中,所以我不确定为什么状态代码没有反映这一点。

127.0.0.1:6379> GET xxx
(nil)


任何想法,为什么这是失败的将是真正的赞赏。

yhuiod9q

yhuiod9q1#

404更改为:

return jsonify({'message': 'Key not found'}), 404

字符串

相关问题