Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

134 lines · 3.7 KiB · Python

Last changed by

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.conftest4    ~~~~~~~~~~~~~~56    :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7    :license: BSD, see LICENSE for more details.8"""9import flask10import gc11import os12import sys13import pkgutil14import pytest15import textwrap161718@pytest.fixture19def test_apps(monkeypatch):20    monkeypatch.syspath_prepend(21        os.path.abspath(os.path.join(22            os.path.dirname(__file__), 'test_apps'))23    )2425@pytest.fixture(autouse=True)26def leak_detector(request):27    def ensure_clean_request_context():28        # make sure we're not leaking a request context since we are29        # testing flask internally in debug mode in a few cases30        leaks = []31        while flask._request_ctx_stack.top is not None:32            leaks.append(flask._request_ctx_stack.pop())33        assert leaks == []34    request.addfinalizer(ensure_clean_request_context)353637@pytest.fixture(params=(True, False))38def limit_loader(request, monkeypatch):39    """Patch pkgutil.get_loader to give loader without get_filename or archive.4041    This provides for tests where a system has custom loaders, e.g. Google App42    Engine's HardenedModulesHook, which have neither the `get_filename` method43    nor the `archive` attribute.4445    This fixture will run the testcase twice, once with and once without the46    limitation/mock.47    """48    if not request.param:49        return5051    class LimitedLoader(object):52        def __init__(self, loader):53            self.loader = loader5455        def __getattr__(self, name):56            if name in ('archive', 'get_filename'):57                msg = 'Mocking a loader which does not have `%s.`' % name58                raise AttributeError(msg)59            return getattr(self.loader, name)6061    old_get_loader = pkgutil.get_loader6263    def get_loader(*args, **kwargs):64        return LimitedLoader(old_get_loader(*args, **kwargs))65    monkeypatch.setattr(pkgutil, 'get_loader', get_loader)666768@pytest.fixture69def modules_tmpdir(tmpdir, monkeypatch):70    '''A tmpdir added to sys.path'''71    rv = tmpdir.mkdir('modules_tmpdir')72    monkeypatch.syspath_prepend(str(rv))73    return rv747576@pytest.fixture77def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):78    monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))79    return modules_tmpdir808182@pytest.fixture83def site_packages(modules_tmpdir, monkeypatch):84    '''Create a fake site-packages'''85    rv = modules_tmpdir \86        .mkdir('lib')\87        .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\88        .mkdir('site-packages')89    monkeypatch.syspath_prepend(str(rv))90    return rv919293@pytest.fixture94def install_egg(modules_tmpdir, monkeypatch):95    '''Generate egg from package name inside base and put the egg into96    sys.path'''97    def inner(name, base=modules_tmpdir):98        if not isinstance(name, str):99            raise ValueError(name)100        base.join(name).ensure_dir()101        base.join(name).join('__init__.py').ensure()102103        egg_setup = base.join('setup.py')104        egg_setup.write(textwrap.dedent("""105        from setuptools import setup106        setup(name='{0}',107              version='1.0',108              packages=['site_egg'],109              zip_safe=True)110        """.format(name)))111112        import subprocess113        subprocess.check_call(114            [sys.executable, 'setup.py', 'bdist_egg'],115            cwd=str(modules_tmpdir)116        )117        egg_path, = modules_tmpdir.join('dist/').listdir()118        monkeypatch.syspath_prepend(str(egg_path))119        return egg_path120    return inner121122123@pytest.fixture124def purge_module(request):125    def inner(name):126        request.addfinalizer(lambda: sys.modules.pop(name, None))127    return inner128129130@pytest.yield_fixture(autouse=True)131def catch_deprecation_warnings(recwarn):132    yield133    gc.collect()134    assert not recwarn.list