當前位置: 首頁>>代碼示例>>Python>>正文


Python pytest.param方法代碼示例

本文整理匯總了Python中pytest.param方法的典型用法代碼示例。如果您正苦於以下問題:Python pytest.param方法的具體用法?Python pytest.param怎麽用?Python pytest.param使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pytest的用法示例。


在下文中一共展示了pytest.param方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: epochs

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def epochs(epoch_1960, request):
    """Timestamp at 1960-01-01 in various forms.

    * pd.Timestamp
    * datetime.datetime
    * numpy.datetime64
    * str
    """
    assert request.param in {'timestamp', 'pydatetime', 'datetime64',
                             "str_1960"}
    if request.param == 'timestamp':
        return epoch_1960
    elif request.param == 'pydatetime':
        return epoch_1960.to_pydatetime()
    elif request.param == "datetime64":
        return epoch_1960.to_datetime64()
    else:
        return str(epoch_1960) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:test_tools.py

示例2: __init__

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def __init__(self,
                 valuegetter,  # type: Callable[[], Any]
                 id=None,      # type: str
                 marks=()      # type: Sequence
                 ):
        """
        Creates a reference to a value getter, to be used in `parametrize_plus`.

        A `lazy_value` is the same thing than a function-scoped fixture, except that the value getter function is not a
        fixture and therefore can neither be parametrized nor depend on fixtures. It should have no mandatory argument.

        Note that a `lazy_value` can be included in a `pytest.param` without problem. In that case the id defined by
        `pytest.param` will take precedence over the one defined in `lazy_value` if any. The marks, however,
        will all be kept wherever they are defined.

        :param valuegetter: a callable without mandatory arguments
        :param id: an optional id. Otherwise `valuegetter.__name__` will be used by default
        :param marks: optional marks. `valuegetter` marks will also be preserved.
        """
        self.valuegetter = valuegetter
        self._id = id
        self._marks = marks 
開發者ID:smarie,項目名稱:python-pytest-cases,代碼行數:24,代碼來源:fixture_parametrize_plus.py

示例3: explicit

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def explicit(param  # type: ParamAlternative
                 ):
        if isinstance(param, SingleParamAlternative):
            # return "%s_is_P%s" % (param.param_name, param.argvalues_index)
            return "%s_is_%s" % (param.argnames_str, param.get_id())
        elif isinstance(param, MultiParamAlternative):
            return "%s_is_P%stoP%s" % (param.argnames_str, param.argvalues_index_from, param.argvalues_index_to - 1)
        elif isinstance(param, FixtureParamAlternative):
            return "%s_is_%s" % (param.argnames_str, param.alternative_name)
        elif isinstance(param, ProductParamAlternative):
            return "%s_is_P%s" % (param.argnames_str, param.argvalues_index)
        else:
            raise TypeError("Unsupported alternative: %r" % param)

    # @staticmethod
    # def compact(param):
    #     return "U%s" % param.alternative_name 
開發者ID:smarie,項目名稱:python-pytest-cases,代碼行數:19,代碼來源:fixture_parametrize_plus.py

示例4: is_fixture_union_params

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def is_fixture_union_params(params):
    """
    Internal helper to quickly check if a bunch of parameters correspond to a union fixture.
    :param params:
    :return:
    """
    try:
        if len(params) < 1:
            return False
        else:
            if getattr(params, '__module__', '').startswith('pytest_cases'):
                # a value_ref_tuple or another proxy object created somewhere in our code, not a list
                return False
            p0 = params[0]
            if is_marked_parameter_value(p0):
                p0 = get_marked_parameter_values(p0)[0]
            return isinstance(p0, UnionFixtureAlternative)
    except TypeError:
        raise InvalidParamsList(params) 
開發者ID:smarie,項目名稱:python-pytest-cases,代碼行數:21,代碼來源:fixture_core1_unions.py

示例5: get_param_names

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def get_param_names(fnode):
    """
    Returns a list of parameter names for the given pytest Function node.
    parameterization marks containing several names are split

    :param fnode:
    :return:
    """
    p_markers = get_parametrization_markers(fnode)
    param_names = []
    for paramz_mark in p_markers:
        param_names += get_param_argnames_as_list(paramz_mark.args[0])
    return param_names


# ---------------- working on functions 
開發者ID:smarie,項目名稱:python-pytest-cases,代碼行數:18,代碼來源:common_pytest.py

示例6: get_pytest_marks_on_function

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def get_pytest_marks_on_function(f, as_decorators=False):
    """
    Utility to return *ALL* pytest marks (not only parametrization) applied on a function

    :param f:
    :param as_decorators: transforms the marks into decorators before returning them
    :return:
    """
    try:
        mks = f.pytestmark
    except AttributeError:
        try:
            # old pytest < 3: marks are set as fields on the function object
            # but they do not have a particulat type, their type is 'instance'...
            mks = [v for v in vars(f).values() if str(v).startswith("<MarkInfo '")]
        except AttributeError:
            mks = []

    if as_decorators:
        return transform_marks_into_decorators(mks)
    else:
        return mks 
開發者ID:smarie,項目名稱:python-pytest-cases,代碼行數:24,代碼來源:common_pytest.py

