Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

211 lines · 5.3 KiB · Python

Last changed by

Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.conftest4    ~~~~~~~~~~~~~~56    :copyright: © 2010 by the Pallets team.7    :license: BSD, see LICENSE for more details.8"""910import gc11import os12import pkgutil13import sys14import textwrap1516import pytest17from _pytest import monkeypatch1819import flask20from flask import Flask as _Flask212223@pytest.fixture(scope="session", autouse=True)24def _standard_os_environ():25    """Set up ``os.environ`` at the start of the test session to have26    standard values. Returns a list of operations that is used by27    :func:`._reset_os_environ` after each test.28    """29    mp = monkeypatch.MonkeyPatch()30    out = (31        (os.environ, "FLASK_APP", monkeypatch.notset),32        (os.environ, "FLASK_ENV", monkeypatch.notset),33        (os.environ, "FLASK_DEBUG", monkeypatch.notset),34        (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),35        (os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),36    )3738    for _, key, value in out:39        if value is monkeypatch.notset:40            mp.delenv(key, False)41        else:42            mp.setenv(key, value)4344    yield out45    mp.undo()464748@pytest.fixture(autouse=True)49def _reset_os_environ(monkeypatch, _standard_os_environ):50    """Reset ``os.environ`` to the standard environ after each test,51    in case a test changed something without cleaning up.52    """53    monkeypatch._setitem.extend(_standard_os_environ)545556class Flask(_Flask):57    testing = True58    secret_key = "test key"596061@pytest.fixture62def app():63    app = Flask("flask_test", root_path=os.path.dirname(__file__))64    return app656667@pytest.fixture68def app_ctx(app):69    with app.app_context() as ctx:70        yield ctx717273@pytest.fixture74def req_ctx(app):75    with app.test_request_context() as ctx:76        yield ctx777879@pytest.fixture80def client(app):81    return app.test_client()828384@pytest.fixture85def test_apps(monkeypatch):86    monkeypatch.syspath_prepend(87        os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))88    )899091@pytest.fixture(autouse=True)92def leak_detector():93    yield9495    # make sure we're not leaking a request context since we are96    # testing flask internally in debug mode in a few cases97    leaks = []98    while flask._request_ctx_stack.top is not None:99        leaks.append(flask._request_ctx_stack.pop())100    assert leaks == []101102103@pytest.fixture(params=(True, False))104def limit_loader(request, monkeypatch):105    """Patch pkgutil.get_loader to give loader without get_filename or archive.106107    This provides for tests where a system has custom loaders, e.g. Google App108    Engine's HardenedModulesHook, which have neither the `get_filename` method109    nor the `archive` attribute.110111    This fixture will run the testcase twice, once with and once without the112    limitation/mock.113    """114    if not request.param:115        return116117    class LimitedLoader(object):118        def __init__(self, loader):119            self.loader = loader120121        def __getattr__(self, name):122            if name in ("archive", "get_filename"):123                msg = "Mocking a loader which does not have `%s.`" % name124                raise AttributeError(msg)125            return getattr(self.loader, name)126127    old_get_loader = pkgutil.get_loader128129    def get_loader(*args, **kwargs):130        return LimitedLoader(old_get_loader(*args, **kwargs))131132    monkeypatch.setattr(pkgutil, "get_loader", get_loader)133134135@pytest.fixture136def modules_tmpdir(tmpdir, monkeypatch):137    """A tmpdir added to sys.path."""138    rv = tmpdir.mkdir("modules_tmpdir")139    monkeypatch.syspath_prepend(str(rv))140    return rv141142143@pytest.fixture144def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):145    monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))146    return modules_tmpdir147148149@pytest.fixture150def site_packages(modules_tmpdir, monkeypatch):151    """Create a fake site-packages."""152    rv = (153        modules_tmpdir.mkdir("lib")154        .mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))155        .mkdir("site-packages")156    )157    monkeypatch.syspath_prepend(str(rv))158    return rv159160161@pytest.fixture162def install_egg(modules_tmpdir, monkeypatch):163    """Generate egg from package name inside base and put the egg into164    sys.path."""165166    def inner(name, base=modules_tmpdir):167        if not isinstance(name, str):168            raise ValueError(name)169        base.join(name).ensure_dir()170        base.join(name).join("__init__.py").ensure()171172        egg_setup = base.join("setup.py")173        egg_setup.write(174            textwrap.dedent(175                """176        from setuptools import setup177        setup(name='{0}',178              version='1.0',179              packages=['site_egg'],180              zip_safe=True)181        """.format(182                    name183                )184            )185        )186187        import subprocess188189        subprocess.check_call(190            [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)191        )192        egg_path, = modules_tmpdir.join("dist/").listdir()193        monkeypatch.syspath_prepend(str(egg_path))194        return egg_path195196    return inner197198199@pytest.fixture200def purge_module(request):201    def inner(name):202        request.addfinalizer(lambda: sys.modules.pop(name, None))203204    return inner205206207@pytest.fixture(autouse=True)208def catch_deprecation_warnings(recwarn):209    yield210    gc.collect()211    assert not recwarn.list, "\n".join(str(w.message) for w in recwarn.list)