How to use istestfunc method in Pytest

Best Python code snippet using pytest

structures.py

Source:structures.py Github

copy

Full Screen

...16 def warned(self):17 warnings.warn(warning, stacklevel=2)18 return getter(self)19 return property(getter if warning is None else warned, doc="alias for " + name)20def istestfunc(func):21 return (22 hasattr(func, "__call__")23 and getattr(func, "__name__", "<lambda>") != "<lambda>"24 )25def get_empty_parameterset_mark(config, argnames, func):26 from ..nodes import Collector27 requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)28 if requested_mark in ("", None, "skip"):29 mark = MARK_GEN.skip30 elif requested_mark == "xfail":31 mark = MARK_GEN.xfail(run=False)32 elif requested_mark == "fail_at_collect":33 f_name = func.__name__34 _, lineno = getfslineno(func)35 raise Collector.CollectError(36 "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)37 )38 else:39 raise LookupError(requested_mark)40 fs, lineno = getfslineno(func)41 reason = "got empty parameter set %r, function %s at %s:%d" % (42 argnames,43 func.__name__,44 fs,45 lineno,46 )47 return mark(reason=reason)48class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):49 @classmethod50 def param(cls, *values, **kwargs):51 marks = kwargs.pop("marks", ())52 if isinstance(marks, MarkDecorator):53 marks = (marks,)54 else:55 assert isinstance(marks, (tuple, list, set))56 id_ = kwargs.pop("id", None)57 if id_ is not None:58 if not isinstance(id_, six.string_types):59 raise TypeError(60 "Expected id to be a string, got {}: {!r}".format(type(id_), id_)61 )62 id_ = ascii_escaped(id_)63 if kwargs:64 warnings.warn(65 PYTEST_PARAM_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=366 )67 return cls(values, marks, id_)68 @classmethod69 def extract_from(cls, parameterset, force_tuple=False):70 """71 :param parameterset:72 a legacy style parameterset that may or may not be a tuple,73 and may or may not be wrapped into a mess of mark objects74 :param force_tuple:75 enforce tuple wrapping so single argument tuple values76 don't get decomposed and break tests77 """78 if isinstance(parameterset, cls):79 return parameterset80 if force_tuple:81 return cls.param(parameterset)82 else:83 return cls(parameterset, marks=[], id=None)84 @classmethod85 def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):86 if not isinstance(argnames, (tuple, list)):87 argnames = [x.strip() for x in argnames.split(",") if x.strip()]88 force_tuple = len(argnames) == 189 else:90 force_tuple = False91 parameters = [92 ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues93 ]94 del argvalues95 if parameters:96 # check all parameter sets have the correct number of values97 for param in parameters:98 if len(param.values) != len(argnames):99 msg = (100 '{nodeid}: in "parametrize" the number of names ({names_len}):\n'101 " {names}\n"102 "must be equal to the number of values ({values_len}):\n"103 " {values}"104 )105 fail(106 msg.format(107 nodeid=function_definition.nodeid,108 values=param.values,109 names=argnames,110 names_len=len(argnames),111 values_len=len(param.values),112 ),113 pytrace=False,114 )115 else:116 # empty parameter set (likely computed at runtime): create a single117 # parameter set with NOSET values, with the "empty parameter set" mark applied to it118 mark = get_empty_parameterset_mark(config, argnames, func)119 parameters.append(120 ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)121 )122 return argnames, parameters123@attr.s(frozen=True)124class Mark(object):125 #: name of the mark126 name = attr.ib(type=str)127 #: positional arguments of the mark decorator128 args = attr.ib() # List[object]129 #: keyword arguments of the mark decorator130 kwargs = attr.ib() # Dict[str, object]131 def combined_with(self, other):132 """133 :param other: the mark to combine with134 :type other: Mark135 :rtype: Mark136 combines by appending aargs and merging the mappings137 """138 assert self.name == other.name139 return Mark(140 self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)141 )142@attr.s143class MarkDecorator(object):144 """ A decorator for test functions and test classes. When applied145 it will create :class:`MarkInfo` objects which may be146 :ref:`retrieved by hooks as item keywords <excontrolskip>`.147 MarkDecorator instances are often created like this::148 mark1 = pytest.mark.NAME # simple MarkDecorator149 mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator150 and can then be applied as decorators to test functions::151 @mark2152 def test_function():153 pass154 When a MarkDecorator instance is called it does the following:155 1. If called with a single class as its only positional argument and no156 additional keyword arguments, it attaches itself to the class so it157 gets applied automatically to all test cases found in that class.158 2. If called with a single function as its only positional argument and159 no additional keyword arguments, it attaches a MarkInfo object to the160 function, containing all the arguments already stored internally in161 the MarkDecorator.162 3. When called in any other case, it performs a 'fake construction' call,163 i.e. it returns a new MarkDecorator instance with the original164 MarkDecorator's content updated with the arguments passed to this165 call.166 Note: The rules above prevent MarkDecorator objects from storing only a167 single function or class reference as their positional argument with no168 additional keyword or positional arguments.169 """170 mark = attr.ib(validator=attr.validators.instance_of(Mark))171 name = alias("mark.name")172 args = alias("mark.args")173 kwargs = alias("mark.kwargs")174 @property175 def markname(self):176 return self.name # for backward-compat (2.4.1 had this attr)177 def __eq__(self, other):178 return self.mark == other.mark if isinstance(other, MarkDecorator) else False179 def __repr__(self):180 return "<MarkDecorator %r>" % (self.mark,)181 def with_args(self, *args, **kwargs):182 """ return a MarkDecorator with extra arguments added183 unlike call this can be used even if the sole argument is a callable/class184 :return: MarkDecorator185 """186 mark = Mark(self.name, args, kwargs)187 return self.__class__(self.mark.combined_with(mark))188 def __call__(self, *args, **kwargs):189 """ if passed a single callable argument: decorate it with mark info.190 otherwise add *args/**kwargs in-place to mark information. """191 if args and not kwargs:192 func = args[0]193 is_class = inspect.isclass(func)194 if len(args) == 1 and (istestfunc(func) or is_class):195 store_mark(func, self.mark)196 return func197 return self.with_args(*args, **kwargs)198def get_unpacked_marks(obj):199 """200 obtain the unpacked marks that are stored on an object201 """202 mark_list = getattr(obj, "pytestmark", [])203 if not isinstance(mark_list, list):204 mark_list = [mark_list]205 return normalize_mark_list(mark_list)206def normalize_mark_list(mark_list):207 """208 normalizes marker decorating helpers to mark objects...

Full Screen

Full Screen

mark.py

Source:mark.py Github

copy

Full Screen

...157 x = beginning[0].split("(", 1)[0]158 l.add(x)159 if name not in self._markers:160 raise AttributeError("%r not a registered marker" % (name,))161def istestfunc(func):162 return hasattr(func, "__call__") and \163 getattr(func, "__name__", "<lambda>") != "<lambda>"164class MarkDecorator:165 """ A decorator for test functions and test classes. When applied166 it will create :class:`MarkInfo` objects which may be167 :ref:`retrieved by hooks as item keywords <excontrolskip>`.168 MarkDecorator instances are often created like this::169 mark1 = pytest.mark.NAME # simple MarkDecorator170 mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator171 and can then be applied as decorators to test functions::172 @mark2173 def test_function():174 pass175 When a MarkDecorator instance is called it does the following:176 1. If called with a single class as its only positional argument and no177 additional keyword arguments, it attaches itself to the class so it178 gets applied automatically to all test cases found in that class.179 2. If called with a single function as its only positional argument and180 no additional keyword arguments, it attaches a MarkInfo object to the181 function, containing all the arguments already stored internally in182 the MarkDecorator.183 3. When called in any other case, it performs a 'fake construction' call,184 i.e. it returns a new MarkDecorator instance with the original185 MarkDecorator's content updated with the arguments passed to this186 call.187 Note: The rules above prevent MarkDecorator objects from storing only a188 single function or class reference as their positional argument with no189 additional keyword or positional arguments.190 """191 def __init__(self, name, args=None, kwargs=None):192 self.name = name193 self.args = args or ()194 self.kwargs = kwargs or {}195 @property196 def markname(self):197 return self.name # for backward-compat (2.4.1 had this attr)198 def __repr__(self):199 d = self.__dict__.copy()200 name = d.pop('name')201 return "<MarkDecorator %r %r>" % (name, d)202 def __call__(self, *args, **kwargs):203 """ if passed a single callable argument: decorate it with mark info.204 otherwise add *args/**kwargs in-place to mark information. """205 if args and not kwargs:206 func = args[0]207 is_class = inspect.isclass(func)208 if len(args) == 1 and (istestfunc(func) or is_class):209 if is_class:210 if hasattr(func, 'pytestmark'):211 mark_list = func.pytestmark212 if not isinstance(mark_list, list):213 mark_list = [mark_list]214 # always work on a copy to avoid updating pytestmark215 # from a superclass by accident216 mark_list = mark_list + [self]217 func.pytestmark = mark_list218 else:219 func.pytestmark = [self]220 else:221 holder = getattr(func, self.name, None)222 if holder is None:...

Full Screen

Full Screen

app_pytest.py

Source:app_pytest.py Github

copy

Full Screen

...17 if name[0] == "_":18 raise AttributeError("Marker name must NOT start with underscore")19 return MarkDecorator(name)20mark = MarkGenerator()21def istestfunc(func):22 return hasattr(func, "__call__") and \23 getattr(func, "__name__", "<lambda>") != "<lambda>"24class MarkDecorator:25 """ A decorator for test functions and test classes. When applied26 it will create :class:`MarkInfo` objects which may be27 :ref:`retrieved by hooks as item keywords <excontrolskip>`.28 MarkDecorator instances are often created like this::29 mark1 = pytest.mark.NAME # simple MarkDecorator30 mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator31 and can then be applied as decorators to test functions::32 @mark233 def test_function():34 pass35 When a MarkDecorator instance is called it does the following:36 1. If called with a single class as its only positional argument and no37 additional keyword arguments, it attaches itself to the class so it38 gets applied automatically to all test cases found in that class.39 2. If called with a single function as its only positional argument and40 no additional keyword arguments, it attaches a MarkInfo object to the41 function, containing all the arguments already stored internally in42 the MarkDecorator.43 3. When called in any other case, it performs a 'fake construction' call,44 i.e. it returns a new MarkDecorator instance with the original45 MarkDecorator's content updated with the arguments passed to this46 call.47 Note: The rules above prevent MarkDecorator objects from storing only a48 single function or class reference as their positional argument with no49 additional keyword or positional arguments.50 """51 def __init__(self, name, args=None, kwargs=None):52 self.name = name53 self.args = args or ()54 self.kwargs = kwargs or {}55 def __repr__(self):56 d = self.__dict__.copy()57 name = d.pop('name')58 return "<MarkDecorator %r %r>" % (name, d)59 def __call__(self, *args, **kwargs):60 """ if passed a single callable argument: decorate it with mark info.61 otherwise add *args/**kwargs in-place to mark information. """62 if args and not kwargs:63 func = args[0]64 if len(args) == 1 and istestfunc(func):65 holder = getattr(func, self.name, None)66 if holder is None:67 holder = MarkInfo(68 self.name, self.args, self.kwargs69 )70 setattr(func, self.name, holder)71 else:72 holder.add(self.args, self.kwargs)73 return func74 kw = self.kwargs.copy()75 kw.update(kwargs)76 args = self.args + args77 return self.__class__(self.name, args=args, kwargs=kw)78class MarkInfo:...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful