desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Parse an entry point group'
@classmethod def parse_group(cls, group, lines, dist=None):
if (not MODULE(group)): raise ValueError('Invalid group name', group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if (ep.name in this): raise ValueError('Duplicate entry point', group, ep.name) this[ep.name] = ep return thi...
'Parse a map of entry point groups'
@classmethod def parse_map(cls, data, dist=None):
if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for (group, lines) in data: if (group is None): if (not lines): continue raise ValueError('Entry points must be listed in groups') ...
'List of Requirements needed for this distro if `extras` are used'
def requires(self, extras=()):
dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra(('%s has no such extra feature %r' % (self, ext))) return deps
'Ensure distribution is importable on `path` (default=sys.path)'
def activate(self, path=None):
if (path is None): path = sys.path self.insert_on(path) if (path is sys.path): fixup_namespace_packages(self.location) list(map(declare_namespace, self._get_metadata('namespace_packages.txt')))
'Return what this distribution\'s standard .egg filename should be'
def egg_name(self):
filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR))) if self.platform: filename += ('-' + self.platform) return filename
'Delegate all unrecognized public attributes to .metadata provider'
def __getattr__(self, attr):
if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr)
'Return a ``Requirement`` that matches this distribution exactly'
def as_requirement(self):
return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
'Return the `name` entry point of `group` or raise ImportError'
def load_entry_point(self, group, name):
ep = self.get_entry_info(group, name) if (ep is None): raise ImportError(('Entry point %r not found' % ((group, name),))) return ep.load()
'Return the entry point map for `group`, or the full entry map'
def get_entry_map(self, group=None):
try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self) if (group is not None): return ep_map.get(group, {}) return ep_map
'Return the EntryPoint object for `group`+`name`, or ``None``'
def get_entry_info(self, group, name):
return self.get_entry_map(group).get(name)
'Insert self.location in path before its nearest parent directory'
def insert_on(self, path, loc=None):
loc = (loc or self.location) if (not loc): return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [((p and _normalize_cached(p)) or p) for p in path] for (p, item) in enumerate(npath): if (item == nloc): break elif ((item == bdir) and (self....
'Copy this distribution, substituting in any changed keyword args'
def clone(self, **kw):
for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
'Parse and cache metadata'
@property def _parsed_pkg_info(self):
try: return self._pkg_info except AttributeError: from email.parser import Parser self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO)) return self._pkg_info
'Convert \'Foobar (1); baz\' to (\'Foobar ==1\', \'baz\') Split environment marker, add == prefix to version specifiers as necessary, and remove parenthesis.'
def _preparse_requirement(self, requires_dist):
parts = (requires_dist.split(';', 1) + ['']) distvers = parts[0].strip() mark = parts[1].strip() distvers = re.sub(self.EQEQ, '\\1==\\2\\3', distvers) distvers = distvers.replace('(', '').replace(')', '') return (distvers, mark)
'Recompute this distribution\'s dependencies.'
def _compute_dependencies(self):
from _markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] for req in (self._parsed_pkg_info.get_all('Requires-Dist') or []): (distvers, mark) = self._preparse_requirement(req) parsed = next(parse_requirements(distvers)) parsed.marker_fn = compile...
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
def __init__(self, project_name, specs, extras):
(self.unsafe_name, project_name) = (project_name, safe_name(project_name)) (self.project_name, self.key) = (project_name, project_name.lower()) index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs] index.sort() self.specs = [(op, ver) for (parsed, trans, op, ver) in index] ...
'Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests.'
def loadTestsFromModule(self, module):
tests = [] if (module.__name__ != 'setuptools.tests.doctest'): tests.append(TestLoader.loadTestsFromModule(self, module)) if hasattr(module, 'additional_tests'): tests.append(module.additional_tests()) if hasattr(module, '__path__'): for file in resource_listdir(module.__name__, ...
'Build modules, packages, and copy data files to build directory'
def run(self):
if ((not self.py_modules) and (not self.packages)): return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() self.run_2to3(self.__updated_files, False) self.run_2to3(self.__updated_files, True) self.run_2to3...
'Generate list of \'(package,src_dir,build_dir,filenames)\' tuples'
def _get_data_files(self):
self.analyze_manifest() data = [] for package in (self.packages or ()): src_dir = self.get_package_dir(package) build_dir = os.path.join(*([self.build_lib] + package.split('.'))) plen = (len(src_dir) + 1) filenames = [file[plen:] for file in self.find_data_files(package, src_...
'Return filenames for package\'s data files in \'src_dir\''
def find_data_files(self, package, src_dir):
globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = self.manifest_files.get(package, [])[:] for pattern in globs: files.extend(glob(os.path.join(src_dir, convert_path(pattern)))) return self.exclude_data_files(package, src_dir, files)
'Copy data files into build directory'
def build_package_data(self):
for (package, src_dir, build_dir, filenames) in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) srcfile = os.path.join(src_dir, filename) (outf, copied) = self.copy_file(srcfile, targe...
'Check namespace packages\' __init__ for declare_namespace'
def check_package(self, package, package_dir):
try: return self.packages_checked[package] except KeyError: pass init_py = _build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if ((not init_py) or (not self.distribution.namespace_packages)): return init_py for pkg in self.distrib...
'Filter filenames for package\'s data files in \'src_dir\''
def exclude_data_files(self, package, src_dir, files):
globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend(fnmatch.filter(files, os.path.join(src_dir, convert_path(pattern)))) bad = dict.fromkeys(bad) seen = {} return [f for f in files if ((f not in bad) and (...
'Write an executable file to the scripts directory'
def write_script(self, script_name, contents, mode='t', *ignored):
from setuptools.command.easy_install import chmod, current_umask log.info('Installing %s script to %s', script_name, self.install_dir) target = os.path.join(self.install_dir, script_name) self.outfiles.append(target) mask = current_umask() if (not self.dry_run): ensure_direct...
'Build extensions in build directory, then copy if --inplace'
def run(self):
(old_inplace, self.inplace) = (self.inplace, 0) _build_ext.run(self) self.inplace = old_inplace if old_inplace: self.copy_extensions_to_source()
'Return true if \'ext\' links to a dynamic lib in the same package'
def links_to_dynamic(self, ext):
libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join((ext._full_name.split('.')[:(-1)] + [''])) for libname in ext.libraries: if ((pkg + libname) in libnames): return True return False
'Write `data` to `filename` or delete if empty If `data` is non-empty, this routine is the same as ``write_file()``. If `data` is empty but not ``None``, this is the same as calling ``delete_file(filename)`. If `data` is ``None``, then this is a no-op unless `filename` exists, in which case a warning is issued about t...
def write_or_delete_file(self, what, filename, data, force=False):
if data: self.write_file(what, filename, data) elif os.path.exists(filename): if ((data is None) and (not force)): log.warn('%s not set in setup(), but %s exists', what, filename) return else: self.delete_file(filename)
'Write `data` to `filename` (if not a dry run) after announcing it `what` is used in a log message to identify what is being written to the file.'
def write_file(self, what, filename, data):
log.info('writing %s to %s', what, filename) if (sys.version_info >= (3,)): data = data.encode('utf-8') if (not self.dry_run): f = open(filename, 'wb') f.write(data) f.close()
'Delete `filename` (if not a dry run) after announcing it'
def delete_file(self, filename):
log.info('deleting %s', filename) if (not self.dry_run): os.unlink(filename)
'Generate SOURCES.txt manifest file'
def find_sources(self):
manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') mm = manifest_maker(self.distribution) mm.manifest = manifest_filename mm.run() self.filelist = mm.filelist
'Write the file list in \'self.filelist\' (presumably as filled in by \'add_defaults()\' and \'read_template()\') to the manifest file named by \'self.manifest\'.'
def write_manifest(self):
if (sys.version_info >= (3,)): files = [] for file in self.filelist.files: try: file.encode('utf-8') except UnicodeEncodeError: log.warn(("'%s' not UTF-8 encodable -- skipping" % file)) else: files.app...
'Calls `os.path.expanduser` on install_base, install_platbase and root.'
def expand_basedirs(self):
self._expand_attrs(['install_base', 'install_platbase', 'root'])
'Calls `os.path.expanduser` on install dirs.'
def expand_dirs(self):
self._expand_attrs(['install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data'])
'Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you\'re already in deep doodoo.'
def pseudo_tempname(self):
try: pid = os.getpid() except: pid = random.randint(0, maxsize) return os.path.join(self.install_dir, ('test-easy-install-%s' % pid))
'Verify that self.install_dir is .pth-capable dir, if needed'
def check_site_dir(self):
instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') is_site_dir = (instdir in self.all_site_dirs) if ((not is_site_dir) and (not self.multi_version)): is_site_dir = self.check_pth_processing() else: testfile = (self.pseudo_tempname() + '.wr...
'Empirically verify whether .pth files are supported in inst. dir'
def check_pth_processing(self):
instdir = self.install_dir log.info('Checking .pth file support in %s', instdir) pth_file = (self.pseudo_tempname() + '.pth') ok_file = (pth_file + '.ok') ok_exists = os.path.exists(ok_file) try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirnam...
'Write all the scripts for `dist`, unless scripts are excluded'
def install_egg_scripts(self, dist):
if ((not self.exclude_scripts) and dist.metadata_isdir('scripts')): for script_name in dist.metadata_listdir('scripts'): if dist.metadata_isdir(('scripts/' + script_name)): continue self.install_script(dist, script_name, dist.get_metadata(('scripts/' + script_name))) ...
'Sets the install directories by applying the install schemes.'
def select_scheme(self, name):
scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = ('install_' + key) if (getattr(self, attrname) is None): setattr(self, attrname, scheme[key])
'Generate a legacy script wrapper and install it'
def install_script(self, dist, script_name, script_text, dev_path=None):
spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) def get_template(filename): '\n There are a couple of template scripts in the package. This\n ...
'Write an executable file to the scripts directory'
def write_script(self, script_name, contents, mode='t', blockers=()):
self.delete_blockers([os.path.join(self.script_dir, x) for x in blockers]) log.info('Installing %s script to %s', script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) mask = current_umask() if (not self.dry_run): ensure_dir...
'Extract a bdist_wininst to the directories an egg would use'
def exe_to_egg(self, dist_filename, egg_tmp):
prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src, dst): s = src.lower() for (old, new) in prefixes: if s.startswith(old): src = (new + src[len(old):]) parts = src.split('/') ...
'Helpful installation message for display to package users'
def installation_report(self, req, dist, what='Installed'):
msg = '\n%(what)s %(eggloc)s%(extras)s' if (self.multi_version and (not self.no_report)): msg += '\n\nBecause this distribution was installed --multi-version, before you can\nimport modules from this package in an application, you will need to\...
'When easy_install is about to run bdist_egg on a source dist, that source dist might have \'setup_requires\' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.'
def _set_fetcher_options(self, base):
ei_opts = self.distribution.get_option_dict('easy_install').copy() fetch_directives = ('find_links', 'site_dirs', 'index_url', 'optimize', 'site_dirs', 'allow_hosts') fetch_options = {} for (key, val) in ei_opts.items(): if (key not in fetch_directives): continue fetch_option...
'Make sure there\'s a site.py in the target dir, if needed'
def install_site_py(self):
if self.sitepy_installed: return sitepy = os.path.join(self.install_dir, 'site.py') source = resource_string('setuptools', 'site-patch.py') current = '' if os.path.exists(sitepy): log.debug('Checking existing site.py in %s', self.install_dir) f = open(sitepy, 'rb'...
'Create directories under ~.'
def create_home_path(self):
if (not self.user): return home = convert_path(os.path.expanduser('~')) for (name, path) in iteritems(self.config_vars): if (path.startswith(home) and (not os.path.isdir(path))): self.debug_print(("os.makedirs('%s', 0700)" % path)) os.makedirs(path, 448)
'Write changed .pth file back to disk'
def save(self):
if (not self.dirty): return data = '\n'.join(map(self.make_relative, self.paths)) if data: log.debug('Saving %s', self.filename) data = ("import sys; sys.__plen = len(sys.path)\n%s\nimport sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=geta...
'Add `dist` to the distribution map'
def add(self, dist):
if ((dist.location not in self.paths) and ((dist.location not in self.sitedirs) or (dist.location == os.getcwd()))): self.paths.append(dist.location) self.dirty = True Environment.add(self, dist)
'Remove `dist` from the distribution map'
def remove(self, dist):
while (dist.location in self.paths): self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist)
'Yield write_script() argument tuples for a distribution\'s entrypoints'
@classmethod def get_script_args(cls, dist, executable=sys_executable, wininst=False):
gen_class = cls.get_writer(wininst) spec = str(dist.as_requirement()) header = get_script_header('', executable, wininst) for type_ in ('console', 'gui'): group = (type_ + '_scripts') for (name, ep) in dist.get_entry_map(group).items(): script_text = (gen_class.template % loc...
'Get a script writer suitable for Windows'
@classmethod def get_writer(cls):
writer_lookup = dict(executable=WindowsExecutableLauncherWriter, natural=cls) launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable') return writer_lookup[launcher]
'For Windows, add a .py extension'
@classmethod def _get_script_args(cls, type_, name, header, script_text):
ext = dict(console='.pya', gui='.pyw')[type_] if (ext not in os.environ['PATHEXT'].lower().split(';')): warnings.warn(('%s not listed in PATHEXT; scripts will not be recognized as executables.' % ext), UserWarning) old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', ...
'Make sure \'pythonw\' is used for gui and and \'python\' is used for console (regardless of what sys.executable is).'
@staticmethod def _adjust_header(type_, orig_header):
pattern = 'pythonw.exe' repl = 'python.exe' if (type_ == 'gui'): (pattern, repl) = (repl, pattern) pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE) new_header = pattern_ob.sub(string=orig_header, repl=repl) clean_header = new_header[2:(-1)].strip('"') if ((sys.platform == '...
'For Windows, add a .py extension and an .exe launcher'
@classmethod def _get_script_args(cls, type_, name, header, script_text):
if (type_ == 'gui'): launcher_type = 'gui' ext = '-script.pyw' old = ['.pyw'] else: launcher_type = 'cli' ext = '-script.py' old = ['.py', '.pyc', '.pyo'] hdr = cls._adjust_header(type_, header) blockers = [(name + x) for x in old] (yield ((name + ext)...
'Read the manifest file (named by \'self.manifest\') and use it to fill in \'self.filelist\', the list of files to include in the source distribution.'
def read_manifest(self):
log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest, 'rbU') for line in manifest: if (sys.version_info >= (3,)): try: line = line.decode('UTF-8') except UnicodeDecodeError: log.warn(('%r not UTF-8 ...
'Invoke reinitialized command `cmdname` with keyword args'
def call_command(self, cmdname, **kw):
for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd
'Create missing package __init__ files'
def make_init_files(self):
init_files = [] for (base, dirs, files) in walk_egg(self.bdist_dir): if (base == self.bdist_dir): continue for name in files: if name.endswith('.py'): if ('__init__.py' not in files): pkg = base[(len(self.bdist_dir) + 1):].replace(os.se...
'Copy metadata (egg info) to the target_dir'
def copy_metadata_to(self, target_dir):
norm_egg_info = os.path.normpath(self.egg_info) prefix = os.path.join(norm_egg_info, '') for path in self.ei_cmd.filelist.files: if path.startswith(prefix): target = os.path.join(target_dir, path[len(prefix):]) ensure_directory(target) self.copy_file(path, target)...
'Get a list of relative paths to C extensions in the output distro'
def get_ext_outputs(self):
all_outputs = [] ext_outputs = [] paths = {self.bdist_dir: ''} for (base, dirs, files) in os.walk(self.bdist_dir): for filename in files: if (os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS): all_outputs.append((paths[base] + filename)) for filename...
'Retrieve the directory revision informatino using svnversion'
def get_revision(self):
(code, data) = _run_command(['svnversion', '-c', self.path]) if code: log.warn('svnversion failed') return 0 parsed = self.revision_re.match(data) if parsed: return int(parsed.group(2)) else: return 0
'Iterate over the svn:external references in the repository path.'
def iter_externals(self):
for item in self.externals: (yield item)
'Iterate over the non-deleted file entries in the repository path'
def iter_files(self):
for (item, kind) in self.entries: if (kind.lower() == 'file'): (yield item)
'Iterate over the non-deleted file entries in the repository path'
def iter_dirs(self, include_root=True):
if include_root: (yield self.path) for (item, kind) in self.entries: if (kind.lower() == 'dir'): (yield item)
'Get repository URL'
def get_url(self):
urlre = re.compile('url="([^"]+)"') return urlre.search(self.data).group(1)
''
@skipIf((not test_svn._svn_check), 'No SVN to text, in the first place') def test_version_10_format(self):
version_str = svn_utils.SvnInfo.get_svn_version() version = [int(x) for x in version_str.split('.')[:2]] if (version != [1, 6]): if hasattr(self, 'skipTest'): self.skipTest('') else: sys.stderr.write('\n Skipping due to SVN Version\n') ...
''
def test_version_10_format_legacy_parser(self):
path_variable = None for env in os.environ: if (env.lower() == 'path'): path_variable = env if path_variable: old_path = os.environ[path_variable] os.environ[path_variable] = '' warning_filters = warnings.filters warnings.filters = warning_filters[:] try: ...
'A bad URL with a double scheme should raise a DistutilsError.'
def test_bad_url_double_scheme(self):
index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' try: index.open_url(url) except distutils.errors.DistutilsError: error = sys.exc_info()[1] msg = unicode(error) assert (('nonnumeric por...
'Download links from the pypi simple index should be used before external download links. https://bitbucket.org/tarek/distribute/issue/163 Usecase : - someone uploads a package on pypi, a md5 is generated - someone manually copies this link (with the md5 in the url) onto an external page accessible from the package pag...
def test_links_priority(self):
if sys.platform.startswith('java'): return server = IndexServer() server.start() index_url = (server.base_url() + 'test_links_priority/simple/') pi = setuptools.package_index.PackageIndex(index_url) requirement = pkg_resources.Requirement.parse('foobar') pi.find_packages(requirement)...
'Test the basic usage of _vcs_split_rev_from_url'
def test__vcs_split_rev_from_url(self):
vsrfu = setuptools.package_index.PackageIndex._vcs_split_rev_from_url (url, rev) = vsrfu('https://example.com/bar@2995') self.assertEqual(url, 'https://example.com/bar') self.assertEqual(rev, '2995')
'local_open should be able to read an index from the file system.'
def test_local_index(self):
f = open('index.html', 'w') f.write('<div>content</div>') f.close() try: url = (('file:' + pathname2url(os.getcwd())) + '/') res = setuptools.package_index.local_open(url) finally: os.remove('index.html') assert ('content' in res.read())
'Content checks should succeed silently if no hash is present'
def test_other_fragment(self):
checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#something%20completely%20different') checker.feed('anything'.encode('ascii')) self.assertTrue(checker.is_valid())
'Content checks should succeed if a hash is empty'
def test_blank_md5(self):
checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=') checker.feed('anything'.encode('ascii')) self.assertTrue(checker.is_valid())
'Stop the server'
def stop(self):
time.sleep(0.1) self._run = False url = ('http://127.0.0.1:%(server_port)s/' % vars(self)) try: if (sys.version_info >= (2, 6)): urllib2.urlopen(url, timeout=5) else: urllib2.urlopen(url) except URLError: pass self.thread.join() self.socket.clo...
'The setuptools project should implement the setuptools package.'
def testSetuptoolsProjectName(self):
self.assertEqual(Requirement.parse('setuptools').project_name, 'setuptools') self.assertEqual(Requirement.parse('setuptools == 0.7').project_name, 'setuptools') self.assertEqual(Requirement.parse('setuptools == 0.7a1').project_name, 'setuptools') self.assertEqual(Requirement.parse('setuptool...
'assertIn and assertTrue does not exist in Python2.3'
def _assertIn(self, member, container):
if (member not in container): standardMsg = ('%s not found in %s' % (safe_repr(member), safe_repr(container))) self.fail(self._formatMessage(msg, standardMsg))
'Test nested namespace packages Create namespace packages in the following tree : site-packages-1/pkg1/pkg2 site-packages-2/pkg1/pkg2 Check both are in the _namespace_packages dict and that their __path__ is correct'
def test_two_levels_deep(self):
sys.path.append(os.path.join(self._tmpdir, 'site-pkgs2')) os.makedirs(os.path.join(self._tmpdir, 'site-pkgs', 'pkg1', 'pkg2')) os.makedirs(os.path.join(self._tmpdir, 'site-pkgs2', 'pkg1', 'pkg2')) ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n" for site in ['site-pkgs', 'site-pk...
'It should be possible to execute a setup.py with a Byte Order Mark'
def test_setup_py_with_BOM(self):
target = pkg_resources.resource_filename(__name__, 'script-with-bom.py') namespace = types.ModuleType('namespace') setuptools.sandbox.execfile(target, vars(namespace)) assert (namespace.result == 'passed')
'Create a new DocTest containing the given examples. The DocTest\'s globals are initialized with a copy of `globs`.'
def __init__(self, examples, globs, name, filename, lineno, docstring):
assert (not isinstance(examples, basestring)), 'DocTest no longer accepts str; use DocTestParser instead' self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno
'Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages.'
def parse(self, string, name='<string>'):
string = string.expandtabs() min_indent = self._min_indent(string) if (min_indent > 0): string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] (charno, lineno) = (0, 0) for m in self._EXAMPLE_RE.finditer(string): output.append(string[charno:m.start()]) ...
'Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information.'
def get_doctest(self, string, globs, name, filename, lineno):
return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
'Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it\'s most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called "line 1" then. The optional argumen...
def get_examples(self, string, name='<string>'):
return [x for x in self.parse(string, name) if isinstance(x, Example)]
'Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example\'s source code (with prompts and indentation stripped); and `want` is the example\'s expected output (with indentation stripped). `name` is the string\'s name, and `lineno` is the line numbe...
def _parse_example(self, m, name, lineno):
indent = len(m.group('indent')) source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno) source = '\n'.join([sl[(indent + 4):] for sl in source_lines]) want = m.group('w...
'Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string\'s name, and `lineno` is the line number where the example starts; both are used for error messages.'
def _find_options(self, source, name, lineno):
options = {} for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)): raise ValueError(('line %r of the...
'Return the minimum indentation of any non-blank line in `s`'
def _min_indent(self, s):
indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if (len(indents) > 0): return min(indents) else: return 0
'Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError.'
def _check_prompt_blank(self, lines, indent, name, lineno):
for (i, line) in enumerate(lines): if ((len(line) >= (indent + 4)) and (line[(indent + 3)] != ' ')): raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), name, line[indent:(indent + 3)], line)))
'Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError.'
def _check_prefix(self, lines, prefix, name, lineno):
for (i, line) in enumerate(lines): if (line and (not line.startswith(prefix))): raise ValueError(('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (((lineno + i) + 1), name, line)))
'Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument...
def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True):
self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty self._namefilter = _namefilter
'Return a list of the DocTests that are defined by the given object\'s docstring, or by any of its contained objects\' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the co...
def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
if (name is None): name = getattr(obj, '__name__', None) if (name is None): raise ValueError(("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))) if (module is False): module = None elif (module is None)...
'Return true if the given object should not be examined.'
def _filter(self, obj, prefix, base):
return ((self._namefilter is not None) and self._namefilter(prefix, base))
'Return true if the given object is defined in the given module.'
def _from_module(self, module, object):
if (module is None): return True elif inspect.isfunction(object): return (module.__dict__ is func_globals(object)) elif inspect.isclass(object): return (module.__name__ == object.__module__) elif (inspect.getmodule(object) is not None): return (module is inspect.getmodule...
'Find tests for the given object and any contained objects, and add them to `tests`.'
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if self._verbose: print ('Finding tests in %s' % name) if (id(obj) in seen): return seen[id(obj)] = 1 test = self._get_test(obj, name, module, globs, source_lines) if (test is not None): tests.append(test) if (inspect.ismodule(obj) and self._recurse): for...
'Return a DocTest for the given object, if it defines a docstring; otherwise, return None.'
def _get_test(self, obj, name, module, globs, source_lines):
if isinstance(obj, basestring): docstring = obj else: try: if (obj.__doc__ is None): docstring = '' else: docstring = obj.__doc__ if (not isinstance(docstring, basestring)): docstring = str(docstring) ...
'Return a line number of the given object\'s docstring. Note: this method assumes that the object has a docstring.'
def _find_lineno(self, obj, source_lines):
lineno = None if inspect.ismodule(obj): lineno = 0 if inspect.isclass(obj): if (source_lines is None): return None pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))) for (i, line) in enumerate(source_lines): if pat.match(line): ...
'Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg \'verbose\' prints lots of stuff if true, only failures if false; by default, it\'s true iff \'-v\' is in sys.argv. Optional a...
def __init__(self, checker=None, verbose=None, optionflags=0):
self._checker = (checker or OutputChecker()) if (verbose is None): verbose = ('-v' in sys.argv) self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags self.tries = 0 self.failures = 0 self._name2ft = {} self._fakeout = _SpoofOut()
'Report that the test runner is about to process the given example. (Only displays a message if verbose=True)'
def report_start(self, out, test, example):
if self._verbose: if example.want: out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want))) else: out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
'Report that the given example ran successfully. (Only displays a message if verbose=True)'
def report_success(self, out, test, example, got):
if self._verbose: out('ok\n')
'Report that the given example failed.'
def report_failure(self, out, test, example, got):
out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
'Report that the given example raised an unexpected exception.'
def report_unexpected_exception(self, out, test, example, exc_info):
out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
'Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the num...
def __run(self, test, compileflags, out):
failures = tries = 0 original_optionflags = self.optionflags (SUCCESS, FAILURE, BOOM) = range(3) check = self._checker.check_output for (examplenum, example) in enumerate(test.examples): quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0)) self.optionflags = or...
'Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples.'
def __record_outcome(self, test, f, t):
(f2, t2) = self._name2ft.get(test.name, (0, 0)) self._name2ft[test.name] = ((f + f2), (t + t2)) self.failures += f self.tries += t
'Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after t...
def run(self, test, compileflags=None, out=None, clear_globs=True):
self.test = test if (compileflags is None): compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if (out is None): out = save_stdout.write sys.stdout = self._fakeout save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) sel...