为 Web 应用程序编写测试

Writing a test for a web application

我一边学习一边写一个web应用,我写了一个接收文件的函数。现在我想为 it.i 编写一个测试函数,我正在使用 pytest。

在测试函数中,我将被要求提交一个文件,我已经检查过 requests 是否这样做,但我没有得到它。请显示一些光线,以便我可以为以下给定函数创建一个测试函数。

@app.post('/check/<number>')
def file_upload(number):
    u_name = request.forms.get('username')  # accepting username
    time = datetime.datetime.now()
    # type(uploaded) == <class 'bytes'>
    uploaded = request.files.get('upload').file.read()  # uploaded outputs by user
    expected = questions[number].output
    expected = expected.strip()
    uploaded = uploaded.strip()
    ans = (uploaded == expected)
    usernames[u_name].append(Submission(question=number, time=time,
                                        output=uploaded, result=ans))
    if not ans:
        return 'Wrong answer'
    else:
        return 'Solved! Great Job!'

我想要 200 响应,同时 运行 测试文件。

使用WebTest:

from webtest import TestApp

test_app = TestApp(app)
resp = test_app.post('/check/123')  # by default, this fails if your app returns anything except HTTP 2XX

Stack Overflow 中的一些其他示例:

Unit testing Bottle app with WebTest