Skip to content

flask 代码测试

简单测试

新建一个程序

python
from flask import Flask, request


def create_app():
    app = Flask(__name__)

    @app.get('/')
    def index():
        return "<h1>Hello World!</h1>"

    return app

新增测试配置

python
import pytest
from app import create_app


@pytest.fixture()
def app():
    app = create_app()
    app.config.update({
        "TESTING": True,
    })

    # other setup can go here

    yield app

    # clean up / reset resources here


@pytest.fixture()
def client(app):
    return app.test_client()


@pytest.fixture()
def runner(app):
    return app.test_cli_runner()

然后新建测试文件

python
def test_request_example(client):
    response = client.get("/")
    assert b"<h1>Hello World!</h1>" in response.data

文件上传测试

python
def create_app():
    app = Flask(__name__)

    @app.post('/upload')
    def test_upload():
        print(request.form)
        print(request.files)
        return "<h1>Upload</h1>"

    return app
python
from pathlib import Path

# get the resources folder in the tests folder
resources = Path(__file__).parent / "resources"


def test_upload(client):
    response = client.post("/upload", data={
        "name": "Flask",
        "theme": "dark",
        "picture": (resources / "picture.png").open("rb"),
    })
    assert response.status_code == 200