How to use path_matches_patterns method in Pytest

Best Python code snippet using pytest

python.py

Source:python.py Github

copy

Full Screen

...164def pytest_collect_file(path, parent):165 ext = path.ext166 if ext == ".py":167 if not parent.session.isinitpath(path):168 if not path_matches_patterns(169 path, parent.config.getini("python_files") + ["__init__.py"]170 ):171 return172 ihook = parent.session.gethookproxy(path)173 return ihook.pytest_pycollect_makemodule(path=path, parent=parent)174def path_matches_patterns(path, patterns):175 """Returns True if the given py.path.local matches one of the patterns in the list of globs given"""176 return any(path.fnmatch(pattern) for pattern in patterns)177def pytest_pycollect_makemodule(path, parent):178 if path.basename == "__init__.py":179 return Package(path, parent)180 return Module(path, parent)181@hookimpl(hookwrapper=True)182def pytest_pycollect_makeitem(collector, name, obj):183 outcome = yield184 res = outcome.get_result()185 if res is not None:186 return187 # nothing was collected elsewhere, let's do it here188 if safe_isclass(obj):189 if collector.istestclass(obj, name):190 outcome.force_result(Class(name, parent=collector))191 elif collector.istestfunction(obj, name):192 # mock seems to store unbound methods (issue473), normalize it193 obj = getattr(obj, "__func__", obj)194 # We need to try and unwrap the function if it's a functools.partial195 # or a funtools.wrapped.196 # We musn't if it's been wrapped with mock.patch (python 2 only)197 if not (isfunction(obj) or isfunction(get_real_func(obj))):198 filename, lineno = getfslineno(obj)199 warnings.warn_explicit(200 message=PytestCollectionWarning(201 "cannot collect %r because it is not a function." % name202 ),203 category=None,204 filename=str(filename),205 lineno=lineno + 1,206 )207 elif getattr(obj, "__test__", True):208 if is_generator(obj):209 res = Function(name, parent=collector)210 reason = deprecated.YIELD_TESTS.format(name=name)211 res.add_marker(MARK_GEN.xfail(run=False, reason=reason))212 res.warn(PytestCollectionWarning(reason))213 else:214 res = list(collector._genfunctions(name, obj))215 outcome.force_result(res)216def pytest_make_parametrize_id(config, val, argname=None):217 return None218class PyobjContext(object):219 module = pyobj_property("Module")220 cls = pyobj_property("Class")221 instance = pyobj_property("Instance")222class PyobjMixin(PyobjContext):223 _ALLOW_MARKERS = True224 def __init__(self, *k, **kw):225 super(PyobjMixin, self).__init__(*k, **kw)226 @property227 def obj(self):228 """Underlying Python object."""229 obj = getattr(self, "_obj", None)230 if obj is None:231 self._obj = obj = self._getobj()232 # XXX evil hack233 # used to avoid Instance collector marker duplication234 if self._ALLOW_MARKERS:235 self.own_markers.extend(get_unpacked_marks(self.obj))236 return obj237 @obj.setter238 def obj(self, value):239 self._obj = value240 def _getobj(self):241 """Gets the underlying Python object. May be overwritten by subclasses."""242 return getattr(self.parent.obj, self.name)243 def getmodpath(self, stopatmodule=True, includemodule=False):244 """ return python path relative to the containing module. """245 chain = self.listchain()246 chain.reverse()247 parts = []248 for node in chain:249 if isinstance(node, Instance):250 continue251 name = node.name252 if isinstance(node, Module):253 name = os.path.splitext(name)[0]254 if stopatmodule:255 if includemodule:256 parts.append(name)257 break258 parts.append(name)259 parts.reverse()260 s = ".".join(parts)261 return s.replace(".[", "[")262 def reportinfo(self):263 # XXX caching?264 obj = self.obj265 compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None)266 if isinstance(compat_co_firstlineno, int):267 # nose compatibility268 fspath = sys.modules[obj.__module__].__file__269 if fspath.endswith(".pyc"):270 fspath = fspath[:-1]271 lineno = compat_co_firstlineno272 else:273 fspath, lineno = getfslineno(obj)274 modpath = self.getmodpath()275 assert isinstance(lineno, int)276 return fspath, lineno, modpath277class PyCollector(PyobjMixin, nodes.Collector):278 def funcnamefilter(self, name):279 return self._matches_prefix_or_glob_option("python_functions", name)280 def isnosetest(self, obj):281 """ Look for the __test__ attribute, which is applied by the282 @nose.tools.istest decorator283 """284 # We explicitly check for "is True" here to not mistakenly treat285 # classes with a custom __getattr__ returning something truthy (like a286 # function) as test classes.287 return safe_getattr(obj, "__test__", False) is True288 def classnamefilter(self, name):289 return self._matches_prefix_or_glob_option("python_classes", name)290 def istestfunction(self, obj, name):291 if self.funcnamefilter(name) or self.isnosetest(obj):292 if isinstance(obj, staticmethod):293 # static methods need to be unwrapped294 obj = safe_getattr(obj, "__func__", False)295 return (296 safe_getattr(obj, "__call__", False)297 and fixtures.getfixturemarker(obj) is None298 )299 else:300 return False301 def istestclass(self, obj, name):302 return self.classnamefilter(name) or self.isnosetest(obj)303 def _matches_prefix_or_glob_option(self, option_name, name):304 """305 checks if the given name matches the prefix or glob-pattern defined306 in ini configuration.307 """308 for option in self.config.getini(option_name):309 if name.startswith(option):310 return True311 # check that name looks like a glob-string before calling fnmatch312 # because this is called for every name in each collected module,313 # and fnmatch is somewhat expensive to call314 elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(315 name, option316 ):317 return True318 return False319 def collect(self):320 if not getattr(self.obj, "__test__", True):321 return []322 # NB. we avoid random getattrs and peek in the __dict__ instead323 # (XXX originally introduced from a PyPy need, still true?)324 dicts = [getattr(self.obj, "__dict__", {})]325 for basecls in inspect.getmro(self.obj.__class__):326 dicts.append(basecls.__dict__)327 seen = {}328 values = []329 for dic in dicts:330 for name, obj in list(dic.items()):331 if name in seen:332 continue333 seen[name] = True334 res = self._makeitem(name, obj)335 if res is None:336 continue337 if not isinstance(res, list):338 res = [res]339 values.extend(res)340 values.sort(key=lambda item: item.reportinfo()[:2])341 return values342 def _makeitem(self, name, obj):343 # assert self.ihook.fspath == self.fspath, self344 return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj)345 def _genfunctions(self, name, funcobj):346 module = self.getparent(Module).obj347 clscol = self.getparent(Class)348 cls = clscol and clscol.obj or None349 fm = self.session._fixturemanager350 definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)351 fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)352 metafunc = Metafunc(353 definition, fixtureinfo, self.config, cls=cls, module=module354 )355 methods = []356 if hasattr(module, "pytest_generate_tests"):357 methods.append(module.pytest_generate_tests)358 if hasattr(cls, "pytest_generate_tests"):359 methods.append(cls().pytest_generate_tests)360 if methods:361 self.ihook.pytest_generate_tests.call_extra(362 methods, dict(metafunc=metafunc)363 )364 else:365 self.ihook.pytest_generate_tests(metafunc=metafunc)366 if not metafunc._calls:367 yield Function(name, parent=self, fixtureinfo=fixtureinfo)368 else:369 # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs370 fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)371 # add_funcarg_pseudo_fixture_def may have shadowed some fixtures372 # with direct parametrization, so make sure we update what the373 # function really needs.374 fixtureinfo.prune_dependency_tree()375 for callspec in metafunc._calls:376 subname = "%s[%s]" % (name, callspec.id)377 yield Function(378 name=subname,379 parent=self,380 callspec=callspec,381 callobj=funcobj,382 fixtureinfo=fixtureinfo,383 keywords={callspec.id: True},384 originalname=name,385 )386class Module(nodes.File, PyCollector):387 """ Collector for test classes and functions. """388 def _getobj(self):389 return self._importtestmodule()390 def collect(self):391 self._inject_setup_module_fixture()392 self._inject_setup_function_fixture()393 self.session._fixturemanager.parsefactories(self)394 return super(Module, self).collect()395 def _inject_setup_module_fixture(self):396 """Injects a hidden autouse, module scoped fixture into the collected module object397 that invokes setUpModule/tearDownModule if either or both are available.398 Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with399 other fixtures (#517).400 """401 setup_module = _get_non_fixture_func(self.obj, "setUpModule")402 if setup_module is None:403 setup_module = _get_non_fixture_func(self.obj, "setup_module")404 teardown_module = _get_non_fixture_func(self.obj, "tearDownModule")405 if teardown_module is None:406 teardown_module = _get_non_fixture_func(self.obj, "teardown_module")407 if setup_module is None and teardown_module is None:408 return409 @fixtures.fixture(autouse=True, scope="module")410 def xunit_setup_module_fixture(request):411 if setup_module is not None:412 _call_with_optional_argument(setup_module, request.module)413 yield414 if teardown_module is not None:415 _call_with_optional_argument(teardown_module, request.module)416 self.obj.__pytest_setup_module = xunit_setup_module_fixture417 def _inject_setup_function_fixture(self):418 """Injects a hidden autouse, function scoped fixture into the collected module object419 that invokes setup_function/teardown_function if either or both are available.420 Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with421 other fixtures (#517).422 """423 setup_function = _get_non_fixture_func(self.obj, "setup_function")424 teardown_function = _get_non_fixture_func(self.obj, "teardown_function")425 if setup_function is None and teardown_function is None:426 return427 @fixtures.fixture(autouse=True, scope="function")428 def xunit_setup_function_fixture(request):429 if request.instance is not None:430 # in this case we are bound to an instance, so we need to let431 # setup_method handle this432 yield433 return434 if setup_function is not None:435 _call_with_optional_argument(setup_function, request.function)436 yield437 if teardown_function is not None:438 _call_with_optional_argument(teardown_function, request.function)439 self.obj.__pytest_setup_function = xunit_setup_function_fixture440 def _importtestmodule(self):441 # we assume we are only called once per module442 importmode = self.config.getoption("--import-mode")443 try:444 mod = self.fspath.pyimport(ensuresyspath=importmode)445 except SyntaxError:446 raise self.CollectError(447 _pytest._code.ExceptionInfo.from_current().getrepr(style="short")448 )449 except self.fspath.ImportMismatchError:450 e = sys.exc_info()[1]451 raise self.CollectError(452 "import file mismatch:\n"453 "imported module %r has this __file__ attribute:\n"454 " %s\n"455 "which is not the same as the test file we want to collect:\n"456 " %s\n"457 "HINT: remove __pycache__ / .pyc files and/or use a "458 "unique basename for your test file modules" % e.args459 )460 except ImportError:461 from _pytest._code.code import ExceptionInfo462 exc_info = ExceptionInfo.from_current()463 if self.config.getoption("verbose") < 2:464 exc_info.traceback = exc_info.traceback.filter(filter_traceback)465 exc_repr = (466 exc_info.getrepr(style="short")467 if exc_info.traceback468 else exc_info.exconly()469 )470 formatted_tb = safe_str(exc_repr)471 raise self.CollectError(472 "ImportError while importing test module '{fspath}'.\n"473 "Hint: make sure your test modules/packages have valid Python names.\n"474 "Traceback:\n"475 "{traceback}".format(fspath=self.fspath, traceback=formatted_tb)476 )477 except _pytest.runner.Skipped as e:478 if e.allow_module_level:479 raise480 raise self.CollectError(481 "Using pytest.skip outside of a test is not allowed. "482 "To decorate a test function, use the @pytest.mark.skip "483 "or @pytest.mark.skipif decorators instead, and to skip a "484 "module use `pytestmark = pytest.mark.{skip,skipif}."485 )486 self.config.pluginmanager.consider_module(mod)487 return mod488class Package(Module):489 def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):490 session = parent.session491 nodes.FSCollector.__init__(492 self, fspath, parent=parent, config=config, session=session, nodeid=nodeid493 )494 self.name = fspath.dirname495 self.trace = session.trace496 self._norecursepatterns = session._norecursepatterns497 self.fspath = fspath498 def setup(self):499 # not using fixtures to call setup_module here because autouse fixtures500 # from packages are not called automatically (#4085)501 setup_module = _get_non_fixture_func(self.obj, "setUpModule")502 if setup_module is None:503 setup_module = _get_non_fixture_func(self.obj, "setup_module")504 if setup_module is not None:505 _call_with_optional_argument(setup_module, self.obj)506 teardown_module = _get_non_fixture_func(self.obj, "tearDownModule")507 if teardown_module is None:508 teardown_module = _get_non_fixture_func(self.obj, "teardown_module")509 if teardown_module is not None:510 func = partial(_call_with_optional_argument, teardown_module, self.obj)511 self.addfinalizer(func)512 def _recurse(self, dirpath):513 if dirpath.basename == "__pycache__":514 return False515 ihook = self.gethookproxy(dirpath.dirpath())516 if ihook.pytest_ignore_collect(path=dirpath, config=self.config):517 return518 for pat in self._norecursepatterns:519 if dirpath.check(fnmatch=pat):520 return False521 ihook = self.gethookproxy(dirpath)522 ihook.pytest_collect_directory(path=dirpath, parent=self)523 return True524 def gethookproxy(self, fspath):525 # check if we have the common case of running526 # hooks with all conftest.py filesall conftest.py527 pm = self.config.pluginmanager528 my_conftestmodules = pm._getconftestmodules(fspath)529 remove_mods = pm._conftest_plugins.difference(my_conftestmodules)530 if remove_mods:531 # one or more conftests are not in use at this fspath532 proxy = FSHookProxy(fspath, pm, remove_mods)533 else:534 # all plugis are active for this fspath535 proxy = self.config.hook536 return proxy537 def _collectfile(self, path, handle_dupes=True):538 assert path.isfile(), "%r is not a file (isdir=%r, exists=%r, islink=%r)" % (539 path,540 path.isdir(),541 path.exists(),542 path.islink(),543 )544 ihook = self.gethookproxy(path)545 if not self.isinitpath(path):546 if ihook.pytest_ignore_collect(path=path, config=self.config):547 return ()548 if handle_dupes:549 keepduplicates = self.config.getoption("keepduplicates")550 if not keepduplicates:551 duplicate_paths = self.config.pluginmanager._duplicatepaths552 if path in duplicate_paths:553 return ()554 else:555 duplicate_paths.add(path)556 if self.fspath == path: # __init__.py557 return [self]558 return ihook.pytest_collect_file(path=path, parent=self)559 def isinitpath(self, path):560 return path in self.session._initialpaths561 def collect(self):562 this_path = self.fspath.dirpath()563 init_module = this_path.join("__init__.py")564 if init_module.check(file=1) and path_matches_patterns(565 init_module, self.config.getini("python_files")566 ):567 yield Module(init_module, self)568 pkg_prefixes = set()569 for path in this_path.visit(rec=self._recurse, bf=True, sort=True):570 # We will visit our own __init__.py file, in which case we skip it.571 is_file = path.isfile()572 if is_file:573 if path.basename == "__init__.py" and path.dirpath() == this_path:574 continue575 parts_ = parts(path.strpath)576 if any(577 pkg_prefix in parts_ and pkg_prefix.join("__init__.py") != path578 for pkg_prefix in pkg_prefixes...

