[英]How can i write UnitTest for my Flask API
I'm fairly new to unit testing, and im required to write some unit test for my flask api.我对单元测试相当陌生,我需要为我的 flask api 编写一些单元测试。 Any idea how I can write unit tests for this code below?知道如何为下面的代码编写单元测试吗? Any examples and help will be appreciated.任何示例和帮助将不胜感激。 I tried to create a seperate file to start unittesting but im not able to import the flask app into the file as it gives me module errors.我尝试创建一个单独的文件来开始单元测试,但我无法将 flask 应用程序导入文件,因为它给了我模块错误。 And ontop of that im not sure how to test each function in this application.除此之外,我不确定如何在此应用程序中测试每个 function。
from flask import Flask, request, Response, send_file
import machine_learning_model.Object_detection.yoloModel as yoloModel
import jsonpickle
import numpy as np
import cv2
import base64
import json
import ast
import requests
app = Flask(__name__)
url_base = 'http://192.168.1.6:5000'
predict_image_api = '/v1/api/predict'
bounding_box_API = '/v1/resoures/predict_images/'
# Load YOLO model
labels, colors = yoloModel.load_label("coco.names")
net, ln = yoloModel.load_model()
# route http posts to this method
@app.route(predict_image_api, methods=['GET', 'POST'])
def predict():
loaded_body = parse_json_from_request(request)
# Conversion of base64 image back to its binary
img_original = base64.b64decode(loaded_body['image'])
# Conversion of image data to unit8
jpg_as_np = np.frombuffer(img_original, dtype=np.uint8)
# Decoding the image
image = cv2.imdecode(jpg_as_np, cv2.IMREAD_COLOR)
idxs, boxes, confiences, centers, classIDs = yoloModel.detectObjectFromImage(image, net, ln)
objectProperty = yoloModel.bouding_box(idxs, image, boxes, colors, labels, classIDs, confiences)
response = {
'objectProperty':''
}
response['objectProperty'] = objectProperty
print(response)
# encode response using jsonpickle
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
@app.route(bounding_box_API+'<name>', methods=['GET'])
def get_image(name):
filename = 'predict_images/output_resize_%s.jpg' % name
print(filename)
return send_file(filename, mimetype='image/gif')
def parse_json_from_request(request):
body_dict = request.json
body_str = json.dumps(body_dict)
loaded_body = ast.literal_eval(body_str)
return loaded_body
if __name__ == "__main__":
# start flask app
app.run()
First of all, I recommend to use pytest .首先,我推荐使用pytest 。
In order to be correcly unit-tested, your program should be split into simple functions that preferably perform only 1 task.为了进行正确的单元测试,您的程序应拆分为最好只执行一项任务的简单函数。
Since you are working with requests
, you may want to test your HTTP calls.由于您正在处理requests
,您可能需要测试您的 HTTP 调用。 A good way to test them is to use responses in order to mock the target server or API.测试它们的一个好方法是使用响应来模拟目标服务器或 API。
Pragmatically, start to create a folder tests/
and create a file per class or per function, named after the class or the function you want to test (like so test_your_function.py
). Pragmatically, start to create a folder tests/
and create a file per class or per function, named after the class or the function you want to test (like so test_your_function.py
). Inside this file, write unit tests for your functions (ie a function that starts by test_
so that pytest
will identify it as a unit test).在此文件中,为您的函数编写单元测试(即,以 test_ 开头的test_
以便pytest
将其识别为单元测试)。 Each unit test should contain an assert tested_output_value == expected_output_value
statement, so that your unit test fails if your function does not return the desired tested_output_value
.每个单元测试都应该包含一个assert tested_output_value == expected_output_value
语句,这样如果您的 function 没有返回所需的tested_output_value
,您的单元测试就会失败。
For instance, if you want to test your function predict
one way to do it would be write a function that requests your localhost server and to verify that the response is what you expected.例如,如果您想测试您的 function predict
一种方法是编写一个请求您的本地主机服务器的 function 并验证响应是否符合您的预期。 NB: Before running pytest, make sure that you have started your server;)注意:在运行 pytest 之前,请确保您已经启动了您的服务器;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.