From 9b2e18e4d1b95ef505f87561ac06aba50ada3609 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 21 Oct 2013 20:39:09 +0200 Subject: doc/examples/*.py: Update examples to the new API Closes: #639022 --- doc/examples/sources.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'doc/examples/sources.py') diff --git a/doc/examples/sources.py b/doc/examples/sources.py index bc08ad69..238ca48c 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -8,9 +8,9 @@ apt_pkg.init() #sources = apt_pkg.SourceRecords(cache) sources = apt_pkg.SourceRecords() -sources.Restart() -while sources.Lookup('hello'): - print sources.Package, sources.Version, sources.Maintainer, \ - sources.Section, `sources.Binaries` - print sources.Files - print sources.Index.ArchiveURI(sources.Files[0][2]) +sources.restart() +while sources.lookup('hello'): + print sources.package, sources.version, sources.maintainer, \ + sources.section, `sources.binaries` + print sources.files + print sources.index.archive_uri(sources.files[0][2]) -- cgit v1.2.3 From 3bf9c3fe4d19ed4d985dc8b7747a737699f46a7e Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Tue, 31 Dec 2013 23:25:13 +0100 Subject: make test_pep8.py pass --- apt/auth.py | 39 +++++---- apt/debfile.py | 148 ++++++++++++++++++++++------------- apt/package.py | 12 +-- apt/progress/gtk2.py | 8 +- apt/progress/text.py | 9 ++- apt/utils.py | 2 +- aptsources/distinfo.py | 11 ++- aptsources/distro.py | 45 +++++------ aptsources/sourceslist.py | 38 ++++----- doc/examples/acquire.py | 7 +- doc/examples/action.py | 2 +- doc/examples/architecture.py | 2 +- doc/examples/build-deps-old.py | 2 +- doc/examples/checkstate.py | 4 +- doc/examples/deb_inspect.py | 4 +- doc/examples/depcache.py | 2 +- doc/examples/inst.py | 2 +- doc/examples/progress.py | 9 ++- doc/examples/sources.py | 2 +- doc/source/conf.py | 9 +-- doc/source/examples/cache-pkgfile.py | 2 +- setup.py | 16 ++-- tests/old/__init__.py | 1 - tests/old/cache.py | 4 +- tests/old/depcache.py | 6 +- tests/old/pkgproblemresolver.py | 6 +- tests/old/pkgrecords.py | 2 +- tests/old/pkgsrcrecords.py | 2 +- tests/old/refcount.py | 5 +- tests/test_all.py | 9 ++- tests/test_apt_cache.py | 43 +++++----- tests/test_aptsources.py | 12 ++- tests/test_auth.py | 11 ++- tests/test_configuration.py | 5 +- tests/test_debfile.py | 30 ++++--- tests/test_debfile_multiarch.py | 7 +- tests/test_group.py | 1 - tests/test_hashes.py | 2 +- tests/test_lp659438.py | 2 +- tests/test_paths.py | 10 ++- tests/test_pep8.py | 2 +- tests/test_policy.py | 2 +- tests/test_progress.py | 5 +- tests/test_size_to_str.py | 136 ++++++++++++++++---------------- tests/test_tagfile.py | 1 + tests/test_utils.py | 22 ++++-- utils/doclint.py | 21 +++-- utils/get_ubuntu_mirrors.py | 2 +- 48 files changed, 399 insertions(+), 325 deletions(-) (limited to 'doc/examples/sources.py') diff --git a/apt/auth.py b/apt/auth.py index d5a66b4a..acc612a9 100644 --- a/apt/auth.py +++ b/apt/auth.py @@ -67,7 +67,8 @@ def _call_apt_key_script(*args, **kwargs): # configuration from the chroot to the apt-key script by using # a temporary APT_CONFIG file. The apt-key script uses apt-config # shell internally - conf = tempfile.NamedTemporaryFile(prefix="apt-key", suffix=".conf") + conf = tempfile.NamedTemporaryFile( + prefix="apt-key", suffix=".conf") conf.write(apt_pkg.config.dump().encode("UTF-8")) conf.flush() env["APT_CONFIG"] = conf.name @@ -84,11 +85,12 @@ def _call_apt_key_script(*args, **kwargs): output, stderr = proc.communicate(content) if proc.returncode: - raise AptKeyError("The apt-key script failed with return code %s:\n" - "%s\n" - "stdout: %s\n" - "stderr: %s" % (proc.returncode, " ".join(cmd), - output,stderr)) + raise AptKeyError( + "The apt-key script failed with return code %s:\n" + "%s\n" + "stdout: %s\n" + "stderr: %s" % ( + proc.returncode, " ".join(cmd), output, stderr)) elif stderr: sys.stderr.write(stderr) # Forward stderr @@ -97,6 +99,7 @@ def _call_apt_key_script(*args, **kwargs): if conf is not None: conf.close() + def add_key_from_file(filename): """Import a GnuPG key file to trust repositores signed by it. @@ -109,6 +112,7 @@ def add_key_from_file(filename): raise AptKeyError("Key file cannot be accessed: %s" % filename) _call_apt_key_script("add", filename) + def add_key_from_keyserver(keyid, keyserver): """Import a GnuPG key file to trust repositores signed by it. @@ -125,8 +129,9 @@ def add_key_from_keyserver(keyid, keyserver): finally: shutil.rmtree(tmp_keyring_dir) + def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): - if len(keyid) < 160/8: + if len(keyid) < (160 / 8): raise AptKeyError("Only long keyids (v4, 160bit) are supported") # create a temp keyring dir tmp_secret_keyring = os.path.join(tmp_keyring_dir, "secring.gpg") @@ -136,14 +141,14 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "gpg", "--no-default-keyring", "--no-options", "--homedir", tmp_keyring_dir, - ] + ] # download the key to a temp keyring first res = subprocess.call(gpg_default_options + [ "--secret-keyring", tmp_secret_keyring, "--keyring", tmp_keyring, "--keyserver", keyserver, "--recv", keyid, - ]) + ]) if res != 0: raise AptKeyError("recv from '%s' failed for '%s'" % ( keyserver, keyid)) @@ -154,7 +159,7 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "--keyring", tmp_keyring, "--output", tmp_export_keyring, "--export", keyid, - ]) + ]) if res != 0: raise AptKeyError("export of '%s' failed", keyid) # now verify the fingerprint, this is probably redundant as we @@ -166,10 +171,10 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "--fingerprint", "--batch", "--with-colons", - ], - stdout=subprocess.PIPE, - universal_newlines=True).communicate()[0] - got_fingerprint=None + ], + stdout=subprocess.PIPE, + universal_newlines=True).communicate()[0] + got_fingerprint = None for line in output.splitlines(): if line.startswith("fpr:"): got_fingerprint = line.split(":")[9] @@ -185,6 +190,7 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): # finally add it add_key_from_file(tmp_export_keyring) + def add_key(content): """Import a GnuPG key to trust repositores signed by it. @@ -194,6 +200,7 @@ def add_key(content): _call_apt_key_script("adv", "--quiet", "--batch", "--import", "-", stdin=content) + def remove_key(fingerprint): """Remove a GnuPG key to no longer trust repositores signed by it. @@ -202,6 +209,7 @@ def remove_key(fingerprint): """ _call_apt_key_script("rm", fingerprint) + def export_key(fingerprint): """Return the GnuPG key in text format. @@ -210,6 +218,7 @@ def export_key(fingerprint): """ return _call_apt_key_script("export", fingerprint) + def update(): """Update the local keyring with the archive keyring and remove from the local keyring the archive keys which are no longer valid. The @@ -218,6 +227,7 @@ def update(): """ return _call_apt_key_script("update") + def net_update(): """Work similar to the update command above, but get the archive keyring from an URI instead and validate it against a master key. @@ -228,6 +238,7 @@ def net_update(): """ return _call_apt_key_script("net-update") + def list_keys(): """Returns a list of TrustedKey instances for each key which is used to trust repositories. diff --git a/apt/debfile.py b/apt/debfile.py index c845b1f2..679c8468 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -27,17 +27,19 @@ import sys from apt_pkg import gettext as _ from StringIO import StringIO + class NoDebArchiveException(IOError): """Exception which is raised if a file is no Debian archive.""" + class DebPackage(object): """A Debian Package (.deb file).""" # Constants for comparing the local package file with the version # in the cache - (VERSION_NONE, - VERSION_OUTDATED, - VERSION_SAME, + (VERSION_NONE, + VERSION_OUTDATED, + VERSION_SAME, VERSION_NEWER) = range(4) debug = 0 @@ -68,7 +70,7 @@ class DebPackage(object): self._sections = apt_pkg.TagSection(control) self.pkgname = self._sections["Package"] self._check_was_run = False - + def __getitem__(self, key): return self._sections[key] @@ -91,15 +93,15 @@ class DebPackage(object): """ return the list of files in control.tar.gt """ control = [] try: - self._debfile.control.go(lambda item, data: control.append(item.name)) + self._debfile.control.go( + lambda item, data: control.append(item.name)) except SystemError: return [_("List of control files for '%s' could not be read") % self.filename] return sorted(control) - # helper that will return a pkgname with a multiarch suffix if needed - def _maybe_append_multiarch_suffix(self, pkgname, + def _maybe_append_multiarch_suffix(self, pkgname, in_conflict_checking=False): # trivial cases if ":" in pkgname: @@ -108,7 +110,7 @@ class DebPackage(object): return pkgname elif self._cache.is_virtual_package(pkgname): return pkgname - elif (pkgname in self._cache and + elif (pkgname in self._cache and self._cache[pkgname].candidate and self._cache[pkgname].candidate.architecture == "all"): return pkgname @@ -126,7 +128,7 @@ class DebPackage(object): return pkgname # for conflicts we need a special case here, any not multiarch enabled # package has a implicit conflict - if (in_conflict_checking and + if (in_conflict_checking and not (cand.multi_arch & cand.MULTI_ARCH_SAME)): return pkgname return multiarch_pkgname @@ -150,7 +152,9 @@ class DebPackage(object): # check for virtual pkgs if not depname in self._cache: if self._cache.is_virtual_package(depname): - self._dbg(3, "_is_or_group_satisfied(): %s is virtual dep" % depname) + self._dbg( + 3, "_is_or_group_satisfied(): %s is virtual dep" % + depname) for pkg in self._cache.get_providing_packages(depname): if pkg.is_installed: return True @@ -163,13 +167,15 @@ class DebPackage(object): # if no real dependency is installed, check if there is # a package installed that provides this dependency # (e.g. scrollkeeper dependecies are provided by rarian-compat) - # but only do that if there is no version required in the + # but only do that if there is no version required in the # dependency (we do not supprot versionized dependencies) if not oper: for ppkg in self._cache.get_providing_packages( depname, include_nonvirtual=True): if ppkg.is_installed: - self._dbg(3, "found installed '%s' that provides '%s'" % (ppkg.name, depname)) + self._dbg( + 3, "found installed '%s' that provides '%s'" % ( + ppkg.name, depname)) return True return False @@ -212,16 +218,19 @@ class DebPackage(object): or_str += dep[0] if ver and oper: or_str += " (%s %s)" % (dep[2], dep[1]) - if dep != or_group[len(or_group)-1]: + if dep != or_group[len(or_group) - 1]: or_str += "|" - self._failure_string += _("Dependency is not satisfiable: %s\n") % or_str + self._failure_string += _( + "Dependency is not satisfiable: %s\n") % or_str return False def _check_single_pkg_conflict(self, pkgname, ver, oper): """Return True if a pkg conflicts with a real installed/marked pkg.""" # FIXME: deal with conflicts against its own provides # (e.g. Provides: ftp-server, Conflicts: ftp-server) - self._dbg(3, "_check_single_pkg_conflict() pkg='%s' ver='%s' oper='%s'" % (pkgname, ver, oper)) + self._dbg( + 3, "_check_single_pkg_conflict() pkg='%s' ver='%s' oper='%s'" % ( + pkgname, ver, oper)) pkg = self._cache[pkgname] if pkg.is_installed: pkgver = pkg.installed.version @@ -265,8 +274,8 @@ class DebPackage(object): if self.pkgname == pkg.name: self._dbg(3, "conflict on self, ignoring") continue - if self._check_single_pkg_conflict(pkg.name, ver, - oper): + if self._check_single_pkg_conflict( + pkg.name, ver, oper): self._installed_conflicts.add(pkg.name) continue if self._check_single_pkg_conflict(depname, ver, oper): @@ -289,7 +298,8 @@ class DebPackage(object): # find depends for key in "Depends", "Pre-Depends": try: - depends.extend(apt_pkg.parse_depends(self._sections[key], False)) + depends.extend( + apt_pkg.parse_depends(self._sections[key], False)) except KeyError: pass return depends @@ -349,22 +359,22 @@ class DebPackage(object): return res def check_breaks_existing_packages(self): - """ - check if installing the package would break exsisting + """ + check if installing the package would break exsisting package on the system, e.g. system has: smc depends on smc-data (= 1.4) and user tries to installs smc-data 1.6 """ # show progress information as this step may take some time size = float(len(self._cache)) - steps = max(int(size/50), 1) + steps = max(int(size / 50), 1) debver = self._sections["Version"] debarch = self._sections["Architecture"] # store what we provide so that we can later check against that - provides = [ x[0][0] for x in self.provides] + provides = [x[0][0] for x in self.provides] for (i, pkg) in enumerate(self._cache): - if i%steps == 0: - self._cache.op_progress.update(float(i)/size*100.0) + if i % steps == 0: + self._cache.op_progress.update(float(i) / size * 100.0) if not pkg.is_installed: continue # check if the exising dependencies are still satisfied @@ -373,14 +383,21 @@ class DebPackage(object): for dep_or in pkg.installed.dependencies: for dep in dep_or.or_dependencies: if dep.name == self.pkgname: - if not apt_pkg.check_dep(debver, dep.relation, dep.version): + if not apt_pkg.check_dep( + debver, dep.relation, dep.version): self._dbg(2, "would break (depends) %s" % pkg.name) - # TRANSLATORS: the first '%s' is the package that breaks, the second the dependency that makes it break, the third the relation (e.g. >=) and the latest the version for the releation - self._failure_string += _("Breaks existing package '%(pkgname)s' dependency %(depname)s (%(deprelation)s %(depversion)s)") % { - 'pkgname' : pkg.name, - 'depname' : dep.name, - 'deprelation' : dep.relation, - 'depversion' : dep.version} + # TRANSLATORS: the first '%s' is the package that + # breaks, the second the dependency that makes it + # break, the third the relation (e.g. >=) and the + # latest the version for the releation + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "dependency %(depname)s " + "(%(deprelation)s %(depversion)s)") % { + 'pkgname': pkg.name, + 'depname': dep.name, + 'deprelation': dep.relation, + 'depversion': dep.version} self._cache.op_progress.done() return False # now check if there are conflicts against this package on @@ -388,25 +405,41 @@ class DebPackage(object): if "Conflicts" in ver.depends_list: for conflicts_ver_list in ver.depends_list["Conflicts"]: for c_or in conflicts_ver_list: - if c_or.target_pkg.name == self.pkgname and c_or.target_pkg.architecture == debarch: - if apt_pkg.check_dep(debver, c_or.comp_type, c_or.target_ver): - self._dbg(2, "would break (conflicts) %s" % pkg.name) - # TRANSLATORS: the first '%s' is the package that conflicts, the second the packagename that it conflicts with (so the name of the deb the user tries to install), the third is the relation (e.g. >=) and the last is the version for the relation - self._failure_string += _("Breaks existing package '%(pkgname)s' conflict: %(targetpkg)s (%(comptype)s %(targetver)s)") % { - 'pkgname' : pkg.name, - 'targetpkg' : c_or.target_pkg.name, - 'comptype' : c_or.comp_type, - 'targetver' : c_or.target_ver } + if (c_or.target_pkg.name == self.pkgname and + c_or.target_pkg.architecture == debarch): + if apt_pkg.check_dep( + debver, c_or.comp_type, c_or.target_ver): + self._dbg( + 2, "would break (conflicts) %s" % pkg.name) + # TRANSLATORS: the first '%s' is the package + # that conflicts, the second the packagename + # that it conflicts with (so the name of the + # deb the user tries to install), the third is + # the relation (e.g. >=) and the last is the + # version for the relation + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "conflict: %(targetpkg)s " + "(%(comptype)s %(targetver)s)") % { + 'pkgname': pkg.name, + 'targetpkg': c_or.target_pkg.name, + 'comptype': c_or.comp_type, + 'targetver': c_or.target_ver} self._cache.op_progress.done() return False if (c_or.target_pkg.name in provides and self.pkgname != pkg.name): - self._dbg(2, "would break (conflicts) %s" % provides) - self._failure_string += _("Breaks existing package '%(pkgname)s' that conflict: '%(targetpkg)s'. But the '%(debfile)s' provides it via: '%(provides)s'") % { - 'provides' : ",".join(provides), - 'debfile' : self.filename, - 'targetpkg' : c_or.target_pkg.name, - 'pkgname' : pkg.name } + self._dbg( + 2, "would break (conflicts) %s" % provides) + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "that conflict: '%(targetpkg)s'. But the " + "'%(debfile)s' provides it via: " + "'%(provides)s'") % { + 'provides': ",".join(provides), + 'debfile': self.filename, + 'targetpkg': c_or.target_pkg.name, + 'pkgname': pkg.name} self._cache.op_progress.done() return False self._cache.op_progress.done() @@ -453,7 +486,7 @@ class DebPackage(object): self._failure_string = _("No Architecture field in the package") return False arch = self._sections["Architecture"] - if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): + if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): if arch in apt_pkg.get_architectures(): self._multiarch = arch self.pkgname = "%s:%s" % (self.pkgname, self._multiarch) @@ -467,7 +500,8 @@ class DebPackage(object): if self.compare_to_version_in_cache() == self.VERSION_OUTDATED: if self._cache[self.pkgname].installed: # the deb is older than the installed - self._failure_string = _("A later version is already installed") + self._failure_string = _( + "A later version is already installed") return False # FIXME: this sort of error handling sux @@ -477,7 +511,7 @@ class DebPackage(object): if not self.check_conflicts(): return False - # check if installing it would break anything on the + # check if installing it would break anything on the # current system if not self.check_breaks_existing_packages(): return False @@ -513,8 +547,6 @@ class DebPackage(object): pass # check depends for or_group in depends: - #print "or_group: %s" % or_group - #print "or_group satified: %s" % self._is_or_group_satisfied(or_group) if not self._is_or_group_satisfied(or_group): if not self._satisfy_or_group(or_group): return False @@ -533,7 +565,8 @@ class DebPackage(object): """Return missing dependencies.""" self._dbg(1, "Installing: %s" % self._need_pkgs) if not self._check_was_run: - raise AttributeError("property only available after check() was run") + raise AttributeError( + "property only available after check() was run") return self._need_pkgs @property @@ -546,7 +579,8 @@ class DebPackage(object): remove = [] unauthenticated = [] if not self._check_was_run: - raise AttributeError("property only available after check() was run") + raise AttributeError( + "property only available after check() was run") for pkg in self._cache: if pkg.marked_install or pkg.marked_upgrade: install.append(pkg.name) @@ -565,7 +599,7 @@ class DebPackage(object): def to_hex(in_data): hex = "" for (i, c) in enumerate(in_data): - if i%80 == 0: + if i % 80 == 0: hex += "\n" hex += "%2.2x " % ord(c) return hex @@ -588,7 +622,7 @@ class DebPackage(object): else: s += chr(b) return s - + def _get_content(self, part, name, auto_decompress=True, auto_hex=True): if name.startswith("./"): name = name[2:] @@ -643,6 +677,7 @@ class DebPackage(object): install_progress.finishUpdate() return res + class DscSrcPackage(DebPackage): """A locally available source package.""" @@ -698,7 +733,7 @@ class DscSrcPackage(DebPackage): " ".join(self.binaries)) self._sections["Description"] = s self._check_was_run = False - + def check(self): """Check if the package is installable..""" if not self.check_conflicts(): @@ -712,6 +747,7 @@ class DscSrcPackage(DebPackage): # after _satisfy_depends() should probably be done return self._satisfy_depends(self.depends) + def _test(): """Test function""" from apt.cache import Cache diff --git a/apt/package.py b/apt/package.py index 79dac71d..d4217195 100644 --- a/apt/package.py +++ b/apt/package.py @@ -26,16 +26,8 @@ import re import socket import subprocess import urllib2 -try: - from collections import Mapping, Sequence -except ImportError: - # (for Python < 2.6) pylint: disable-msg=C0103 - Sequence = Mapping = object - -try: - from collections import Sequence -except ImportError: - Sequence = object + +from collections import Mapping, Sequence import apt_pkg import apt.progress.text diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index 63e531fa..b978c34f 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -27,6 +27,7 @@ pygtk.require('2.0') import gtk try: import glib + glib # pyflakes except ImportError: import gobject as glib import gobject @@ -87,7 +88,6 @@ class GOpProgress(gobject.GObject, base.OpProgress): self.emit("status-finished") - class GInstallProgress(gobject.GObject, base.InstallProgress): """Installation progress with GObject signals. @@ -241,12 +241,12 @@ class GAcquireProgress(gobject.GObject, base.AcquireProgress): current_item = self.total_items if self.current_cps > 0: text = (_("Downloading file %(current)li of %(total)li with " - "%(speed)s/s") % \ + "%(speed)s/s") % {"current": current_item, "total": self.total_items, "speed": apt_pkg.size_to_str(self.current_cps)}) else: - text = (_("Downloading file %(current)li of %(total)li") % \ + text = (_("Downloading file %(current)li of %(total)li") % {"current": current_item, "total": self.total_items}) @@ -358,7 +358,7 @@ class GtkAptProgress(gtk.VBox): if percent is None or percent == -1: self._progressbar.pulse() else: - self._progressbar.set_fraction(percent/100.0) + self._progressbar.set_fraction(percent / 100.0) while gtk.events_pending(): gtk.main_iteration() diff --git a/apt/progress/text.py b/apt/progress/text.py index c5eec092..76a4309e 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -47,7 +47,7 @@ class TextProgress(object): # Fill remaining stuff with whitespace if self._width > len(msg): self._file.write((self._width - len(msg)) * ' ') - elif maximize: # Needed for OpProgress. + elif maximize: # Needed for OpProgress. self._width = max(self._width, len(msg)) if newline: self._file.write("\n") @@ -114,7 +114,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress): import struct buf = fcntl.ioctl(self._file, termios.TIOCGWINSZ, 8 * ' ') dummy, col, dummy, dummy = struct.unpack('hhhh', buf) - self._width = col - 1 # 1 for the cursor + self._width = col - 1 # 1 for the cursor def ims_hit(self, item): """Called when an item is update (e.g. not modified on the server).""" @@ -188,8 +188,9 @@ class AcquireProgress(base.AcquireProgress, TextProgress): # Add the total size and percent if worker.total_size and not worker.current_item.owner.complete: - val += "/%sB %i%%" % (apt_pkg.size_to_str(worker.total_size), - worker.current_size*100.0/worker.total_size) + val += "/%sB %i%%" % ( + apt_pkg.size_to_str(worker.total_size), + worker.current_size * 100.0 / worker.total_size) val += ']' diff --git a/apt/utils.py b/apt/utils.py index 08140258..9451f4bc 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -32,7 +32,7 @@ def get_maintenance_end_date(release_date, m_months): years = m_months // 12 months = m_months % 12 support_end_year = (release_date.year + years + - (release_date.month + months)//12) + (release_date.month + months) // 12) support_end_month = (release_date.month + months) % 12 # special case: this happens when e.g. doing 2010-06 + 18 months if support_end_month == 0: diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index d80721e5..b03e68f8 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -33,6 +33,7 @@ import apt_pkg from apt_pkg import gettext as _ + class Template(object): def __init__(self): @@ -152,9 +153,7 @@ def split_url(url): class DistInfo(object): - def __init__(self, - dist = None, - base_dir = "/usr/share/python-apt/templates"): + def __init__(self, dist=None, base_dir="/usr/share/python-apt/templates"): self.metarelease_uri = '' self.templates = [] self.arch = apt_pkg.config.find("APT::Architecture") @@ -196,7 +195,7 @@ class DistInfo(object): self.metarelease_uri = value elif field == 'Suite': self.finish_template(template, component) - component=None + component = None template = Template() template.name = value template.distribution = dist @@ -265,8 +264,8 @@ class DistInfo(object): elif field == 'ParentComponent': component.set_parent_component(value) self.finish_template(template, component) - template=None - component=None + template = None + component = None def finish_template(self, template, component): " finish the current tempalte " diff --git a/aptsources/distro.py b/aptsources/distro.py index e9facbfb..a71d5af2 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -85,7 +85,7 @@ class Distribution(object): break if self.source_template is None: raise NoDistroTemplateException( - "Error: could not find a distribution template for %s/%s" % + "Error: could not find a distribution template for %s/%s" % (self.id, self.codename)) # find main and child sources @@ -95,40 +95,40 @@ class Distribution(object): enabled_comps = [] #source_code = [] for source in self.sourceslist.list: - if (source.invalid == False and + if (source.invalid is False and self.is_codename(source.dist) and source.template and - source.template.official == True and + source.template.official is True and self.is_codename(source.template.name)): #print "yeah! found a distro repo: %s" % source.line # cdroms need do be handled differently if (source.uri.startswith("cdrom:") and - source.disabled == False): + source.disabled is False): self.cdrom_sources.append(source) cdrom_comps.extend(source.comps) elif (source.uri.startswith("cdrom:") and - source.disabled == True): + source.disabled is True): self.cdrom_sources.append(source) elif (source.type == self.binary_type and - source.disabled == False): + source.disabled is False): self.main_sources.append(source) comps.extend(source.comps) media.append(source.uri) elif (source.type == self.binary_type and - source.disabled == True): + source.disabled is True): self.disabled_sources.append(source) elif (source.type == self.source_type - and source.disabled == False): + and source.disabled is False): self.source_code_sources.append(source) elif (source.type == self.source_type and - source.disabled == True): + source.disabled is True): self.disabled_sources.append(source) - if (source.invalid == False and + if (source.invalid is False and source.template in self.source_template.children): - if (source.disabled == False + if (source.disabled is False and source.type == self.binary_type): self.child_sources.append(source) - elif (source.disabled == False + elif (source.disabled is False and source.type == self.source_type): self.source_code_sources.append(source) else: @@ -189,7 +189,7 @@ class Distribution(object): z = locale.find(".") if z == -1: z = len(locale) - country_code = locale[a+1:z].lower() + country_code = locale[a + 1:z].lower() if mirror_template: self.nearest_server = mirror_template % country_code @@ -205,7 +205,7 @@ class Distribution(object): i = server.find("://") l = server.find(".archive.ubuntu.com") if i != -1 and l != -1: - country = server[i+len("://"):l] + country = server[i + len("://"):l] if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % self.countries[country] @@ -280,10 +280,11 @@ class Distribution(object): new_source = self.sourceslist.add(type, uri, dist, comps, comment) # if source code is enabled add a deb-src line after the new # source - if self.get_source_code == True and type == self.binary_type: - self.sourceslist.add(self.source_type, uri, dist, comps, comment, - file=new_source.file, - pos=self.sourceslist.list.index(new_source)+1) + if self.get_source_code is True and type == self.binary_type: + self.sourceslist.add( + self.source_type, uri, dist, comps, comment, + file=new_source.file, + pos=self.sourceslist.list.index(new_source) + 1) def enable_component(self, comp): """ @@ -344,7 +345,7 @@ class Distribution(object): # check if there is a main source at all if len(self.main_sources) < 1: # create a new main source - self.add_source(comps=["%s"%comp]) + self.add_source(comps=["%s" % comp]) else: # add the comp to all main, child and source code sources for source in sources: @@ -354,10 +355,10 @@ class Distribution(object): add_component_only_once(source, comps_per_sdist) # check if there is a main source code source at all - if self.get_source_code == True: + if self.get_source_code is True: if len(self.source_code_sources) < 1: # create a new main source - self.add_source(type=self.source_type, comps=["%s"%comp]) + self.add_source(type=self.source_type, comps=["%s" % comp]) else: # add the comp to all main, child and source code sources for source in self.source_code_sources: @@ -435,7 +436,7 @@ class DebianDistribution(Distribution): i = server.find("://ftp.") l = server.find(".debian.org") if i != -1 and l != -1: - country = server[i+len("://ftp."):l] + country = server[i + len("://ftp."):l] if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % gettext.dgettext( diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 69e7e107..1b68d52e 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -62,12 +62,12 @@ def is_mirror(master_uri, compare_uri): compare_srv = compare_uri.split("//")[1] master_srv = master_uri.split("//")[1] #print "%s == %s " % (add_srv, orig_srv) - except IndexError: # ok, somethings wrong here + except IndexError: # ok, somethings wrong here #print "IndexError" return False # remove the leading "." (if any) and see if that helps if "." in compare_srv and \ - compare_srv[compare_srv.index(".")+1:] == master_srv: + compare_srv[compare_srv.index(".") + 1:] == master_srv: #print "Mirror" return True return False @@ -100,7 +100,7 @@ class SourceEntry(object): self.line = line # the original sources.list line if file is None: file = apt_pkg.config.find_dir( - "Dir::Etc")+apt_pkg.config.find("Dir::Etc::sourcelist") + "Dir::Etc") + apt_pkg.config.find("Dir::Etc::sourcelist") self.file = file # the file that the entry is located in self.parse(line) self.template = None # type DistInfo.Suite @@ -131,10 +131,10 @@ class SourceEntry(object): pieces.append(tmp) tmp = line[i] else: - p_found=True + p_found = True tmp += line[i] elif line[i] == "]": - p_found=False + p_found = False tmp += line[i] elif space_found and not line[i].isspace(): # we skip one or more space @@ -157,7 +157,7 @@ class SourceEntry(object): line = self.line.strip() #print line # check if the source is enabled/disabled - if line == "" or line == "#": # empty line + if line == "" or line == "#": # empty line self.invalid = True return if line[0] == "#": @@ -172,7 +172,7 @@ class SourceEntry(object): # check for another "#" in the line (this is treated as a comment) i = line.find("#") if i > 0: - self.comment = line[i+1:] + self.comment = line[i + 1:] line = line[:i] # source is ok, split it and see what we have pieces = self.mysplit(line) @@ -201,7 +201,7 @@ class SourceEntry(object): self.trusted = apt_pkg.string_to_bool(value) else: self.invalid = True - + # URI self.uri = pieces[1].strip() if len(self.uri) < 1: @@ -241,7 +241,8 @@ class SourceEntry(object): line += self.type if self.architectures and self.trusted is not None: - line += " [arch=%s trusted=%s]" % (",".join(self.architectures), "yes" if self.trusted else "no") + line += " [arch=%s trusted=%s]" % ( + ",".join(self.architectures), "yes" if self.trusted else "no") elif self.trusted is not None: line += " [trusted=%s]" % ("yes" if self.trusted else "no") elif self.architectures: @@ -250,7 +251,7 @@ class SourceEntry(object): if len(self.comps) > 0: line += " " + " ".join(self.comps) if self.comment != "": - line += " #"+self.comment + line += " #" + self.comment line += "\n" return line @@ -303,7 +304,8 @@ class SourcesList(object): all(predicate(source) for predicate in predicates)): yield source - def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None, architectures=[]): + def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None, + architectures=[]): """ Add a new source to the sources.list. The method will search for existing matching repos and will try to @@ -315,8 +317,8 @@ class SourcesList(object): # we can modify it later comps = orig_comps[:] sources = self.__find(lambda s: set(s.architectures) == architectures, - disabled=False, invalid=False, type=type, uri=uri, - dist=dist) + disabled=False, invalid=False, type=type, + uri=uri, dist=dist) # check if we have this source already in the sources.list for source in sources: for new_comp in comps: @@ -329,7 +331,6 @@ class SourcesList(object): sources = self.__find(lambda s: set(s.architectures) == architectures, invalid=False, type=type, uri=uri, dist=dist) - for source in sources: # if there is a repo with the same (type, uri, dist) just add the # components @@ -363,14 +364,13 @@ class SourcesList(object): def restore_backup(self, backup_ext): " restore sources.list files based on the backup extension " file = apt_pkg.config.find_file("Dir::Etc::sourcelist") - if os.path.exists(file+backup_ext) and \ - os.path.exists(file): - shutil.copy(file+backup_ext, file) + if os.path.exists(file + backup_ext) and os.path.exists(file): + shutil.copy(file + backup_ext, file) # now sources.list.d partsdir = apt_pkg.config.find_dir("Dir::Etc::sourceparts") for file in glob.glob("%s/*.list" % partsdir): - if os.path.exists(file+backup_ext): - shutil.copy(file+backup_ext, file) + if os.path.exists(file + backup_ext): + shutil.copy(file + backup_ext, file) def backup(self, backup_ext=None): """ make a backup of the current source files, if no backup extension diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 7381ad68..1971ba2f 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -34,7 +34,8 @@ progress = apt.progress.text.AcquireProgress() fetcher = apt_pkg.Acquire(progress) pm = apt_pkg.PackageManager(depcache) pm.get_archives(fetcher, list, recs) -print "%s (%s)" % (apt_pkg.size_to_str(fetcher.fetch_needed), fetcher.fetch_needed) +print "%s (%s)" % ( + apt_pkg.size_to_str(fetcher.fetch_needed), fetcher.fetch_needed) actiongroup = apt_pkg.ActionGroup(depcache) for pkg in cache.packages: depcache.mark_keep(pkg) @@ -65,7 +66,7 @@ for item in fetcher.items: print item if item.status == item.STAT_ERROR: print "Some error ocured: '%s'" % item.error_text - if item.complete == False: + if item.complete is False: print "No error, still nothing downloaded (%s)" % item.error_text print @@ -75,4 +76,4 @@ print "fetcher.Run() returned: %s" % res print "now runing pm.DoInstall()" res = pm.do_install(1) -print "pm.DoInstall() returned: %s"% res +print "pm.DoInstall() returned: %s" % res diff --git a/doc/examples/action.py b/doc/examples/action.py index 0399bddc..41b55144 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -36,7 +36,7 @@ depcache.init(progress) #sys.exit() # get a canidate version -ver= depcache.get_candidate_ver(iter) +ver = depcache.get_candidate_ver(iter) print "Candidate version: %s " % ver print "\n\nQuerry interface" diff --git a/doc/examples/architecture.py b/doc/examples/architecture.py index 75afb2d1..421c79a7 100644 --- a/doc/examples/architecture.py +++ b/doc/examples/architecture.py @@ -6,7 +6,7 @@ def main(): print "Native architecture:", apt_pkg.config["APT::Architecture"] print "All architectures:", apt_pkg.config.value_list("APT::Architectures") - + if __name__ == '__main__': main() diff --git a/doc/examples/build-deps-old.py b/doc/examples/build-deps-old.py index cc41aa64..4e7e4350 100755 --- a/doc/examples/build-deps-old.py +++ b/doc/examples/build-deps-old.py @@ -54,7 +54,7 @@ if srcrec: # calculate the build depends for all dependencies depends = depcache.get_candidate_ver(base).depends_list -for dep in depends["Depends"]: # FIXME: do we need to consider PreDepends? +for dep in depends["Depends"]: # FIXME: do we need to consider PreDepends? pkg = dep[0].target_pkg srcpkg_name = get_source_pkg(pkg, records, depcache) if not srcpkg_name: diff --git a/doc/examples/checkstate.py b/doc/examples/checkstate.py index 7f046c5d..084fdb87 100755 --- a/doc/examples/checkstate.py +++ b/doc/examples/checkstate.py @@ -19,11 +19,11 @@ for package in packages: continue version = versions[0] for other_version in versions: - if apt_pkg.version_compare(version.ver_str, other_version.ver_str)<0: + if apt_pkg.version_compare(version.ver_str, other_version.ver_str) < 0: version = other_version if package.current_ver: current = package.current_ver - if apt_pkg.version_compare(current.ver_str, version.ver_str)<0: + if apt_pkg.version_compare(current.ver_str, version.ver_str) < 0: upgradable[package.name] = version break else: diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index 3261c734..f6e090a1 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -10,7 +10,8 @@ import os.path def Callback(member, data): """ callback for debExtract """ print "'%s','%s',%u,%u,%u,%u,%u,%u,%u" \ - % (member.name, member.linkname, member.mode, member.uid, member.gid, member.size, member.mtime, member.major, member.minor) + % (member.name, member.linkname, member.mode, member.uid, + member.gid, member.size, member.mtime, member.major, member.minor) if __name__ == "__main__": @@ -35,7 +36,6 @@ if __name__ == "__main__": depends = sections["Depends"] print apt_pkg.parse_depends(depends) - print "extracting archive" dir = "/tmp/deb" os.mkdir(dir) diff --git a/doc/examples/depcache.py b/doc/examples/depcache.py index 919de603..8e33e98b 100644 --- a/doc/examples/depcache.py +++ b/doc/examples/depcache.py @@ -31,7 +31,7 @@ depcache.init(progress) # get a canidate version -ver= depcache.get_candidate_ver(iter) +ver = depcache.get_candidate_ver(iter) print "Candidate version: %s " % ver print "\n\nQuerry interface" diff --git a/doc/examples/inst.py b/doc/examples/inst.py index dd39c25b..25658435 100644 --- a/doc/examples/inst.py +++ b/doc/examples/inst.py @@ -17,7 +17,7 @@ class TextInstallProgress(InstallProgress): InstallProgress.updateInterface(self) if self.last >= self.percent: return - sys.stdout.write("\r[%s] %s\n" %(self.percent, self.status)) + sys.stdout.write("\r[%s] %s\n" % (self.percent, self.status)) sys.stdout.flush() self.last = self.percent diff --git a/doc/examples/progress.py b/doc/examples/progress.py index d7c4fad8..32dac330 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -11,7 +11,7 @@ import apt.progress.base class TextProgress(apt.progress.base.OpProgress): def __init__(self): - self.last=0.0 + self.last = 0.0 def update(self, percent): if (self.last + 1.0) <= percent: @@ -47,8 +47,11 @@ class TextFetchProgress(apt.progress.base.AcquireProgress): def pulse(self, owner): print "pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % ( - apt_pkg.size_to_str(self.current_cps), apt_pkg.size_to_str(self.current_bytes), - apt_pkg.size_to_str(self.total_bytes), self.current_items, self.total_items) + apt_pkg.size_to_str(self.current_cps), + apt_pkg.size_to_str(self.current_bytes), + apt_pkg.size_to_str(self.total_bytes), + self.current_items, + self.total_items) return True def media_change(self, medium, drive): diff --git a/doc/examples/sources.py b/doc/examples/sources.py index 238ca48c..aa783758 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -11,6 +11,6 @@ sources = apt_pkg.SourceRecords() sources.restart() while sources.lookup('hello'): print sources.package, sources.version, sources.maintainer, \ - sources.section, `sources.binaries` + sources.section, repr(sources.binaries) print sources.files print sources.index.archive_uri(sources.files[0][2]) diff --git a/doc/source/conf.py b/doc/source/conf.py index 163f5074..7a565e16 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -36,7 +36,6 @@ if os.path.exists("../../build"): break - # General configuration # --------------------- @@ -68,7 +67,7 @@ copyright = u'2009-2010, Julian Andres Klode ' # try: - release=os.environ['DEBVER'] + release = os.environ['DEBVER'] except KeyError: from subprocess import Popen, PIPE p1 = Popen(["dpkg-parsechangelog", "-l../../debian/changelog"], @@ -82,7 +81,7 @@ for c in release.split("~")[0].split(".")[2]: if not c.isdigit(): break release_raw += c - + if int(release_raw) >= 90: version_s = release.split("~")[0].split(".")[:3] # Set the version to 0.X.100 if the release is 0.X.9Y (0.7.90 => 0.7.100) @@ -212,8 +211,8 @@ htmlhelp_basename = 'python-aptdoc' # Grouping the document tree into LaTeX files. List of tuples # (source index, target name, title, author, document class [howto/manual]). latex_documents = [ - ('contents', 'python-apt.tex', ur'python-apt Documentation', - ur'Julian Andres Klode ', 'manual'), + ('contents', 'python-apt.tex', ur'python-apt Documentation', + ur'Julian Andres Klode ', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index f4cc2e66..10216c19 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -8,7 +8,7 @@ def main(): cache = apt_pkg.Cache() for pkgfile in cache.file_list: print 'Package-File:', pkgfile.filename - print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' + print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' if pkgfile.not_source: print 'Source: None' else: diff --git a/setup.py b/setup.py index 0c4561c0..cfbbf44e 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,7 @@ if len(sys.argv) > 1 and sys.argv[1] == "build": for template in glob.glob('data/templates/*.mirrors'): import shutil shutil.copy(template, os.path.join("build", template)) - + setup(name="python-apt", description="Python bindings for APT", @@ -70,10 +70,10 @@ setup(name="python-apt", author_email="deity@lists.debian.org", ext_modules=[apt_pkg, apt_inst], packages=['apt', 'apt.progress', 'aptsources'], - data_files = [('share/python-apt/templates', - glob.glob('build/data/templates/*.info')), - ('share/python-apt/templates', - glob.glob('data/templates/*.mirrors'))], - cmdclass = cmdclass, - license = 'GNU GPL', - platforms = 'posix') + data_files=[('share/python-apt/templates', + glob.glob('build/data/templates/*.info')), + ('share/python-apt/templates', + glob.glob('data/templates/*.mirrors'))], + cmdclass=cmdclass, + license='GNU GPL', + platforms='posix') diff --git a/tests/old/__init__.py b/tests/old/__init__.py index afd0f074..e93c0b65 100644 --- a/tests/old/__init__.py +++ b/tests/old/__init__.py @@ -2,7 +2,6 @@ import os import unittest - if __name__ == '__main__': os.chdir(os.path.dirname(__file__)) print os.getcwd() diff --git a/tests/old/cache.py b/tests/old/cache.py index 11156c00..5cbf19d9 100644 --- a/tests/old/cache.py +++ b/tests/old/cache.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running Cache test on all packages:" # first, get all pkgs for pkg in cache.packages: diff --git a/tests/old/depcache.py b/tests/old/depcache.py index cc030ed0..67a47503 100644 --- a/tests/old/depcache.py +++ b/tests/old/depcache.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running DepCache test on all packages" print "(trying to install each and then mark it keep again):" # first, get all pkgs @@ -21,7 +21,7 @@ def main(): i += 1 x = pkg.name # then get each version - ver =depcache.get_candidate_ver(pkg) + ver = depcache.get_candidate_ver(pkg) if ver is not None: depcache.mark_install(pkg) if depcache.inst_count == 0: diff --git a/tests/old/pkgproblemresolver.py b/tests/old/pkgproblemresolver.py index 7714c882..feaa3cb1 100644 --- a/tests/old/pkgproblemresolver.py +++ b/tests/old/pkgproblemresolver.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running DepCache test on all packages" print "(trying to install each and then mark it keep again):" # first, get all pkgs @@ -21,7 +21,7 @@ def main(): i += 1 x = pkg.name # then get each version - ver =depcache.get_candidate_ver(pkg) + ver = depcache.get_candidate_ver(pkg) if ver is not None: depcache.mark_install(pkg) if depcache.broken_count > 0: diff --git a/tests/old/pkgrecords.py b/tests/old/pkgrecords.py index 9e06d44c..3f253bf3 100644 --- a/tests/old/pkgrecords.py +++ b/tests/old/pkgrecords.py @@ -13,7 +13,7 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 + i = 0 print "Running PkgRecords test on all packages:" for pkg in cache.packages: i += 1 diff --git a/tests/old/pkgsrcrecords.py b/tests/old/pkgsrcrecords.py index 36790eff..42b545ed 100644 --- a/tests/old/pkgsrcrecords.py +++ b/tests/old/pkgsrcrecords.py @@ -11,7 +11,7 @@ import sys def main(): apt_pkg.init() cache = apt_pkg.Cache() - i=0 + i = 0 print "Running PkgSrcRecords test on all packages:" for x in cache.packages: i += 1 diff --git a/tests/old/refcount.py b/tests/old/refcount.py index a80595c9..70adc0c1 100755 --- a/tests/old/refcount.py +++ b/tests/old/refcount.py @@ -1,14 +1,13 @@ #!/usr/bin/python-dbg -from pprint import pprint, pformat +from pprint import pprint import apt import sys import gc -import difflib # get initial cache print sys.gettotalrefcount() -progress= apt.progress.OpTextProgress() +progress = apt.progress.OpTextProgress() c = apt.Cache(progress) print "refcount after first cache instance: ", sys.gettotalrefcount() diff --git a/tests/test_all.py b/tests/test_all.py index 25774617..de6cb0c0 100644 --- a/tests/test_all.py +++ b/tests/test_all.py @@ -11,19 +11,21 @@ import sys try: import unittest.runner import unittest + unittest # pyflakes except ImportError: # py2.6 compat import unittest2 as unittest # workaround for py3.2 that apparently does not have this anymore -# it has "abiflags" +# it has "abiflags" if not hasattr(sys, "pydebug"): if sys.abiflags.startswith("d"): sys.pydebug = True else: sys.pydebug = False + def get_library_dir(): # Find the path to the built apt_pkg and apt_inst extensions if not os.path.exists("../build"): @@ -40,14 +42,17 @@ def get_library_dir(): plat_specifier) return os.path.abspath(library_dir) + class MyTestRunner(unittest.runner.TextTestRunner): def __init__(self, *args, **kwargs): kwargs["stream"] = sys.stdout super(MyTestRunner, self).__init__(*args, **kwargs) + if __name__ == '__main__': if not os.access("/etc/apt/sources.list", os.R_OK): - sys.stdout.write("[tests] Skipping because sources.list is not readable\n") + sys.stdout.write( + "[tests] Skipping because sources.list is not readable\n") sys.exit(0) sys.stdout.write("[tests] Running on %s\n" % sys.version.replace("\n", "")) diff --git a/tests/test_apt_cache.py b/tests/test_apt_cache.py index 9940374f..ee4fc50b 100644 --- a/tests/test_apt_cache.py +++ b/tests/test_apt_cache.py @@ -18,6 +18,7 @@ import unittest if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -36,7 +37,8 @@ def if_sources_list_is_readable(f): if os.access("/etc/apt/sources.list", os.R_OK): f(*args, **kwargs) else: - logging.warning("skipping '%s' because sources.list is not readable" % f) + logging.warning( + "skipping '%s' because sources.list is not readable" % f) return wrapper @@ -124,20 +126,23 @@ class TestAptCache(TestCase): cache = apt.Cache(rootdir="./data/test-provides/") cache.open() if len(cache) == 0: - logging.warning("skipping test_get_provided_packages, cache empty?!?") + logging.warning( + "skipping test_get_provided_packages, cache empty?!?") return # a true virtual pkg l = cache.get_providing_packages("mail-transport-agent") self.assertTrue(len(l) > 0) self.assertTrue("postfix" in [p.name for p in l]) - self.assertTrue("mail-transport-agent" in cache["postfix"].candidate.provides) + self.assertTrue( + "mail-transport-agent" in cache["postfix"].candidate.provides) def test_low_level_pkg_provides(self): apt.apt_pkg.config.set("Apt::architecture", "i386") # create highlevel cache and get the lowlevel one from it highlevel_cache = apt.Cache(rootdir="./data/test-provides") if len(highlevel_cache) == 0: - logging.warning("skipping test_log_level_pkg_provides, cache empty?!?") + logging.warning( + "skipping test_log_level_pkg_provides, cache empty?!?") return # low level cache provides list of the pkg cache = highlevel_cache._cache @@ -150,24 +155,24 @@ class TestAptCache(TestCase): break else: self.assertNotReached() - + @if_sources_list_is_readable def test_dpkg_journal_dirty(self): # create tmp env tmpdir = tempfile.mkdtemp() - dpkg_dir = os.path.join(tmpdir,"var","lib","dpkg") - os.makedirs(os.path.join(dpkg_dir,"updates")) - open(os.path.join(dpkg_dir,"status"), "w").close() + dpkg_dir = os.path.join(tmpdir, "var", "lib", "dpkg") + os.makedirs(os.path.join(dpkg_dir, "updates")) + open(os.path.join(dpkg_dir, "status"), "w").close() apt_pkg.config.set("Dir::State::status", - os.path.join(dpkg_dir,"status")) + os.path.join(dpkg_dir, "status")) cache = apt.Cache() # test empty self.assertFalse(cache.dpkg_journal_dirty) # that is ok, only [0-9] are dpkg jounral entries - open(os.path.join(dpkg_dir,"updates","xxx"), "w").close() - self.assertFalse(cache.dpkg_journal_dirty) + open(os.path.join(dpkg_dir, "updates", "xxx"), "w").close() + self.assertFalse(cache.dpkg_journal_dirty) # that is a dirty journal - open(os.path.join(dpkg_dir,"updates","000"), "w").close() + open(os.path.join(dpkg_dir, "updates", "000"), "w").close() self.assertTrue(cache.dpkg_journal_dirty) @if_sources_list_is_readable @@ -209,29 +214,29 @@ class TestAptCache(TestCase): # update a single sources.list cache = apt.Cache() cache.update(sources_list=sources_list) - # verify we just got the excpected package file + # verify we just got the excpected package file needle_packages = glob.glob( - lists_dir+"/*tests_data_test-repo_Packages*") + lists_dir + "/*tests_data_test-repo_Packages*") self.assertEqual(len(needle_packages), 1) # verify that we *only* got the Packages file from a single source - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(needle_packages, all_packages) # verify that the listcleaner was not run and the marker file is # still there self.assertTrue("marker" in os.listdir(lists_dir)) - # now run update again (without the "normal" sources.list that # contains test-repo2 and verify that we got the normal sources.list cache.update() - needle_packages = glob.glob(lists_dir+"/*tests_data_test-repo2_Packages*") + needle_packages = glob.glob( + lists_dir + "/*tests_data_test-repo2_Packages*") self.assertEqual(len(needle_packages), 1) - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(needle_packages, all_packages) # and another update with a single source only cache = apt.Cache() cache.update(sources_list=sources_list) - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(len(all_packages), 2) apt_pkg.config.set("dir::state", old_state) apt_pkg.config.set("dir::etc::sourcelist", old_source_list) diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 0b74cb79..4539b2d1 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -70,7 +70,6 @@ class TestAptSources(unittest.TestCase): ["main"], architectures=["amd64", "i386"]) self.assertTrue(sources.list == before.list) - # test to add something new: multiverse sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", @@ -150,8 +149,7 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - - assert sources.list[8].invalid == False + assert sources.list[8].invalid is False assert sources.list[8].type == "deb" assert sources.list[8].architectures == ["amd64", "i386"] assert sources.list[8].uri == "http://de.archive.ubuntu.com/ubuntu/" @@ -166,11 +164,11 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - - assert sources.list[9].invalid == False + assert sources.list[9].invalid is False assert sources.list[9].type == "deb" assert sources.list[9].architectures == ["amd64", "i386"] - self.assertEqual( sources.list[9].uri, "http://de.archive.ubuntu.com/ubuntu/") + self.assertEqual( + sources.list[9].uri, "http://de.archive.ubuntu.com/ubuntu/") assert sources.list[9].dist == "natty" assert sources.list[9].comps == ["main"] assert sources.list[9].trusted @@ -198,7 +196,7 @@ class TestAptSources(unittest.TestCase): comps = comps.union(set(entry.comps)) self.assertTrue("multiverse" in comps) self.assertTrue("universe" in comps) - + def testDistribution(self): """aptsources: Test distribution detection.""" apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" diff --git a/tests/test_auth.py b/tests/test_auth.py index bc353427..a9cfe736 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -15,6 +15,8 @@ import unittest if sys.version_info[0] > 2: from http.server import HTTPServer from http.server import SimpleHTTPRequestHandler as HTTPRequestHandler + HTTPServer # pyflakes + HTTPRequestHandler # pyflakes else: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler as HTTPRequestHandler @@ -22,6 +24,7 @@ else: if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -215,7 +218,8 @@ class TestAuthKeys(TestCase): def test_add_key_from_keyserver_too_short(self): """Ensure that short keyids are not imported""" with self.assertRaises(apt.auth.AptKeyError): - apt.auth.add_key_from_keyserver("46925553", "hkp://localhost:19191") + apt.auth.add_key_from_keyserver( + "46925553", "hkp://localhost:19191") def test_add_key_from_server_mitm(self): """Verify that the key fingerprint is verified after download""" @@ -227,7 +231,8 @@ class TestAuthKeys(TestCase): "0101010178F7FE5C3E65D8AF8B48AD6246925553", "hkp://localhost:%d" % self.keyserver_port) self.assertTrue( - str(cm.exception).startswith("Fingerprints do not match"), cm.exception) + str(cm.exception).startswith("Fingerprints do not match"), + cm.exception) def testAddKeyFromServer(self): """Install a GnuPG key from a remote server.""" @@ -236,7 +241,7 @@ class TestAuthKeys(TestCase): with self._discard_stderr(): apt.auth.add_key_from_keyserver( - "0xa1bD8E9D78F7FE5C3E65D8AF8B48AD6246925553", + "0xa1bD8E9D78F7FE5C3E65D8AF8B48AD6246925553", "hkp://localhost:%d" % self.keyserver_port) ret = apt.auth.list_keys() diff --git a/tests/test_configuration.py b/tests/test_configuration.py index 80509cff..adf33719 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -7,7 +7,6 @@ # notice and this notice are preserved. """Unit tests for verifying the correctness of apt_pkg.Configuration""" import unittest - import apt_pkg @@ -21,9 +20,9 @@ class TestConfiguration(unittest.TestCase): def test_lp707416(self): """configuration: Test empty arguments (LP: #707416)""" self.assertRaises(ValueError, apt_pkg.parse_commandline, - apt_pkg.config,[], []) + apt_pkg.config, [], []) self.assertRaises(SystemError, apt_pkg.parse_commandline, - apt_pkg.config,[], ["cmd", "--arg0"]) + apt_pkg.config, [], ["cmd", "--arg0"]) if __name__ == "__main__": diff --git a/tests/test_debfile.py b/tests/test_debfile.py index 9379884a..ec3bf518 100644 --- a/tests/test_debfile.py +++ b/tests/test_debfile.py @@ -19,6 +19,7 @@ if libdir: import apt_pkg import apt.debfile + class TestDebfile(unittest.TestCase): """ test the debfile """ @@ -32,31 +33,31 @@ class TestDebfile(unittest.TestCase): # Conflicts: apt (<= 0.1) ('gdebi-test4.deb', True), # Conflicts: apt (>= 0.1) - ('gdebi-test5.deb', False), + ('gdebi-test5.deb', False), # invalid unicode in descr ('gdebi-test6.deb', True), # provides/conflicts against "foobarbaz" ('gdebi-test7.deb', True), # provides/conflicts/replaces against "mail-transport-agent" # (should fails if mail-transport-agent is installed) - ('gdebi-test8.deb', False), + ('gdebi-test8.deb', False), # provides/conflicts against real pkg ('gdebi-test9.deb', True), - # provides debconf-tiny and the real debconf conflicts with + # provides debconf-tiny and the real debconf conflicts with ('gdebi-test10.deb', False), ] def setUp(self): apt_pkg.init_config() - apt_pkg.config.set("APT::Architecture","i386") + apt_pkg.config.set("APT::Architecture", "i386") # FIXME: When run via test_all.py, the tests fail without this if it # is set in the system. apt_pkg.config.clear("APT::Architectures") - apt_pkg.config.set("Dir::State::status", + apt_pkg.config.set("Dir::State::status", "./data/test_debs/var/lib/dpkg/status") - apt_pkg.config.set("Dir::State::lists", + apt_pkg.config.set("Dir::State::lists", "./data/test_debs/var/lib/apt/lists") - apt_pkg.config.set("Dir::Etc::sourcelist", + apt_pkg.config.set("Dir::Etc::sourcelist", "./data/test_debs/etc/apt/sources.list") apt_pkg.init_system() self.cache = apt.Cache() @@ -76,7 +77,8 @@ class TestDebfile(unittest.TestCase): def testDebFile(self): deb = apt.debfile.DebPackage(cache=self.cache) for (filename, expected_res) in self.TEST_DEBS: - logging.debug("testing %s, expecting %s" % (filename, expected_res)) + logging.debug("testing %s, expecting %s" % ( + filename, expected_res)) deb.open(os.path.join("data", "test_debs", filename)) res = deb.check() self.assertEqual(res, expected_res, @@ -85,7 +87,8 @@ class TestDebfile(unittest.TestCase): def test_utf8_sections(self): deb = apt.debfile.DebPackage(cache=self.cache) - deb.open(os.path.join("data","test_debs","utf8-package_1.0-1_all.deb")) + deb.open( + os.path.join("data", "test_debs", "utf8-package_1.0-1_all.deb")) self.assertEqual(deb["Maintainer"], "Samuel Lidén Borell ") @@ -99,7 +102,8 @@ class TestDebfile(unittest.TestCase): deb = apt.debfile.DebPackage(cache=self.cache) deb.open(os.path.join("data", "test_debs", "gdebi-test12.deb")) content = deb.data_content("usr/bin/binary") - self.assertTrue(content.startswith("Automatically converted to printable ascii:\n\x7fELF ")) + self.assertTrue(content.startswith( + "Automatically converted to printable ascii:\n\x7fELF ")) # control file needle = """Package: gdebi-test12 Version: 1.0 @@ -136,7 +140,8 @@ Description: testpackage for gdebi - contains usr/bin/binary for file reading apt_pkg.config["APT::Architecture"] = "amd64" apt_pkg.init_system() - allowed_any = apt.debfile.DebPackage("./data/test_debs/testdep-allowed-any_1.0-1_i386.deb") + allowed_any = apt.debfile.DebPackage( + "./data/test_debs/testdep-allowed-any_1.0-1_i386.deb") self.assertTrue(allowed_any.check(), allowed_any._failure_string) def test_multi_arch_same(self): @@ -144,7 +149,8 @@ Description: testpackage for gdebi - contains usr/bin/binary for file reading apt_pkg.config["APT::Architectures::"] = "amd64" apt_pkg.config["APT::Architecture"] = "amd64" apt_pkg.init_system() - same = apt.debfile.DebPackage("./data/test_debs/testdep-same-arch_1.0-1_i386.deb") + same = apt.debfile.DebPackage( + "./data/test_debs/testdep-same-arch_1.0-1_i386.deb") self.assertTrue(same.check(), same._failure_string) diff --git a/tests/test_debfile_multiarch.py b/tests/test_debfile_multiarch.py index cf6479b1..045daf72 100644 --- a/tests/test_debfile_multiarch.py +++ b/tests/test_debfile_multiarch.py @@ -18,13 +18,15 @@ import apt import apt_pkg import apt.debfile + class TestDebfileMultiarch(unittest.TestCase): """ test the multiarch debfile """ def test_multiarch_deb_check(self): if apt_pkg.get_architectures() != ["amd64", "i386"]: # TODO: use unittest.skip - #logging.warning("skipping test because running on a non-multiarch system") + #logging.warning("skipping test because running on a " + # "non-multiarch system") return deb = apt.debfile.DebPackage( "./data/test_debs/multiarch-test1_i386.deb") @@ -48,10 +50,9 @@ class TestDebfileMultiarch(unittest.TestCase): installable = deb.check() #print deb._failure_string self.assertFalse(installable) - self.assertEqual(deb._failure_string, + self.assertEqual(deb._failure_string, "Conflicts with the installed package 'lib3ds-1-3'") - if __name__ == "__main__": unittest.main() diff --git a/tests/test_group.py b/tests/test_group.py index 3c3a5b7a..e70d2479 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -22,7 +22,6 @@ class TestGroup(unittest.TestCase): list(group) == list(group) - def test_cache_groups(self): """group: Iterate over all groups""" assert len(list(self.cache.groups)) == self.cache.group_count diff --git a/tests/test_hashes.py b/tests/test_hashes.py index 660373cb..be817f88 100644 --- a/tests/test_hashes.py +++ b/tests/test_hashes.py @@ -90,7 +90,7 @@ class TestHashString(unittest.TestCase): def tearDown(self): """Cleanup, Close the file object used for the tests.""" - self.file.close() + self.file.close() def test_md5(self): """hashes: Test apt_pkg.HashString().md5""" diff --git a/tests/test_lp659438.py b/tests/test_lp659438.py index 334f574d..40943d10 100644 --- a/tests/test_lp659438.py +++ b/tests/test_lp659438.py @@ -20,7 +20,7 @@ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Licensed under the GNU General Public License Version 2 -__author__ = "Sebastian Heinlein " +__author__ = "Sebastian Heinlein " import os import shutil diff --git a/tests/test_paths.py b/tests/test_paths.py index 48f86c52..62ea1665 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -30,8 +30,10 @@ class TestPath(unittest.TestCase): def test_acquire(self): apt_pkg.AcquireFile(apt_pkg.Acquire(), "http://example.com", destdir=self.file_bytes, destfile=self.file_bytes) - apt_pkg.AcquireFile(apt_pkg.Acquire(), "http://example.com", - destdir=self.file_unicode, destfile=self.file_unicode) + apt_pkg.AcquireFile(apt_pkg.Acquire(), + "http://example.com", + destdir=self.file_unicode, + destfile=self.file_unicode) def test_ararchive(self): archive = apt_inst.ArArchive(u"data/test_debs/data-tar-xz.deb") @@ -65,7 +67,7 @@ class TestPath(unittest.TestCase): apt_inst.TarFile(os.path.join(self.dir_bytes, b"control.tar.gz")) def test_configuration(self): - with open(self.file_unicode, 'w' ) as config: + with open(self.file_unicode, 'w') as config: config.write("Hello { World 1; };") apt_pkg.read_config_file(apt_pkg.config, self.file_bytes) apt_pkg.read_config_file(apt_pkg.config, self.file_unicode) @@ -95,7 +97,7 @@ class TestPath(unittest.TestCase): self.assertEqual(size1, size2) self.assertEqual(str(hash1), str(hash2)) self.assertEqual(str(hash1), ("SHA256:fefed230e286d832ab6eb0fb7b72" - + "442165b50df23a68402ae6e9d265a31920a2")) + "442165b50df23a68402ae6e9d265a31920a2")) def test_lock(self): apt_pkg.get_lock(self.file_unicode, True) diff --git a/tests/test_pep8.py b/tests/test_pep8.py index e6a672cf..2e1f43fc 100755 --- a/tests/test_pep8.py +++ b/tests/test_pep8.py @@ -5,7 +5,7 @@ import unittest class PackagePep8TestCase(unittest.TestCase): - def test_all_code(self): + def test_pep8(self): res = 0 py_dir = os.path.join(os.path.dirname(__file__), "..") res += subprocess.call( diff --git a/tests/test_policy.py b/tests/test_policy.py index f7d41152..f15cf2d1 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -9,6 +9,7 @@ import apt import unittest + class TestAptPolicy(unittest.TestCase): def test_apt_policy_lowlevel(self): @@ -34,6 +35,5 @@ class TestAptPolicy(unittest.TestCase): pkg.candidate.policy_priority < 1001) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_progress.py b/tests/test_progress.py index 508da7d4..01cd8a2d 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -12,6 +12,7 @@ import apt import apt_pkg import os + class TestAcquireProgress(apt.progress.base.AcquireProgress): def pulse(self, owner): self.pulsed = True @@ -19,6 +20,7 @@ class TestAcquireProgress(apt.progress.base.AcquireProgress): # but often this is forgoten (and causes odd error messages) # so the lib supports it. we test the lack of support value here + class TestProgress(unittest.TestCase): def setUp(self): @@ -35,7 +37,7 @@ class TestProgress(unittest.TestCase): apt_pkg.config.set("Dir::state::lists", "./tmp") # create artifical line deb_line = "deb file:%s/data/fake-packages/ /\n" % basedir - with open("fetch_sources.list","w") as fobj: + with open("fetch_sources.list", "w") as fobj: fobj.write(deb_line) apt_pkg.config.set("Dir::Etc::sourcelist", "fetch_sources.list") apt_pkg.config.clear("APT::Update::Post-Invoke") @@ -47,5 +49,6 @@ class TestProgress(unittest.TestCase): cache.update(progress) self.assertTrue(progress.pulsed) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_size_to_str.py b/tests/test_size_to_str.py index 2c2c372f..1d0e9232 100644 --- a/tests/test_size_to_str.py +++ b/tests/test_size_to_str.py @@ -1,6 +1,6 @@ #!/usr/bin/python -__author__ = "Barry Warsaw , James Hunt, Michael Vogt" +__author__ = "Barry Warsaw , James Hunt, Michael Vogt" import sys import unittest @@ -9,6 +9,7 @@ import apt_pkg if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -18,74 +19,71 @@ class SizeToStrTestCase(TestCase): DATA = { # XXX: note the trailing spaces for some of these entries! - 10 ** 1 : "10 ", - 10 ** 2 : "100 ", - 10 ** 3 : "1000 ", - 10 ** 4 : "10.0 k", - 10 ** 5 : "100 k", - 10 ** 6 : "1000 k", - 10 ** 7 : "10.0 M", - 10 ** 8 : "100 M", - 10 ** 9 : "1000 M", - 10 ** 10 : "10.0 G", - 10 ** 11 : "100 G", - 10 ** 12 : "1000 G", - 10 ** 13 : "10.0 T", - 10 ** 14 : "100 T", - 10 ** 15 : "1000 T", - 10 ** 16 : "10.0 P", - 10 ** 17 : "100 P", - 10 ** 18 : "1000 P", - 10 ** 19 : "10.0 E", - 10 ** 20 : "100 E", - 10 ** 21 : "1000 E", - 10 ** 22 : "10.0 Z", - 10 ** 23 : "100.0 Z", - 10 ** 24 : "1000 Z", -# 10 ** 25 : "10.0 Y", - 10 ** 26 : "100 Y", - 10 ** 27 : "1000 Y", - + 10 ** 1: "10 ", + 10 ** 2: "100 ", + 10 ** 3: "1000 ", + 10 ** 4: "10.0 k", + 10 ** 5: "100 k", + 10 ** 6: "1000 k", + 10 ** 7: "10.0 M", + 10 ** 8: "100 M", + 10 ** 9: "1000 M", + 10 ** 10: "10.0 G", + 10 ** 11: "100 G", + 10 ** 12: "1000 G", + 10 ** 13: "10.0 T", + 10 ** 14: "100 T", + 10 ** 15: "1000 T", + 10 ** 16: "10.0 P", + 10 ** 17: "100 P", + 10 ** 18: "1000 P", + 10 ** 19: "10.0 E", + 10 ** 20: "100 E", + 10 ** 21: "1000 E", + 10 ** 22: "10.0 Z", + 10 ** 23: "100.0 Z", + 10 ** 24: "1000 Z", + #10 ** 25: "10.0 Y", + 10 ** 26: "100 Y", + 10 ** 27: "1000 Y", # That's our limit :) - 10 ** 28 : "10000 Y", - - 0 : "0 ", - 1 : "1 ", - 1024 : "1024 ", - 10240 : "10.2 k", - 102400 : "102 k", - 1024000 : "1024 k", - 10240000 : "10.2 M", - 102400000 : "102 M", - 2147483647 : "2147 M", - 2147483648 : "2147 M", - 1024000000 : "1024 M", - 10240000000 : "10.2 G", - - 9 : "9 ", - 99 : "99 ", - 999 : "999 ", - 9999 : "9999 ", - 99999 : "100.0 k", - 999999 : "1000 k", - 9999999 : "10000 k", - 99999999 : "100.0 M", - 999999999 : "1000 M", - 9999999999 : "10000 M", - 99999999999 : "100.0 G", - 999999999999 : "1000 G", - 9999999999999 : "10000 G", - 99999999999999 : "100.0 T", - 999999999999999 : "1000 T", - 9999999999999999 : "10.0 P", - 99999999999999999 : "100 P", - 999999999999999999 : "1000 P", - 9999999999999999999 : "10.0 E", - 99999999999999999999 : "100 E", - 999999999999999999999 : "1000 E", - 9999999999999999999999 : "10.0 Z", - 999999999999999999999999 : "1000 Z", - } + 10 ** 28: "10000 Y", + 0: "0 ", + 1: "1 ", + 1024: "1024 ", + 10240: "10.2 k", + 102400: "102 k", + 1024000: "1024 k", + 10240000: "10.2 M", + 102400000: "102 M", + 2147483647: "2147 M", + 2147483648: "2147 M", + 1024000000: "1024 M", + 10240000000: "10.2 G", + 9: "9 ", + 99: "99 ", + 999: "999 ", + 9999: "9999 ", + 99999: "100.0 k", + 999999: "1000 k", + 9999999: "10000 k", + 99999999: "100.0 M", + 999999999: "1000 M", + 9999999999: "10000 M", + 99999999999: "100.0 G", + 999999999999: "1000 G", + 9999999999999: "10000 G", + 99999999999999: "100.0 T", + 999999999999999: "1000 T", + 9999999999999999: "10.0 P", + 99999999999999999: "100 P", + 999999999999999999: "1000 P", + 9999999999999999999: "10.0 E", + 99999999999999999999: "100 E", + 999999999999999999999: "1000 E", + 9999999999999999999999: "10.0 Z", + 999999999999999999999999: "1000 Z", + } def test_from_data(self): for k, v in self.DATA.items(): @@ -96,7 +94,7 @@ class SizeToStrTestCase(TestCase): def test_raise_on_unsupported(self): for v in ["hello", None, {}, [], ()]: with self.assertRaises(TypeError): - apt_pkg.size_to_str(v) + apt_pkg.size_to_str(v) class RegressionTestCase(unittest.TestCase): diff --git a/tests/test_tagfile.py b/tests/test_tagfile.py index f26f851b..6ff6a32a 100644 --- a/tests/test_tagfile.py +++ b/tests/test_tagfile.py @@ -27,6 +27,7 @@ if libdir: import apt_pkg + class TestTagFile(unittest.TestCase): """ test the apt_pkg.TagFile """ diff --git a/tests/test_utils.py b/tests/test_utils.py index 35c0a466..12d5a554 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -13,12 +13,13 @@ import unittest from apt.utils import ( get_maintenance_end_date, get_release_date_from_release_file, - ) +) + class TestUtils(unittest.TestCase): def test_get_release_date_from_release_file(self): - path = os.path.join(os.path.dirname(__file__), + path = os.path.join(os.path.dirname(__file__), "data", "misc", "foo_Release") t = get_release_date_from_release_file(path) self.assertEqual(str(datetime.datetime.utcfromtimestamp(t)), @@ -28,33 +29,38 @@ class TestUtils(unittest.TestCase): months_of_support = 18 # test historic releases, jaunty release_date = datetime.datetime(2009, 4, 23) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2010) self.assertEqual(end_month, 10) # test historic releases, karmic release_date = datetime.datetime(2009, 10, 29) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2011) self.assertEqual(end_month, 4) # test maverick release_date = datetime.datetime(2010, 10, 10) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2012) self.assertEqual(end_month, 4) # test with modulo zero release_date = datetime.datetime(2010, 6, 10) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2011) self.assertEqual(end_month, 12) # test dapper months_of_support = 60 release_date = datetime.datetime(2008, 4, 24) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2013) self.assertEqual(end_month, 4) - + # what datetime says #d = datetime.timedelta(18*30) #print "end date: ", release_date + d diff --git a/utils/doclint.py b/utils/doclint.py index a387b05f..f010ec53 100644 --- a/utils/doclint.py +++ b/utils/doclint.py @@ -35,19 +35,22 @@ def handle(filename): continue for member in objects.get(modname + '.' + modmember): if not member in dir(module.__dict__[modmember]): - print 'W: Unknown', modname + '.' + modmember + '.' + member - - assert(types[objects[modname+"."+modmember][member][1]] in ('method', 'attribute')) + print ('W: Unknown', modname + '.' + modmember + + '.' + member) + t = types[objects[modname + "." + modmember][member][1]] + assert(t in ('method', 'attribute')) all = getattr(module, '__all__', []) for modmember in dir(module): - if getattr(module.__dict__[modmember], "__module__", modname) != modname: + if (getattr(module.__dict__[modmember], "__module__", modname) != + modname): continue if isinstance(module.__dict__[modmember], type(module)): continue if modmember.startswith("_"): continue - if not modmember in objects[modname] and (not all or modmember in all): + if (not modmember in objects[modname] and + (not all or modmember in all)): print 'E: Missing', modname + '.' + modmember elif not modmember in objects[modname]: print 'W: Missing', modname + '.' + modmember @@ -64,14 +67,16 @@ def handle(filename): continue except: pass - if not member in objects.get(modname + '.' + modmember, ""): - print 'E: Missing', modname + '.' + modmember + '.' + member + if not member in objects.get( + modname + '.' + modmember, ""): + print('E: Missing', modname + '.' + modmember + '.' + + member) if __name__ == '__main__': scriptdir = os.path.dirname(__file__) parentdir = os.path.join(scriptdir, "..") - directory = os.path.join(parentdir, "doc", "build", "pickle") + directory = os.path.join(parentdir, "doc", "build", "pickle") directory = os.path.normpath(directory) sys.path.insert(0, os.path.abspath(parentdir)) handle(os.path.join(directory, "searchindex.pickle")) diff --git a/utils/get_ubuntu_mirrors.py b/utils/get_ubuntu_mirrors.py index cf509088..01344852 100755 --- a/utils/get_ubuntu_mirrors.py +++ b/utils/get_ubuntu_mirrors.py @@ -37,7 +37,7 @@ req = urllib2.Request("https://wiki.ubuntu.com/Archive?action=raw") try: print "Downloading mirrors list from the Ubuntu wiki..." - uri=urllib2.urlopen(req) + uri = urllib2.urlopen(req) p = re.compile('^.*((http|ftp):\/\/[A-Za-z0-9-.:\/_]+).*\n*$') for line in uri.readlines(): if r"[[Anchor(dvd-images)]]" in line: -- cgit v1.2.3