Python 3.x 文件上传的单元测试用例
我创建了一个flask应用程序,在这里我上传一个文件,然后预测文件的类型。我想为同样的问题编写单元测试用例。我不熟悉python中的单元测试,因此非常困惑!。我的代码有两部分,第一部分是Main函数,它调用分类方法 main.py-在这里上传文件,然后调用func_predict函数,该函数返回输出Python 3.x 文件上传的单元测试用例,python-3.x,unit-testing,Python 3.x,Unit Testing,我创建了一个flask应用程序,在这里我上传一个文件,然后预测文件的类型。我想为同样的问题编写单元测试用例。我不熟悉python中的单元测试,因此非常困惑!。我的代码有两部分,第一部分是Main函数,它调用分类方法 main.py-在这里上传文件,然后调用func_predict函数,该函数返回输出 upload_parser = api.parser() upload_parser.add_argument('file', location='files',
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)
现在我的困惑是,我如何模拟上传的文件,上传的文件是文件存储类型。另外,我应该为哪种方法执行测试,应该是“/分类”还是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()
我完全迷路了!我知道之前有过一些问题,但我想不出来 我终于偶然发现了如何测试它,以防有人在寻找类似的东西
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包装它。这对我有用