我是Python的新手,我尝试在Flask上实现REST API服务。我遇到了与代码测试有关的问题。我的Flask应用看起来像这样:from flask import Flask, jsonify, make_response, requestfrom flask_httpauth import HTTPBasicAuthimport osauth = HTTPBasicAuth()@auth.get_passworddef get_password(username): if username == os.environ['SERVICE_KEY']: return os.environ['SERVICE_PASS'] return None@auth.error_handlerdef unauthorized(): return make_response(jsonify({'error': 'Unauthorized access'}), 403)app = Flask(__name__)tweets = [ { 'id': 1, 'profileId': '1', 'message': 'My test tweet' }, { 'id': 2, 'profileId': '1', 'message': 'Second tweet!' }]@app.route('/api/v1/tweets', methods=['GET'])@auth.login_requireddef get_tweets(): return jsonify({'tweets': tweets}), 200@app.errorhandler(404)@auth.login_requireddef not_found(error): return make_response(jsonify({'error': 'Not found'}), 404)if __name__ == '__main__': app.run(debug=True)这是我的测试(当前仅用于not_found方法):import unittestfrom app import appclass TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_404(self): rv = self.app.get('/i-am-not-found') self.assertEqual(rv.status_code, 404)if __name__ == '__main__': unittest.main()但是,当我尝试运行测试时,由于收到“未经授权的访问”响应而失败:>python test.pyF======================================================================FAIL: test_404 (__main__.TestApp)----------------------------------------------------------------------Traceback (most recent call last): File "test.py", line 25, in test_404 self.assertEqual(rv.status_code, 404)AssertionError: 403 != 404----------------------------------------------------------------------Ran 1 test in 0.000sFAILED (failures=1)哪种测试路由方法的方法更正确地处理授权?我该如何修复失败的测试?
添加回答
举报
0/150
提交
取消