示例7: test_subsequent_contexts

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def test_subsequent_contexts():
    # Force a very fast fit
    with StepwiseContext(max_dur=.5), \
            pytest.warns(UserWarning):
        auto_arima(lynx, stepwise=True)

    # Out of scope, should be EMPTY
    assert ContextStore.get_or_empty(ContextType.STEPWISE).get_type() \
        is ContextType.EMPTY

    # Now show that we DON'T hit early termination by time here
    with StepwiseContext(max_steps=100), \
            pytest.warns(UserWarning) as uw:

        ctx = ContextStore.get_or_empty(ContextType.STEPWISE)
        assert ctx.get_type() is ContextType.STEPWISE
        assert ctx.max_dur is None

        auto_arima(lynx, stepwise=True)
        # assert that max_dur was NOT reached
        assert not any(str(w.message)
                       .startswith('early termination') for w in uw)


# test param validation of ContextStore's add, get and remove members 
開發者ID:alkaline-ml,項目名稱:pmdarima,代碼行數:27,代碼來源:test_context.py

示例8: all_test_vectors

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def all_test_vectors() -> Iterable[Any]:
    """Collect and iterate through all test vectors."""

    with open(test_vectors_filename(), "r") as vectors_file:
        raw_vectors = json.load(vectors_file)

    for vector in raw_vectors:
        vector_name = "::".join([vector["key-type"], vector["algorithm-suite"]])
        plaintext = base64.b64decode(vector["plaintext"].encode("utf-8"))
        ciphertext = base64.b64decode(vector["ciphertext"].encode("utf-8"))
        yield pytest.param(
            TestVector(
                plaintext=plaintext,
                ciphertext=ciphertext,
                key_type=vector["key-type"],
                algorithm_suite=vector["algorithm-suite"],
            ),
            id=vector_name,
        ) 
開發者ID:aws,項目名稱:aws-encryption-sdk-python,代碼行數:21,代碼來源:integration_test_utils.py

示例9: up

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def up(self, request):
        return urlmatch.UrlPattern(request.param) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:4,代碼來源:test_urlmatch.py

示例10: signal_obj

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def signal_obj(request):
    klass, wrap = request.param
    obj = klass()
    if wrap:
        debug.log_signals(obj)
    return obj 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:8,代碼來源:test_debug.py

示例11: freezer

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def freezer(request, monkeypatch):
    if request.param and not getattr(sys, 'frozen', False):
        monkeypatch.setattr(sys, 'frozen', True, raising=False)
        monkeypatch.setattr(sys, 'executable', qutebrowser.__file__)
    elif not request.param and getattr(sys, 'frozen', False):
        # Want to test unfrozen tests, but we are frozen
        pytest.skip("Can't run with sys.frozen = True!") 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:9,代碼來源:test_utils.py

示例12: gen_classes

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def gen_classes():  # pylint: disable=no-method-argument
        """Yield all configtypes classes to test.

        Not a method as it's used in decorators.
        """
        for _name, member in inspect.getmembers(configtypes, inspect.isclass):
            if member in [configtypes.BaseType, configtypes.MappingType,
                          configtypes._Numeric, configtypes.FontBase]:
                pass
            elif (member is configtypes.List or
                  member is configtypes.ListOrValue):
                yield pytest.param(
                    functools.partial(member, valtype=configtypes.Int()),
                    id=member.__name__ + '-Int')
                yield pytest.param(
                    functools.partial(member, valtype=configtypes.Url()),
                    id=member.__name__ + '-Url')
            elif member is configtypes.Dict:
                yield pytest.param(
                    functools.partial(member, keytype=configtypes.String(),
                                      valtype=configtypes.String()),
                    id=member.__name__)
            elif member is configtypes.FormatString:
                yield pytest.param(
                    functools.partial(member, fields=['a', 'b']),
                    id=member.__name__)
            elif issubclass(member, configtypes.BaseType):
                yield member 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:30,代碼來源:test_configtypes.py

示例13: iter_struct_object_dtypes

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def iter_struct_object_dtypes():
    """
    Iterates over a few complex dtypes and object pattern which
    fill the array with a given object (defaults to a singleton).

    Yields
    ------
    dtype : dtype
    pattern : tuple
        Structured tuple for use with `np.array`.
    count : int
        Number of objects stored in the dtype.
    singleton : object
        A singleton object. The returned pattern is constructed so that
        all objects inside the datatype are set to the singleton.
    """
    obj = object()

    dt = np.dtype([('b', 'O', (2, 3))])
    p = ([[obj] * 3] * 2,)
    yield pytest.param(dt, p, 6, obj, id="<subarray>")

    dt = np.dtype([('a', 'i4'), ('b', 'O', (2, 3))])
    p = (0, [[obj] * 3] * 2)
    yield pytest.param(dt, p, 6, obj, id="<subarray in field>")

    dt = np.dtype([('a', 'i4'),
                   ('b', [('ba', 'O'), ('bb', 'i1')], (2, 3))])
    p = (0, [[(obj, 0)] * 3] * 2)
    yield pytest.param(dt, p, 6, obj, id="<structured subarray 1>")

    dt = np.dtype([('a', 'i4'),
                   ('b', [('ba', 'O'), ('bb', 'O')], (2, 3))])
    p = (0, [[(obj, obj)] * 3] * 2)
    yield pytest.param(dt, p, 12, obj, id="<structured subarray 2>") 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:37,代碼來源:test_dtype.py

示例14: spmatrix

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def spmatrix(request):
    from scipy import sparse
    return getattr(sparse, request.param + '_matrix') 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:5,代碼來源:conftest.py

示例15: unique_nulls_fixture

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import param [as 別名]
def unique_nulls_fixture(request):
    """
    Fixture for each null type in pandas, each null type exactly once
    """
    return request.param


# Generate cartesian product of unique_nulls_fixture: 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:conftest.py


注:本文中的pytest.param方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。