在Flask单元测试中获得400

时间:2017-06-16 14:48:43

标签: python unit-testing flask

我正在为Flask中的文件上传功能编写单元测试。

该应用程序在本地运行良好,但单元测试会抛出400.谢谢!

这是我的app.py

from flask import Flask, render_template, request
app = Flask(__name__)
app.config["TESTING"] = True


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/uploader', methods = ['GET','POST'] )
def upload_photo():
    if request.method == 'POST':
        photo = request.files['photo']
        resp = app.make_response(photo.read())  
        resp.mimetype = 'image/jpeg'
        return resp

if __name__ == '__main__':
    app.run(debug=True)

这是我的测试:

import unittest
import io
from app import app


class TestCase(unittest.TestCase):

    def setUp(self):
        self.client = app.test_client()

    def test_upload_photo(self):            
        result = self.client.post('/uploader', 
    content_type='multipart/form-data', follow_redirects=True, 
    data=dict(upload_var=(io.BytesIO(b'photo'), 'photo')))
        print(result.data) 
        self.assertTrue(result.status_code == 200)


if __name__ == "__main__":
    unittest.main()`

1 个答案:

答案 0 :(得分:0)

将数据字典中的upload_var更改为photo,因为您的处理程序函数期望调用该文件。