首页 > 解决方案 > 文件上传烧瓶的单元测试用例

问题描述

我创建了一个烧瓶应用程序,我在其中上传一个文件,然后预测文件的类型。我想为此编写单元测试用例。我是 python 单元测试的新手,因此非常困惑!我的代码有两部分,第一部分是 Main 函数,然后调用分类方法。

main.py - 这里文件正在上传,然后我们调用 func_predict 函数返回输出

upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
                       type=FileStorage, required=True)
@api.route('/classification')
@api.expect(upload_parser)
class classification(Resource):

    def post(self):
    """
       predict the document
    """
        args = upload_parser.parse_args()
        uploaded_file = args['file']
        filename = uploaded_file.filename
        prediction,confidence = func_predict(uploaded_file)
        return {'file_name':filename,'prediction': prediction,'confidence':confidence}, 201

predict.py :该文件包含执行实际预测工作的 func_predict 函数。它将上传的文件作为输入

def func_predict(file):
    filename = file.filename #filename
    extension = os.path.splitext(filename)[1][1:].lower() #file_extension
    path = os.path.join(UPLOAD_FOLDER, filename) #store the temporary path of the file
    output = {}
    try:
    # Does some processing.... some lines which are not relevant and then returns the two values
    return (''.join(y_pred),max_prob)

现在我的困惑是,我如何模拟上传的文件,上传的文件是 FileStorage 类型的。另外,我应该对哪种方法进行测试,应该是“/分类”还是 func_predict。

我试过下面的方法,虽然我没有得到任何成功。我创建了一个 test.py 文件并从 main.py 导入了分类方法,然后将文件名传递给数据

from flask import Flask, Request
import io
import unittest
from main import classification

class TestFileFail(unittest.TestCase):

    def test_1(self):

        app = Flask(__name__)
        app.debug = True
        app.request_class = MyRequest


        client = app.test_client()
        resp = client.post(
            '/classification',
            data = {
            'file': 'C:\\Users\\aswathi.nambiar\\Desktop\\Desktop docs\\W8_ECI_1.pdf'
        }, content_type='multipart/form-data'
    )
        print(resp.data)

        self.assertEqual(
        'ok',
        resp.data,
    )


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

我完全迷路了!我知道有更早的问题,但我无法弄清楚。

标签: python-3.xunit-testing

解决方案


我终于偶然发现了如何测试它,以防有人在寻找类似的东西。

from predict_main_restplus import func_predict 
from werkzeug.datastructures import FileStorage
file = None

def test_classification_correct():
    with open('W8-EXP_1.pdf', 'rb') as fp:
        file = FileStorage(fp)
        a , b = func_predict(file)
        assert (a, b) == ('W-8EXP',90.15652760121652)

所以,我们在这里测试 predict.py 中的预测函数,它返回两个值,预测结果和预测的置信度。我们可以使用 open(file) 模拟上传,然后用 FileStorage 包装它。这对我有用。


推荐阅读