运行测试之前的 Pytest 和数据库清理

Mos*_*sin 4 python testing integration-testing pytest python-3.x

我正在使用 Flask 构建 Web 服务和 pytest 进行测试

我正在使用 pytest 固定装置来设置和拆除测试资源,但我需要测试一个 POST 端点,它将在数据库中创建一些记录

我们如何清理这些记录?

xve*_*ges 5

您可以使用夹具来进行清理

@pytest.fixture
def cleanup():
    yield
    # This is executed when the test using the fixture is done
    db_cleanup()

def test_records_created(cleanup):     # pylint: disable=redefined-outer-name,unused-argument
    response = app.test_client().post('/path', json=payload)
    assert response.status_code == 200
    assert ...
Run Code Online (Sandbox Code Playgroud)