1""" core implementation of testing process: init, session, runtest loop. """ 2from __future__ import absolute_import, division, print_function 3 4import functools 5import os 6import six 7import sys 8 9import _pytest 10from _pytest import nodes 11import _pytest._code 12import py 13try: 14 from collections import MutableMapping as MappingMixin 15except ImportError: 16 from UserDict import DictMixin as MappingMixin 17 18from _pytest.config import directory_arg, UsageError, hookimpl 19from _pytest.outcomes import exit 20from _pytest.runner import collect_one_node 21 22tracebackcutdir = py.path.local(_pytest.__file__).dirpath() 23 24# exitcodes for the command line 25EXIT_OK = 0 26EXIT_TESTSFAILED = 1 27EXIT_INTERRUPTED = 2 28EXIT_INTERNALERROR = 3 29EXIT_USAGEERROR = 4 30EXIT_NOTESTSCOLLECTED = 5 31 32 33def pytest_addoption(parser): 34 parser.addini("norecursedirs", "directory patterns to avoid for recursion", 35 type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv']) 36 parser.addini("testpaths", "directories to search for tests when no files or directories are given in the " 37 "command line.", 38 type="args", default=[]) 39 # parser.addini("dirpatterns", 40 # "patterns specifying possible locations of test files", 41 # type="linelist", default=["**/test_*.txt", 42 # "**/test_*.py", "**/*_test.py"] 43 # ) 44 group = parser.getgroup("general", "running and selection options") 45 group._addoption('-x', '--exitfirst', action="store_const", 46 dest="maxfail", const=1, 47 help="exit instantly on first error or failed test."), 48 group._addoption('--maxfail', metavar="num", 49 action="store", type=int, dest="maxfail", default=0, 50 help="exit after first num failures or errors.") 51 group._addoption('--strict', action="store_true", 52 help="marks not registered in configuration file raise errors.") 53 group._addoption("-c", metavar="file", type=str, dest="inifilename", 54 help="load configuration from `file` instead of trying to locate one of the implicit " 55 "configuration files.") 56 group._addoption("--continue-on-collection-errors", action="store_true", 57 default=False, dest="continue_on_collection_errors", 58 help="Force test execution even if collection errors occur.") 59 60 group = parser.getgroup("collect", "collection") 61 group.addoption('--collectonly', '--collect-only', action="store_true", 62 help="only collect tests, don't execute them."), 63 group.addoption('--pyargs', action="store_true", 64 help="try to interpret all arguments as python packages.") 65 group.addoption("--ignore", action="append", metavar="path", 66 help="ignore path during collection (multi-allowed).") 67 # when changing this to --conf-cut-dir, config.py Conftest.setinitial 68 # needs upgrading as well 69 group.addoption('--confcutdir', dest="confcutdir", default=None, 70 metavar="dir", type=functools.partial(directory_arg, optname="--confcutdir"), 71 help="only load conftest.py's relative to specified dir.") 72 group.addoption('--noconftest', action="store_true", 73 dest="noconftest", default=False, 74 help="Don't load any conftest.py files.") 75 group.addoption('--keepduplicates', '--keep-duplicates', action="store_true", 76 dest="keepduplicates", default=False, 77 help="Keep duplicate tests.") 78 group.addoption('--collect-in-virtualenv', action='store_true', 79 dest='collect_in_virtualenv', default=False, 80 help="Don't ignore tests in a local virtualenv directory") 81 82 group = parser.getgroup("debugconfig", 83 "test session debugging and configuration") 84 group.addoption('--basetemp', dest="basetemp", default=None, metavar="dir", 85 help="base temporary directory for this test run.") 86 87 88def pytest_configure(config): 89 __import__('pytest').config = config # compatibiltiy 90 91 92def wrap_session(config, doit): 93 """Skeleton command line program""" 94 session = Session(config) 95 session.exitstatus = EXIT_OK 96 initstate = 0 97 try: 98 try: 99 config._do_configure() 100 initstate = 1 101 config.hook.pytest_sessionstart(session=session) 102 initstate = 2 103 session.exitstatus = doit(config, session) or 0 104 except UsageError: 105 raise 106 except Failed: 107 session.exitstatus = EXIT_TESTSFAILED 108 except KeyboardInterrupt: 109 excinfo = _pytest._code.ExceptionInfo() 110 if initstate < 2 and isinstance(excinfo.value, exit.Exception): 111 sys.stderr.write('{0}: {1}\n'.format( 112 excinfo.typename, excinfo.value.msg)) 113 config.hook.pytest_keyboard_interrupt(excinfo=excinfo) 114 session.exitstatus = EXIT_INTERRUPTED 115 except: # noqa 116 excinfo = _pytest._code.ExceptionInfo() 117 config.notify_exception(excinfo, config.option) 118 session.exitstatus = EXIT_INTERNALERROR 119 if excinfo.errisinstance(SystemExit): 120 sys.stderr.write("mainloop: caught Spurious SystemExit!\n") 121 122 finally: 123 excinfo = None # Explicitly break reference cycle. 124 session.startdir.chdir() 125 if initstate >= 2: 126 config.hook.pytest_sessionfinish( 127 session=session, 128 exitstatus=session.exitstatus) 129 config._ensure_unconfigure() 130 return session.exitstatus 131 132 133def pytest_cmdline_main(config): 134 return wrap_session(config, _main) 135 136 137def _main(config, session): 138 """ default command line protocol for initialization, session, 139 running tests and reporting. """ 140 config.hook.pytest_collection(session=session) 141 config.hook.pytest_runtestloop(session=session) 142 143 if session.testsfailed: 144 return EXIT_TESTSFAILED 145 elif session.testscollected == 0: 146 return EXIT_NOTESTSCOLLECTED 147 148 149def pytest_collection(session): 150 return session.perform_collect() 151 152 153def pytest_runtestloop(session): 154 if (session.testsfailed and 155 not session.config.option.continue_on_collection_errors): 156 raise session.Interrupted( 157 "%d errors during collection" % session.testsfailed) 158 159 if session.config.option.collectonly: 160 return True 161 162 for i, item in enumerate(session.items): 163 nextitem = session.items[i + 1] if i + 1 < len(session.items) else None 164 item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) 165 if session.shouldfail: 166 raise session.Failed(session.shouldfail) 167 if session.shouldstop: 168 raise session.Interrupted(session.shouldstop) 169 return True 170 171 172def _in_venv(path): 173 """Attempts to detect if ``path`` is the root of a Virtual Environment by 174 checking for the existence of the appropriate activate script""" 175 bindir = path.join('Scripts' if sys.platform.startswith('win') else 'bin') 176 if not bindir.exists(): 177 return False 178 activates = ('activate', 'activate.csh', 'activate.fish', 179 'Activate', 'Activate.bat', 'Activate.ps1') 180 return any([fname.basename in activates for fname in bindir.listdir()]) 181 182 183def pytest_ignore_collect(path, config): 184 ignore_paths = config._getconftest_pathlist("collect_ignore", path=path.dirpath()) 185 ignore_paths = ignore_paths or [] 186 excludeopt = config.getoption("ignore") 187 if excludeopt: 188 ignore_paths.extend([py.path.local(x) for x in excludeopt]) 189 190 if py.path.local(path) in ignore_paths: 191 return True 192 193 allow_in_venv = config.getoption("collect_in_virtualenv") 194 if _in_venv(path) and not allow_in_venv: 195 return True 196 197 # Skip duplicate paths. 198 keepduplicates = config.getoption("keepduplicates") 199 duplicate_paths = config.pluginmanager._duplicatepaths 200 if not keepduplicates: 201 if path in duplicate_paths: 202 return True 203 else: 204 duplicate_paths.add(path) 205 206 return False 207 208 209class FSHookProxy: 210 def __init__(self, fspath, pm, remove_mods): 211 self.fspath = fspath 212 self.pm = pm 213 self.remove_mods = remove_mods 214 215 def __getattr__(self, name): 216 x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods) 217 self.__dict__[name] = x 218 return x 219 220 221class _CompatProperty(object): 222 def __init__(self, name): 223 self.name = name 224 225 def __get__(self, obj, owner): 226 if obj is None: 227 return self 228 229 # TODO: reenable in the features branch 230 # warnings.warn( 231 # "usage of {owner!r}.{name} is deprecated, please use pytest.{name} instead".format( 232 # name=self.name, owner=type(owner).__name__), 233 # PendingDeprecationWarning, stacklevel=2) 234 return getattr(__import__('pytest'), self.name) 235 236 237class NodeKeywords(MappingMixin): 238 def __init__(self, node): 239 self.node = node 240 self.parent = node.parent 241 self._markers = {node.name: True} 242 243 def __getitem__(self, key): 244 try: 245 return self._markers[key] 246 except KeyError: 247 if self.parent is None: 248 raise 249 return self.parent.keywords[key] 250 251 def __setitem__(self, key, value): 252 self._markers[key] = value 253 254 def __delitem__(self, key): 255 raise ValueError("cannot delete key in keywords dict") 256 257 def __iter__(self): 258 seen = set(self._markers) 259 if self.parent is not None: 260 seen.update(self.parent.keywords) 261 return iter(seen) 262 263 def __len__(self): 264 return len(self.__iter__()) 265 266 def keys(self): 267 return list(self) 268 269 def __repr__(self): 270 return "<NodeKeywords for node %s>" % (self.node, ) 271 272 273class Node(object): 274 """ base class for Collector and Item the test collection tree. 275 Collector subclasses have children, Items are terminal nodes.""" 276 277 def __init__(self, name, parent=None, config=None, session=None): 278 #: a unique name within the scope of the parent node 279 self.name = name 280 281 #: the parent collector node. 282 self.parent = parent 283 284 #: the pytest config object 285 self.config = config or parent.config 286 287 #: the session this node is part of 288 self.session = session or parent.session 289 290 #: filesystem path where this node was collected from (can be None) 291 self.fspath = getattr(parent, 'fspath', None) 292 293 #: keywords/markers collected from all scopes 294 self.keywords = NodeKeywords(self) 295 296 #: allow adding of extra keywords to use for matching 297 self.extra_keyword_matches = set() 298 299 # used for storing artificial fixturedefs for direct parametrization 300 self._name2pseudofixturedef = {} 301 302 @property 303 def ihook(self): 304 """ fspath sensitive hook proxy used to call pytest hooks""" 305 return self.session.gethookproxy(self.fspath) 306 307 Module = _CompatProperty("Module") 308 Class = _CompatProperty("Class") 309 Instance = _CompatProperty("Instance") 310 Function = _CompatProperty("Function") 311 File = _CompatProperty("File") 312 Item = _CompatProperty("Item") 313 314 def _getcustomclass(self, name): 315 maybe_compatprop = getattr(type(self), name) 316 if isinstance(maybe_compatprop, _CompatProperty): 317 return getattr(__import__('pytest'), name) 318 else: 319 cls = getattr(self, name) 320 # TODO: reenable in the features branch 321 # warnings.warn("use of node.%s is deprecated, " 322 # "use pytest_pycollect_makeitem(...) to create custom " 323 # "collection nodes" % name, category=DeprecationWarning) 324 return cls 325 326 def __repr__(self): 327 return "<%s %r>" % (self.__class__.__name__, 328 getattr(self, 'name', None)) 329 330 def warn(self, code, message): 331 """ generate a warning with the given code and message for this 332 item. """ 333 assert isinstance(code, str) 334 fslocation = getattr(self, "location", None) 335 if fslocation is None: 336 fslocation = getattr(self, "fspath", None) 337 self.ihook.pytest_logwarning.call_historic(kwargs=dict( 338 code=code, message=message, 339 nodeid=self.nodeid, fslocation=fslocation)) 340 341 # methods for ordering nodes 342 @property 343 def nodeid(self): 344 """ a ::-separated string denoting its collection tree address. """ 345 try: 346 return self._nodeid 347 except AttributeError: 348 self._nodeid = x = self._makeid() 349 return x 350 351 def _makeid(self): 352 return self.parent.nodeid + "::" + self.name 353 354 def __hash__(self): 355 return hash(self.nodeid) 356 357 def setup(self): 358 pass 359 360 def teardown(self): 361 pass 362 363 def listchain(self): 364 """ return list of all parent collectors up to self, 365 starting from root of collection tree. """ 366 chain = [] 367 item = self 368 while item is not None: 369 chain.append(item) 370 item = item.parent 371 chain.reverse() 372 return chain 373 374 def add_marker(self, marker): 375 """ dynamically add a marker object to the node. 376 377 ``marker`` can be a string or pytest.mark.* instance. 378 """ 379 from _pytest.mark import MarkDecorator, MARK_GEN 380 if isinstance(marker, six.string_types): 381 marker = getattr(MARK_GEN, marker) 382 elif not isinstance(marker, MarkDecorator): 383 raise ValueError("is not a string or pytest.mark.* Marker") 384 self.keywords[marker.name] = marker 385 386 def get_marker(self, name): 387 """ get a marker object from this node or None if 388 the node doesn't have a marker with that name. """ 389 val = self.keywords.get(name, None) 390 if val is not None: 391 from _pytest.mark import MarkInfo, MarkDecorator 392 if isinstance(val, (MarkDecorator, MarkInfo)): 393 return val 394 395 def listextrakeywords(self): 396 """ Return a set of all extra keywords in self and any parents.""" 397 extra_keywords = set() 398 item = self 399 for item in self.listchain(): 400 extra_keywords.update(item.extra_keyword_matches) 401 return extra_keywords 402 403 def listnames(self): 404 return [x.name for x in self.listchain()] 405 406 def addfinalizer(self, fin): 407 """ register a function to be called when this node is finalized. 408 409 This method can only be called when this node is active 410 in a setup chain, for example during self.setup(). 411 """ 412 self.session._setupstate.addfinalizer(fin, self) 413 414 def getparent(self, cls): 415 """ get the next parent node (including ourself) 416 which is an instance of the given class""" 417 current = self 418 while current and not isinstance(current, cls): 419 current = current.parent 420 return current 421 422 def _prunetraceback(self, excinfo): 423 pass 424 425 def _repr_failure_py(self, excinfo, style=None): 426 fm = self.session._fixturemanager 427 if excinfo.errisinstance(fm.FixtureLookupError): 428 return excinfo.value.formatrepr() 429 tbfilter = True 430 if self.config.option.fulltrace: 431 style = "long" 432 else: 433 tb = _pytest._code.Traceback([excinfo.traceback[-1]]) 434 self._prunetraceback(excinfo) 435 if len(excinfo.traceback) == 0: 436 excinfo.traceback = tb 437 tbfilter = False # prunetraceback already does it 438 if style == "auto": 439 style = "long" 440 # XXX should excinfo.getrepr record all data and toterminal() process it? 441 if style is None: 442 if self.config.option.tbstyle == "short": 443 style = "short" 444 else: 445 style = "long" 446 447 try: 448 os.getcwd() 449 abspath = False 450 except OSError: 451 abspath = True 452 453 return excinfo.getrepr(funcargs=True, abspath=abspath, 454 showlocals=self.config.option.showlocals, 455 style=style, tbfilter=tbfilter) 456 457 repr_failure = _repr_failure_py 458 459 460class Collector(Node): 461 """ Collector instances create children through collect() 462 and thus iteratively build a tree. 463 """ 464 465 class CollectError(Exception): 466 """ an error during collection, contains a custom message. """ 467 468 def collect(self): 469 """ returns a list of children (items and collectors) 470 for this collection node. 471 """ 472 raise NotImplementedError("abstract") 473 474 def repr_failure(self, excinfo): 475 """ represent a collection failure. """ 476 if excinfo.errisinstance(self.CollectError): 477 exc = excinfo.value 478 return str(exc.args[0]) 479 return self._repr_failure_py(excinfo, style="short") 480 481 def _prunetraceback(self, excinfo): 482 if hasattr(self, 'fspath'): 483 traceback = excinfo.traceback 484 ntraceback = traceback.cut(path=self.fspath) 485 if ntraceback == traceback: 486 ntraceback = ntraceback.cut(excludepath=tracebackcutdir) 487 excinfo.traceback = ntraceback.filter() 488 489 490class FSCollector(Collector): 491 def __init__(self, fspath, parent=None, config=None, session=None): 492 fspath = py.path.local(fspath) # xxx only for test_resultlog.py? 493 name = fspath.basename 494 if parent is not None: 495 rel = fspath.relto(parent.fspath) 496 if rel: 497 name = rel 498 name = name.replace(os.sep, nodes.SEP) 499 super(FSCollector, self).__init__(name, parent, config, session) 500 self.fspath = fspath 501 502 def _check_initialpaths_for_relpath(self): 503 for initialpath in self.session._initialpaths: 504 if self.fspath.common(initialpath) == initialpath: 505 return self.fspath.relto(initialpath.dirname) 506 507 def _makeid(self): 508 relpath = self.fspath.relto(self.config.rootdir) 509 510 if not relpath: 511 relpath = self._check_initialpaths_for_relpath() 512 if os.sep != nodes.SEP: 513 relpath = relpath.replace(os.sep, nodes.SEP) 514 return relpath 515 516 517class File(FSCollector): 518 """ base class for collecting tests from a file. """ 519 520 521class Item(Node): 522 """ a basic test invocation item. Note that for a single function 523 there might be multiple test invocation items. 524 """ 525 nextitem = None 526 527 def __init__(self, name, parent=None, config=None, session=None): 528 super(Item, self).__init__(name, parent, config, session) 529 self._report_sections = [] 530 531 def add_report_section(self, when, key, content): 532 """ 533 Adds a new report section, similar to what's done internally to add stdout and 534 stderr captured output:: 535 536 item.add_report_section("call", "stdout", "report section contents") 537 538 :param str when: 539 One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``. 540 :param str key: 541 Name of the section, can be customized at will. Pytest uses ``"stdout"`` and 542 ``"stderr"`` internally. 543 544 :param str content: 545 The full contents as a string. 546 """ 547 if content: 548 self._report_sections.append((when, key, content)) 549 550 def reportinfo(self): 551 return self.fspath, None, "" 552 553 @property 554 def location(self): 555 try: 556 return self._location 557 except AttributeError: 558 location = self.reportinfo() 559 # bestrelpath is a quite slow function 560 cache = self.config.__dict__.setdefault("_bestrelpathcache", {}) 561 try: 562 fspath = cache[location[0]] 563 except KeyError: 564 fspath = self.session.fspath.bestrelpath(location[0]) 565 cache[location[0]] = fspath 566 location = (fspath, location[1], str(location[2])) 567 self._location = location 568 return location 569 570 571class NoMatch(Exception): 572 """ raised if matching cannot locate a matching names. """ 573 574 575class Interrupted(KeyboardInterrupt): 576 """ signals an interrupted test run. """ 577 __module__ = 'builtins' # for py3 578 579 580class Failed(Exception): 581 """ signals an stop as failed test run. """ 582 583 584class Session(FSCollector): 585 Interrupted = Interrupted 586 Failed = Failed 587 588 def __init__(self, config): 589 FSCollector.__init__(self, config.rootdir, parent=None, 590 config=config, session=self) 591 self.testsfailed = 0 592 self.testscollected = 0 593 self.shouldstop = False 594 self.shouldfail = False 595 self.trace = config.trace.root.get("collection") 596 self._norecursepatterns = config.getini("norecursedirs") 597 self.startdir = py.path.local() 598 self.config.pluginmanager.register(self, name="session") 599 600 def _makeid(self): 601 return "" 602 603 @hookimpl(tryfirst=True) 604 def pytest_collectstart(self): 605 if self.shouldfail: 606 raise self.Failed(self.shouldfail) 607 if self.shouldstop: 608 raise self.Interrupted(self.shouldstop) 609 610 @hookimpl(tryfirst=True) 611 def pytest_runtest_logreport(self, report): 612 if report.failed and not hasattr(report, 'wasxfail'): 613 self.testsfailed += 1 614 maxfail = self.config.getvalue("maxfail") 615 if maxfail and self.testsfailed >= maxfail: 616 self.shouldfail = "stopping after %d failures" % ( 617 self.testsfailed) 618 pytest_collectreport = pytest_runtest_logreport 619 620 def isinitpath(self, path): 621 return path in self._initialpaths 622 623 def gethookproxy(self, fspath): 624 # check if we have the common case of running 625 # hooks with all conftest.py filesall conftest.py 626 pm = self.config.pluginmanager 627 my_conftestmodules = pm._getconftestmodules(fspath) 628 remove_mods = pm._conftest_plugins.difference(my_conftestmodules) 629 if remove_mods: 630 # one or more conftests are not in use at this fspath 631 proxy = FSHookProxy(fspath, pm, remove_mods) 632 else: 633 # all plugis are active for this fspath 634 proxy = self.config.hook 635 return proxy 636 637 def perform_collect(self, args=None, genitems=True): 638 hook = self.config.hook 639 try: 640 items = self._perform_collect(args, genitems) 641 self.config.pluginmanager.check_pending() 642 hook.pytest_collection_modifyitems(session=self, 643 config=self.config, items=items) 644 finally: 645 hook.pytest_collection_finish(session=self) 646 self.testscollected = len(items) 647 return items 648 649 def _perform_collect(self, args, genitems): 650 if args is None: 651 args = self.config.args 652 self.trace("perform_collect", self, args) 653 self.trace.root.indent += 1 654 self._notfound = [] 655 self._initialpaths = set() 656 self._initialparts = [] 657 self.items = items = [] 658 for arg in args: 659 parts = self._parsearg(arg) 660 self._initialparts.append(parts) 661 self._initialpaths.add(parts[0]) 662 rep = collect_one_node(self) 663 self.ihook.pytest_collectreport(report=rep) 664 self.trace.root.indent -= 1 665 if self._notfound: 666 errors = [] 667 for arg, exc in self._notfound: 668 line = "(no name %r in any of %r)" % (arg, exc.args[0]) 669 errors.append("not found: %s\n%s" % (arg, line)) 670 # XXX: test this 671 raise UsageError(*errors) 672 if not genitems: 673 return rep.result 674 else: 675 if rep.passed: 676 for node in rep.result: 677 self.items.extend(self.genitems(node)) 678 return items 679 680 def collect(self): 681 for parts in self._initialparts: 682 arg = "::".join(map(str, parts)) 683 self.trace("processing argument", arg) 684 self.trace.root.indent += 1 685 try: 686 for x in self._collect(arg): 687 yield x 688 except NoMatch: 689 # we are inside a make_report hook so 690 # we cannot directly pass through the exception 691 self._notfound.append((arg, sys.exc_info()[1])) 692 693 self.trace.root.indent -= 1 694 695 def _collect(self, arg): 696 names = self._parsearg(arg) 697 path = names.pop(0) 698 if path.check(dir=1): 699 assert not names, "invalid arg %r" % (arg,) 700 for path in path.visit(fil=lambda x: x.check(file=1), 701 rec=self._recurse, bf=True, sort=True): 702 for x in self._collectfile(path): 703 yield x 704 else: 705 assert path.check(file=1) 706 for x in self.matchnodes(self._collectfile(path), names): 707 yield x 708 709 def _collectfile(self, path): 710 ihook = self.gethookproxy(path) 711 if not self.isinitpath(path): 712 if ihook.pytest_ignore_collect(path=path, config=self.config): 713 return () 714 return ihook.pytest_collect_file(path=path, parent=self) 715 716 def _recurse(self, path): 717 ihook = self.gethookproxy(path.dirpath()) 718 if ihook.pytest_ignore_collect(path=path, config=self.config): 719 return 720 for pat in self._norecursepatterns: 721 if path.check(fnmatch=pat): 722 return False 723 ihook = self.gethookproxy(path) 724 ihook.pytest_collect_directory(path=path, parent=self) 725 return True 726 727 def _tryconvertpyarg(self, x): 728 """Convert a dotted module name to path. 729 730 """ 731 import pkgutil 732 try: 733 loader = pkgutil.find_loader(x) 734 except ImportError: 735 return x 736 if loader is None: 737 return x 738 # This method is sometimes invoked when AssertionRewritingHook, which 739 # does not define a get_filename method, is already in place: 740 try: 741 path = loader.get_filename(x) 742 except AttributeError: 743 # Retrieve path from AssertionRewritingHook: 744 path = loader.modules[x][0].co_filename 745 if loader.is_package(x): 746 path = os.path.dirname(path) 747 return path 748 749 def _parsearg(self, arg): 750 """ return (fspath, names) tuple after checking the file exists. """ 751 parts = str(arg).split("::") 752 if self.config.option.pyargs: 753 parts[0] = self._tryconvertpyarg(parts[0]) 754 relpath = parts[0].replace("/", os.sep) 755 path = self.config.invocation_dir.join(relpath, abs=True) 756 if not path.check(): 757 if self.config.option.pyargs: 758 raise UsageError( 759 "file or package not found: " + arg + 760 " (missing __init__.py?)") 761 else: 762 raise UsageError("file not found: " + arg) 763 parts[0] = path 764 return parts 765 766 def matchnodes(self, matching, names): 767 self.trace("matchnodes", matching, names) 768 self.trace.root.indent += 1 769 nodes = self._matchnodes(matching, names) 770 num = len(nodes) 771 self.trace("matchnodes finished -> ", num, "nodes") 772 self.trace.root.indent -= 1 773 if num == 0: 774 raise NoMatch(matching, names[:1]) 775 return nodes 776 777 def _matchnodes(self, matching, names): 778 if not matching or not names: 779 return matching 780 name = names[0] 781 assert name 782 nextnames = names[1:] 783 resultnodes = [] 784 for node in matching: 785 if isinstance(node, Item): 786 if not names: 787 resultnodes.append(node) 788 continue 789 assert isinstance(node, Collector) 790 rep = collect_one_node(node) 791 if rep.passed: 792 has_matched = False 793 for x in rep.result: 794 # TODO: remove parametrized workaround once collection structure contains parametrization 795 if x.name == name or x.name.split("[")[0] == name: 796 resultnodes.extend(self.matchnodes([x], nextnames)) 797 has_matched = True 798 # XXX accept IDs that don't have "()" for class instances 799 if not has_matched and len(rep.result) == 1 and x.name == "()": 800 nextnames.insert(0, name) 801 resultnodes.extend(self.matchnodes([x], nextnames)) 802 else: 803 # report collection failures here to avoid failing to run some test 804 # specified in the command line because the module could not be 805 # imported (#134) 806 node.ihook.pytest_collectreport(report=rep) 807 return resultnodes 808 809 def genitems(self, node): 810 self.trace("genitems", node) 811 if isinstance(node, Item): 812 node.ihook.pytest_itemcollected(item=node) 813 yield node 814 else: 815 assert isinstance(node, Collector) 816 rep = collect_one_node(node) 817 if rep.passed: 818 for subnode in rep.result: 819 for x in self.genitems(subnode): 820 yield x 821 node.ihook.pytest_collectreport(report=rep) 822