unit-testing - 无法使用 python 对图像上传进行单元测试

标签 unit-testing python-2.7 flask

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

该函数期望从 request.files['file'] 获取图像文件。 “file”是图像表单字段的名称。

我不知道如何运行我的函数作为测试并向其传递 request.files[] 参数,就像我对其他字段值(名称、密码、邮件、电话...)所做的那样

这是我想测试的功能(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', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6e7f696e5a6e7f696e34797577" rel="noreferrer noopener nofollow">[email protected]</a>', 'passwordTest', 'passwordTest', '900102030')
        assert 'Registered Successfully' in rv.data
        #existing username/user
        rv = self.registering('Hulda', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea829f868e8baa829f868e8bc4898587" rel="noreferrer noopener nofollow">[email protected]</a>', 'passwordHulda', 'passwordHulda', '900102030')
        assert 'Username Taken' in rv.data
         #no username
        rv = self.registering('', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3340525d47525d527340525d47525d521d505c5e" rel="noreferrer noopener nofollow">[email protected]</a>', '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', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dfeece3f9ece3eccdfeece3f9ece3eca3eee2e0" rel="noreferrer noopener nofollow">[email protected]</a>', '', 'passwordSantana', '900102030')
        assert 'Password required' in rv.data
        #no password confirmation
        rv = self.registering('Santana', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e291838c96838c83a291838c96838c83cc818d8f" rel="noreferrer noopener nofollow">[email protected]</a>', 'passwordSantana', '', '900102030')
        assert 'Confirm password' in rv.data
        #no password match
        rv = self.registering('Santana', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f487959a80959a95b487959a80959a95da979b99" rel="noreferrer noopener nofollow">[email protected]</a>', 'passwordSantana', 'passwordSsssssntana', '900102030')
        assert 'Retype passwords' in rv.data
        #no phone
        rv = self.registering('Santana', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1360727d67727d725360727d67727d723d707c7e" rel="noreferrer noopener nofollow">[email protected]</a>', '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', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a6b7a1a692a6b7a1a6fcb1bdbf" rel="noreferrer noopener nofollow">[email protected]</a>', 'passwordTest', 'passwordTest', '900102030')
    assert 'Registered Successfully' in rv.data

关于unit-testing - 无法使用 python 对图像上传进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28276453/

相关文章:

android - 如何使用 Mockk 模拟和测试 RxJava/RxAndroid?

c# - 使用 .runsettings 文件时,代码覆盖率中不包含异步方法

python - 如何使用 eyes3 和 python2.7 从 mp3 文件访问发布日期或年份

python - 如何将值存储为特定于用户的全局变量?

python - 使用 Flask-SQLAlchemy 事件 API 广播到 Flask-SocketIO?

c# - 使用 Moq 模拟不安全的接口(interface)

unit-testing - 如何使用新的测试库测试 Dart Polymer 元素?

python - Python 中每次保存的文件命名计数

python - 使用 Python 在 Windows 中发送 SIGINT

python - 使用 Flask ReSTLess 自定义 GET 方法