Skip to content

Instantly share code, notes, and snippets.

@FGtatsuro
Last active July 5, 2018 23:59
Show Gist options
  • Save FGtatsuro/e9e4665211760ba8031715d0351a2495 to your computer and use it in GitHub Desktop.
Save FGtatsuro/e9e4665211760ba8031715d0351a2495 to your computer and use it in GitHub Desktop.
General fixtures of pytests
from ..misc import Namespace
config1 = 'config1_dev'
config2 = Namespace({
'config2_inner1_key1': {'config2_inner2_key1': 'config2_value1'},
'config2_inner1_key2': Namespace(config2_inner2_key2='config2_value2')
})
# dict is converted to Namespace
config3 = {
'config3_inner1_key1': {'config3_inner2_key1': 'config3_value1'},
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import functools
import importlib
import sys
from pathlib import Path
import pytest
from ._logging import get_logger
from ._requests import create_session
from .misc import Namespace
logger = get_logger(__name__)
__all__ = ('session', 'register_teardown', 'configs')
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def register_teardown():
"""Register a teardown function.
We can call this function multiple times, thus multiple teardown functions are accepted.
After execution of each test functions, registered functions run
in reverse order of registration.
"""
# FYI: https://docs.pytest.org/en/latest/fixture.html#factories-as-fixtures
teardown_funcs = []
def _register(func, *args, **kwargs):
teardown_funcs.append(functools.partial(func, *args, **kwargs))
yield _register
logger.debug('')
logger.debug('##### TearDown #####')
for f in reversed(teardown_funcs):
f()
@pytest.fixture(scope='session')
def configs(pytestconfig):
"""Handle test configs.
'tests/configs/*.py' are regarded as test config files,
and we can access each config via configs.(module_name).
Configs are loaded only once in test execution.
FYI: https://docs.pytest.org/en/latest/fixture.html#scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session # noqa
"""
top_namespace = Namespace()
# TODO: Get path of configs directory from command line option.
configs = Path(__file__).parent.joinpath('configs')
module_names = set(c.stem for c in configs.glob('*.py') if c.name != '__init__.py')
# Convert dict to Namespace in config.
for module_name in module_names:
module = importlib.import_module(f'..configs.{module_name}', __name__)
module_namespace = Namespace()
for module_attribute in (attr for attr in dir(module) if not attr.startswith('__')):
value = getattr(module, module_attribute)
if isinstance(value, dict) and not isinstance(value, Namespace):
value = Namespace(value)
setattr(module_namespace, module_attribute, value)
setattr(top_namespace, module_name, module_namespace)
# Set an alias for main config
mainconfig = pytestconfig.getoption('mainconfig')
if mainconfig not in module_names:
logger.error("This main config doesn't exist in configs directory.")
# FYI: https://docs.pytest.org/en/latest/usage.html#possible-exit-codes
sys.exit(4)
setattr(top_namespace, 'main', getattr(top_namespace, mainconfig))
yield top_namespace
# https://wiki.python.org/moin/Vim
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment