Python pytest.mark() Examples

The following are 30 code examples for showing how to use pytest.mark(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pytest , or try the search function .

Example 1
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 6 votes vote down vote up
def get_empty_parameterset_mark(config, argnames, func):
    from ..nodes import Collector

    requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
    if requested_mark in ("", None, "skip"):
        mark = MARK_GEN.skip
    elif requested_mark == "xfail":
        mark = MARK_GEN.xfail(run=False)
    elif requested_mark == "fail_at_collect":
        f_name = func.__name__
        _, lineno = getfslineno(func)
        raise Collector.CollectError(
            "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
        )
    else:
        raise LookupError(requested_mark)
    fs, lineno = getfslineno(func)
    reason = "got empty parameter set %r, function %s at %s:%d" % (
        argnames,
        func.__name__,
        fs,
        lineno,
    )
    return mark(reason=reason) 
Example 2
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 6 votes vote down vote up
def extract_from(cls, parameterset, force_tuple=False):
        """
        :param parameterset:
            a legacy style parameterset that may or may not be a tuple,
            and may or may not be wrapped into a mess of mark objects

        :param force_tuple:
            enforce tuple wrapping so single argument tuple values
            don't get decomposed and break tests
        """

        if isinstance(parameterset, cls):
            return parameterset
        if force_tuple:
            return cls.param(parameterset)
        else:
            return cls(parameterset, marks=[], id=None) 
Example 3
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 6 votes vote down vote up
def get_empty_parameterset_mark(config, argnames, func):
    from ..nodes import Collector

    requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
    if requested_mark in ("", None, "skip"):
        mark = MARK_GEN.skip
    elif requested_mark == "xfail":
        mark = MARK_GEN.xfail(run=False)
    elif requested_mark == "fail_at_collect":
        f_name = func.__name__
        _, lineno = getfslineno(func)
        raise Collector.CollectError(
            "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
        )
    else:
        raise LookupError(requested_mark)
    fs, lineno = getfslineno(func)
    reason = "got empty parameter set %r, function %s at %s:%d" % (
        argnames,
        func.__name__,
        fs,
        lineno,
    )
    return mark(reason=reason) 
Example 4
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 6 votes vote down vote up
def extract_from(cls, parameterset, force_tuple=False):
        """
        :param parameterset:
            a legacy style parameterset that may or may not be a tuple,
            and may or may not be wrapped into a mess of mark objects

        :param force_tuple:
            enforce tuple wrapping so single argument tuple values
            don't get decomposed and break tests
        """

        if isinstance(parameterset, cls):
            return parameterset
        if force_tuple:
            return cls.param(parameterset)
        else:
            return cls(parameterset, marks=[], id=None) 
Example 5
def __init__(self, mark):
        bound = get_parametrize_signature().bind(*mark.args, **mark.kwargs)
        try:
            remaining_kwargs = bound.arguments['kwargs']
        except KeyError:
            pass
        else:
            if len(remaining_kwargs) > 0:
                warn("parametrize kwargs not taken into account: %s. Please report it at"
                     " https://github.com/smarie/python-pytest-cases/issues" % remaining_kwargs)
        self.param_names = get_param_argnames_as_list(bound.arguments['argnames'])
        self.param_values = bound.arguments['argvalues']
        try:
            bound.apply_defaults()
            self.param_ids = bound.arguments['ids']
        except AttributeError:
            # can happen if signature is from funcsigs so we have to apply ourselves
            self.param_ids = bound.arguments.get('ids', None)


# -------- tools to get the parametrization mark whatever the pytest version 
Example 6
Project: bazarr   Author: morpheus65535   File: tree_construction.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _getParserTests(self, treeName, treeAPIs):
        if treeAPIs is not None and "adapter" in treeAPIs:
            return
        for namespaceHTMLElements in (True, False):
            if namespaceHTMLElements:
                nodeid = "%s::parser::namespaced" % treeName
            else:
                nodeid = "%s::parser::void-namespace" % treeName
            item = ParserTest(nodeid,
                              self,
                              self.testdata,
                              treeAPIs["builder"] if treeAPIs is not None else None,
                              namespaceHTMLElements)
            item.add_marker(getattr(pytest.mark, treeName))
            item.add_marker(pytest.mark.parser)
            if namespaceHTMLElements:
                item.add_marker(pytest.mark.namespaced)
            if treeAPIs is None:
                item.add_marker(pytest.mark.skipif(True, reason="Treebuilder not loaded"))
            yield item 
Example 7
Project: suds   Author: suds-community   File: indirect_parametrize.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def indirect_parametrize(func, *args, **kwargs):
    """
    Decorator registering a custom parametrization function for a pytest test.

    This pytest.mark.indirect_parametrize() replacement allows the use of
    indirect parametrization functions taking no input parameters or, with
    pytest versions prior to 2.5.2, functions taking only keyword arguments.

    If a pytest.mark.indirect_parametrize() call is made with such an indirect
    parametrization function, it decorates the given function instead of
    storing and using it to decorate the intended function later on.

    """
    # In pytest versions prior to 2.5.2 pytest.mark.indirect_parametrize()
    # special handling occurs even when passing it additional keyword arguments
    # so we have to make sure we are passing it at least one additional
    # positional argument.
    def wrapper(func, *args, **kwargs):
        return func(*args, **kwargs)
    return pytest.mark.indirect_parametrize(wrapper, func, *args, **kwargs) 
Example 8
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):
        argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
        parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
        del argvalues

        if parameters:
            # check all parameter sets have the correct number of values
            for param in parameters:
                if len(param.values) != len(argnames):
                    msg = (
                        '{nodeid}: in "parametrize" the number of names ({names_len}):\n'
                        "  {names}\n"
                        "must be equal to the number of values ({values_len}):\n"
                        "  {values}"
                    )
                    fail(
                        msg.format(
                            nodeid=function_definition.nodeid,
                            values=param.values,
                            names=argnames,
                            names_len=len(argnames),
                            values_len=len(param.values),
                        ),
                        pytrace=False,
                    )
        else:
            # empty parameter set (likely computed at runtime): create a single
            # parameter set with NOTSET values, with the "empty parameter set" mark applied to it
            mark = get_empty_parameterset_mark(config, argnames, func)
            parameters.append(
                ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)
            )
        return argnames, parameters 
