def __new__(cls, clsname, bases, dct): klass = type.__new__(cls, clsname, bases, dct) for app_name in set(settings.INSTALLED_APPS): name = app_name.split('.')[-1] setattr(klass, name, pytest.fixture(scope='session')(django_app(app_name))) for model in apps.get_models(): name = model._meta.object_name setattr(klass, name, pytest.fixture(scope='session')(django_model(model))) return klass
def decorator(func): step_func = func if step_type == GIVEN: if not hasattr(func, '_pytestfixturefunction'): # avoid overfixturing of a fixture func = pytest.fixture(func) step_func = lambda request: request.getfuncargvalue(func.func_name) step_func.__name__ = step_name setattr(get_caller_module(), step_name, pytest.fixture(lambda: step_func)) return func
def decorate(fn): name = fn.__name__ self._factories[name] = fn # conn, teardown = self.connection_for(name) def wrapper(*args, **kw): # This check might be unnecessary assert self._current_connection == name return fn(*args, **kw) wrapper.__wrapped__ = fn pytest.fixture(scope="session")(wrapper) return wrapper
def simple_fixture(name, params, fmt=None): """Helper to create a pytest fixture using only name and params. Parameters ---------- name : str Name of the parameters used for the ``ids`` argument to `pytest.fixture`. params : sequence Values to be taken as parameters in the fixture. They are used as ``params`` argument to `pytest.fixture`. fmt : str, optional Use this format string for the generation of the ``ids``. For each value, the id string is generated as:: fmt.format(name=name, value=value) hence the format string must use ``{name}`` and ``{value}``. Default: ``" {name} = '{value}' "`` for string parameters, otherwise ``" {name} = {value} "`` """ if fmt is None: try: params[0] + '' except TypeError: # Not a string type fmt = " {name} = {value} " else: # String type fmt = " {name} = '{value}' " ids = [fmt.format(name=name, value=value) for value in params] wrapper = pytest.fixture(scope='module', ids=ids, params=params) return wrapper(lambda request: request.param)
def decorator(func): step_func = func if step_type == GIVEN: if not hasattr(func, "_pytestfixturefunction"): # Avoid multiple wrapping of a fixture func = pytest.fixture(func) step_func = lambda request: request.getfuncargvalue(func.__name__) step_func.__doc__ = func.__doc__ step_func.fixture = func.__name__ step_func.__name__ = force_encode(step_name) step_func.step_type = step_type step_func.converters = converters @pytest.fixture def lazy_step_func(): return step_func # Preserve the docstring lazy_step_func.__doc__ = func.__doc__ if pattern: lazy_step_func.pattern = pattern if converters: lazy_step_func.converters = converters contribute_to_module(get_caller_module(), step_name, lazy_step_func) return func
def given(name, fixture=None, converters=None, scope='function', target_fixture=None): """Given step decorator. :param name: Given step name. :param fixture: Optional name of the fixture to reuse. :param converters: Optional `dict` of the argument or parameter converters in form {<param_name>: <converter function>}. :scope: Optional fixture scope :param target_fixture: Target fixture name to replace by steps definition function :raises: StepError in case of wrong configuration. :note: Can't be used as a decorator when the fixture is specified. """ if fixture is not None: module = get_caller_module() def step_func(request): return request.getfuncargvalue(fixture) step_func.step_type = GIVEN step_func.converters = converters step_func.__name__ = name step_func.fixture = fixture func = pytest.fixture(scope=scope)(lambda: step_func) func.__doc__ = 'Alias for the "{0}" fixture.'.format(fixture) _, name = parse_line(name) contribute_to_module(module, get_step_fixture_name(name, GIVEN), func) return _not_a_fixture_decorator return _step_decorator(GIVEN, name, converters=converters, scope=scope, target_fixture=target_fixture)
def given(name, fixture=None, converters=None): """Given step decorator. :param name: Given step name. :param fixture: Optional name of the fixture to reuse. :param converters: Optional `dict` of the argument or parameter converters in form {<param_name>: <converter function>}. :raises: StepError in case of wrong configuration. :note: Can't be used as a decorator when the fixture is specified. """ if fixture is not None: module = get_caller_module() step_func = lambda request: request.getfuncargvalue(fixture) step_func.step_type = GIVEN step_func.converters = converters step_func.__name__ = name step_func.fixture = fixture func = pytest.fixture(lambda: step_func) func.__doc__ = 'Alias for the "{0}" fixture.'.format(fixture) contribute_to_module(module, remove_prefix(name), func) return _not_a_fixture_decorator return _step_decorator(GIVEN, name, converters=converters)
def decorator(func): step_func = func if step_type == GIVEN: if not hasattr(func, '_pytestfixturefunction'): # Avoid multiple wrapping a fixture func = pytest.fixture(func) step_func = lambda request: request.getfuncargvalue(func.__name__) step_func.__doc__ = func.__doc__ step_func.__name__ = step_name @pytest.fixture def lazy_step_func(): return step_func # Preserve a docstring lazy_step_func.__doc__ = func.__doc__ contribute_to_module( get_caller_module(), step_name, lazy_step_func, ) return func
def _make_fixture(cls, name): factory = getattr(cls, name + '_factory') def fixture(self): return factory.create() fixture.__name__ = name return pytest.fixture(fixture)
def _get_role_fixture(role_name): def fixture(testuser_id, webapp_without_login): with webapp_without_login.app.app_context(): user = models.User.query.get(testuser_id) user.roles.append(models.Role.query.filter_by(name=role_name).one()) models.db.session.commit() fixture.__name__ = "{}_role".format(role_name) return pytest.fixture(fixture)
def calc_motor_fixture(name): def get_motor(beacon): m = beacon.get(name) m.no_offset = False yield m m.stop() m.wait_move() get_motor.__name__ = name return pytest.fixture(get_motor)
def make_uri_fixture(name): """ Create a pytest fixture named NAME that resolves to a URI object '<ex://NAME>'. """ # noinspection PyShadowingNames def func(conn): return conn.createURI('ex://' + name) func.__name__ = name return pytest.fixture(func, name=name)
def make_fixture(arg): args_attr = 'base_args__' + arg kwargs_attr = 'base_kwargs__' + arg def fixture(self, cls): args = getattr(self, args_attr) kwargs = getattr(self, kwargs_attr) return cls(*args, **kwargs) fixture.__name__ = arg return pytest.fixture(fixture)
def instance_fixture(func): """ Mark function as an instance fixture. It marks function as a fixture and also applies pytest.mark.instance_fixture """ func = pytest.fixture(func) func = pytest.mark.instance_fixture(func) func.__is_instance_fixture = True return func
def fixture(scope="function", params=None, autouse=False, ids=None, name=None): """ When running under pytest, this is the same as the pytest.fixture decorator. See https://docs.pytest.org/en/latest/reference.html#pytest-fixture """ if _use_native_pytest: # XXX sorting of fixtures based on scope does not work, see # https://github.com/pytest-dev/pytest/issues/4143#issuecomment-431794076 # When ran under pytest, use native functionality. return pytest.fixture(scope, params, autouse, ids, name) init_fallback_fixtures_once() return _fallback.fixture(scope, params, autouse, ids, name)
def setup_pytest_browser_fixture(BrowserClass): def browser(live_server, settings): # also require the live_server fixture from pytest-django # django runserver doesnt support https. # todo: can just replace live_server with own fixture that # runs the stunnel script instead # todo: or can do local setting imports and have a testing one? settings.SESSION_COOKIE_SECURE = False settings.CSRF_COOKIE_SECURE = False _browser = BrowserClass(host_address=live_server.url) yield _browser # use quit instead of close to release all resources _browser.quit() return pytest.fixture(browser)
def motor_fixture(name): def get_motor(beacon): m = beacon.get(name) yield m m.stop() m.wait_move() m.apply_config() m.controller.set_hw_limits(m, None, None) m.dial(0) m.position(0) for hook in m.motion_hooks: hook.nb_pre_move = 0 hook.nb_post_move = 0 get_motor.__name__ = name return pytest.fixture(get_motor)
def pytest_configure(config): # Enable stdout and stderr analysis, unless output capture is disabled if config.getoption('capture') != 'no': global check_test_output check_test_output = pytest.fixture(autouse=True)(check_test_output) # If we are running from the source directory, make sure that we load # modules from here basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if not config.getoption('installed'): llfuse_path = os.path.join(basedir, 'src') if (os.path.exists(os.path.join(basedir, 'setup.py')) and os.path.exists(os.path.join(basedir, 'src', 'llfuse.pyx'))): sys.path.insert(0, llfuse_path) # Make sure that called processes use the same path pp = os.environ.get('PYTHONPATH', None) if pp: pp = '%s:%s' % (llfuse_path, pp) else: pp = llfuse_path os.environ['PYTHONPATH'] = pp try: import faulthandler except ImportError: pass else: faulthandler.enable() # When running from VCS repo, enable all warnings if os.path.exists(os.path.join(basedir, 'MANIFEST.in')): import warnings warnings.resetwarnings() warnings.simplefilter('error') logdebug = config.getoption('logdebug') if logdebug: root_logger = logging.getLogger() formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(threadName)s ' '%(funcName)s: %(message)s', datefmt="%H:%M:%S") handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) root_logger.addHandler(handler) root_logger.setLevel(logging.DEBUG)
def given(name, fixture=None): """Given step decorator. :param name: Given step name. :param fixture: Optional name of the fixture to reuse. :raises: StepError in case of wrong configuration. :note: Can't be used as a decorator when the fixture is specified. """ name = remove_prefix(name) if fixture is not None: module = get_caller_module() func = getattr(module, fixture, lambda request: request.getfuncargvalue(fixture)) setattr(module, name, pytest.fixture(lambda: func)) return _not_a_fixture_decorator return _step_decorator(GIVEN, name)
def model_fixture(func): """ Marks function that returns a Model instance as a fixture Consider the example:: @model_fixture def foo(): return ... This is the same as:: @pytest.fixture @pytest.mark.db def foo(): return ... """ return pytest.fixture(pytest.mark.db(func))
def fixture(**kwargs): pytest_fn = pytest.fixture(**kwargs) def _dec(fn): def _fn(request, *args, **kwargs): if not hasattr(request, '__zk_finalizers'): request.addfinalizer(mock_zookeeper.dump) request.addfinalizer(mock_zookeeper.reset) setattr(request, '__zk_finalizers', True) mangled_name = "%s__%s__%s" % (fn.__name__, str(args), str(kwargs)) if hasattr(request, mangled_name): val = getattr(request, mangled_name) else: val = fn(request, *args, **kwargs) setattr(request, mangled_name, val) return val _fn.__name__ = fn.__name__ _fn.__doc__ = fn.__doc__ return pytest_fn(_fn) return _dec
def make_fixture(name, module, func, args=None, **kwargs): """Make fixture function and inject arguments. :param name: Fixture name. :param module: Python module to contribute the fixture into. :param func: Fixture implementation function. :param args: Argument names. """ args = [] if args is None else list(args) if "request" not in args: args.insert(0, "request") deps = ", ".join(args) context = dict(_fixture_impl=func, kwargs=kwargs) context.update(kwargs) exec(FIXTURE_FUNC_FORMAT.format(name=name, deps=deps), context) fixture_func = context[name] fixture_func.__module__ = module fixture = pytest.fixture(fixture_func) setattr(module, name, fixture) return fixture
def pytest_pycollect_makemodule(path, parent): """ py.test hook called when a new test module is generated. If your test module contains a class named "Fixtures" with :class:`Fixture` instances as (class) attributes, this will set up "lazy" fixtures to use within the test module. """ mod = path.pyimport() fixtures = getattr(mod, 'Fixtures', None) if not fixtures is None: fixtures = [item for item in fixtures.__dict__.items() if (callable(item[1]) and not item[0].startswith('_'))] for (fx_name, func) in fixtures: if getfixturemarker(func) is None: fxt = pytest.fixture(scope='function')(func) else: fxt = func setattr(mod, fx_name, fxt) return pytest.Module(path, parent)
def given(name, fixture=None): """Given step decorator. :param name: Given step name. :param fixture: Optional name of the fixture to reuse. :raises: StepError in case of wrong configuration. :note: Can't be used as a decorator when the fixture is specified. """ if fixture is not None: frame = inspect.stack()[1] module = inspect.getmodule(frame[0]) func = getattr(module, fixture, None) if func is None: func = pytest.fixture(lambda request: request.getfuncargvalue(fixture)) setattr(module, fixture, func) _decorate_step(func, GIVEN, name) return _not_a_fixture_decorator return _step_decorator(GIVEN, name)
def decorator(func): step_func = func parser_instance = get_parser(step_name) parsed_step_name = parser_instance.name if step_type == GIVEN: if not hasattr(func, "_pytestfixturefunction"): # Avoid multiple wrapping of a fixture func = pytest.fixture(scope=scope)(func) def step_func(request): result = request.getfuncargvalue(func.__name__) if target_fixture: inject_fixture(request, target_fixture, result) return result step_func.__doc__ = func.__doc__ step_func.fixture = func.__name__ step_func.__name__ = force_encode(parsed_step_name) @pytest.fixture(scope=scope) def lazy_step_func(): return step_func step_func.step_type = step_type lazy_step_func = contribute_to_module( get_caller_module(), get_step_fixture_name(parsed_step_name, step_type), lazy_step_func) lazy_step_func.step_type = step_type # Preserve the docstring lazy_step_func.__doc__ = func.__doc__ step_func.parser = lazy_step_func.parser = parser_instance if converters: step_func.converters = lazy_step_func.converters = converters return func
def decorator_factory(func): fixture_kwargs = {} if 'scope' in kwargs: fixture_kwargs['scope'] = kwargs.pop('scope') if 'autouse' in kwargs: fixture_kwargs['autouse'] = kwargs.pop('autouse') if 'params' in kwargs: fixture_kwargs['params'] = list(kwargs.pop('params')) if 'ids' in kwargs: fixture_kwargs['ids'] = list(kwargs.pop('ids')) if kwargs: fixture_kwargs.setdefault('params', []).extend(kwargs.values()) fixture_kwargs.setdefault('ids', []).extend(kwargs.keys()) if args: fixture_kwargs.setdefault('params', []).extend(args) return pytest.fixture(**fixture_kwargs)(func)
difficult to run in other contexts. """ from hil.test_common import * from hil.dev_support import have_dry_run from hil import config, server import pytest @pytest.fixture def configure(): config_testsuite() config.load_extensions() fail_on_log_warnings = pytest.fixture(autouse=True)(fail_on_log_warnings) fresh_database = pytest.fixture(fresh_database) @pytest.fixture def server_init(): server.register_drivers() server.validate_state() with_request_context = pytest.yield_fixture(with_request_context) headnode_cleanup = pytest.fixture(headnode_cleanup) pytestmark = pytest.mark.usefixtures('configure', 'server_init', 'fresh_database', 'with_request_context', 'headnode_cleanup')
# you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS # IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language # governing permissions and limitations under the License. from hil.dev_support import no_dry_run import pytest from hil.test_common import * fail_on_log_warnings = pytest.fixture(autouse=True)(fail_on_log_warnings) # We test two ways of using the decorator: applying it to a freestanding # function, and applying it to an instance method. def _function(): @no_dry_run def func(): assert False func() def _method(): class Cls:
def _generate_fixture(container): def _fixture(): yield container _fixture.__doc__ = f"Provides access to Brownie ContractContainer object '{container._name}'" return pytest.fixture(scope="session")(_fixture)
@when("writing to pwscf.in without specifying a structure") def writing_no_structure(empty_pwscf, tmpdir): empty_pwscf.write(tmpdir.join("pwscf.in")) @then("the file pwscf.in appears and can be read") def read_pwscf(tmpdir): from pylada.espresso import Pwscf assert tmpdir.join("pwscf.in").check(file=True) result = Pwscf() result.read(tmpdir.join("pwscf.in")) return result pwscf_out = pytest.fixture(read_pwscf) @then("pwscf.electrons.whawha is equal to 1.5") def check_float_attribute_exists(pwscf_out): from numpy import abs assert hasattr(getattr(pwscf_out, "electrons"), "whawha") actual = float(getattr(getattr(pwscf_out, "electrons"), "whawha")) assert abs(actual - 1.5) < 1e-12 @then("wavefunction cutoff is equal to 14.0 Ry") def check_ecutwfc(pwscf_out): import quantities from numpy import allclose assert pwscf_out.system.ecutwfc.units == quantities.Ry
# FIXME: Move this to dolfin for user access? def reconstruct_refined_form(form, functions, mesh): function_mapping = {} for u in functions: w = Function(u.leaf_node().function_space()) w.assign(u.leaf_node()) function_mapping[u] = w domain = mesh.leaf_node().ufl_domain() newform = replace_integral_domains(replace(form, function_mapping), domain) return newform, function_mapping # This must be scope function, because the tests will modify some of the objects, # including the mesh which gets its hierarchial adapted submeshes attached. fixt = pytest.fixture(scope="function") @fixt def mesh(): return UnitSquareMesh(8, 8) @fixt def V(mesh): return FunctionSpace(mesh, "Lagrange", 1) @fixt def u(V): return Function(V) @fixt def a(V):
c=count - x, d=99 - y) b.author = author if y % 4 != 0: b.prequel = abooks[(2 * y + 1) % len(abooks)] abooks.append(b) data.append(b) with temporary_database(request.param) as dburl: with S(dburl) as s: Base.metadata.create_all(s.connection()) s.add_all(data) yield dburl dburl = pytest.fixture(params=['postgresql', 'mysql'])(_dburl) pg_only_dburl = pytest.fixture(params=['postgresql'])(_dburl) @pytest.fixture(params=['postgresql', 'mysql']) def joined_inheritance_dburl(request): with temporary_database(request.param) as dburl: with S(dburl) as s: JoinedInheritanceBase.metadata.create_all(s.connection()) s.add_all([ Mammal(name='Human', vertebra_count=33, leg_count=2, nipple_count=2), Mammal(name='Dog', vertebra_count=36,
import pytest from . import VirtualEnv def _virtualenv_fixture(cloaked): def fn(workspace): venv = VirtualEnv(workspace, cloaked=cloaked) if cloaked: venv.freeze() yield venv if cloaked: venv.thaw() # Workaround workspace not cleaning itself as it should... venv.workspace.delete = True venv.workspace.teardown() return fn virtualenv = pytest.fixture(_virtualenv_fixture(True)) naked_virtualenv = pytest.fixture(_virtualenv_fixture(False))
from hil.test_common import config_testsuite, fresh_database, \ fail_on_log_warnings, server_init from hil import api, config, rest import json import pytest @pytest.fixture def configure(): """Configure HIL""" config_testsuite() config.load_extensions() fail_on_log_warnings = pytest.fixture(autouse=True)(fail_on_log_warnings) fresh_database = pytest.fixture(fresh_database) server_init = pytest.fixture(server_init) pytestmark = pytest.mark.usefixtures('configure', 'fresh_database', 'server_init') def test_many_http_queries(): """Put a few objects in the db, then bombard the api with queries. This is intended to shake out problems like the resource leak discussed in issue #454. """
autospec=autospec, new_callable=new_callable, **kwargs) def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: """ Return an object that has the same interface to the `mock` module, but takes care of automatically undoing all patches after each test method. """ result = MockerFixture(pytestconfig) yield result result.stopall() mocker = pytest.fixture()(_mocker) # default scope is function class_mocker = pytest.fixture(scope="class")(_mocker) module_mocker = pytest.fixture(scope="module")(_mocker) package_mocker = pytest.fixture(scope="package")(_mocker) session_mocker = pytest.fixture(scope="session")(_mocker) _mock_module_patches = [] # type: List[Any] _mock_module_originals = {} # type: Dict[str, Any] def assert_wrapper(__wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any) -> None: __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return
def fixture_wrapper(func): for t in types: registered_types.setdefault(t, []).append(func.__name__) return pytest.fixture(**kwargs)(func)
def make_G(): # Set up a test problem G = np.eye(n) normal = np.random.normal norm = np.linalg.norm for jj in range(5): gg = normal(size=n) hh = gg * gg.T G += (hh + hh.T) * 0.5 G += normal(size=n) * normal(size=n) return G G = pytest.fixture(make_G) def make_b(): return np.random.normal(size=n) b = pytest.fixture(make_b) tol = 1e-10 show = False maxit = None @pytest.mark.parametrize('xp', [ pytest.param(cupy,
"hil.ext.obm.ipmi = ", "[devel]", "dry_run = True", "[headnode]", "base_imgs = base-headnode, img1, img2, img3, img4", "[database]", "uri = sqlite:///" + tmpdir + "/hil.db", ]) with open(tmpdir + '/hil.cfg', 'w') as f: f.write(cfg) config.load(tmpdir + '/hil.cfg') config.configure_logging() config.load_extensions() fresh_database = pytest.fixture(fresh_database) @pytest.fixture() def run_obmd(tmpdir): """Set up and start obmd.""" check_call(['go', 'get', 'github.com/CCI-MOC/obmd']) config_file_path = tmpdir + '/obmd-config.json' with open(config_file_path, 'w') as f: f.write( json.dumps({ 'AdminToken': ADMIN_TOKEN, 'ListenAddr': ':8080', }))
""" Simple tests for odlpp.cuda This is mostly compilation tests, main suite is in odl """ import odlcuda.odlcuda_ as cuda import pytest vec_ids = [str(el) for el in dir(cuda) if el.startswith("CudaVector")] vec_params = [getattr(cuda, vec_id) for vec_id in vec_ids] vector_type_fixture = pytest.fixture(scope="module", ids=vec_ids, params=vec_params) @vector_type_fixture def vector_type(request): return request.param def test_has_vectors(): # Assert at least 1 vector exists assert len(vec_ids) > 0 def test_vector_init(vector_type): vec = vector_type(1) assert vec is not None def test_get_set(vector_type): vec = vector_type(1) vec[0] = 3
def disable_setup(request, monkeypatch): setup = getattr(request.module, "setup", None) isfixture = hasattr(setup, "_pytestfixturefunction") if setup is not None and not isfixture and py.builtin.callable(setup): monkeypatch.setattr(setup, "_pytestfixturefunction", pytest.fixture(), raising=False)
import json import pytest import requests from passlib.hash import sha512_crypt ep = "http://127.0.0.1:8000" username = "******" password = "******" http_client = HybridHTTPClient(endpoint=ep, username=username, password=password) C = Client(ep, http_client) # Initializing client library fail_on_log_warnings = pytest.fixture(fail_on_log_warnings) fresh_database = pytest.fixture(fresh_database) server_init = pytest.fixture(server_init) obmd_cfg = pytest.fixture(obmd_cfg) intial_db = pytest.fixture(initial_db) @pytest.fixture def dummy_verify(): """replace sha512_crypt.verify with something faster (albeit broken). This fixture is for testing User related client calls which use database authentication backend. This fixture works around a serious consequence of using the database backend: doing password hashing is **SLOW** (by design; the algorithms
@pytest.fixture def configure(): """Configure HIL""" config_testsuite() config_merge({ 'extensions': { 'hil.ext.switches.brocade': '', 'hil.ext.switches.dell': '', 'hil.ext.switches.nexus': '', }, }) config.load_extensions() fresh_database = pytest.fixture(fresh_database) fail_on_log_warnings = pytest.fixture(fail_on_log_warnings) server_init = pytest.fixture(server_init) with_request_context = pytest.yield_fixture(with_request_context) default_fixtures = [ 'fail_on_log_warnings', 'configure', 'fresh_database', 'server_init', 'with_request_context' ] pytestmark = pytest.mark.usefixtures(*default_fixtures) class TestPortValidate: """Test port_register with invalid port names for various switches.""" def test_register_port_invalid_name_brocade(self):
import pytest from tests.test_api_non_workspaced_base import GenericAPITest from tests.factories import UserFactory from faraday.server.models import User from faraday.server.api.modules.preferences import PreferencesView from tests.utils.url import v2_to_v3 pytest.fixture('logged_user') class TestPreferences(GenericAPITest): model = User factory = UserFactory api_endpoint = 'preferences' view_class = PreferencesView def test_add_preference(self, test_client): preferences = {'field1': 1, 'field2': 'str1'} data = {'preferences': preferences} response = test_client.post(self.url(), data=data) assert response.status_code == 200 response = test_client.get(self.url()) assert response.status_code == 200 assert response.json['preferences'] == preferences def test_list_preferences_from_session(self, test_client): preferences = {'field1': 1, 'field2': 'str1'}
import pytest from owmeta_pytest_plugin import bundle_versions, bundle_fixture_helper example_bundle = pytest.fixture(bundle_fixture_helper('example/aBundle')) @bundle_versions('example_bundle', [23]) @pytest.mark.bundle_remote('test') def test_bundle_remote(owm_project, example_bundle): owm_project.fetch(example_bundle)
import pytest from uuid import uuid4 from django.contrib.auth.models import AnonymousUser from django.contrib.messages.storage import default_storage from django.contrib.sessions.backends.base import SessionBase from django.core.files.uploadedfile import InMemoryUploadedFile from django.test.client import RequestFactory as drf from django.urls import reverse from caisse.models import Caisse from mrsrequest.models import MRSRequest from mrsrequest.views import MRSRequestCreateView id = mrsrequest_uuid = pytest.fixture( lambda: '2b88b740-3920-44e9-b086-c851f58e7ea7') class RequestFactory(drf): def __init__(self, user): self.user = user super().__init__() def generic(self, *args, **kwargs): request = super().generic(*args, **kwargs) request.session = SessionBase() request.user = self.user request._messages = default_storage(request) return request
return _check_real(lambda s, t: [0, 0, 0]) @pytest.fixture def simple_volume(): return _check_real(lambda t1, t2, t3: [0, 0, 0]) @pytest.fixture(params=[False, True]) def weyl_system(request): """ Creates a Weyl point system. """ res = z2pack.hm.System(lambda k: np.array([[k[2], k[0] - 1j * k[1]], [k[0] + 1j * k[1], -k[2]]])) if request.param: res = OverlapMockSystem(res) return res def weyl_line_creator(kz): return lambda t: [np.cos(t * 2 * np.pi), np.sin(t * 2 * np.pi), kz] weyl_line = pytest.fixture(weyl_line_creator) @pytest.fixture def weyl_surface(): return z2pack.shape.Sphere([0, 0, 0], 1.)
from protowhat.sct_syntax import ( ChainedCall, ChainExtender, EagerChain, ExGen, LazyChain, LazyChainStart, state_dec_gen, ) from tests.helper import state, dummy_checks sct_dict = {} Ex = ExGen(sct_dict, None) state_dec = state_dec_gen(sct_dict) state = pytest.fixture(state) dummy_checks = pytest.fixture(dummy_checks) @pytest.fixture def addx(): return lambda state, x: state + x @pytest.fixture def f(): return LazyChain(ChainedCall(lambda state, b: state + b, kwargs={"b": "b"})) @pytest.fixture
from jupyter_server.utils import url_path_join from jupyterlab_server import LabConfig from tornado.escape import url_escape from traitlets import Unicode from jupyterlab.labapp import LabApp def mkdir(tmp_path, *parts): path = tmp_path.joinpath(*parts) if not path.exists(): path.mkdir(parents=True) return path app_settings_dir = pytest.fixture( lambda tmp_path: mkdir(tmp_path, "app_settings")) user_settings_dir = pytest.fixture( lambda tmp_path: mkdir(tmp_path, "user_settings")) schemas_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "schemas")) workspaces_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "workspaces")) @pytest.fixture def make_lab_app(jp_root_dir, jp_template_dir, app_settings_dir, user_settings_dir, schemas_dir, workspaces_dir): def _make_lab_app(**kwargs): class TestLabApp(LabApp): base_url = "/lab" extension_url = "/lab" default_url = Unicode( "/", help="The default URL to redirect to from `/`")
enabled_remotes.update(REMOTES) else: default_enabled = {k for k, v in REMOTES.items() if v} enabled_remotes.update(default_enabled) for remote_name in REMOTES: enabled_opt = _get_opt(remote_name, "enable") disabled_opt = _get_opt(remote_name, "disable") enabled = config.getoption(enabled_opt) disabled = config.getoption(disabled_opt) if disabled and enabled: continue # default behavior if both flags are supplied if disabled: enabled_remotes.discard(remote_name) if enabled: enabled_remotes.add(remote_name) @pytest.fixture() def custom_template(tmp_dir, dvc): import shutil template = tmp_dir / "custom_template.json" shutil.copy(tmp_dir / ".dvc" / "plots" / "default.json", template) return template scriptify_fixture = pytest.fixture(lambda: scriptify, name="scriptify")
from student import StudentDB import pytest pytest.fixture(scope='module') def db(): print('============Setup===============') db = StudentDB() db.connect('data.json') return db # def teardown_module(module): # print('============Teardown===============') # global db # db.close() def test_scott_data(db): scott_data = db.get_data('Scott') assert scott_data['id'] == 1 assert scott_data['name'] == 'Scott' assert scott_data['result'] == 'pass' def test_mark_data(db): mark_data = db.get_data('Mark')
def fixture(self, *arg, **kw): return pytest.fixture(*arg, **kw)
import uuid import pytest from fixtures import context, lambda_module # pylint: disable=import-error from helpers import mock_table # pylint: disable=import-error,no-name-in-module lambda_module = pytest.fixture(scope="module", params=[{ "function_dir": "on_created", "module_name": "main", "environ": { "ENVIRONMENT": "test", "TABLE_NAME": "TABLE_NAME", "POWERTOOLS_TRACE_DISABLED": "true" } }])(lambda_module) context = pytest.fixture(context) @pytest.fixture def order_id(): return str(uuid.uuid4()) @pytest.fixture def payment_token(): return str(uuid.uuid4()) def test_save_payment_token(lambda_module, order_id, payment_token): """ Test save_payment_token()
exc = LoggedFailure("foo") assert exc.message[0] == '\x1b', "Message starts with ANSI sequence" class GroupMock(Group, list): def get_command(self, ctx, cmd_name): self.append((ctx, cmd_name)) class AliasedGroupWithMock(AliasedGroup, GroupMock): """Go watch Raymond's ‘Super considered super!’ @ https://youtu.be/EiOglTERPEo""" MAP = dict(foo='bar') aliased_group = pytest.fixture()(lambda: AliasedGroupWithMock()) class AliasedGroupTests(): def test_alias_group_maps_to_canonical_name(self, aliased_group): aliased_group.get_command(None, 'foo') assert aliased_group == [(None, 'bar')] def test_alias_group_passes_on_unmapped_name(self, aliased_group): aliased_group.get_command(None, 'foobar') assert aliased_group == [(None, 'foobar')] class ConfigurationTests(): def test_configuration_from_context_creation_works(self): ctx = Bunch(info_name='foobarbaz', obj=None)
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fixtures for writing tests that execute WDL workflows using Cromwell. For testability purposes, the implementaiton of these fixtures is done in the pytest_wdl.fixtures module. """ from pytest_wdl import fixtures import pytest user_config_file = pytest.fixture(scope="session")(fixtures.user_config_file) user_config = pytest.fixture(scope="session")(fixtures.user_config) project_root_files = pytest.fixture(scope="module")( fixtures.project_root_files) project_root = pytest.fixture(scope="module")(fixtures.project_root) workflow_data_descriptor_file = pytest.fixture(scope="module")( fixtures.workflow_data_descriptor_file) workflow_data_descriptors = pytest.fixture(scope="module")( fixtures.workflow_data_descriptors) workflow_data_resolver = pytest.fixture(scope="module")( fixtures.workflow_data_resolver) workflow_data = pytest.fixture(scope="function")(fixtures.workflow_data) import_paths = pytest.fixture(scope="module")(fixtures.import_paths) import_dirs = pytest.fixture(scope="module")(fixtures.import_dirs) workflow_runner = pytest.fixture(scope="function")(fixtures.workflow_runner)
def polygon_without_type(polygon): """a GeoJSON Polygon without a type key""" del polygon['type'] return polygon @pytest.fixture def text_file(tmpdir): """a file that does not contain valid JSON""" f = tmpdir.join('test.txt') with f.open('w', encoding='ascii') as tmpfile: tmpfile.write('plaintext') return str(f) @pytest.fixture def unequal_positions(position): """a 2-tuple pair of distinct GeoJSON Position""" position2 = list(position) position2[0] = position[0] + 1 return position, position2 # Make functions in gjtk.random fixtures: for name in dir(gjtk.random): if name.startswith('_'): continue attr = getattr(gjtk.random, name) if callable(attr): globals()[name] = pytest.fixture(attr, name=name)
from bs4 import BeautifulSoup as Soup from .fixtures import app_client import pytest import re import urllib.parse pytest.fixture(scope='module')(app_client) def test_homepage(app_client): response = app_client.get('/', gather_request=False) assert response.status == 200 assert 'test_tables' in response.text def test_database_page(app_client): response = app_client.get('/test_tables', allow_redirects=False, gather_request=False) assert response.status == 302 response = app_client.get('/test_tables', gather_request=False) assert 'test_tables' in response.text def test_invalid_custom_sql(app_client): response = app_client.get('/test_tables?sql=.schema', gather_request=False) assert response.status == 400 assert 'Statement must be a SELECT' in response.text def test_view(app_client):
import test.integration.fixtures def is_gz_file(filepath): with open(filepath, 'rb') as test_f: return binascii.hexlify(test_f.read(2)) == b'1f8b' def find_files(root_dir, filt): matches = [] for root, dirnames, filenames in os.walk(root_dir): for filename in fnmatch.filter(filenames, filt): yield join(root, filename) krona = pytest.fixture(scope='module')(test.integration.fixtures.krona) krona_db = pytest.fixture(scope='module')(test.integration.fixtures.krona_db) taxonomy_db = pytest.fixture(scope='module')(test.integration.fixtures.taxonomy_db) @pytest.fixture(scope='module') def fastq_to_sam(): return tools.picard.FastqToSamTool() @pytest.fixture(scope='module') def sam_to_fastq(): return tools.picard.SamToFastqTool() @pytest.fixture(scope='module')
@pytest.fixture def configure(): config_testsuite() config_merge({ 'haas.ext.switches.dell': { 'save': 'True' }, 'haas.ext.switches.nexus': { 'save': 'True' } }) config.load_extensions() fail_on_log_warnings = pytest.fixture(autouse=True)(fail_on_log_warnings) fresh_database = pytest.fixture(fresh_database) @pytest.fixture def server_init(): server.register_drivers() server.validate_state() with_request_context = pytest.yield_fixture(with_request_context) site_layout = pytest.fixture(site_layout) pytestmark = pytest.mark.usefixtures('configure', 'server_init', 'fresh_database', 'with_request_context',
return fresh_database(request) @pytest.fixture def server_init(): server.register_drivers() server.validate_state() @pytest.yield_fixture def with_request_context(): with rest.RequestContext(): yield site_layout = pytest.fixture(site_layout) pytestmark = pytest.mark.usefixtures("configure", "server_init", "db", "with_request_context", "site_layout") class TestNativeNetwork(NetworkTest): def test_isolated_networks(self, db): def create_networks(): nodes = self.collect_nodes(db) # Create two networks network_create_simple("net-0", "anvil-nextgen") network_create_simple("net-1", "anvil-nextgen") ports = self.get_all_ports(nodes)
from jupyterlab import LabApp from jupyterlab_server import LabConfig from jupyterlab_server.tests.utils import here from jupyterlab_server.app import LabServerApp from jupyter_server.utils import url_path_join def mkdir(tmp_path, *parts): path = tmp_path.joinpath(*parts) if not path.exists(): path.mkdir(parents=True) return path app_settings_dir = pytest.fixture( lambda tmp_path: mkdir(tmp_path, 'app_settings')) user_settings_dir = pytest.fixture( lambda tmp_path: mkdir(tmp_path, 'user_settings')) schemas_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, 'schemas')) workspaces_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, 'workspaces')) @pytest.fixture def make_lab_app(jp_root_dir, jp_template_dir, app_settings_dir, user_settings_dir, schemas_dir, workspaces_dir): def _make_lab_app(**kwargs): class TestLabApp(LabApp): base_url = '/lab' extension_url = '/lab' default_url = Unicode( '/', help='The default URL to redirect to from `/`')