conftest.py
This file
Path
tests/conftest.py
112 lines · 2.5 KiB · Python
Last changed by
Merge branch 'stable'David Lordbefore adoption6a2f545
History of this fileTake it
1import os2import sys34import pytest56from flask import Flask7from flask.globals import app_ctx as _app_ctx8910@pytest.fixture(autouse=True)11def _standard_os_environ(monkeypatch):12 """Set up ``os.environ`` at the start of every test to have13 standard values.14 """15 for key in (16 "FLASK_ENV_FILE",17 "FLASK_APP",18 "FLASK_DEBUG",19 "FLASK_RUN_FROM_CLI",20 "WERKZEUG_RUN_MAIN",21 ):22 monkeypatch.delenv(key, False)2324 yield252627@pytest.fixture28def app():29 app = Flask("flask_test", root_path=os.path.dirname(__file__))30 app.config.update(31 TESTING=True,32 SECRET_KEY="test key",33 )34 return app353637@pytest.fixture38def app_ctx(app):39 with app.app_context() as ctx:40 yield ctx414243@pytest.fixture44def req_ctx(app):45 with app.test_request_context() as ctx:46 yield ctx474849@pytest.fixture50def client(app):51 return app.test_client()525354@pytest.fixture55def test_apps(monkeypatch):56 monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))57 original_modules = set(sys.modules.keys())5859 yield6061 # Remove any imports cached during the test. Otherwise "import app"62 # will work in the next test even though it's no longer on the path.63 for key in sys.modules.keys() - original_modules:64 sys.modules.pop(key)656667@pytest.fixture(autouse=True)68def leak_detector():69 """Fails if any app contexts are still pushed when a test ends. Pops all70 contexts so subsequent tests are not affected.71 """72 yield73 leaks = []7475 while _app_ctx:76 leaks.append(_app_ctx._get_current_object())77 _app_ctx.pop()7879 assert not leaks808182@pytest.fixture83def modules_tmp_path(tmp_path, monkeypatch):84 """A temporary directory added to sys.path."""85 rv = tmp_path / "modules_tmp"86 rv.mkdir()87 monkeypatch.syspath_prepend(os.fspath(rv))88 return rv899091@pytest.fixture92def modules_tmp_path_prefix(modules_tmp_path, monkeypatch):93 monkeypatch.setattr(sys, "prefix", os.fspath(modules_tmp_path))94 return modules_tmp_path959697@pytest.fixture98def site_packages(modules_tmp_path, monkeypatch):99 """Create a fake site-packages."""100 py_dir = f"python{sys.version_info.major}.{sys.version_info.minor}"101 rv = modules_tmp_path / "lib" / py_dir / "site-packages"102 rv.mkdir(parents=True)103 monkeypatch.syspath_prepend(os.fspath(rv))104 return rv105106107@pytest.fixture108def purge_module(request):109 def inner(name):110 request.addfinalizer(lambda: sys.modules.pop(name, None))111112 return inner