Example 9
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def combined_with(self, other):
        """
        :param other: the mark to combine with
        :type other: Mark
        :rtype: Mark

        combines by appending args and merging the mappings
        """
        assert self.name == other.name
        return Mark(
            self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)
        ) 
Example 10
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __eq__(self, other):
        return self.mark == other.mark if isinstance(other, MarkDecorator) else False 
Example 11
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def with_args(self, *args, **kwargs):
        """ return a MarkDecorator with extra arguments added

        unlike call this can be used even if the sole argument is a callable/class

        :return: MarkDecorator
        """

        mark = Mark(self.name, args, kwargs)
        return self.__class__(self.mark.combined_with(mark)) 
Example 12
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        """ if passed a single callable argument: decorate it with mark info.
            otherwise add *args/**kwargs in-place to mark information. """
        if args and not kwargs:
            func = args[0]
            is_class = inspect.isclass(func)
            if len(args) == 1 and (istestfunc(func) or is_class):
                store_mark(func, self.mark)
                return func
        return self.with_args(*args, **kwargs) 
Example 13
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def normalize_mark_list(mark_list):
    """
    normalizes marker decorating helpers to mark objects

    :type mark_list: List[Union[Mark, Markdecorator]]
    :rtype: List[Mark]
    """
    extracted = [
        getattr(mark, "mark", mark) for mark in mark_list
    ]  # unpack MarkDecorator
    for mark in extracted:
        if not isinstance(mark, Mark):
            raise TypeError("got {!r} instead of Mark".format(mark))
    return [x for x in extracted if isinstance(x, Mark)] 
