如何始终为使用 PyTest 测试的 Flask 应用程序提供上下文?
How to always provide a context for Flask app tested with PyTest?
我尝试在 Flask 应用程序上使用 Pytest 实施单元测试,但我很难做到。
我的 Flask 应用程序在大多数功能(这里 some_method)上使用配置文件来说明。因此,似乎 我应该为每次调用我想测试的任何方法 提供一个上下文。似乎我可以在每次调用时使用“with app.app_context():”来实现它。
我读了 official testing documentation 但他们谈论创建客户端。由于我想做单元测试,我需要调用非顶层的子函数。
有没有办法始终提供上下文,而无需在每次调用时手动推送上下文?
请在下面找到我当前的实现:
main.py
from flask import current_app
def main(request):
current_app.config.from_envvar('APPLICATION_SETTINGS')
print(some_method())
return 'OK'
def some_method():
# doing some stuff using the context
world = current_app.config['SECRET_KEY']
return world
test_main.py
import pytest
from flask import current_app, Flask
from main import main, some_method
@pytest.fixture
def app():
app = Flask(__name__)
# load here any potential configuration configuration
return app
def test_some_method(app):
with app.app_context():
# calling and doing some assertion
some_method()
PS:我的主文件中没有 app = Flask(name) 因为我在 Functions Framework 上 运行
pytest-flask 似乎在任何调用中配置上下文。
conftest.py
import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
return app
test_main.py
import pytest
from flask import current_app, Flask
from main import main, some_method
def test_some_method(app):
#with app.app_context():
# calling and doing some assertion
some_method()
有效。
我尝试在 Flask 应用程序上使用 Pytest 实施单元测试,但我很难做到。
我的 Flask 应用程序在大多数功能(这里 some_method)上使用配置文件来说明。因此,似乎 我应该为每次调用我想测试的任何方法 提供一个上下文。似乎我可以在每次调用时使用“with app.app_context():”来实现它。
我读了 official testing documentation 但他们谈论创建客户端。由于我想做单元测试,我需要调用非顶层的子函数。
有没有办法始终提供上下文,而无需在每次调用时手动推送上下文?
请在下面找到我当前的实现:
main.py
from flask import current_app
def main(request):
current_app.config.from_envvar('APPLICATION_SETTINGS')
print(some_method())
return 'OK'
def some_method():
# doing some stuff using the context
world = current_app.config['SECRET_KEY']
return world
test_main.py
import pytest
from flask import current_app, Flask
from main import main, some_method
@pytest.fixture
def app():
app = Flask(__name__)
# load here any potential configuration configuration
return app
def test_some_method(app):
with app.app_context():
# calling and doing some assertion
some_method()
PS:我的主文件中没有 app = Flask(name) 因为我在 Functions Framework 上 运行
pytest-flask 似乎在任何调用中配置上下文。
conftest.py
import pytest
from flask import Flask
@pytest.fixture
def app():
app = Flask(__name__)
return app
test_main.py
import pytest
from flask import current_app, Flask
from main import main, some_method
def test_some_method(app):
#with app.app_context():
# calling and doing some assertion
some_method()
有效。