无法使用 python 对图片上传进行单元测试

Can't unit-test image upload with python

我有一个函数可以通过 POST 从表单接收数据。我有一些文本字段和一个文件字段以上传图像 (.jpg)。

该函数期望从 request.files['file'] 获取图像文件。作为"file"图像表单域的名称。

我不知道如何 运行 我的函数作为测试并将它传递给 request.files[] 参数,就像我对其他字段值(名称、密码、邮件、 phone...)

这是我要测试的功能(app.py):

@app.route('/registering', methods=['GET', 'POST'])
def registering():
    if request.method == 'POST':
        userCheck = request.form['username']
        userCheck2 = request.form['email']
        userCheck3 = request.form['password']
        userCheck4 = request.form['passwordCheck']
        userCheck5 = request.form['phone']

        file = request.files['file']
        if file and allowed_file(file.filename):

            newUser = users(userCheck, userCheck2, userCheck5, userCheck3)
            db.session.add(newUser)
            db.session.commit()
            userName = users.query.filter_by(
                    userName=userCheck, userPass=userCheck3).first()

            session['logged_in'] = True
            session['user_id'] = userName.id

            filename = str(userName.id)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename + ".jpg"))

            flash('"Registered Successfully"')
            return redirect(url_for('friendList'))

    else:
        return render_template('register.html')

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

这是我的测试 (app_tests.py):

import os
import app
import unittest
import tempfile

class AppTestCase(unittest.TestCase):

    def setUp(self):
        self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
        app.app.config['TESTING'] = True
        self.app = app.app.test_client()

    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(app.app.config['DATABASE'])


    def registering(self, username, email, password, passwordCheck, phone, file):
    return self.app.post('/registering', data=dict(
        username=username, 
        email=email, 
        password=password, 
        passwordCheck=passwordCheck, 
        phone=phone,
        file=file
    ), follow_redirects=True)

    def test_registering(self):
        #successfully registered

        rv = self.registering('TestUser', 'test@test.com', 'passwordTest', 'passwordTest', '900102030')
        assert 'Registered Successfully' in rv.data
        #existing username/user
        rv = self.registering('Hulda', 'hulda@hulda.com', 'passwordHulda', 'passwordHulda', '900102030')
        assert 'Username Taken' in rv.data
         #no username
        rv = self.registering('', 'santana@santana.com', 'passwordSantana', 'passwordSantana', '900102030')
        assert 'Username required' in rv.data
        #no email
        rv = self.registering('Santana', '', 'passwordSantana', 'passwordSantana', '900102030')
        assert 'Email required' in rv.data
        #no password
        rv = self.registering('Santana', 'santana@santana.com', '', 'passwordSantana', '900102030')
        assert 'Password required' in rv.data
        #no password confirmation
        rv = self.registering('Santana', 'santana@santana.com', 'passwordSantana', '', '900102030')
        assert 'Confirm password' in rv.data
        #no password match
        rv = self.registering('Santana', 'santana@santana.com', 'passwordSantana', 'passwordSsssssntana', '900102030')
        assert 'Retype passwords' in rv.data
        #no phone
        rv = self.registering('Santana', 'santana@santana.com', 'passwordSantana', 'passwordSantana', '')
        assert 'Phone required' in rv.data

我找到了解决方案。给你,以防有人有相同的测试需求:

def registering(self, username, email, password, passwordCheck, phone):
    with open('static/test.jpg') as test:
        imgStringIO = StringIO(test.read())

    return self.app.post('/registering',
        content_type='multipart/form-data',
        data=dict(
            {'file': (imgStringIO, 'test.jpg')},
            username=username,
            email=email,
            password=password,
            passwordCheck=passwordCheck,
            phone=phone
        ), follow_redirects=True
    )


def test_03_registering(self):
    rv = self.registering('TestUser', 'test@test.com', 'passwordTest', 'passwordTest', '900102030')
    assert 'Registered Successfully' in rv.data

FWIW - 在 pytest 中测试烧瓶应用程序时,我执行了以下操作:

@pytest.fixture
def example_image():
    filename = 'data/example_image.jpeg'
    fileobj = open(fileobj, 'rb')
    return FileStorage(stream=fileobj, filename="example_image.jpeg", content_type="image")

备注文件必须是'rb'类型

def test_image_upload(client, example_image):
data = {
    'model_id': 2,
    'image': example_image,
}
headers = {'content_type': 'multipart/form-data'}
response = client.post(ROUTE, data=data, headers=headers)
assert response.status_code == 200

这将测试查找以下内容的代码路径

request.files.get('image')