Example 14
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def store_mark(obj, mark):
    """store a Mark on an object
    this is used to implement the Mark declarations/decorators correctly
    """
    assert isinstance(mark, Mark), mark
    # always reassign name to avoid updating pytestmark
    # in a reference that was only borrowed
    obj.pytestmark = get_unpacked_marks(obj) + [mark] 
Example 15
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __getattr__(self, name):
        if name[0] == "_":
            raise AttributeError("Marker name must NOT start with underscore")

        if self._config is not None:
            # We store a set of markers as a performance optimisation - if a mark
            # name is in the set we definitely know it, but a mark may be known and
            # not in the set.  We therefore start by updating the set!
            if name not in self._markers:
                for line in self._config.getini("markers"):
                    # example lines: "skipif(condition): skip the given test if..."
                    # or "hypothesis: tests which use Hypothesis", so to get the
                    # marker name we split on both `:` and `(`.
                    marker = line.split(":")[0].split("(")[0].strip()
                    self._markers.add(marker)

            # If the name is not in the set of known marks after updating,
            # then it really is time to issue a warning or an error.
            if name not in self._markers:
                if self._config.option.strict_markers:
                    fail(
                        "{!r} not found in `markers` configuration option".format(name),
                        pytrace=False,
                    )
                else:
                    warnings.warn(
                        "Unknown pytest.mark.%s - is this a typo?  You can register "
                        "custom marks to avoid this warning - for details, see "
                        "https://docs.pytest.org/en/latest/mark.html" % name,
                        PytestUnknownMarkWarning,
                    )

        return MarkDecorator(Mark(name, (), {})) 
Example 16
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):
        argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
        parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
        del argvalues

        if parameters:
            # check all parameter sets have the correct number of values
            for param in parameters:
                if len(param.values) != len(argnames):
                    msg = (
                        '{nodeid}: in "parametrize" the number of names ({names_len}):\n'
                        "  {names}\n"
                        "must be equal to the number of values ({values_len}):\n"
                        "  {values}"
                    )
                    fail(
                        msg.format(
                            nodeid=function_definition.nodeid,
                            values=param.values,
                            names=argnames,
                            names_len=len(argnames),
                            values_len=len(param.values),
                        ),
                        pytrace=False,
                    )
        else:
            # empty parameter set (likely computed at runtime): create a single
            # parameter set with NOTSET values, with the "empty parameter set" mark applied to it
            mark = get_empty_parameterset_mark(config, argnames, func)
            parameters.append(
                ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)
            )
        return argnames, parameters 
Example 17
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def combined_with(self, other):
        """
        :param other: the mark to combine with
        :type other: Mark
        :rtype: Mark

        combines by appending args and merging the mappings
        """
        assert self.name == other.name
        return Mark(
            self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)
        ) 
Example 18
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __eq__(self, other):
        return self.mark == other.mark if isinstance(other, MarkDecorator) else False 
Example 19
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def with_args(self, *args, **kwargs):
        """ return a MarkDecorator with extra arguments added

        unlike call this can be used even if the sole argument is a callable/class

        :return: MarkDecorator
        """

        mark = Mark(self.name, args, kwargs)
        return self.__class__(self.mark.combined_with(mark)) 
Example 20
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        """ if passed a single callable argument: decorate it with mark info.
            otherwise add *args/**kwargs in-place to mark information. """
        if args and not kwargs:
            func = args[0]
            is_class = inspect.isclass(func)
            if len(args) == 1 and (istestfunc(func) or is_class):
                store_mark(func, self.mark)
                return func
        return self.with_args(*args, **kwargs) 
