我正在尝试为具有非常简单流程的烧瓶应用程序编写测试。它在json中接收一个字符串,发布到外部api,获取数据,然后返回数据。看起来如下:
import requests
import flask
from flask import request, jsonify, make_response
from xml.etree import ElementTree
import os
app = flask.Flask(__name__)
port = int(os.getenv("PORT"))
base_url = os.getenv("URL")
@app.route('/my-route', methods=['POST'])
def authenticate():
data = request.get_json()
string_in_json = data['string_in_the_json']
passing_parameter = f"String={string_in_json}"
r = requests.get(f'{base_url}?{passing_parameter}')
return make_response(jsonify(response_text=r.text), 200)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)
我正在尝试为此编写一个测试,该测试在调用authenticate()
时实际上并没有调用requests.get
,而是只返回了200
的状态代码和一个{"test_string": "test"}
的json我尝试了以下操作:
from my_api import app
from flask import json
from unittest.mock import Mock, patch
import unittest
class TestAuthenticate(unittest.TestCase):
@patch('authenticate')
def test_authenticate(self, api):
with app.test_client() as client:
sent = {'return_url'}
api.return_value.ok = True
response = app.authenticate()
assert response.status_code == 200
但是它给我一个错误,提示验证模块不存在。我该如何工作?我也更喜欢使用pytest,但是我不确定过程看起来如何。