def address(self): if self._nose_obj is not None: return test_address(self._nose_obj) obj = resolve_name(self._dt_test.name) if isproperty(obj): # properties have no connection to the class they are in # so we can't just look 'em up, we have to first look up # the class, then stick the prop on the end parts = self._dt_test.name.split(".") class_name = ".".join(parts[:-1]) cls = resolve_name(class_name) base_addr = test_address(cls) return (base_addr[0], base_addr[1], ".".join([base_addr[2], parts[-1]])) else: return test_address(obj)
def ancestry(self, context): """Return the ancestry of the context (that is, all of the packages and modules containing the context), in order of descent with the outermost ancestor last. This method is a generator. """ log.debug("get ancestry %s", context) if context is None: return # Methods include reference to module they are defined in, we # don't want that, instead want the module the class is in now # (classes are re-ancestored elsewhere). if hasattr(context, 'im_class'): context = context.__self__.__class__ elif hasattr(context, '__self__'): context = context.__self__.__class__ if hasattr(context, '__module__'): ancestors = context.__module__.split('.') elif hasattr(context, '__name__'): ancestors = context.__name__.split('.')[:-1] else: raise TypeError("%s has no ancestors?" % context) while ancestors: log.debug(" %s ancestors %s", context, ancestors) yield resolve_name('.'.join(ancestors)) ancestors.pop()
def _context(self): try: return self.test.context except AttributeError: pass try: return self.test.__class__ except AttributeError: pass try: return resolve_name(self.test.__module__) except AttributeError: pass return None
def docstring_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): obj_name = arguments[0] obj = resolve_name(obj_name) rst = ViewList() rst.append(obj.__doc__, '<docstring>') print("CALLED", obj_name, obj, rst) node = nodes.section() surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
def ancestry(self, context): """Return the ancestry of the context (that is, all of the packages and modules containing the context), in order of descent with the outermost ancestor last. This method is a generator. """ log.debug("get ancestry %s", context) if context is None: return if hasattr(context, '__module__'): ancestors = context.__module__.split('.') elif hasattr(context, '__name__'): ancestors = context.__name__.split('.')[:-1] else: raise TypeError("%s has no ancestors?" % context) while ancestors: log.debug(" %s ancestors %s", context, ancestors) yield resolve_name('.'.join(ancestors)) ancestors.pop()
def get_tests_from_xml_files(paths, config): '''Retrieve the suite of tests from an xml file produced by the xunit plugin Start cpnose like this to make the file: python cpnose.py --collect-only --with-xunit --xunit-file=<path> paths - paths to xml files returns a test suite with the paths ''' factory = ContextSuiteFactory(config=config) hierarchy = {} classes = {} for path in paths: xml = parse(path) for test_suite in xml.getElementsByTagName("testsuite"): for test_case in test_suite.getElementsByTagName("testcase"): full_class_name = test_case.getAttribute("classname") name = test_case.getAttribute("name") parts = full_class_name.split(".") leaf = hierarchy for part in parts: if part not in leaf: leaf[part] = {} leaf = leaf[part] module_name, class_name = full_class_name.rsplit(".", 1) try: if full_class_name not in classes: klass = resolve_name(full_class_name) classes[full_class_name] = klass else: klass = classes[full_class_name] if klass is None: continue test = klass(name) leaf[name] = test except: logger.warning("Failed to load test %s.%s" % (full_class_name, name), exc_info=True) return get_suite_from_dictionary(factory, hierarchy)
def load_tests(self, basename): obj = resolve_name(basename) if not self.ismodule(obj) or not self.ispackage(obj): return dirname = os.path.dirname(obj.__file__) childs = os.listdir(dirname) childs.sort() childs = map(lambda name: (name, os.path.join(dirname, name)), childs) for name, fullname in childs: if os.path.isdir(fullname) and ispackage(fullname): self.load_tests(basename + '.' + name) if not os.path.isfile(fullname) or skip_pattern_re.match(name) or \ not name.endswith('.py') or name == '__init__.py': continue if self.test_match_re.match(name): self.load_tests(basename + '.' + name[:-3])
def load_settings(self, settings): # If settings module was set try to load or die with error if settings is not None: try: resolve_name(settings) except (AttributeError, ImportError): return self.error(settings) else: settings = 'settings' try: resolve_name(settings) except (AttributeError, ImportError): dirname = os.getcwd() loaded = False subdirs = \ filter(lambda name: os.path.isdir(os.path.join(dirname, name)), os.listdir(dirname)) subdirs.sort() for name in subdirs: settings = name + '.settings' try: resolve_name(settings) except (AttributeError, ImportError, ValueError): pass else: loaded = True break if not loaded: self.error(None, dirname, subdirs) os.environ['DJANGO_SETTINGS_MODULE'] = settings
def autoplugin_directive( dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine ): mod_name = arguments[0] mod = resolve_name(mod_name) plug_name = options.get("plugin", None) if plug_name: obj = getattr(mod, plug_name) else: for entry in dir(mod): obj = getattr(mod, entry) if isclass(obj) and issubclass(obj, Plugin) and obj is not Plugin: plug_name = "%s.%s" % (mod_name, entry) break # mod docstring rst = ViewList() rst.append(".. automodule :: %s\n" % mod_name, "<autodoc>") rst.append("", "<autodoc>") # options rst.append("Options", "<autodoc>") rst.append("-------", "<autodoc>") rst.append("", "<autodoc>") plug = obj() opts = OptBucket() plug.options(opts, {}) for opt in opts: rst.append(opt.options(), "<autodoc>") rst.append(" \n", "<autodoc>") rst.append(" " + opt.help + "\n", "<autodoc>") rst.append("\n", "<autodoc>") # plugin class rst.append("Plugin", "<autodoc>") rst.append("------", "<autodoc>") rst.append("", "<autodoc>") rst.append(".. autoclass :: %s\n" % plug_name, "<autodoc>") rst.append(" :members:\n", "<autodoc>") rst.append(" :show-inheritance:\n", "<autodoc>") rst.append("", "<autodoc>") # source rst.append("Source", "<autodoc>") rst.append("------", "<autodoc>") rst.append(".. include :: %s\n" % mod.__file__.replace(".pyc", ".py"), "<autodoc>") rst.append(" :literal:\n", "<autodoc>") rst.append("", "<autodoc>") node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
def autoplugin_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): mod_name = arguments[0] mod = resolve_name(mod_name) plug_name = options.get('plugin', None) if plug_name: obj = getattr(mod, plug_name) else: for entry in dir(mod): obj = getattr(mod, entry) if isclass(obj) and issubclass(obj, Plugin) and obj is not Plugin: plug_name = '%s.%s' % (mod_name, entry) break # mod docstring rst = ViewList() rst.append('.. automodule :: %s\n' % mod_name, '<autodoc>') rst.append('', '<autodoc>') # options rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') plug = obj() opts = OptBucket() plug.options(opts, {}) for opt in opts: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') # plugin class rst.append('Plugin', '<autodoc>') rst.append('------', '<autodoc>') rst.append('', '<autodoc>') rst.append('.. autoclass :: %s\n' % plug_name, '<autodoc>') rst.append(' :members:\n', '<autodoc>') rst.append(' :show-inheritance:\n', '<autodoc>') rst.append('', '<autodoc>') # source rst.append('Source', '<autodoc>') rst.append('------', '<autodoc>') rst.append('.. include :: %s\n' % os.path.abspath( mod.__file__.replace('.pyc', '.py') ), '<autodoc>') rst.append(' :literal:\n', '<autodoc>') rst.append('', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
def address(self): if self._nose_obj is not None: return test_address(self._nose_obj) return test_address(resolve_name(self._dt_test.name))
def _context(self): return resolve_name(self.test.__module__)
from django.test import TestCase from django.conf import settings from nose.util import resolve_name DJANGO_WEBTEST_BASE_TESTCASE = getattr( settings, 'DJANGO_WEBTEST_BASE_TESTCASE', 'django.test.TestCase' ) DJANGO_WEBTEST_BASE_TESTCASE = resolve_name(DJANGO_WEBTEST_BASE_TESTCASE)
def loadTestsFromName(self, name, module=None, discovered=False): """Load tests from the entity with the given name. The name may indicate a file, directory, module, or any object within a module. See `nose.util.split_test_name` for details on test name parsing. """ # FIXME refactor this method into little bites? log.debug("load from %s (%s)", name, module) suite = self.suiteClass # give plugins first crack plug_tests = self.config.plugins.loadTestsFromName(name, module) if plug_tests: return suite(plug_tests) addr = TestAddress(name, workingDir=self.workingDir) if module: # Two cases: # name is class.foo # The addr will be incorrect, since it thinks class.foo is # a dotted module name. It's actually a dotted attribute # name. In this case we want to use the full submitted # name as the name to load from the module. # name is module:class.foo # The addr will be correct. The part we want is the part after # the :, which is in addr.call. if addr.call: name = addr.call parent, obj = self.resolve(name, module) if (isclass(parent) and getattr(parent, '__module__', None) != module.__name__ and not isinstance(obj, Failure)): parent = transplant_class(parent, module.__name__) obj = getattr(parent, obj.__name__) log.debug("parent %s obj %s module %s", parent, obj, module) if isinstance(obj, Failure): return suite([obj]) else: return suite( ContextList([self.makeTest(obj, parent)], context=parent)) else: if addr.module: try: if addr.filename is None: module = resolve_name(addr.module) else: self.config.plugins.beforeImport( addr.filename, addr.module) # FIXME: to support module.name names, # do what resolve-name does and keep trying to # import, popping tail of module into addr.call, # until we either get an import or run out of # module parts try: module = self.importer.importFromPath( addr.filename, addr.module) finally: self.config.plugins.afterImport( addr.filename, addr.module) except (KeyboardInterrupt, SystemExit): raise except: exc = sys.exc_info() return suite([ Failure(exc[0], exc[1], exc[2], address=addr.totuple()) ]) if addr.call: return self.loadTestsFromName(addr.call, module) else: return self.loadTestsFromModule(module, addr.filename, discovered=discovered) elif addr.filename: path = addr.filename if addr.call: package = getpackage(path) if package is None: return suite([ Failure(ValueError, "Can't find callable %s in file %s: " "file is not a python module" % (addr.call, path), address=addr.totuple()) ]) return self.loadTestsFromName(addr.call, module=package) else: if op_isdir(path): # In this case we *can* be lazy since we know # that each module in the dir will be fully # loaded before its tests are executed; we # also know that we're not going to be asked # to load from . and ./some_module.py *as part # of this named test load* return LazySuite(lambda: self.loadTestsFromDir(path)) elif op_isfile(path): return self.loadTestsFromFile(path) else: return suite([ Failure(OSError, "No such file %s" % path, address=addr.totuple()) ]) else: # just a function? what to do? I think it can only be # handled when module is not None return suite([ Failure(ValueError, "Unresolvable test name %s" % name, address=addr.totuple()) ])
def _context(self): """ Gets the context (module) of this test. """ return resolve_name(self.test.__module__)
from django.conf import settings from django.test import TestCase from nose.util import resolve_name __all__ = ('IP', 'PORT', 'SITE', 'DjangoTestCase') IP = getattr(settings, 'TDDSPRY_IP', '127.0.0.1') PORT = getattr(settings, 'TDDSPRY_PORT', 8088) SITE = 'http://%s:%s/' % (IP, PORT) DjangoTestCase = getattr(settings, 'TDDSPRY_TEST_CASE', TestCase) if isinstance(DjangoTestCase, basestring): DjangoTestCase = resolve_name(DjangoTestCase)
def loadTestsFromName(self, name, module=None, discovered=False): """Load tests from the entity with the given name. The name may indicate a file, directory, module, or any object within a module. See `nose.util.split_test_name` for details on test name parsing. """ # FIXME refactor this method into little bites? log.debug("load from %s (%s)", name, module) suite = self.suiteClass # give plugins first crack plug_tests = self.config.plugins.loadTestsFromName(name, module) if plug_tests: return suite(plug_tests) addr = TestAddress(name, workingDir=self.workingDir) if module: # Two cases: # name is class.foo # The addr will be incorrect, since it thinks class.foo is # a dotted module name. It's actually a dotted attribute # name. In this case we want to use the full submitted # name as the name to load from the module. # name is module:class.foo # The addr will be correct. The part we want is the part after # the :, which is in addr.call. if addr.call: name = addr.call parent, obj = self.resolve(name, module) if (isclass(parent) and getattr(parent, '__module__', None) != module.__name__ and not isinstance(obj, Failure)): parent = transplant_class(parent, module.__name__) obj = getattr(parent, obj.__name__) log.debug("parent %s obj %s module %s", parent, obj, module) if isinstance(obj, Failure): return suite([obj]) else: return suite(ContextList([self.makeTest(obj, parent)], context=parent)) else: if addr.module: try: if addr.filename is None: module = resolve_name(addr.module) else: self.config.plugins.beforeImport( addr.filename, addr.module) # FIXME: to support module.name names, # do what resolve-name does and keep trying to # import, popping tail of module into addr.call, # until we either get an import or run out of # module parts try: module = self.importer.importFromPath( addr.filename, addr.module) finally: self.config.plugins.afterImport( addr.filename, addr.module) except (KeyboardInterrupt, SystemExit): raise except: exc = sys.exc_info() return suite([Failure(exc[0], exc[1], exc[2], address=addr.totuple())]) if addr.call: return self.loadTestsFromName(addr.call, module) else: return self.loadTestsFromModule( module, addr.filename, discovered=discovered) elif addr.filename: path = addr.filename if addr.call: package = getpackage(path) if package is None: return suite([ Failure(ValueError, "Can't find callable %s in file %s: " "file is not a python module" % (addr.call, path), address=addr.totuple())]) return self.loadTestsFromName(addr.call, module=package) else: if op_isdir(path): # In this case we *can* be lazy since we know # that each module in the dir will be fully # loaded before its tests are executed; we # also know that we're not going to be asked # to load from . and ./some_module.py *as part # of this named test load* return LazySuite( lambda: self.loadTestsFromDir(path)) elif op_isfile(path): return self.loadTestsFromFile(path) else: return suite([ Failure(OSError, "No such file %s" % path, address=addr.totuple())]) else: # just a function? what to do? I think it can only be # handled when module is not None return suite([ Failure(ValueError, "Unresolvable test name %s" % name, address=addr.totuple())])
def autoplugin_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): mod_name = arguments[0] mod = resolve_name(mod_name) plug_name = options.get('plugin', None) if plug_name: obj = getattr(mod, plug_name) else: for entry in dir(mod): obj = getattr(mod, entry) if isclass(obj) and issubclass(obj, Plugin) and obj is not Plugin: plug_name = '%s.%s' % (mod_name, entry) break # mod docstring rst = ViewList() rst.append('.. automodule :: %s\n' % mod_name, '<autodoc>') rst.append('', '<autodoc>') # options rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') plug = obj() opts = OptBucket() plug.options(opts, {}) for opt in opts: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') # plugin class rst.append('Plugin', '<autodoc>') rst.append('------', '<autodoc>') rst.append('', '<autodoc>') rst.append('.. autoclass :: %s\n' % plug_name, '<autodoc>') rst.append(' :members:\n', '<autodoc>') rst.append(' :show-inheritance:\n', '<autodoc>') rst.append('', '<autodoc>') # source rst.append('Source', '<autodoc>') rst.append('------', '<autodoc>') rst.append('.. include :: %s\n' % os.path.relpath( mod.__file__.replace('.pyc', '.py'), os.getcwd()), '<autodoc>') rst.append(' :literal:\n', '<autodoc>') rst.append('', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children