• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pytest.fixture函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pytest.fixture函数的典型用法代码示例。如果您正苦于以下问题:Python fixture函数的具体用法?Python fixture怎么用?Python fixture使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了fixture函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __new__

 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
开发者ID:krya,项目名称:pydjango,代码行数:9,代码来源:fixtures.py


示例2: decorator

    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
开发者ID:DZittersteyn,项目名称:pytest-bdd,代码行数:11,代码来源:steps.py


示例3: decorate

        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
开发者ID:katerose,项目名称:encoded,代码行数:13,代码来源:data.py


示例4: given

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)
开发者ID:gilmrjc,项目名称:pytest-bdd,代码行数:29,代码来源:steps.py


示例5: simple_fixture

    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)
开发者ID:odlgroup,项目名称:odl,代码行数:35,代码来源:testutils.py


示例6: decorator

    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
开发者ID:curzona,项目名称:pytest-bdd,代码行数:26,代码来源:steps.py


示例7: given

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)
开发者ID:albertjan,项目名称:pytest-bdd,代码行数:26,代码来源:steps.py


示例8: decorator

    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
开发者ID:webappzero,项目名称:pytest-bdd,代码行数:29,代码来源:steps.py


示例9: _make_fixture

    def _make_fixture(cls, name):
        factory = getattr(cls, name + '_factory')

        def fixture(self):
            return factory.create()

        fixture.__name__ = name
        return pytest.fixture(fixture)
开发者ID:fabiommendes,项目名称:codeschool,代码行数:8,代码来源:base.py


示例10: _get_role_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)
开发者ID:omergertel,项目名称:backslash,代码行数:9,代码来源:conftest.py


示例11: calc_motor_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)
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:9,代码来源:conftest.py


示例12: make_uri_fixture

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)
开发者ID:franzinc,项目名称:agraph-python,代码行数:10,代码来源:conftest.py


示例13: instance_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
开发者ID:fabiommendes,项目名称:smallvectors,代码行数:11,代码来源:base.py


示例14: make_fixture

        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)
开发者ID:fabiommendes,项目名称:smallvectors,代码行数:11,代码来源:base.py


示例15: fixture

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)
开发者ID:ljakab,项目名称:wireshark,代码行数:12,代码来源:fixtures.py


示例16: setup_pytest_browser_fixture

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)
开发者ID:alisazhou,项目名称:examplejs,代码行数:14,代码来源:browser_fixture.py


示例17: motor_fixture

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)
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:15,代码来源:conftest.py


示例18: pytest_configure

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)
开发者ID:johanalenius,项目名称:main,代码行数:47,代码来源:conftest.py


示例19: given

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)
开发者ID:DZittersteyn,项目名称:pytest-bdd,代码行数:17,代码来源:steps.py


示例20: model_fixture

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))
开发者ID:fabiommendes,项目名称:codeschool,代码行数:18,代码来源:conftest.py



注:本文中的pytest.fixture函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pytest.importorskip函数代码示例发布时间:2022-05-27
下一篇:
Python pytest.fail函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap