def test_test_address(self): # test addresses are specified as # package.module:class.method # /path/to/file.py:class.method # converted into 3-tuples (file, module, callable) # all terms optional test_address = util.test_address absfile = util.absfile class Foo: def bar(self): pass def baz(): pass f = Foo() class FooTC(unittest.TestCase): def test_one(self): pass def test_two(self): pass class CustomTestType(type): pass class CustomTC(unittest.TestCase): __metaclass__ = CustomTestType def test_one(self): pass def test_two(self): pass foo_funct = case.FunctionTestCase(baz) foo_functu = unittest.FunctionTestCase(baz) foo_mtc = case.MethodTestCase(Foo.bar) me = util.src(absfile(__file__)) self.assertEqual(test_address(baz), (me, __name__, 'baz')) assert test_address(Foo) == (me, __name__, 'Foo') assert test_address(Foo.bar) == (me, __name__, 'Foo.bar') assert test_address(f) == (me, __name__, 'Foo') assert test_address(f.bar) == (me, __name__, 'Foo.bar') assert test_address(nose) == (util.src(absfile(nose.__file__)), 'nose', None) # test passing the actual test callable, as the # missed test plugin must do self.assertEqual(test_address(FooTC('test_one')), (me, __name__, 'FooTC.test_one')) self.assertEqual(test_address(CustomTC('test_one')), (me, __name__, 'CustomTC.test_one')) self.assertEqual(test_address(foo_funct), (me, __name__, 'baz')) self.assertEqual(test_address(foo_functu), (me, __name__, 'baz')) self.assertEqual(test_address(foo_mtc), (me, __name__, 'Foo.bar'))
def test_test_address(self): # test addresses are specified as # package.module:class.method # /path/to/file.py:class.method # converted into 3-tuples (file, module, callable) # all terms optional test_address = util.test_address absfile = util.absfile class Foo: def bar(self): pass def baz(): pass f = Foo() class FooTC(unittest.TestCase): def test_one(self): pass def test_two(self): pass class CustomTestType(type): pass class CustomTC(unittest.TestCase): __metaclass__ = CustomTestType def test_one(self): pass def test_two(self): pass foo_funct = case.FunctionTestCase(baz) foo_functu = unittest.FunctionTestCase(baz) foo_mtc = case.MethodTestCase(unbound_method(Foo, Foo.bar)) me = util.src(absfile(__file__)) self.assertEqual(test_address(baz), (me, __name__, 'baz')) assert test_address(Foo) == (me, __name__, 'Foo') assert test_address(unbound_method(Foo, Foo.bar)) == (me, __name__, 'Foo.bar') assert test_address(f) == (me, __name__, 'Foo') assert test_address(f.bar) == (me, __name__, 'Foo.bar') assert test_address(nose) == ( util.src(absfile(nose.__file__)), 'nose', None) # test passing the actual test callable, as the # missed test plugin must do self.assertEqual(test_address(FooTC('test_one')), (me, __name__, 'FooTC.test_one')) self.assertEqual(test_address(CustomTC('test_one')), (me, __name__, 'CustomTC.test_one')) self.assertEqual(test_address(foo_funct), (me, __name__, 'baz')) self.assertEqual(test_address(foo_functu), (me, __name__, 'baz')) self.assertEqual(test_address(foo_mtc), (me, __name__, 'Foo.bar'))
def wantModuleCoverage(self, name, module): if not hasattr(module, "__file__"): log.debug("no coverage of %s: no __file__", name) return False module_file = src(module.__file__) if not module_file or not module_file.endswith(".py"): log.debug("no coverage of %s: not a python file", name) return False if self.coverPackages: for package in self.coverPackages: if re.findall(r"^%s\b" % re.escape(package), name) and ( self.coverTests or not self.conf.testMatch.search(name) ): log.debug("coverage for %s", name) return True if name in self.skipModules: log.debug("no coverage for %s: loaded before coverage start", name) return False if self.conf.testMatch.search(name) and not self.coverTests: log.debug("no coverage for %s: is a test", name) return False # accept any package that passed the previous tests, unless # coverPackages is on -- in that case, if we wanted this # module, we would have already returned True return not self.coverPackages
def wantModuleCoverage(self, name, module): if not hasattr(module, '__file__'): log.debug("no coverage of %s: no __file__", name) return False module_file = src(module.__file__) if not module_file or not module_file.endswith('.py'): log.debug("no coverage of %s: not a python file", name) return False if self.coverPackages: for package in self.coverPackages: if (re.findall(r'^%s\b' % re.escape(package), name) and (self.coverTests or not self.conf.testMatch.search(name))): log.debug("coverage for %s", name) return True if name in self.skipModules: log.debug("no coverage for %s: loaded before coverage start", name) return False if self.conf.testMatch.search(name) and not self.coverTests: log.debug("no coverage for %s: is a test", name) return False # accept any package that passed the previous tests, unless # coverPackages is on -- in that case, if we wanted this # module, we would have already returned True return not self.coverPackages
def loadTestsFromModule(self, module): if not self.matches(module.__name__): npd.log.debug("Doctest doesn't want module %s", module) return try: tests = self.finder.find(module) except AttributeError: # nose allows module.__test__ = False; doctest does not and # throws AttributeError return if not tests: return tests.sort() module_file = src(module.__file__) for test in tests: if not test.examples: continue if not test.filename: test.filename = module_file # Set test namespace; test altered in place self.set_test_context(test) yield self.doctest_case_class(test, optionflags=self.doctest_optflags, checker=self.out_check_class(), result_var=self.doctest_result_var)
def loadTestsFromModule(self, module): """Load doctests from the module. """ log.debug("loading from %s", module) if not self.matches(module.__name__): log.debug("Doctest doesn't want module %s", module) return try: tests = self.finder.find(module) except AttributeError: log.exception("Attribute error loading from %s", module) # nose allows module.__test__ = False; doctest does not and throws # AttributeError return if not tests: log.debug("No tests found in %s", module) return tests.sort() module_file = src(module.__file__) # FIXME this breaks the id plugin somehow (tests probably don't # get wrapped in result proxy or something) cases = [] for test in tests: if not test.examples: continue if not test.filename: test.filename = module_file cases.append(DocTestCase(test, optionflags=self.optionflags, result_var=self.doctest_result_var)) if cases: yield self.suiteClass(cases, context=module, can_split=False)
def test_address(self): from nose.util import absfile, src class TC(unittest.TestCase): def runTest(self): raise Exception("error") def dummy(i): pass def test(): pass class Test: def test(self): pass def test_gen(self): def tryit(i): pass for i in range(0, 2): yield tryit, i def try_something(self, a, b): pass fl = src(absfile(__file__)) case = nose.case.Test(TC()) self.assertEqual(case.address(), (fl, __name__, 'TC.runTest')) case = nose.case.Test(nose.case.FunctionTestCase(test)) self.assertEqual(case.address(), (fl, __name__, 'test')) case = nose.case.Test( nose.case.FunctionTestCase(dummy, arg=(1, ), descriptor=test)) self.assertEqual(case.address(), (fl, __name__, 'test')) case = nose.case.Test( nose.case.MethodTestCase(unbound_method(Test, Test.test))) self.assertEqual(case.address(), (fl, __name__, 'Test.test')) case = nose.case.Test( nose.case.MethodTestCase(unbound_method(Test, Test.try_something), arg=( 1, 2, ), descriptor=unbound_method( Test, Test.test_gen))) self.assertEqual(case.address(), (fl, __name__, 'Test.test_gen')) case = nose.case.Test( nose.case.MethodTestCase(unbound_method(Test, Test.test_gen), test=dummy, arg=(1, ))) self.assertEqual(case.address(), (fl, __name__, 'Test.test_gen'))
def test_subcommand_success(): """Make sure shiva finds and delegates to a Deployment instance method and extracts the result, when all goes well. """ status, output = inner_main([src(__file__), '--shiva-subcommand', 'get_lock_name']) eq_(wake_pickle(output), 'harvey') eq_(status, 0)
def test_subcommand_should_not_deploy(): """If a shiva subcommand raises ShouldNotDeploy, it should get pickled and printed. """ status, output = inner_main([src(__file__), '--shiva-subcommand', 'check_out']) assert_raises(ShouldNotDeploy, wake_pickle, output) eq_(status, 0)
def makeName(self, addr): log.debug("Make name %s", addr) filename, module, call = addr if filename is not None: head = src(filename) else: head = module if call is not None: return "%s:%s" % (head, call) return head
def _printError(self, kind, err, test, isFailure=True): """Output a human-readable error report to the stream. kind -- the (string) type of incident the precipitated this call err -- exc_info()-style traceback triple test -- the test that precipitated this call """ if isFailure or self._showAdvisories: # Don't bind third item to a local var; that can create circular # refs which are expensive to collect. See the sys.exc_info() docs. exception_type, exception_value = err[:2] extracted_tb = extract_tb(err[2]) formatted_traceback = ''.join(format_list(extracted_tb)) # TODO: Canonicalize the path to remove /kitsune/../kitsune # nonsense. Don't relativize, though, as that hurts the ability to # paste into running editors. writeln = self.stream.writeln write = self.stream.write with self.bar.dodging(): writeln('\n' + (self._codes['bold'] if isFailure else '') + '%s: %s' % (kind, nose_selector(test))) if isFailure: # Then show traceback # File name and line num in a format vi can take: try: address = test_address(test) except TypeError: # Explodes if the function passed to @with_setup # applied to a test generator has an error. address = None if address: # None if no such callable found. No sense # trying to find the test frame if there's no # such thing. file, line = frame_of_test(address, exception_type, exception_value, extracted_tb)[:2] writeln(' ' * len(kind) + ' %s +%s %s' % (os.environ.get('EDITOR', 'vi'), line, human_path(src(file), self._cwd))) write(self._codes['sgr0']) # end bold # Traceback: # TODO: Think about using self._exc_info_to_string, which # does some pretty whizzy skipping of unittest frames. write(formatted_traceback) # Exception: write(''.join(format_exception_only(exception_type, exception_value))) else: write(self._codes['sgr0']) # end bold
def test_address(self): from nose.util import absfile, src class TC(unittest.TestCase): def runTest(self): raise Exception("error") def dummy(i): pass def test(): pass class Test: def test(self): pass def test_gen(self): def tryit(i): pass for i in range (0, 2): yield tryit, i def try_something(self, a, b): pass fl = src(absfile(__file__)) case = nose.case.Test(TC()) self.assertEqual(case.address(), (fl, __name__, 'TC.runTest')) case = nose.case.Test(nose.case.FunctionTestCase(test)) self.assertEqual(case.address(), (fl, __name__, 'test')) case = nose.case.Test(nose.case.FunctionTestCase( dummy, arg=(1,), descriptor=test)) self.assertEqual(case.address(), (fl, __name__, 'test')) case = nose.case.Test(nose.case.MethodTestCase( unbound_method(Test, Test.test))) self.assertEqual(case.address(), (fl, __name__, 'Test.test')) case = nose.case.Test( nose.case.MethodTestCase(unbound_method(Test, Test.try_something), arg=(1,2,), descriptor=unbound_method(Test, Test.test_gen))) self.assertEqual(case.address(), (fl, __name__, 'Test.test_gen')) case = nose.case.Test( nose.case.MethodTestCase(unbound_method(Test, Test.test_gen), test=dummy, arg=(1,))) self.assertEqual(case.address(), (fl, __name__, 'Test.test_gen'))
def loadTestsFromModule(self, module): if not self.matches(module.__name__): npd.log.debug("Doctest doesn't want module %s", module) return try: tests = self.finder.find(module) except AttributeError: # nose allows module.__test__ = False; doctest does not and # throws AttributeError return if not tests: return tests.sort() module_file = src(module.__file__) for test in tests: if not test.examples: continue if not test.filename: test.filename = module_file pkg_name = get_package_name(os.path.dirname(test.filename)) # Each doctest should execute in an environment equivalent to # starting Python and executing "import numpy as np", and, # for SciPy packages, an additional import of the local # package (so that scipy.linalg.basic.py's doctests have an # implicit "from scipy import linalg" as well. # # Note: __file__ allows the doctest in NoseTester to run # without producing an error test.globs = { '__builtins__': __builtins__, '__file__': '__main__', '__name__': '__main__', 'np': numpy } # add appropriate scipy import for SciPy tests if 'scipy' in pkg_name: p = pkg_name.split('.') p1 = '.'.join(p[:-1]) p2 = p[-1] test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2]) # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS yield NumpyDocTestCase(test, optionflags=optionflags, checker=NumpyOutputChecker())
def loadTestsFromModule(self, module): if not self.matches(module.__name__): npd.log.debug("Doctest doesn't want module %s", module) return try: tests = self.finder.find(module) except AttributeError: # nose allows module.__test__ = False; doctest does not and # throws AttributeError return if not tests: return tests.sort() module_file = src(module.__file__) for test in tests: if not test.examples: continue if not test.filename: test.filename = module_file pkg_name = get_package_name(os.path.dirname(test.filename)) # Each doctest should execute in an environment equivalent to # starting Python and executing "import numpy as np", and, # for SciPy packages, an additional import of the local # package (so that scipy.linalg.basic.py's doctests have an # implicit "from scipy import linalg" as well. # # Note: __file__ allows the doctest in NoseTester to run # without producing an error test.globs = {'__builtins__':__builtins__, '__file__':'__main__', '__name__':'__main__', 'np':numpy} # add appropriate scipy import for SciPy tests if 'scipy' in pkg_name: p = pkg_name.split('.') p1 = '.'.join(p[:-1]) p2 = p[-1] test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2]) # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS yield NumpyDocTestCase(test, optionflags=optionflags, checker=NumpyOutputChecker())
def test_index_when_syntax_error_below_test_frame(): """Make sure we manage to find the test frame if there's a SyntaxError below it. Here we present to ``index_of_test_frame()`` a traceback that represents this test raising a SyntaxError indirectly, in a function called by same test. """ extracted_tb = [('/nose/case.py', 183, 'runTest', 'self.test(*self.arg)'), # Legit path so the frame finder can compare to the address of DummyCase: (src(realpath(__file__)), 34, 'test_index_when_syntax_error_below_test_frame', 'deeper()'), ('/noseprogressive/tests/test_utils.py', 33, 'deeper', 'import noseprogressive.tests.syntaxerror')] eq_(index_of_test_frame(extracted_tb, SyntaxError, SyntaxError('invalid syntax', ('/tests/syntaxerror.py', 1, 1, ':bad\n')), dummy_test), 1)
def loadTestsFromModule(self, module): if not self.matches(module.__name__): log.debug("Doctest doesn't want module %s", module) return try: tests = self.finder.find(module) except AttributeError: # nose allows module.__test__ = False; doctest does not and throws # AttributeError return if not tests: return tests.sort() module_file = src(module.__file__) for test in tests: if not test.examples: continue if not test.filename: test.filename = module_file yield DocTestCase(test)
def __init__(self, name, workingDir=None): if workingDir is None: workingDir = os.getcwd() self.name = name self.workingDir = workingDir self.filename, self.module, self.call = split_test_name(name) log.debug('Test name %s resolved to file %s, module %s, call %s', name, self.filename, self.module, self.call) if self.filename is None: if self.module is not None: self.filename = getfilename(self.module, self.workingDir) if self.filename: self.filename = src(self.filename) if not op_isabs(self.filename): self.filename = op_abspath(op_join(workingDir, self.filename)) if self.module is None: self.module = getpackage(self.filename) log.debug( 'Final resolution of test name %s: file %s module %s call %s', name, self.filename, self.module, self.call)
def test_index_when_syntax_error_below_test_frame(): """Make sure we manage to find the test frame if there's a SyntaxError below it. Here we present to ``index_of_test_frame()`` a traceback that represents this test raising a SyntaxError indirectly, in a function called by same test. """ extracted_tb = [ ('/nose/case.py', 183, 'runTest', 'self.test(*self.arg)'), # Legit path so the frame finder can compare to the address of DummyCase: (src(realpath(__file__)), 34, 'test_index_when_syntax_error_below_test_frame', 'deeper()'), ('/noseprogressive/tests/test_utils.py', 33, 'deeper', 'import noseprogressive.tests.syntaxerror') ] eq_( index_of_test_frame( extracted_tb, SyntaxError, SyntaxError('invalid syntax', ('/tests/syntaxerror.py', 1, 1, ':bad\n')), dummy_test), 1)
def loadTestsFromDir(self, path): """Load tests from the directory at path. This is a generator -- each suite of tests from a module or other file is yielded and is expected to be executed before the next file is examined. """ log.debug("load from dir %s", path) plugins = self.config.plugins plugins.beforeDirectory(path) if self.config.addPaths: paths_added = add_path(path, self.config) entries = os.listdir(path) sort_list(entries, regex_last_key(self.config.testMatch)) for entry in entries: # this hard-coded initial-dot test will be removed: # http://code.google.com/p/python-nose/issues/detail?id=82 if entry.startswith('.'): continue if src(entry) == '__init__.py': continue entry_path = op_abspath(op_join(path, entry)) is_file = op_isfile(entry_path) wanted = False if is_file: is_dir = False wanted = self.selector.wantFile(entry_path) else: is_dir = op_isdir(entry_path) if is_dir: # this hard-coded initial-underscore test will be removed: # http://code.google.com/p/python-nose/issues/detail?id=82 if entry.startswith('_'): continue wanted = self.selector.wantDirectory(entry_path) is_package = ispackage(entry_path) # Python 3.3 now implements PEP 420: Implicit Namespace Packages. # As a result, it's now possible that parent paths that have a # segment with the same basename as our package ends up # in module.__path__. So we have to keep track of what we've # visited, and not-revisit them again. if wanted and not self._haveVisited(entry_path): self._addVisitedPath(entry_path) if is_file: plugins.beforeContext() if entry.endswith('.py'): yield self.loadTestsFromName( entry_path, discovered=True) else: yield self.loadTestsFromFile(entry_path) plugins.afterContext() elif is_package: # Load the entry as a package: given the full path, # loadTestsFromName() will figure it out yield self.loadTestsFromName( entry_path, discovered=True) else: # Another test dir in this one: recurse lazily yield self.suiteClass( lambda: self.loadTestsFromDir(entry_path)) tests = [] for test in plugins.loadTestsFromDir(path): tests.append(test) # TODO: is this try/except needed? try: if tests: yield self.suiteClass(tests) except (KeyboardInterrupt, SystemExit): raise except: yield self.suiteClass([Failure(*sys.exc_info())]) # pop paths if self.config.addPaths: for p in paths_added: remove_path(p) plugins.afterDirectory(path)
def format_traceback(extracted_tb, exc_type, exc_value, cwd='', term=None, function_color=12, dim_color=8, editor='vi', template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE): """Return an iterable of formatted Unicode traceback frames. Also include a pseudo-frame at the end representing the exception itself. Format things more compactly than the stock formatter, and make every frame an editor shortcut. """ def format_shortcut(editor, path, line_number, function=None): """Return a pretty-printed editor shortcut.""" return template.format( editor=editor, line_number=line_number or 0, path=path, function=function or u'', hash_if_function=u' # ' if function else u'', function_format=term.color(function_color), # Underline is also nice and doesn't make us # worry about appearance on different background # colors. normal=term.normal, dim_format=term.color(dim_color) + term.bold, line_number_max_width=line_number_max_width, term=term) template += '\n' # Newlines are awkward to express on the command line. extracted_tb = _unicode_decode_extracted_tb(extracted_tb) if not term: term = Terminal() if extracted_tb: # Shorten file paths: for i, (file, line_number, function, text) in enumerate(extracted_tb): extracted_tb[i] = human_path(src(file), cwd), line_number, function, text line_number_max_width = len( unicode(max(the_line for _, the_line, _, _ in extracted_tb))) # Stack frames: for i, (path, line_number, function, text) in enumerate(extracted_tb): text = (text and text.strip()) or u'' yield (format_shortcut(editor, path, line_number, function) + (u' %s\n' % text)) # Exception: if exc_type is SyntaxError: # Format a SyntaxError to look like our other traceback lines. # SyntaxErrors have a format different from other errors and include a # file path which looks out of place in our newly highlit, editor- # shortcutted world. if hasattr(exc_value, 'filename') and hasattr(exc_value, 'lineno'): exc_lines = [ format_shortcut(editor, exc_value.filename, exc_value.lineno) ] formatted_exception = format_exception_only( SyntaxError, exc_value)[1:] else: # The logcapture plugin may format exceptions as strings, # stripping them of the full filename and lineno exc_lines = [] formatted_exception = format_exception_only(SyntaxError, exc_value) formatted_exception.append( u'(Try --nologcapture for a more detailed traceback)\n') else: exc_lines = [] formatted_exception = format_exception_only(exc_type, exc_value) exc_lines.extend([_decode(f) for f in formatted_exception]) yield u''.join(exc_lines)
def format_traceback(extracted_tb, exc_type, exc_value, cwd='', term=None, function_color=12, dim_color=8, editor='vi', template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE): """Return an iterable of formatted Unicode traceback frames. Also include a pseudo-frame at the end representing the exception itself. Format things more compactly than the stock formatter, and make every frame an editor shortcut. """ def format_shortcut(editor, path, line_number, function=None): """Return a pretty-printed editor shortcut.""" return template.format(editor=editor, line_number=line_number or 0, path=path, function=function or u'', hash_if_function=u' # ' if function else u'', function_format=term.color(function_color), # Underline is also nice and doesn't make us # worry about appearance on different background # colors. normal=term.normal, dim_format=term.color(dim_color) + term.bold, line_number_max_width=line_number_max_width, term=term) template += '\n' # Newlines are awkward to express on the command line. extracted_tb = _unicode_decode_extracted_tb(extracted_tb) if not term: term = Terminal() if extracted_tb: # Shorten file paths: for i, (file, line_number, function, text) in enumerate(extracted_tb): extracted_tb[i] = human_path(src(file), cwd), line_number, function, text line_number_max_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb))) # Stack frames: for i, (path, line_number, function, text) in enumerate(extracted_tb): text = (text and text.strip()) or u'' yield (format_shortcut(editor, path, line_number, function) + (u' %s\n' % text)) # Exception: if exc_type is SyntaxError: # Format a SyntaxError to look like our other traceback lines. # SyntaxErrors have a format different from other errors and include a # file path which looks out of place in our newly highlit, editor- # shortcutted world. if hasattr(exc_value, 'filename') and hasattr(exc_value, 'lineno'): exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)] formatted_exception = format_exception_only(SyntaxError, exc_value)[1:] else: # The logcapture plugin may format exceptions as strings, # stripping them of the full filename and lineno exc_lines = [] formatted_exception = format_exception_only(SyntaxError, exc_value) formatted_exception.append(u'(Try --nologcapture for a more detailed traceback)\n') else: exc_lines = [] formatted_exception = format_exception_only(exc_type, exc_value) exc_lines.extend([_decode(f) for f in formatted_exception]) yield u''.join(exc_lines)
def format_traceback(extracted_tb, exc_type, exc_value, cwd='', term=None, function_color=12, dim_color=8, editor='vi'): """Return an iterable of formatted Unicode traceback frames. Also include a pseudo-frame at the end representing the exception itself. Format things more compactly than the stock formatter, and make every frame an editor shortcut. """ def format_shortcut(editor, file, line, function=None): """Return a pretty-printed editor shortcut.""" return template % dict(editor=editor, line=line, file=file, function=(u' # ' + function) if function else u'', funcemph=term.color(function_color), # Underline is also nice and doesn't make us # worry about appearance on different background # colors. plain=term.normal, fade=term.color(dim_color) + term.bold) extracted_tb = _unicode_decode_extracted_tb(extracted_tb) if not term: term = Terminal() if extracted_tb: # Shorten file paths: for i, (file, line, function, text) in enumerate(extracted_tb): extracted_tb[i] = human_path(src(file), cwd), line, function, text line_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb))) template = (u' %(fade)s%(editor)s +%(line)-' + unicode(line_width) + u's ' '%(file)s%(plain)s' '%(funcemph)s%(function)s%(plain)s\n') # Stack frames: for i, (file, line, function, text) in enumerate(extracted_tb): text = (text and text.strip()) or u'' yield (format_shortcut(editor, file, line, function) + (u' %s\n' % text)) # Exception: if exc_type is SyntaxError: # Format a SyntaxError to look like our other traceback lines. # SyntaxErrors have a format different from other errors and include a # file path which looks out of place in our newly highlit, editor- # shortcutted world. exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)] formatted_exception = format_exception_only(SyntaxError, exc_value)[1:] else: exc_lines = [] formatted_exception = format_exception_only(exc_type, exc_value) exc_lines.extend([_decode(f) for f in formatted_exception]) yield u''.join(exc_lines)
def loadTestsFromDir(self, path): """Load tests from the directory at path. This is a generator -- each suite of tests from a module or other file is yielded and is expected to be executed before the next file is examined. """ log.debug("load from dir %s", path) plugins = self.config.plugins plugins.beforeDirectory(path) if self.config.addPaths: paths_added = add_path(path, self.config) entries = os.listdir(path) sort_list(entries, regex_last_key(self.config.testMatch)) for entry in entries: # this hard-coded initial-dot test will be removed: # http://code.google.com/p/python-nose/issues/detail?id=82 if entry.startswith('.'): continue if src(entry) == '__init__.py': continue entry_path = op_abspath(op_join(path, entry)) is_file = op_isfile(entry_path) wanted = False if is_file: is_dir = False wanted = self.selector.wantFile(entry_path) else: is_dir = op_isdir(entry_path) if is_dir: # this hard-coded initial-underscore test will be removed: # http://code.google.com/p/python-nose/issues/detail?id=82 if entry.startswith('_'): continue wanted = self.selector.wantDirectory(entry_path) is_package = ispackage(entry_path) # Python 3.3 now implements PEP 420: Implicit Namespace Packages. # As a result, it's now possible that parent paths that have a # segment with the same basename as our package ends up # in module.__path__. So we have to keep track of what we've # visited, and not-revisit them again. if wanted and not self._haveVisited(entry_path): self._addVisitedPath(entry_path) if is_file: plugins.beforeContext() if entry.endswith('.py'): yield self.loadTestsFromName(entry_path, discovered=True) else: yield self.loadTestsFromFile(entry_path) plugins.afterContext() elif is_package: # Load the entry as a package: given the full path, # loadTestsFromName() will figure it out yield self.loadTestsFromName(entry_path, discovered=True) else: # Another test dir in this one: recurse lazily yield self.suiteClass( lambda: self.loadTestsFromDir(entry_path)) tests = [] for test in plugins.loadTestsFromDir(path): tests.append(test) # TODO: is this try/except needed? try: if tests: yield self.suiteClass(tests) except (KeyboardInterrupt, SystemExit): raise except: yield self.suiteClass([Failure(*sys.exc_info())]) # pop paths if self.config.addPaths: for p in paths_added: remove_path(p) plugins.afterDirectory(path)