conftest.py
This file
Path
tests/conftest.py
198 lines · 5.2 KiB · Python
Last changed by
Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
History of this fileTake it
1import os2import pkgutil3import sys4import textwrap56import pytest7from _pytest import monkeypatch89import flask10from flask import Flask as _Flask111213@pytest.fixture(scope="session", autouse=True)14def _standard_os_environ():15 """Set up ``os.environ`` at the start of the test session to have16 standard values. Returns a list of operations that is used by17 :func:`._reset_os_environ` after each test.18 """19 mp = monkeypatch.MonkeyPatch()20 out = (21 (os.environ, "FLASK_ENV_FILE", monkeypatch.notset),22 (os.environ, "FLASK_APP", monkeypatch.notset),23 (os.environ, "FLASK_ENV", monkeypatch.notset),24 (os.environ, "FLASK_DEBUG", monkeypatch.notset),25 (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),26 (os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),27 )2829 for _, key, value in out:30 if value is monkeypatch.notset:31 mp.delenv(key, False)32 else:33 mp.setenv(key, value)3435 yield out36 mp.undo()373839@pytest.fixture(autouse=True)40def _reset_os_environ(monkeypatch, _standard_os_environ):41 """Reset ``os.environ`` to the standard environ after each test,42 in case a test changed something without cleaning up.43 """44 monkeypatch._setitem.extend(_standard_os_environ)454647class Flask(_Flask):48 testing = True49 secret_key = "test key"505152@pytest.fixture53def app():54 app = Flask("flask_test", root_path=os.path.dirname(__file__))55 return app565758@pytest.fixture59def app_ctx(app):60 with app.app_context() as ctx:61 yield ctx626364@pytest.fixture65def req_ctx(app):66 with app.test_request_context() as ctx:67 yield ctx686970@pytest.fixture71def client(app):72 return app.test_client()737475@pytest.fixture76def test_apps(monkeypatch):77 monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))78 original_modules = set(sys.modules.keys())7980 yield8182 # Remove any imports cached during the test. Otherwise "import app"83 # will work in the next test even though it's no longer on the path.84 for key in sys.modules.keys() - original_modules:85 sys.modules.pop(key)868788@pytest.fixture(autouse=True)89def leak_detector():90 yield9192 # make sure we're not leaking a request context since we are93 # testing flask internally in debug mode in a few cases94 leaks = []95 while flask._request_ctx_stack.top is not None:96 leaks.append(flask._request_ctx_stack.pop())97 assert leaks == []9899100@pytest.fixture(params=(True, False))101def limit_loader(request, monkeypatch):102 """Patch pkgutil.get_loader to give loader without get_filename or archive.103104 This provides for tests where a system has custom loaders, e.g. Google App105 Engine's HardenedModulesHook, which have neither the `get_filename` method106 nor the `archive` attribute.107108 This fixture will run the testcase twice, once with and once without the109 limitation/mock.110 """111 if not request.param:112 return113114 class LimitedLoader:115 def __init__(self, loader):116 self.loader = loader117118 def __getattr__(self, name):119 if name in {"archive", "get_filename"}:120 raise AttributeError(f"Mocking a loader which does not have {name!r}.")121 return getattr(self.loader, name)122123 old_get_loader = pkgutil.get_loader124125 def get_loader(*args, **kwargs):126 return LimitedLoader(old_get_loader(*args, **kwargs))127128 monkeypatch.setattr(pkgutil, "get_loader", get_loader)129130131@pytest.fixture132def modules_tmpdir(tmpdir, monkeypatch):133 """A tmpdir added to sys.path."""134 rv = tmpdir.mkdir("modules_tmpdir")135 monkeypatch.syspath_prepend(str(rv))136 return rv137138139@pytest.fixture140def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):141 monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))142 return modules_tmpdir143144145@pytest.fixture146def site_packages(modules_tmpdir, monkeypatch):147 """Create a fake site-packages."""148 rv = (149 modules_tmpdir.mkdir("lib")150 .mkdir(f"python{sys.version_info.major}.{sys.version_info.minor}")151 .mkdir("site-packages")152 )153 monkeypatch.syspath_prepend(str(rv))154 return rv155156157@pytest.fixture158def install_egg(modules_tmpdir, monkeypatch):159 """Generate egg from package name inside base and put the egg into160 sys.path."""161162 def inner(name, base=modules_tmpdir):163 base.join(name).ensure_dir()164 base.join(name).join("__init__.py").ensure()165166 egg_setup = base.join("setup.py")167 egg_setup.write(168 textwrap.dedent(169 f"""170 from setuptools import setup171 setup(172 name="{name}",173 version="1.0",174 packages=["site_egg"],175 zip_safe=True,176 )177 """178 )179 )180181 import subprocess182183 subprocess.check_call(184 [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)185 )186 (egg_path,) = modules_tmpdir.join("dist/").listdir()187 monkeypatch.syspath_prepend(str(egg_path))188 return egg_path189190 return inner191192193@pytest.fixture194def purge_module(request):195 def inner(name):196 request.addfinalizer(lambda: sys.modules.pop(name, None))197198 return inner