Python Flask-将jsonify响应作为字符串加载

时间:2018-12-03 18:22:37

标签: python flask python-unittest

在您阅读之前,让我告诉您我已经搜索过它,但是找不到它的分辨率。

我正在使用Update Patient Set CellPhone_Number = Concat(City_PhoneCode, '9', CellPhone_Number) 编写具有GET和POST请求的Flask API的测试用例。 之前,我使用端点调用该函数,并且测试用例运行平稳,但是测试范围未涵盖服务器代码unittest。因此,我试图通过直接在测试文件node.py中调用定义的方法来运行它。

node.py

Test1.py

Test1.py

@app.route('/address/<addressId>', methods = ["GET"])
def address(addressId):
    response = searchAddress(sheet_t,addressId)
    if len(response) == 0:
        return jsonify({"note":"No transactions not found for user"})
    else:
        return jsonify(response)

错误

import unittest
import n as node
from flask import Flask
import json

app = Flask(__name__)

class TestSearch(unittest.TestCase):

    def test_address(self):
        data1 = {
            "transactions": [
                {
                    "amount": 10,
                    "recipient": "ABC",
                    "sender": "DEF",
                }
            ]
        }
        data2 = json.dumps(data1)
        res = node.address("ABC")
        self.assertEquals(res,data2)

if __name__ == '__main__':
    unittest.main()

在这里,我无法将jsonify响应作为字符串加载到测试方法上。关于如何做到这一点的任何想法?

我无法通过执行====================================================================== ERROR: test_address (__main__.TestSearch) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:/POC/test1.py", line 21, in test_address res = node.address("ABC") File "C:\POC\node.py", line 444, in address return jsonify(response) File "C:\ProgramData\Anaconda3\lib\site-packages\flask\json\__init__.py", line 309, in jsonify if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug: File "C:\ProgramData\Anaconda3\lib\site-packages\werkzeug\local.py", line 347, in __getattr__ return getattr(self._get_current_object(), name) File "C:\ProgramData\Anaconda3\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object return self.__local() File "C:\ProgramData\Anaconda3\lib\site-packages\flask\globals.py", line 51, in _find_app raise RuntimeError(_app_ctx_err_msg) RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information. ---------------------------------------------------------------------- Ran 1 test in 0.006s FAILED (errors=1) 而不是json.dumps()来更改服务器代码。

1 个答案:

答案 0 :(得分:1)

这与以字符串形式加载任何内容都没有关系。

如错误所述,您正在应用程序上下文之外工作–您试图直接调用处理程序函数,而不是使用测试框架。您应该阅读Flask docs,了解如何使用测试客户端。