Full Screen

Full Screen

config.py

Source:config.py Github

copy

Full Screen

...157 # - Find all recursive link modifiers in paths under link_item and adjust their link_mode.158 if op_type.is_recursive():159 # Break up paths by simple operations:160 link_paths = link_item.glob("**/*")161 link_paths = filter(lambda p: not path_matches_patterns(p, link_config.ignore), link_paths)162 seen_prefixes: Set[str] = set()163 for link_path in link_paths:164 op_type_switch, src_path, dst_path = _determine_operation(165 link_config, link_item.parent, link_path,166 )167 if str(src_path) in seen_prefixes:168 continue169 if src_path.is_dir() and op_type == op_type_switch:170 continue171 seen_prefixes.add(str(src_path))172 topic_ops.append(LogicalSyncPlan(173 type=str(op_type_switch),174 src_path=src_path,175 dst_path=dst_path,...

Full Screen

Full Screen

replace-header.py

Source:replace-header.py Github

copy

Full Screen

...102 emit_notice(new_file, template, notice_lines)103 new_file.writelines(contents[line_number:])104 new_file.close()105 os.replace(new_filename, filename)106def path_matches_patterns(path, patterns):107 for pattern in patterns:108 if path.match(pattern):109 return True110 return False111def process_files(templates, files, notice_lines, args):112 for f in files:113 path = Path(f)114 if args.exclude is None or not path_matches_patterns(path, args.exclude):115 if path.is_dir():116 process_files(templates, path.iterdir(), notice_lines, args)117 elif args.include is None or path_matches_patterns(path, args.include):118 process_file(templates, f, notice, args.replace, args.copyright_regex)119parser = argparse.ArgumentParser()120parser.add_argument('files', help='Files (or directories) to replace', nargs='*')121parser.add_argument('--notice', help='File containing copyright notice', type=argparse.FileType('r'))122parser.add_argument('--copyright-regex', help='Regular expression matching a copyright line',123 default=DEFAULT_COPYRIGHT_REGEX)124parser.add_argument('--include', action='append', metavar='PATTERN', help='Include matching files (if not excluded)')125parser.add_argument('--exclude', action='append', metavar='PATTERN', help='Exclude matching files (even if included)')126parser.add_argument('--replace', action='store_true', help='Replace any existing copyright notice')127parser.add_argument('--dump', action='store_true', help='Dump the templates database')128templates = read_templates()129args = parser.parse_args()130if args.dump:131 dump_templates(templates, sys.stdout)...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

...16def coalesce(*args: T) -> T:17 for arg in args:18 if arg is not None:19 return arg20def path_matches_patterns(path: PosixPath, patterns: Iterable[str]) -> bool:21 for ignore_pattern in patterns:22 if path.match(ignore_pattern):23 return True...

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