conftest.py
This file
Path
tests/conftest.py
160 lines · 4.2 KiB · Python
Last changed by
Merge branch '2.3.x'David Lordbefore adoption57e926c
History of this fileTake it
1import os2import pkgutil3import sys45import pytest6from _pytest import monkeypatch78from flask import Flask9from flask.globals import request_ctx101112@pytest.fixture(scope="session", autouse=True)13def _standard_os_environ():14 """Set up ``os.environ`` at the start of the test session to have15 standard values. Returns a list of operations that is used by16 :func:`._reset_os_environ` after each test.17 """18 mp = monkeypatch.MonkeyPatch()19 out = (20 (os.environ, "FLASK_ENV_FILE", monkeypatch.notset),21 (os.environ, "FLASK_APP", monkeypatch.notset),22 (os.environ, "FLASK_DEBUG", monkeypatch.notset),23 (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),24 (os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),25 )2627 for _, key, value in out:28 if value is monkeypatch.notset:29 mp.delenv(key, False)30 else:31 mp.setenv(key, value)3233 yield out34 mp.undo()353637@pytest.fixture(autouse=True)38def _reset_os_environ(monkeypatch, _standard_os_environ):39 """Reset ``os.environ`` to the standard environ after each test,40 in case a test changed something without cleaning up.41 """42 monkeypatch._setitem.extend(_standard_os_environ)434445@pytest.fixture46def app():47 app = Flask("flask_test", root_path=os.path.dirname(__file__))48 app.config.update(49 TESTING=True,50 SECRET_KEY="test key",51 )52 return app535455@pytest.fixture56def app_ctx(app):57 with app.app_context() as ctx:58 yield ctx596061@pytest.fixture62def req_ctx(app):63 with app.test_request_context() as ctx:64 yield ctx656667@pytest.fixture68def client(app):69 return app.test_client()707172@pytest.fixture73def test_apps(monkeypatch):74 monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))75 original_modules = set(sys.modules.keys())7677 yield7879 # Remove any imports cached during the test. Otherwise "import app"80 # will work in the next test even though it's no longer on the path.81 for key in sys.modules.keys() - original_modules:82 sys.modules.pop(key)838485@pytest.fixture(autouse=True)86def leak_detector():87 yield8889 # make sure we're not leaking a request context since we are90 # testing flask internally in debug mode in a few cases91 leaks = []92 while request_ctx:93 leaks.append(request_ctx._get_current_object())94 request_ctx.pop()9596 assert leaks == []979899@pytest.fixture(params=(True, False))100def limit_loader(request, monkeypatch):101 """Patch pkgutil.get_loader to give loader without get_filename or archive.102103 This provides for tests where a system has custom loaders, e.g. Google App104 Engine's HardenedModulesHook, which have neither the `get_filename` method105 nor the `archive` attribute.106107 This fixture will run the testcase twice, once with and once without the108 limitation/mock.109 """110 if not request.param:111 return112113 class LimitedLoader:114 def __init__(self, loader):115 self.loader = loader116117 def __getattr__(self, name):118 if name in {"archive", "get_filename"}:119 raise AttributeError(f"Mocking a loader which does not have {name!r}.")120 return getattr(self.loader, name)121122 old_get_loader = pkgutil.get_loader123124 def get_loader(*args, **kwargs):125 return LimitedLoader(old_get_loader(*args, **kwargs))126127 monkeypatch.setattr(pkgutil, "get_loader", get_loader)128129130@pytest.fixture131def modules_tmp_path(tmp_path, monkeypatch):132 """A temporary directory added to sys.path."""133 rv = tmp_path / "modules_tmp"134 rv.mkdir()135 monkeypatch.syspath_prepend(os.fspath(rv))136 return rv137138139@pytest.fixture140def modules_tmp_path_prefix(modules_tmp_path, monkeypatch):141 monkeypatch.setattr(sys, "prefix", os.fspath(modules_tmp_path))142 return modules_tmp_path143144145@pytest.fixture146def site_packages(modules_tmp_path, monkeypatch):147 """Create a fake site-packages."""148 py_dir = f"python{sys.version_info.major}.{sys.version_info.minor}"149 rv = modules_tmp_path / "lib" / py_dir / "site-packages"150 rv.mkdir(parents=True)151 monkeypatch.syspath_prepend(os.fspath(rv))152 return rv153154155@pytest.fixture156def purge_module(request):157 def inner(name):158 request.addfinalizer(lambda: sys.modules.pop(name, None))159160 return inner