Example 21
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def normalize_mark_list(mark_list):
    """
    normalizes marker decorating helpers to mark objects

    :type mark_list: List[Union[Mark, Markdecorator]]
    :rtype: List[Mark]
    """
    extracted = [
        getattr(mark, "mark", mark) for mark in mark_list
    ]  # unpack MarkDecorator
    for mark in extracted:
        if not isinstance(mark, Mark):
            raise TypeError("got {!r} instead of Mark".format(mark))
    return [x for x in extracted if isinstance(x, Mark)] 
Example 22
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def store_mark(obj, mark):
    """store a Mark on an object
    this is used to implement the Mark declarations/decorators correctly
    """
    assert isinstance(mark, Mark), mark
    # always reassign name to avoid updating pytestmark
    # in a reference that was only borrowed
    obj.pytestmark = get_unpacked_marks(obj) + [mark] 
Example 23
Project: python-netsurv   Author: sofia-netsurv   File: structures.py    License: MIT License 5 votes vote down vote up
def __getattr__(self, name):
        if name[0] == "_":
            raise AttributeError("Marker name must NOT start with underscore")

        if self._config is not None:
            # We store a set of markers as a performance optimisation - if a mark
            # name is in the set we definitely know it, but a mark may be known and
            # not in the set.  We therefore start by updating the set!
            if name not in self._markers:
                for line in self._config.getini("markers"):
                    # example lines: "skipif(condition): skip the given test if..."
                    # or "hypothesis: tests which use Hypothesis", so to get the
                    # marker name we split on both `:` and `(`.
                    marker = line.split(":")[0].split("(")[0].strip()
                    self._markers.add(marker)

            # If the name is not in the set of known marks after updating,
            # then it really is time to issue a warning or an error.
            if name not in self._markers:
                if self._config.option.strict_markers:
                    fail(
                        "{!r} not found in `markers` configuration option".format(name),
                        pytrace=False,
                    )
                else:
                    warnings.warn(
                        "Unknown pytest.mark.%s - is this a typo?  You can register "
                        "custom marks to avoid this warning - for details, see "
                        "https://docs.pytest.org/en/latest/mark.html" % name,
                        PytestUnknownMarkWarning,
                    )

        return MarkDecorator(Mark(name, (), {})) 
Example 24
def get_param_argnames_as_list(argnames):
    """
    pytest parametrize accepts both coma-separated names and list/tuples.
    This function makes sure that we always return a list
    :param argnames:
    :return:
    """
    if isinstance(argnames, string_types):
        argnames = argnames.replace(' ', '').split(',')
    return list(argnames)


# ------------ container for the mark information that we grab from the fixtures (`@fixture_plus`) 
Example 25
def get_pytest_parametrize_marks(f):
    """
    Returns the @pytest.mark.parametrize marks associated with a function (and only those)

    :param f:
    :return: a tuple containing all 'parametrize' marks
    """
    # pytest > 3.2.0
    marks = getattr(f, 'pytestmark', None)
    if marks is not None:
        return tuple(_ParametrizationMark(m) for m in marks if m.name == 'parametrize')
    else:
        # older versions
        mark_info = getattr(f, 'parametrize', None)
        if mark_info is not None:
            # mark_info.args contains a list of (name, values)
            if len(mark_info.args) % 2 != 0:
                raise ValueError("internal pytest compatibility error - please report")
            nb_parametrize_decorations = len(mark_info.args) // 2
            if nb_parametrize_decorations > 1 and len(mark_info.kwargs) > 0:
                raise ValueError("Unfortunately with this old pytest version it is not possible to have several "
                                 "parametrization decorators while specifying **kwargs, as all **kwargs are "
                                 "merged, leading to inconsistent results. Either upgrade pytest, remove the **kwargs,"
                                 "or merge all the @parametrize decorators into a single one. **kwargs: %s"
                                 % mark_info.kwargs)
            res = []
            for i in range(nb_parametrize_decorations):
                param_name, param_values = mark_info.args[2*i:2*(i+1)]
                res.append(_ParametrizationMark(_LegacyMark(param_name, param_values, **mark_info.kwargs)))
            return tuple(res)
        else:
            return ()


