简体   繁体   English

如何为我的 Flask API 编写 UnitTest

[英]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.

相关问题 如何使用 unittest 测试我的烧瓶应用程序? - How can I test my flask application using unittest? 在测试我的 flask 应用程序时,如何修复我的 unittest 405?= 200 错误? - How can I fix my unittest 405 != 200 error when testing my flask application? 如何在Flask API中返回一个通用的JSON对象? - How can I return a common JSON object in my flask API? 我应该如何在Django中编写视图单元测试? - How should I write view unittest in Django? Flask 单元测试 api url 带变量 - Flask unittest api url with variable 如何为使用Flask和SQL ALChemy构建的REST API模拟单元测试 - How to mock unittest for REST API built using Flask and SQL ALChemy Python UnitTest-如何访问subTests消息而不必手动编写它们? - Python UnitTest - How can I access subTests messages without having to write them manually? 我如何才能加快Flask API的运行速度,该API具有一个获取并行请求的慢速方法? - How can I speed up my Flask API that has a single slow method that gets parallel requests? 如何使用 flask API 保存图像然后将其返回到我的 React 应用程序可以使用它 - How do I save a image using a flask API then return it to my React App can use it 如何使用Python Flask API可靠地保持SSH隧道和MySQL连接打开? - How can I reliably keep a SSH tunnel and MySQL connection open with my Python Flask API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM