Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

133 lines · 3.8 KiB · Python

Last changed by

Merge pull request #1303 from Parkayun/masterMarkus Unterwaditzerbefore adoption5b98266

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 os11import sys12import pkgutil13import pytest14import textwrap151617@pytest.fixture18def test_apps(monkeypatch):19    monkeypatch.syspath_prepend(20        os.path.abspath(os.path.join(21            os.path.dirname(__file__), 'test_apps'))22    )2324@pytest.fixture(autouse=True)25def leak_detector(request):26    def ensure_clean_request_context():27        # make sure we're not leaking a request context since we are28        # testing flask internally in debug mode in a few cases29        leaks = []30        while flask._request_ctx_stack.top is not None:31            leaks.append(flask._request_ctx_stack.pop())32        assert leaks == []33    request.addfinalizer(ensure_clean_request_context)343536@pytest.fixture(params=(True, False))37def limit_loader(request, monkeypatch):38    """Patch pkgutil.get_loader to give loader without get_filename or archive.3940    This provides for tests where a system has custom loaders, e.g. Google App41    Engine's HardenedModulesHook, which have neither the `get_filename` method42    nor the `archive` attribute.4344    This fixture will run the testcase twice, once with and once without the45    limitation/mock.46    """47    if not request.param:48        return4950    class LimitedLoader(object):51        def __init__(self, loader):52            self.loader = loader5354        def __getattr__(self, name):55            if name in ('archive', 'get_filename'):56                msg = 'Mocking a loader which does not have `%s.`' % name57                raise AttributeError(msg)58            return getattr(self.loader, name)5960    old_get_loader = pkgutil.get_loader6162    def get_loader(*args, **kwargs):63        return LimitedLoader(old_get_loader(*args, **kwargs))64    monkeypatch.setattr(pkgutil, 'get_loader', get_loader)656667@pytest.fixture68def modules_tmpdir(tmpdir, monkeypatch):69    '''A tmpdir added to sys.path'''70    rv = tmpdir.mkdir('modules_tmpdir')71    monkeypatch.syspath_prepend(str(rv))72    return rv737475@pytest.fixture76def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):77    monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))78    return modules_tmpdir798081@pytest.fixture82def site_packages(modules_tmpdir, monkeypatch):83    '''Create a fake site-packages'''84    rv = modules_tmpdir \85        .mkdir('lib')\86        .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\87        .mkdir('site-packages')88    monkeypatch.syspath_prepend(str(rv))89    return rv909192@pytest.fixture93def install_egg(modules_tmpdir, monkeypatch):94    '''Generate egg from package name inside base and put the egg into95    sys.path'''96    def inner(name, base=modules_tmpdir):97        if not isinstance(name, str):98            raise ValueError(name)99        base.join(name).ensure_dir()100        base.join(name).join('__init__.py').ensure()101102        egg_setup = base.join('setup.py')103        egg_setup.write(textwrap.dedent("""104        from setuptools import setup105        setup(name='{0}',106              version='1.0',107              packages=['site_egg'],108              zip_safe=True)109        """.format(name)))110111        import subprocess112        subprocess.check_call(113            [sys.executable, 'setup.py', 'bdist_egg'],114            cwd=str(modules_tmpdir)115        )116        egg_path, = modules_tmpdir.join('dist/').listdir()117        monkeypatch.syspath_prepend(str(egg_path))118        return egg_path119    return inner120121122@pytest.fixture123def purge_module(request):124    def inner(name):125        request.addfinalizer(lambda: sys.modules.pop(name, None))126    return inner127128129@pytest.fixture130def catch_deprecation_warnings():131    import warnings132    warnings.simplefilter('default', category=DeprecationWarning)133    return lambda: warnings.catch_warnings(record=True)