# noinspection PyUnusedLocal 
Example 26
def _pytest_mark_parametrize(argnames, argvalues, ids=None, indirect=False, scope=None, **kwargs):
    """ Fake method to have a reference signature of pytest.mark.parametrize"""
    pass 
Example 27
def get_marked_parameter_id(v):
        return v.kwargs.get('id', None)


# ---- tools to reapply marks on test parameter values, whatever the pytest version ----

# Compatibility for the way we put marks on single parameters in the list passed to @pytest.mark.parametrize
# see https://docs.pytest.org/en/3.3.0/skipping.html?highlight=mark%20parametrize#skip-xfail-with-parametrize

# check if pytest.param exists 
Example 28
def transform_marks_into_decorators(marks):
    """
    Transforms the provided marks (MarkInfo) obtained from marked cases, into MarkDecorator so that they can
    be re-applied to generated pytest parameters in the global @pytest.mark.parametrize.

    :param marks:
    :return:
    """
    marks_mod = []
    try:
        # suppress the warning message that pytest generates when calling pytest.mark.MarkDecorator() directly
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            for m in marks:
                md = pytest.mark.MarkDecorator()

                if LooseVersion(pytest.__version__) >= LooseVersion('3.0.0'):
                    if isinstance(m, type(md)):
                        # already a decorator, we can use it
                        marks_mod.append(m)
                    else:
                        md.mark = m
                        marks_mod.append(md)
                else:
                    # always recreate one, type comparison does not work (all generic stuff)
                    md.name = m.name
                    # md.markname = m.name
                    md.args = m.args
                    md.kwargs = m.kwargs

                    # markinfodecorator = getattr(pytest.mark, markinfo.name)
                    # markinfodecorator(*markinfo.args)

                    marks_mod.append(md)

    except Exception as e:
        warn("Caught exception while trying to mark case: [%s] %s" % (type(e), e))
    return marks_mod 
Example 29
Project: pytest   Author: pytest-dev   File: structures.py    License: MIT License 5 votes vote down vote up
def get_empty_parameterset_mark(
    config: Config, argnames: Sequence[str], func
) -> "MarkDecorator":
    from ..nodes import Collector

    fs, lineno = getfslineno(func)
    reason = "got empty parameter set %r, function %s at %s:%d" % (
        argnames,
        func.__name__,
        fs,
        lineno,
    )

    requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
    if requested_mark in ("", None, "skip"):
        mark = MARK_GEN.skip(reason=reason)
    elif requested_mark == "xfail":
        mark = MARK_GEN.xfail(reason=reason, run=False)
    elif requested_mark == "fail_at_collect":
        f_name = func.__name__
        _, lineno = getfslineno(func)
        raise Collector.CollectError(
            "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
        )
    else:
        raise LookupError(requested_mark)
    return mark 
Example 30
Project: pytest   Author: pytest-dev   File: structures.py    License: MIT License 5 votes vote down vote up
def extract_from(
        cls,
        parameterset: Union["ParameterSet", Sequence[object], object],
        force_tuple: bool = False,
    ) -> "ParameterSet":
        """
        :param parameterset:
            a legacy style parameterset that may or may not be a tuple,
            and may or may not be wrapped into a mess of mark objects

        :param force_tuple:
            enforce tuple wrapping so single argument tuple values
            don't get decomposed and break tests
        """

        if isinstance(parameterset, cls):
            return parameterset
        if force_tuple:
            return cls.param(parameterset)
        else:
            # TODO: Refactor to fix this type-ignore. Currently the following
            # type-checks but crashes:
            #
            #   @pytest.mark.parametrize(('x', 'y'), [1, 2])
            #   def test_foo(x, y): pass
            return cls(parameterset, marks=[], id=None)  # type: ignore[arg-type] # noqa: F821