diff options
65 files changed, 1759 insertions, 1773 deletions
@@ -6,8 +6,9 @@ PYLINT_IGNORE = oldUtils.py PKGNAME = yum VERSION=$(shell awk '/Version:/ { print $$2 }' ${PKGNAME}.spec) RELEASE=$(shell awk '/Release:/ { print $$2 }' ${PKGNAME}.spec) +PYLIBDIR=$(shell python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])') CVSTAG=yum-$(subst .,_,$(VERSION)-$(RELEASE)) -PYTHON=python +PYTHON=python3 WEBHOST = yum.baseurl.org WEB_DOC_PATH = /srv/projects/yum/web/download/docs/yum-api/ @@ -27,7 +28,7 @@ install: install -m 644 $$p $(DESTDIR)/usr/share/yum-cli/$$p; \ done mv $(DESTDIR)/usr/share/yum-cli/yum-updatesd.py $(DESTDIR)/usr/share/yum-cli/yumupd.py - $(PYTHON) -c "import compileall; compileall.compile_dir('$(DESTDIR)/usr/share/yum-cli', 1, '$(PYDIR)', 1)" + $(PYTHON) -c "import compileall; compileall.compile_dir('$(DESTDIR)/usr/share/yum-cli', 1, '$(PYLIBDIR)/yum', 1)" mkdir -p $(DESTDIR)/usr/bin $(DESTDIR)/usr/sbin install -m 755 bin/yum.py $(DESTDIR)/usr/bin/yum diff --git a/bin/yum-updatesd.py b/bin/yum-updatesd.py index 131c182..5f2c9df 100755 --- a/bin/yum-updatesd.py +++ b/bin/yum-updatesd.py @@ -20,6 +20,6 @@ sys.path.insert(0, '/usr/share/yum-cli') try: import yumupd yumupd.main(options) -except KeyboardInterrupt, e: - print >> sys.stderr, "\n\nExiting on user cancel." +except KeyboardInterrupt as e: + print("\n\nExiting on user cancel.", file=sys.stderr) sys.exit(1) @@ -3,7 +3,7 @@ import sys try: import yum except ImportError: - print >> sys.stderr, """\ + print("""\ There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: @@ -20,13 +20,13 @@ If you cannot solve this problem yourself, please go to the yum faq at: http://yum.baseurl.org/wiki/Faq -""" % (sys.exc_value, sys.version) +""" % (sys.exc_info()[1], sys.version), file=sys.stderr) sys.exit(1) sys.path.insert(0, '/usr/share/yum-cli') try: import yummain yummain.user_main(sys.argv[1:], exit_code=True) -except KeyboardInterrupt, e: - print >> sys.stderr, "\n\nExiting on user cancel." +except KeyboardInterrupt as e: + print("\n\nExiting on user cancel.", file=sys.stderr) sys.exit(1) diff --git a/callback.py b/callback.py index 2f6154e..4962a82 100644 --- a/callback.py +++ b/callback.py @@ -75,7 +75,7 @@ class RPMInstallCallback: def _localprint(self, msg): if self.output: - print msg + print(msg) def _makefmt(self, percent, progress = True): l = len(str(self.total_actions)) @@ -162,7 +162,7 @@ class RPMInstallCallback: if total == 0: percent = 0 else: - percent = (bytes*100L)/total + percent = (bytes*100)/total if self.output and sys.stdout.isatty(): fmt = self._makefmt(percent) msg = fmt % (_('Repackage'), h) @@ -178,16 +178,16 @@ class RPMInstallCallback: if total == 0: percent = 0 else: - percent = (bytes*100L)/total + percent = (bytes*100)/total pkgtup = self._dopkgtup(hdr) txmbrs = self.tsInfo.getMembers(pkgtup=pkgtup) for txmbr in txmbrs: try: process = self.myprocess[txmbr.output_state] - except KeyError, e: - print _("Error: invalid output state: %s for %s") % \ - (txmbr.output_state, hdr['name']) + except KeyError as e: + print((_("Error: invalid output state: %s for %s") % \ + (txmbr.output_state, hdr['name']))) else: if self.output and (sys.stdout.isatty() or bytes == total): fmt = self._makefmt(percent) @@ -197,7 +197,7 @@ class RPMInstallCallback: sys.stdout.flush() self.lastmsg = msg if bytes == total: - print " " + print(" ") elif what == rpm.RPMCALLBACK_UNINST_START: @@ -52,7 +52,7 @@ from yum.packages import parsePackages def sigquit(signum, frame): """ SIGQUIT handler for the yum cli. """ - print >> sys.stderr, "Quit signal sent - exiting immediately" + print("Quit signal sent - exiting immediately", file=sys.stderr) sys.exit(1) class CliError(yum.Errors.YumBaseError): @@ -142,7 +142,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): names and summary usages. """ usage = 'yum [options] COMMAND\n\nList of Commands:\n\n' - commands = yum.misc.unique([x for x in self.yum_cli_commands.values() + commands = yum.misc.unique([x for x in list(self.yum_cli_commands.values()) if not (hasattr(x, 'hidden') and x.hidden)]) commands.sort(key=lambda x: x.getNames()[0]) for command in commands: @@ -194,7 +194,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): # Just print out the version if that's what the user wanted if opts.version: - print yum.__version__ + print(yum.__version__) opts.quiet = True opts.verbose = False @@ -237,10 +237,10 @@ class YumBaseCli(yum.YumBase, output.YumOutput): self.logger.warning(msg % opt) setattr(self.conf, opt, getattr(self.main_setopts, opt)) - except yum.Errors.ConfigError, e: + except yum.Errors.ConfigError as e: self.logger.critical(_('Config Error: %s'), e) sys.exit(1) - except ValueError, e: + except ValueError as e: self.logger.critical(_('Options Error: %s'), e) sys.exit(1) @@ -279,7 +279,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): return time.strftime("%Y-%m-%d", time.gmtime(x)) for pkg in sorted(self.rpmdb.returnPackages(patterns=yum_progs)): # We should only have 1 version of each... - if done: print "" + if done: print("") done = True if pkg.epoch == '0': ver = '%s-%s.%s' % (pkg.version, pkg.release, pkg.arch) @@ -288,12 +288,12 @@ class YumBaseCli(yum.YumBase, output.YumOutput): pkg.version, pkg.release, pkg.arch) name = "%s%s%s" % (self.term.MODE['bold'], pkg.name, self.term.MODE['normal']) - print _(" Installed: %s-%s at %s") %(name, ver, - sm_ui_time(pkg.installtime)) - print _(" Built : %s at %s") % (pkg.packager, - sm_ui_time(pkg.buildtime)) - print _(" Committed: %s at %s") % (pkg.committer, - sm_ui_date(pkg.committime)) + print(_(" Installed: %s-%s at %s") %(name, ver, + sm_ui_time(pkg.installtime))) + print(_(" Built : %s at %s") % (pkg.packager, + sm_ui_time(pkg.buildtime))) + print(_(" Committed: %s at %s") % (pkg.committer, + sm_ui_date(pkg.committime))) sys.exit(0) if opts.sleeptime is not None: @@ -434,7 +434,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): if needTs or needTsRemove: try: self._getTs(needTsRemove) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] return self.yum_cli_commands[self.basecmd].doCommand(self, self.basecmd, self.extcmds) @@ -506,7 +506,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): errors = yum.misc.unique(problems[key]) for error in errors: errstring += ' %s: %s\n' % (key, error) - raise yum.Errors.YumBaseError, errstring + raise yum.Errors.YumBaseError(errstring) # Check GPG signatures if self.gpgsigcheck(downloadpkgs) != 0: @@ -529,12 +529,12 @@ class YumBaseCli(yum.YumBase, output.YumOutput): continue rpmlib_only = False if rpmlib_only: - print _("ERROR You need to update rpm to handle:") + print(_("ERROR You need to update rpm to handle:")) else: - print _('ERROR with transaction check vs depsolve:') + print(_('ERROR with transaction check vs depsolve:')) for msg in msgs: - print to_utf8(msg) + print(to_utf8(msg)) if rpmlib_only: return 1, [_('RPM needs to be updated')] @@ -560,8 +560,8 @@ class YumBaseCli(yum.YumBase, output.YumOutput): for descr in tserrors: errstring += ' %s\n' % to_unicode(descr) - raise yum.Errors.YumBaseError, errstring + '\n' + \ - self.errorSummary(errstring) + raise yum.Errors.YumBaseError(errstring + '\n' + \ + self.errorSummary(errstring)) self.verbose_logger.log(yum.logginglevels.INFO_2, _('Transaction Test Succeeded')) @@ -624,9 +624,8 @@ class YumBaseCli(yum.YumBase, output.YumOutput): elif result == 1: if not sys.stdin.isatty() and not self.conf.assumeyes: - raise yum.Errors.YumBaseError, \ - _('Refusing to automatically import keys when running ' \ - 'unattended.\nUse "-y" to override.') + raise yum.Errors.YumBaseError(_('Refusing to automatically import keys when running ' \ + 'unattended.\nUse "-y" to override.')) # the callback here expects to be able to take options which # userconfirm really doesn't... so fake it @@ -634,7 +633,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): else: # Fatal error - raise yum.Errors.YumBaseError, errmsg + raise yum.Errors.YumBaseError(errmsg) return 0 @@ -642,7 +641,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): """ If install argument doesn't match with case, tell the user. """ matches = self.doPackageLists(patterns=[arg], ignore_case=True) matches = matches.installed + matches.available - matches = set(map(lambda x: x.name, matches)) + matches = set([x.name for x in matches]) if matches: msg = self.fmtKeyValFill(_(' * Maybe you meant: '), ", ".join(matches)) @@ -681,7 +680,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): _('Package(s) %s%s%s available, but not installed.'), hibeg, arg, hiend) return - matches = set(map(lambda x: x.name, matches.installed)) + matches = set([x.name for x in matches.installed]) if always_output or matches: self.verbose_logger.log(yum.logginglevels.INFO_2, _('No package %s%s%s available.'), @@ -803,7 +802,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): pkgs = [] if ipkgs: try: - pkgs = self.pkgSack.returnNewestByName(patterns=ipkgs.keys()) + pkgs = self.pkgSack.returnNewestByName(patterns=list(ipkgs.keys())) except yum.Errors.PackageSackError: pkgs = [] @@ -927,7 +926,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): self.reinstall(pattern=arg) except yum.Errors.ReinstallRemoveError: self._checkMaybeYouMeant(arg, always_output=False) - except yum.Errors.ReinstallInstallError, e: + except yum.Errors.ReinstallInstallError as e: for ipkg in e.failed_pkgs: xmsg = '' if 'from_repo' in ipkg.yumdb_info: @@ -937,7 +936,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): self.verbose_logger.log(yum.logginglevels.INFO_2, msg, self.term.MODE['bold'], ipkg, self.term.MODE['normal'], xmsg) - except yum.Errors.ReinstallError, e: + except yum.Errors.ReinstallError as e: assert False, "Shouldn't happen, but just in case" self.verbose_logger.log(yum.logginglevels.INFO_2, e) if len(self.tsInfo) > oldcount: @@ -1026,7 +1025,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): searchlist = ['name', 'summary', 'description', 'url'] dups = self.conf.showdupesfromrepos - args = map(to_unicode, args) + args = list(map(to_unicode, args)) okeys = set() akeys = set() # All keys, used to see if nothing matched @@ -1036,7 +1035,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): def _print_match_section(text): # Print them in the order they were passed used_keys = [arg for arg in args if arg in keys] - print self.fmtSection(text % ", ".join(used_keys)) + print(self.fmtSection(text % ", ".join(used_keys))) # First try just the name/summary fields, and if we get any hits # don't do the other stuff. Unless the user overrides via. "all". @@ -1050,7 +1049,7 @@ class YumBaseCli(yum.YumBase, output.YumOutput): if akeys: if len(mkeys) == len(args): break - print "" + print("") else: mkeys = set(keys) _print_match_section(_('N/S Matched: %s')) @@ -1068,12 +1067,12 @@ class YumBaseCli(yum.YumBase, output.YumOutput): # with _more_ search terms. Thus. if we hit all our search terms. do # nothing. if len(mkeys) == len(args): - print "" + print("") if len(args) == 1: msg = _(' Name and summary matches %sonly%s, use "search all" for everything.') else: msg = _(' Full name and summary matches %sonly%s, use "search all" for everything.') - print msg % (self.term.MODE['bold'], self.term.MODE['normal']) + print(msg % (self.term.MODE['bold'], self.term.MODE['normal'])) matching = [] for (po, keys, matched_value) in matching: @@ -1089,15 +1088,15 @@ class YumBaseCli(yum.YumBase, output.YumOutput): if keys != okeys: if akeys: - print "" + print("") _print_match_section(_('Matched: %s')) okeys = keys akeys.update(keys) self.matchcallback(po, matched_value, args) if mkeys and len(mkeys) != len(args): - print "" - print _(' Name and summary matches %smostly%s, use "search all" for everything.') % (self.term.MODE['bold'], self.term.MODE['normal']) + print("") + print(_(' Name and summary matches %smostly%s, use "search all" for everything.') % (self.term.MODE['bold'], self.term.MODE['normal'])) for arg in args: if arg not in akeys: @@ -1504,10 +1503,10 @@ class YumOptionParser(OptionParser): '--disableplugin', '--enableplugin', '--releasever', '--setopt'), args) - except ValueError, arg: + except ValueError as arg: self.base.usage() - print >> sys.stderr, (_("\n\n%s: %s option requires an argument") % - ('Command line error', arg)) + print((_("\n\n%s: %s option requires an argument") % + ('Command line error', arg)), file=sys.stderr) sys.exit(1) return self.parse_args(args=args)[0] @@ -1560,7 +1559,7 @@ class YumOptionParser(OptionParser): if opts.color not in (None, 'auto', 'always', 'never', 'tty', 'if-tty', 'yes', 'no', 'on', 'off'): - raise ValueError, _("--color takes one of: auto, always, never") + raise ValueError(_("--color takes one of: auto, always, never")) elif opts.color is None: if self.base.conf.color != 'auto': self.base.term.reinit(color=self.base.conf.color) @@ -1585,7 +1584,7 @@ class YumOptionParser(OptionParser): excludelist = self.base.conf.exclude excludelist.append(exclude) self.base.conf.exclude = excludelist - except yum.Errors.ConfigError, e: + except yum.Errors.ConfigError as e: self.logger.critical(e) self.base.usage() sys.exit(1) @@ -1605,7 +1604,7 @@ class YumOptionParser(OptionParser): self.base.repos.enableRepo(repoexp) elif opt == '--disablerepo': self.base.repos.disableRepo(repoexp) - except yum.Errors.ConfigError, e: + except yum.Errors.ConfigError as e: self.logger.critical(e) self.base.usage() sys.exit(1) @@ -1622,7 +1621,7 @@ class YumOptionParser(OptionParser): for repo in self.base.repos.listEnabled(): repo._override_sigchecks = True - except ValueError, e: + except ValueError as e: self.logger.critical(_('Options Error: %s'), e) self.base.usage() sys.exit(1) @@ -1785,10 +1784,10 @@ def _filtercmdline(novalopts, valopts, args): elif a in valopts: if len(args) < 1: - raise ValueError, a + raise ValueError(a) next = args.pop(0) if next[0] == '-': - raise ValueError, a + raise ValueError(a) out.extend([a, next]) diff --git a/debian/changelog b/debian/changelog index 31a956e..019dc37 100755 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +yum (3.4.3-9) experimental; urgency=low + + * Port code from python2.x to python3.x. + + -- Biao Wang <biao716.wang@samsung.com> Thu, 04 Aug 2022 15:37:12 +0000 + yum (3.4.3-0) experimental; urgency=low * Add debian. diff --git a/debian/control b/debian/control index 856b00e..1411e33 100755 --- a/debian/control +++ b/debian/control @@ -3,7 +3,7 @@ Section: admin Priority: extra Maintainer: Thomas Goirand <zigo@debian.org> Uploaders: Mike Miller <mtmiller@ieee.org> -Build-Depends: debhelper (>= 9), python-all (>= 2.6.6-3~), python, python-dev +Build-Depends: debhelper (>= 9), dh-python, python3-all, python3, python3-dev Build-Depends-Indep: intltool Vcs-Browser: http://anonscm.debian.org/gitweb/?p=collab-maint/yum.git Vcs-Git: git://anonscm.debian.org/collab-maint/yum.git @@ -12,15 +12,14 @@ Homepage: http://yum.baseurl.org/ Package: yum Architecture: all -Depends: python (>= 2.5) | python-celementtree, - python-libxml2, - python-rpm, - python-sqlite, - python-sqlitecachec, - python-urlgrabber, +Depends: python3, + python3-libxml2, + python3-rpm, + python3-sqlitecachec, + python3-urlgrabber, rpm (>= 4.4.1), ${misc:Depends}, - ${python:Depends}, + ${python3:Depends}, ${shlibs:Depends} Description: Advanced front-end for rpm Yum (Yellow dog Updater, Modified) is an automatic updater and package diff --git a/debian/rules b/debian/rules index d1766df..19e333f 100755 --- a/debian/rules +++ b/debian/rules @@ -1,6 +1,7 @@ #!/usr/bin/make -f #export DH_VERBOSE=1 +py_stdlib := $(shell python3 -c 'import sysconfig; print(sysconfig.get_paths()["stdlib"])') configure: configure-stamp configure-stamp: @@ -52,8 +53,8 @@ install-indep: rm -f $(CURDIR)/debian/yum/usr/share/man/man*/yum-updatesd* rm -f $(CURDIR)/debian/yum/usr/share/yum-cli/yumupd.py* rmdir $(CURDIR)/debian/yum/usr/sbin - if [ -d $(CURDIR)/debian/yum/usr/lib/python2.7/site-packages ] ; then \ - mv $(CURDIR)/debian/yum/usr/lib/python2.7/site-packages $(CURDIR)/debian/yum/usr/lib/python2.7/dist-packages ; \ + if [ -d $(CURDIR)/debian/yum/$(py_stdlib)/site-packages ] ; then \ + mv $(CURDIR)/debian/yum/$(py_stdlib)/site-packages $(CURDIR)/debian/yum/$(py_stdlib)/dist-packages ; \ fi binary-common: @@ -67,8 +68,8 @@ binary-common: dh_strip dh_compress dh_fixperms - dh_python2 --skip-private - dh_python2 /usr/share/yum-cli + dh_python3 --skip-private + dh_python3 /usr/share/yum-cli dh_makeshlibs dh_installdeb dh_shlibdeps @@ -229,19 +229,19 @@ class YumTerm: # Colors set_fg = self._tigetstr('setf') if set_fg: - for (color, val) in self.__colors.items(): + for (color, val) in list(self.__colors.items()): self.FG_COLOR[color] = curses.tparm(set_fg, val) or '' set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: - for (color, val) in self.__ansi_colors.items(): + for (color, val) in list(self.__ansi_colors.items()): self.FG_COLOR[color] = curses.tparm(set_fg_ansi, val) or '' set_bg = self._tigetstr('setb') if set_bg: - for (color, val) in self.__colors.items(): + for (color, val) in list(self.__colors.items()): self.BG_COLOR[color] = curses.tparm(set_bg, val) or '' set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: - for (color, val) in self.__ansi_colors.items(): + for (color, val) in list(self.__ansi_colors.items()): self.BG_COLOR[color] = curses.tparm(set_bg_ansi, val) or '' def __init__(self, term_stream=None, color='auto'): @@ -327,7 +327,7 @@ class YumOutput: hiend = '' if not highlight: pass - elif not isinstance(highlight, basestring) or highlight == 'bold': + elif not isinstance(highlight, str) or highlight == 'bold': hibeg = self.term.MODE['bold'] elif highlight == 'normal': pass # Minor opt. @@ -403,7 +403,7 @@ class YumOutput: # Find which field all the spaces left will help best helps = 0 val = 0 - for d in xrange(0, cols): + for d in range(0, cols): thelps = self._calc_columns_spaces_helps(columns[d], data[d], total_width) if not thelps: @@ -431,7 +431,7 @@ class YumOutput: continue overflowed_columns = 0 - for d in xrange(0, cols): + for d in range(0, cols): if not data[d]: continue overflowed_columns += 1 @@ -439,7 +439,7 @@ class YumOutput: # Split the remaining spaces among each overflowed column # equally norm = total_width / overflowed_columns - for d in xrange(0, cols): + for d in range(0, cols): if not data[d]: continue columns[d] += norm @@ -449,7 +449,7 @@ class YumOutput: # last one. And put the rest into the remainder column cols -= 1 norm = total_width / cols - for d in xrange(0, cols): + for d in range(0, cols): columns[d] += norm columns[remainder_column] += total_width - (cols * norm) total_width = 0 @@ -459,8 +459,8 @@ class YumOutput: @staticmethod def _fmt_column_align_width(width): if width < 0: - return (u"-", -width) - return (u"", width) + return ("-", -width) + return ("", width) def _col_data(self, col_data): assert len(col_data) == 2 or len(col_data) == 3 @@ -472,7 +472,7 @@ class YumOutput: (hibeg, hiend) = self._highlight(highlight) return (val, width, hibeg, hiend) - def fmtColumns(self, columns, msg=u'', end=u'', text_width=utf8_width): + def fmtColumns(self, columns, msg='', end='', text_width=utf8_width): """ Return a string for columns of data, which can overflow. text_width parameter finds the width of columns, this defaults to utf8 but can be changed to len() if you know it'll be fine. """ @@ -483,7 +483,7 @@ class YumOutput: (val, width, hibeg, hiend) = self._col_data(col_data) if not width: # Don't count this column, invisible text - msg += u"%s" + msg += "%s" data.append(val) continue @@ -493,21 +493,21 @@ class YumOutput: # Don't use utf8_width_fill() because it sucks performance # wise for 1,000s of rows. Also allows us to use len(), when # we can. - msg += u"%s%s%s%s " - if (align == u'-'): + msg += "%s%s%s%s " + if (align == '-'): data.extend([hibeg, val, " " * (width - val_width), hiend]) else: data.extend([hibeg, " " * (width - val_width), val, hiend]) else: - msg += u"%s%s%s\n" + " " * (total_width + width + 1) + msg += "%s%s%s\n" + " " * (total_width + width + 1) data.extend([hibeg, val, hiend]) total_width += width total_width += 1 (val, width, hibeg, hiend) = self._col_data(columns[-1]) (align, width) = self._fmt_column_align_width(width) - val = utf8_width_fill(val, width, left=(align == u'-'), + val = utf8_width_fill(val, width, left=(align == '-'), prefix=hibeg, suffix=hiend) - msg += u"%%s%s" % end + msg += "%%s%s" % end data.append(val) return msg % tuple(data) @@ -521,8 +521,8 @@ class YumOutput: na = '%s%s.%s' % (indent, pkg.name, pkg.arch) hi_cols = [highlight, 'normal', 'normal'] rid = pkg.ui_from_repo - columns = zip((na, ver, rid), columns, hi_cols) - print self.fmtColumns(columns, text_width=len) + columns = list(zip((na, ver, rid), columns, hi_cols)) + print((self.fmtColumns(columns, text_width=len))) def simpleEnvraList(self, pkg, ui_overflow=False, indent='', highlight=False, columns=None): @@ -534,8 +534,8 @@ class YumOutput: envra = '%s%s' % (indent, str(pkg)) hi_cols = [highlight, 'normal', 'normal'] rid = pkg.ui_from_repo - columns = zip((envra, rid), columns, hi_cols) - print self.fmtColumns(columns, text_width=len) + columns = list(zip((envra, rid), columns, hi_cols)) + print((self.fmtColumns(columns, text_width=len))) def fmtKeyValFill(self, key, val): """ Return a key value pair in the common two column output format. """ @@ -578,22 +578,22 @@ class YumOutput: def infoOutput(self, pkg, highlight=False): (hibeg, hiend) = self._highlight(highlight) - print _("Name : %s%s%s") % (hibeg, to_unicode(pkg.name), hiend) - print _("Arch : %s") % to_unicode(pkg.arch) + print((_("Name : %s%s%s") % (hibeg, to_unicode(pkg.name), hiend))) + print((_("Arch : %s") % to_unicode(pkg.arch))) if pkg.epoch != "0": - print _("Epoch : %s") % to_unicode(pkg.epoch) - print _("Version : %s") % to_unicode(pkg.version) - print _("Release : %s") % to_unicode(pkg.release) - print _("Size : %s") % self.format_number(float(pkg.size)) - print _("Repo : %s") % to_unicode(pkg.repoid) + print((_("Epoch : %s") % to_unicode(pkg.epoch))) + print((_("Version : %s") % to_unicode(pkg.version))) + print((_("Release : %s") % to_unicode(pkg.release))) + print((_("Size : %s") % self.format_number(float(pkg.size)))) + print((_("Repo : %s") % to_unicode(pkg.repoid))) if pkg.repoid == 'installed' and 'from_repo' in pkg.yumdb_info: - print _("From repo : %s") % to_unicode(pkg.yumdb_info.from_repo) + print((_("From repo : %s") % to_unicode(pkg.yumdb_info.from_repo))) if self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3): - print _("Committer : %s") % to_unicode(pkg.committer) - print _("Committime : %s") % time.ctime(pkg.committime) - print _("Buildtime : %s") % time.ctime(pkg.buildtime) + print((_("Committer : %s") % to_unicode(pkg.committer))) + print((_("Committime : %s") % time.ctime(pkg.committime))) + print((_("Buildtime : %s") % time.ctime(pkg.buildtime))) if hasattr(pkg, 'installtime'): - print _("Install time: %s") % time.ctime(pkg.installtime) + print((_("Install time: %s") % time.ctime(pkg.installtime))) if pkg.repoid == 'installed': uid = None if 'installed_by' in pkg.yumdb_info: @@ -601,20 +601,20 @@ class YumOutput: uid = int(pkg.yumdb_info.installed_by) except ValueError: # In case int() fails uid = None - print _("Installed by: %s") % self._pwd_ui_username(uid) + print((_("Installed by: %s") % self._pwd_ui_username(uid))) uid = None if 'changed_by' in pkg.yumdb_info: try: uid = int(pkg.yumdb_info.changed_by) except ValueError: # In case int() fails uid = None - print _("Changed by : %s") % self._pwd_ui_username(uid) - print self.fmtKeyValFill(_("Summary : "), self._enc(pkg.summary)) + print((_("Changed by : %s") % self._pwd_ui_username(uid))) + print((self.fmtKeyValFill(_("Summary : "), self._enc(pkg.summary)))) if pkg.url: - print _("URL : %s") % to_unicode(pkg.url) - print self.fmtKeyValFill(_("License : "), to_unicode(pkg.license)) - print self.fmtKeyValFill(_("Description : "),self._enc(pkg.description)) - print "" + print((_("URL : %s") % to_unicode(pkg.url))) + print((self.fmtKeyValFill(_("License : "), to_unicode(pkg.license)))) + print((self.fmtKeyValFill(_("Description : "),self._enc(pkg.description)))) + print("") def updatesObsoletesList(self, uotup, changetype, columns=None): """takes an updates or obsoletes tuple of pkgobjects and @@ -636,7 +636,7 @@ class YumOutput: c_compact = changePkg.compactPrint() i_compact = '%s.%s' % (instPkg.name, instPkg.arch) c_repo = changePkg.repoid - print '%-35.35s [%.12s] %.10s %-20.20s' % (c_compact, c_repo, changetype, i_compact) + print(('%-35.35s [%.12s] %.10s %-20.20s' % (c_compact, c_repo, changetype, i_compact))) def listPkgs(self, lst, description, outputType, highlight_na={}, columns=None, highlight_modes={}): @@ -650,7 +650,7 @@ class YumOutput: thingslisted = 0 if len(lst) > 0: thingslisted = 1 - print '%s' % description + print(('%s' % description)) for pkg in sorted(lst): key = (pkg.name, pkg.arch) highlight = False @@ -686,7 +686,7 @@ class YumOutput: aui = (yui[0], yui[1], nui[0], nui[1]) while True: try: - choice = raw_input(_('Is this ok [y/N]: ')) + choice = eval(input(_('Is this ok [y/N]: '))) except UnicodeEncodeError: raise except UnicodeDecodeError: @@ -698,10 +698,10 @@ class YumOutput: if len(choice) == 0 or choice in aui: break # If the enlish one letter names don't mix, allow them too - if u'y' not in aui and u'y' == choice: + if 'y' not in aui and 'y' == choice: choice = yui[0] break - if u'n' not in aui and u'n' == choice: + if 'n' not in aui and 'n' == choice: break if len(choice) == 0 or choice not in yui: @@ -733,7 +733,7 @@ class YumOutput: # Convert (pkg.name, pkg.arch) to pkg.name dict ret = {} - for (apkg, ipkg) in pkgs.itervalues(): + for (apkg, ipkg) in list(pkgs.values()): pkg = apkg or ipkg ret.setdefault(pkg.name, []).append((apkg, ipkg)) return ret @@ -755,11 +755,11 @@ class YumOutput: indent=' ', columns=None): if not verbose: for item in sorted(pkg_names): - print '%s%s' % (indent, item) + print(('%s%s' % (indent, item))) else: for item in sorted(pkg_names): if item not in pkg_names2pkgs: - print '%s%s' % (indent, item) + print(('%s%s' % (indent, item))) continue for (apkg, ipkg) in sorted(pkg_names2pkgs[item], key=lambda x: x[1] or x[0]): @@ -774,18 +774,18 @@ class YumOutput: columns=columns) def displayPkgsInGroups(self, group): - print _('\nGroup: %s') % group.ui_name + print((_('\nGroup: %s') % group.ui_name)) verb = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3) if verb: - print _(' Group-Id: %s') % to_unicode(group.groupid) + print((_(' Group-Id: %s') % to_unicode(group.groupid))) pkg_names2pkgs = None if verb: pkg_names2pkgs = self._group_names2aipkgs(group.packages) if group.ui_description: - print _(' Description: %s') % to_unicode(group.ui_description) + print((_(' Description: %s') % to_unicode(group.ui_description))) if group.langonly: - print _(' Language: %s') % group.langonly + print((_(' Language: %s') % group.langonly)) sections = ((_(' Mandatory Packages:'), group.mandatory_packages), (_(' Default Packages:'), group.default_packages), @@ -802,7 +802,7 @@ class YumOutput: for (section_name, pkg_names) in sections: if len(pkg_names) > 0: - print section_name + print(section_name) self._displayPkgsFromNames(pkg_names, verb, pkg_names2pkgs, columns=columns) @@ -811,16 +811,16 @@ class YumOutput: verb = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3) for pkg in sorted(results): - print _("package: %s") % pkg.compactPrint() + print((_("package: %s") % pkg.compactPrint())) if len(results[pkg]) == 0: - print _(" No dependencies for this package") + print((_(" No dependencies for this package"))) continue for req in sorted(results[pkg]): reqlist = results[pkg][req] - print _(" dependency: %s") % prco_tuple_to_string(req) + print((_(" dependency: %s") % prco_tuple_to_string(req))) if not reqlist: - print _(" Unsatisfied dependency") + print((_(" Unsatisfied dependency"))) continue seen = {} @@ -829,7 +829,7 @@ class YumOutput: if not verb and key in seen: continue seen[key] = po - print " provider: %s" % po.compactPrint() + print((" provider: %s" % po.compactPrint())) def format_number(self, number, SI=0, space=' '): """Turn numbers into human-readable metric-like numbers""" @@ -857,7 +857,7 @@ class YumOutput: depth = depth + 1 number = number / step - if type(number) == type(1) or type(number) == type(1L): + if type(number) == type(1) or type(number) == type(1): format = '%i%s%s' elif number < 9.95: # must use 9.95 for proper sizing. For example, 9.99 will be @@ -890,14 +890,14 @@ class YumOutput: highlight = self.conf.color_search_match msg = self._sub_highlight(msg, highlight, matchfor,ignore_case=True) - print msg + print(msg) if verbose is None: verbose = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3) if not verbose: return - print _("Repo : %s") % po.ui_from_repo + print((_("Repo : %s") % po.ui_from_repo)) done = False for item in yum.misc.unique(values): item = to_utf8(item) @@ -905,7 +905,7 @@ class YumOutput: continue # Skip double name/summary printing if not done: - print _('Matched from:') + print((_('Matched from:'))) done = True can_overflow = True if False: pass @@ -929,10 +929,10 @@ class YumOutput: item = self._sub_highlight(item, highlight, matchfor, ignore_case=True) if can_overflow: - print self.fmtKeyValFill(key, to_unicode(item)) + print((self.fmtKeyValFill(key, to_unicode(item)))) else: - print key % item - print '\n\n' + print((key % item)) + print('\n\n') def matchcallback_verbose(self, po, values, matchfor=None): return self.matchcallback(po, values, matchfor, verbose=True) @@ -1052,8 +1052,8 @@ class YumOutput: for (action, pkglist) in [(_('Skipped (dependency problems)'), self.skipped_packages), - (_('Not installed'), self._not_found_i.values()), - (_('Not available'), self._not_found_a.values())]: + (_('Not installed'), list(self._not_found_i.values())), + (_('Not available'), list(self._not_found_a.values()))]: lines = [] for po in pkglist: a_wid = _add_line(lines, data, a_wid, po) @@ -1061,7 +1061,7 @@ class YumOutput: pkglist_lines.append((action, lines)) if not data['n']: - return u'' + return '' else: data = [data['n'], {}, data['v'], data['r'], {}] columns = [1, a_wid, 1, 1, 5] @@ -1070,23 +1070,23 @@ class YumOutput: (n_wid, a_wid, v_wid, r_wid, s_wid) = columns assert s_wid == 5 - out = [u""" + out = [""" %s %s %s """ % ('=' * self.term.columns, self.fmtColumns(((_('Package'), -n_wid), (_('Arch'), -a_wid), (_('Version'), -v_wid), (_('Repository'), -r_wid), - (_('Size'), s_wid)), u" "), + (_('Size'), s_wid)), " "), '=' * self.term.columns)] for (action, lines) in pkglist_lines: if lines: - totalmsg = u"%s:\n" % action + totalmsg = "%s:\n" % action for (n, a, evr, repoid, size, obsoletes, hi) in lines: columns = ((n, -n_wid, hi), (a, -a_wid), (evr, -v_wid), (repoid, -r_wid), (size, s_wid)) - msg = self.fmtColumns(columns, u" ", u"\n") + msg = self.fmtColumns(columns, " ", "\n") hibeg, hiend = self._highlight(self.conf.color_update_installed) for obspo in sorted(obsoletes): appended = _(' replacing %s%s%s.%s %s\n') @@ -1173,7 +1173,7 @@ Transaction Summary while msgs: current_msgs = msgs[:len(cols)] out += ' ' - out += self.fmtColumns(zip(current_msgs, cols), end=u'\n') + out += self.fmtColumns(list(zip(current_msgs, cols)), end='\n') msgs = msgs[len(cols):] return out @@ -1470,12 +1470,12 @@ to exit. name = _("Command line") else: name = _("Login user") - print fmt % (utf8_width_fill(_("ID"), 6, 6), + print((fmt % (utf8_width_fill(_("ID"), 6, 6), utf8_width_fill(name, 24, 24), utf8_width_fill(_("Date and time"), 16, 16), utf8_width_fill(_("Action(s)"), 14, 14), - utf8_width_fill(_("Altered"), 7, 7)) - print "-" * 79 + utf8_width_fill(_("Altered"), 7, 7)))) + print(("-" * 79)) fmt = "%6u | %s | %-16.16s | %s | %4u" done = 0 for old in old_tids: @@ -1508,7 +1508,7 @@ to exit. rmark = '<' if old.altered_gt_rpmdb: lmark = '>' - print fmt % (old.tid, name, tm, uiacts, num), "%s%s" % (lmark,rmark) + print((fmt % (old.tid, name, tm, uiacts, num), "%s%s" % (lmark,rmark))) lastdbv = self.history.last() if lastdbv is None: self._rpmdb_warn_checks(warn=False) @@ -1630,7 +1630,7 @@ to exit. mobj.merge(tid) elif mobj is not None: if done: - print "-" * 79 + print(("-" * 79)) done = True self._historyInfoCmd(mobj) @@ -1642,14 +1642,14 @@ to exit. if tid.tid in utids: if done: - print "-" * 79 + print(("-" * 79)) done = True self._historyInfoCmd(tid, pats) if mobj is not None: if done: - print "-" * 79 + print(("-" * 79)) self._historyInfoCmd(mobj) @@ -1673,8 +1673,8 @@ to exit. _pkg_states_available = {'i' : _('Installed'), 'e' : _('Not installed'), 'o' : _('Older'), 'n' : _('Newer')} # max() only in 2.5.z - maxlen = sorted([len(x) for x in (_pkg_states_installed.values() + - _pkg_states_available.values())])[-1] + maxlen = sorted([len(x) for x in (list(_pkg_states_installed.values()) + + list(_pkg_states_available.values()))])[-1] _pkg_states_installed['maxlen'] = maxlen _pkg_states_available['maxlen'] = maxlen def _simple_pkg(pkg, prefix_len, was_installed=False, highlight=False, @@ -1702,21 +1702,21 @@ to exit. else: (hibeg, hiend) = self._highlight('normal') state = utf8_width_fill(state, _pkg_states['maxlen']) - print "%s%s%s%s %-*s %s" % (prefix, hibeg, state, hiend, + print(("%s%s%s%s %-*s %s" % (prefix, hibeg, state, hiend, pkg_max_len, hpkg, - self._hpkg2from_repo(hpkg)) + self._hpkg2from_repo(hpkg)))) if type(old.tid) == type([]): - print _("Transaction ID :"), "%u..%u" % (old.tid[0], old.tid[-1]) + print((_("Transaction ID :"), "%u..%u" % (old.tid[0], old.tid[-1]))) else: - print _("Transaction ID :"), old.tid + print((_("Transaction ID :"), old.tid)) begtm = time.ctime(old.beg_timestamp) - print _("Begin time :"), begtm + print((_("Begin time :"), begtm)) if old.beg_rpmdbversion is not None: if old.altered_lt_rpmdb: - print _("Begin rpmdb :"), old.beg_rpmdbversion, "**" + print((_("Begin rpmdb :"), old.beg_rpmdbversion, "**")) else: - print _("Begin rpmdb :"), old.beg_rpmdbversion + print((_("Begin rpmdb :"), old.beg_rpmdbversion)) if old.end_timestamp is not None: endtm = time.ctime(old.end_timestamp) endtms = endtm.split() @@ -1739,37 +1739,37 @@ to exit. diff = _("(%u hours)") % (diff / (60 * 60)) else: diff = _("(%u days)") % (diff / (60 * 60 * 24)) - print _("End time :"), endtm, diff + print((_("End time :"), endtm, diff)) if old.end_rpmdbversion is not None: if old.altered_gt_rpmdb: - print _("End rpmdb :"), old.end_rpmdbversion, "**" + print((_("End rpmdb :"), old.end_rpmdbversion, "**")) else: - print _("End rpmdb :"), old.end_rpmdbversion + print((_("End rpmdb :"), old.end_rpmdbversion)) if type(name) == type([]): for name in name: - print _("User :"), name + print((_("User :"), name)) else: - print _("User :"), name + print((_("User :"), name)) if type(old.return_code) == type([]): codes = old.return_code if codes[0] is None: - print _("Return-Code :"), "**", _("Aborted"), "**" + print((_("Return-Code :"), "**", _("Aborted"), "**")) codes = codes[1:] if codes: - print _("Return-Code :"), _("Failures:"), ", ".join(codes) + print((_("Return-Code :"), _("Failures:"), ", ".join(codes))) elif old.return_code is None: - print _("Return-Code :"), "**", _("Aborted"), "**" + print((_("Return-Code :"), "**", _("Aborted"), "**")) elif old.return_code: - print _("Return-Code :"), _("Failure:"), old.return_code + print((_("Return-Code :"), _("Failure:"), old.return_code)) else: - print _("Return-Code :"), _("Success") + print((_("Return-Code :"), _("Success"))) if old.cmdline is not None: if type(old.cmdline) == type([]): for cmdline in old.cmdline: - print _("Command Line :"), cmdline + print((_("Command Line :"), cmdline)) else: - print _("Command Line :"), old.cmdline + print((_("Command Line :"), old.cmdline)) if type(old.tid) != type([]): addon_info = self.history.return_addon_data(old.tid) @@ -1778,29 +1778,29 @@ to exit. default_addons = set(['config-main', 'config-repos', 'saved_tx']) non_default = set(addon_info).difference(default_addons) if len(non_default) > 0: - print _("Additional non-default information stored: %d" - % len(non_default)) + print((_("Additional non-default information stored: %d" + % len(non_default)))) if old.trans_with: # This is _possible_, but not common - print _("Transaction performed with:") + print((_("Transaction performed with:"))) pkg_max_len = max((len(str(hpkg)) for hpkg in old.trans_with)) for hpkg in old.trans_with: _simple_pkg(hpkg, 4, was_installed=True, pkg_max_len=pkg_max_len) - print _("Packages Altered:") + print((_("Packages Altered:"))) self.historyInfoCmdPkgsAltered(old, pats) if old.trans_skip: - print _("Packages Skipped:") + print((_("Packages Skipped:"))) pkg_max_len = max((len(str(hpkg)) for hpkg in old.trans_skip)) for hpkg in old.trans_skip: _simple_pkg(hpkg, 4, pkg_max_len=pkg_max_len) if old.rpmdb_problems: - print _("Rpmdb Problems:") + print((_("Rpmdb Problems:"))) for prob in old.rpmdb_problems: key = "%s%s: " % (" " * 4, prob.problem) - print self.fmtKeyValFill(key, prob.text) + print((self.fmtKeyValFill(key, prob.text))) if prob.packages: pkg_max_len = max((len(str(hpkg)) for hpkg in prob.packages)) for hpkg in prob.packages: @@ -1808,17 +1808,17 @@ to exit. pkg_max_len=pkg_max_len) if old.output: - print _("Scriptlet output:") + print((_("Scriptlet output:"))) num = 0 for line in old.output: num += 1 - print "%4d" % num, line + print(("%4d" % num, line)) if old.errors: - print _("Errors:") + print((_("Errors:"))) num = 0 for line in old.errors: num += 1 - print "%4d" % num, line + print(("%4d" % num, line)) _history_state2uistate = {'True-Install' : _('Install'), 'Install' : _('Install'), @@ -1881,9 +1881,9 @@ to exit. last = None if hpkg.state in ('Updated', 'Downgrade'): last = hpkg - print "%s%s%s%s %-*s %s" % (prefix, hibeg, uistate, hiend, + print(("%s%s%s%s %-*s %s" % (prefix, hibeg, uistate, hiend, pkg_max_len, cn, - self._hpkg2from_repo(hpkg)) + self._hpkg2from_repo(hpkg)))) def historySummaryCmd(self, extcmds): tids, printall = self._history_list_transactions(extcmds) @@ -1891,11 +1891,11 @@ to exit. return 1, ['Failed history info'] fmt = "%s | %s | %s | %s" - print fmt % (utf8_width_fill(_("Login user"), 26, 26), + print((fmt % (utf8_width_fill(_("Login user"), 26, 26), utf8_width_fill(_("Time"), 19, 19), utf8_width_fill(_("Action(s)"), 16, 16), - utf8_width_fill(_("Altered"), 8, 8)) - print "-" * 79 + utf8_width_fill(_("Altered"), 8, 8)))) + print(("-" * 79)) fmt = "%s | %s | %s | %8u" data = {'day' : {}, 'week' : {}, 'fortnight' : {}, 'quarter' : {}, 'half' : {}, @@ -1941,9 +1941,9 @@ to exit. count, uiacts = self._history_uiactions(hpkgs) uperiod = _period2user[period] # Should probably use columns here, esp. for uiacts? - print fmt % (utf8_width_fill(name, 26, 26), + print((fmt % (utf8_width_fill(name, 26, 26), utf8_width_fill(uperiod, 19, 19), - utf8_width_fill(uiacts, 16, 16), count) + utf8_width_fill(uiacts, 16, 16), count))) def historyAddonInfoCmd(self, extcmds): tid = None @@ -1973,22 +1973,22 @@ to exit. hist_data = old[0] addon_info = self.history.return_addon_data(hist_data.tid) if len(extcmds) <= 2: - print _("Transaction ID:"), hist_data.tid - print _('Available additional history information:') + print((_("Transaction ID:"), hist_data.tid)) + print((_('Available additional history information:'))) for itemname in self.history.return_addon_data(hist_data.tid): - print ' %s' % itemname - print '' + print((' %s' % itemname)) + print('') return 0, ['history addon-info'] for item in extcmds[2:]: if item in addon_info: - print '%s:' % item - print self.history.return_addon_data(hist_data.tid, item) + print(('%s:' % item)) + print((self.history.return_addon_data(hist_data.tid, item))) else: - print _('%s: No additional data found by this name') % item + print((_('%s: No additional data found by this name') % item)) - print '' + print('') def historyPackageListCmd(self, extcmds): """ Shows the user a list of data about the history, from the point @@ -2005,10 +2005,10 @@ to exit. fmt = "%s | %s | %s" # REALLY Needs to use columns! - print fmt % (utf8_width_fill(_("ID"), 6, 6), + print((fmt % (utf8_width_fill(_("ID"), 6, 6), utf8_width_fill(_("Action(s)"), 14, 14), - utf8_width_fill(_("Package"), 53, 53)) - print "-" * 79 + utf8_width_fill(_("Package"), 53, 53)))) + print(("-" * 79)) fmt = "%6u | %s | %-50s" num = 0 for old in self.history.old(tids, limit=limit): @@ -2065,7 +2065,7 @@ to exit. last = hpkg num += 1 - print fmt % (old.tid, uistate, cn), "%s%s" % (lmark,rmark) + print((fmt % (old.tid, uistate, cn), "%s%s" % (lmark,rmark))) # And, again, copy and paste... lastdbv = self.history.last() @@ -2346,14 +2346,14 @@ class YumCliRPMCallBack(RPMBaseCallback): if not hasattr(self, '_max_action_wid'): wid1 = 0 - for val in self.action.values(): + for val in list(self.action.values()): wid_val = utf8_width(val) if wid1 < wid_val: wid1 = wid_val self._max_action_wid = wid1 wid1 = self._max_action_wid - if type(package) not in types.StringTypes: + if type(package) not in (str,): pkgname = str(package) else: pkgname = self.pkgname_ui(package) @@ -2362,7 +2362,7 @@ class YumCliRPMCallBack(RPMBaseCallback): if te_total == 0: percent = 0 else: - percent = (te_current*100L)/te_total + percent = (te_current*100)/te_total if self.output and (sys.stdout.isatty() or te_current == te_total): (fmt, wid1, wid2) = self._makefmt(percent, ts_current, ts_total, @@ -2374,7 +2374,7 @@ class YumCliRPMCallBack(RPMBaseCallback): sys.stdout.flush() self.lastmsg = msg if te_current == te_total: - print " " + print(" ") def scriptout(self, package, msgs): if msgs: @@ -2485,34 +2485,34 @@ def progressbar(current, total, name=None): if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "format_number": - print "" - print " Doing format_number tests, right column should align" - print "" + print("") + print(" Doing format_number tests, right column should align") + print("") x = YumOutput() for i in (0, 0.0, 0.1, 1, 1.0, 1.1, 10, 11, 11.1, 100, 111.1, 1000, 1111, 1024 * 2, 10000, 11111, 99999, 999999, 10**19, 10**20, 10**35): out = x.format_number(i) - print "%36s <%s> %s <%5s>" % (i, out, ' ' * (14 - len(out)), out) + print(("%36s <%s> %s <%5s>" % (i, out, ' ' * (14 - len(out)), out))) if len(sys.argv) > 1 and sys.argv[1] == "progress": - print "" - print " Doing progress, small name" - print "" - for i in xrange(0, 101): + print("") + print(" Doing progress, small name") + print("") + for i in range(0, 101): progressbar(i, 100, "abcd") time.sleep(0.1) - print "" - print " Doing progress, big name" - print "" - for i in xrange(0, 101): + print("") + print(" Doing progress, big name") + print("") + for i in range(0, 101): progressbar(i, 100, "_%s_" % ("123456789 " * 5)) time.sleep(0.1) - print "" - print " Doing progress, no name" - print "" - for i in xrange(0, 101): + print("") + print(" Doing progress, no name") + print("") + for i in range(0, 101): progressbar(i, 100) time.sleep(0.1) @@ -2521,16 +2521,16 @@ if __name__ == "__main__": cb.output = True cb.action["foo"] = "abcd" cb.action["bar"] = "_12345678_.end" - print "" - print " Doing CB, small proc / small pkg" - print "" - for i in xrange(0, 101): + print("") + print(" Doing CB, small proc / small pkg") + print("") + for i in range(0, 101): cb.event("spkg", "foo", i, 100, i, 100) time.sleep(0.1) - print "" - print " Doing CB, big proc / big pkg" - print "" - for i in xrange(0, 101): + print("") + print(" Doing CB, big proc / big pkg") + print("") + for i in range(0, 101): cb.event("lpkg" + "-=" * 15 + ".end", "bar", i, 100, i, 100) time.sleep(0.1) @@ -2539,21 +2539,21 @@ if __name__ == "__main__": 'i18n-rpm-progress'): yum.misc.setup_locale() if len(sys.argv) > 1 and sys.argv[1] in ("progress", "i18n-progress"): - print "" - print " Doing progress, i18n: small name" - print "" - for i in xrange(0, 101): + print("") + print(" Doing progress, i18n: small name") + print("") + for i in range(0, 101): progressbar(i, 100, to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85')) time.sleep(0.1) - print "" + print("") - print "" - print " Doing progress, i18n: big name" - print "" - for i in xrange(0, 101): + print("") + print(" Doing progress, i18n: big name") + print("") + for i in range(0, 101): progressbar(i, 100, to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85' * 5 + ".end")) time.sleep(0.1) - print "" + print("") if len(sys.argv) > 1 and sys.argv[1] in ("progress", "i18n-progress", @@ -2563,17 +2563,17 @@ if __name__ == "__main__": cb.output = True cb.action["foo"] = to_unicode('\xe6\xad\xa3\xe5\x9c\xa8\xe5\xae\x89\xe8\xa3\x85') cb.action["bar"] = cb.action["foo"] * 5 + ".end" - print "" - print " Doing CB, i18n: small proc / small pkg" - print "" - for i in xrange(0, 101): + print("") + print(" Doing CB, i18n: small proc / small pkg") + print("") + for i in range(0, 101): cb.event("spkg", "foo", i, 100, i, 100) time.sleep(0.1) - print "" - print " Doing CB, i18n: big proc / big pkg" - print "" - for i in xrange(0, 101): + print("") + print(" Doing CB, i18n: big proc / big pkg") + print("") + for i in range(0, 101): cb.event("lpkg" + "-=" * 15 + ".end", "bar", i, 100, i, 100) time.sleep(0.1) - print "" + print("") diff --git a/packaging/yum.spec b/packaging/yum.spec index 001970d..53971b9 100644 --- a/packaging/yum.spec +++ b/packaging/yum.spec @@ -16,22 +16,21 @@ Source1: yum.conf Source1001: yum.manifest Url: http://yum.baseurl.org/ -BuildRequires: gettext BuildRequires: intltool -BuildRequires: python-gpgme -BuildRequires: python >= 2.4 -BuildRequires: python-iniparse -BuildRequires: python-nose -BuildRequires: python-urlgrabber >= 3.9.0 +BuildRequires: python3-gpgme +BuildRequires: python3 +BuildRequires: python3-iniparse +BuildRequires: python3-nose +BuildRequires: python3-urlgrabber >= 3.9.0 BuildRequires: rpm >= 4.10.0 -BuildRequires: python-rpm +BuildRequires: python3-rpm BuildRequires: yum-metadata-parser >= 1.1.0 -Requires: python-gpgme -Requires: python >= 2.7 -Requires: python-iniparse -Requires: python-urlgrabber >= 3.9.0 +Requires: python3-gpgme +Requires: python3 +Requires: python3-iniparse +Requires: python3-urlgrabber >= 3.9.0 Requires: rpm >= 4.10.0 -Requires: python-rpm +Requires: python3-rpm Requires: yum-metadata-parser >= 1.1.0 BuildArch: noarch @@ -82,8 +81,8 @@ touch %{buildroot}%{_localstatedir}/lib/yum/uuid # rpmlint bogus stuff... chmod +x %{buildroot}/%{_datadir}/yum-cli/*.py -chmod +x %{buildroot}/%{python_sitelib}/yum/*.py -chmod +x %{buildroot}/%{python_sitelib}/rpmUtils/*.py +chmod +x %{buildroot}/%{python3_sitelib}/yum/*.py +chmod +x %{buildroot}/%{python3_sitelib}/rpmUtils/*.py %find_lang %{name} @@ -103,8 +102,8 @@ chmod +x %{buildroot}/%{python_sitelib}/rpmUtils/*.py %{_sysconfdir}/bash_completion.d %{_datadir}/yum-cli/ %{_bindir}/yum -%{python_sitelib}/yum -%{python_sitelib}/rpmUtils +%{python3_sitelib}/yum +%{python3_sitelib}/rpmUtils %dir %{_localstatedir}/cache/yum %dir %{_localstatedir}/lib/yum %ghost %{_localstatedir}/lib/yum/uuid diff --git a/po/pygettext.py b/po/pygettext.py index 276a433..4a16a04 100644 --- a/po/pygettext.py +++ b/po/pygettext.py @@ -160,9 +160,9 @@ msgstr "" ''' def usage(code, msg=''): - print __doc__ % globals() + print((__doc__ % globals())) if msg: - print msg + print(msg) sys.exit(code) @@ -172,7 +172,7 @@ def make_escapes(pass_iso8859): global escapes if pass_iso8859: # Allow iso-8859 characters to pass through so that e.g. 'msgid - # "Höhe"' would result not result in 'msgid "H\366he"'. Otherwise we + # would result not result in 'msgid "H\366he"'. Otherwise we # escape any character outside the 32..126 range. mod = 128 else: @@ -274,15 +274,15 @@ class TokenEater: sys.stdout = fp # The time stamp in the header doesn't have the same format # as that generated by xgettext... - print pot_header % {'time': timestamp, 'version': __version__} - for k, v in self.__messages.items(): + print((pot_header % {'time': timestamp, 'version': __version__})) + for k, v in list(self.__messages.items()): if not options.writelocations: pass # location comments are different b/w Solaris and GNU: elif options.locationstyle == options.SOLARIS: for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} - print '# File: %(filename)s, line: %(lineno)d' % d + print(('# File: %(filename)s, line: %(lineno)d' % d)) elif options.locationstyle == options.GNU: # fit as many locations on one line, as long as the # resulting line length doesn't exceeds 'options.width' @@ -293,14 +293,14 @@ class TokenEater: if len(locline) + len(s) <= options.width: locline = locline + s else: - print locline + print(locline) locline = "#:" + s if len(locline) > 2: - print locline - print "#, c-format" + print(locline) + print("#, c-format") # TBD: sorting, normalizing - print 'msgid', normalize(k) - print 'msgstr ""\n' + print(('msgid', normalize(k))) + print('msgstr ""\n') finally: sys.stdout = sys.__stdout__ @@ -315,7 +315,7 @@ def main(): 'add-location', 'no-location', 'output-file=', 'output-dir=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=', ]) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) # for holding option values @@ -369,7 +369,7 @@ def main(): elif opt in ('-v', '--verbose'): options.verbose = 1 elif opt in ('-V', '--version'): - print 'pygettext.py (xgettext for Python) %s' % __version__ + print(('pygettext.py (xgettext for Python) %s' % __version__)) sys.exit(0) elif opt in ('-w', '--width'): try: @@ -402,12 +402,12 @@ def main(): for filename in args: if filename == '-': if options.verbose: - print 'Reading standard input' + print('Reading standard input') fp = sys.stdin closep = 0 else: if options.verbose: - print 'Working on %s' % filename + print(('Working on %s' % filename)) fp = open(filename) closep = 1 try: diff --git a/rpmUtils/Makefile b/rpmUtils/Makefile index cd469d2..39033b6 100644 --- a/rpmUtils/Makefile +++ b/rpmUtils/Makefile @@ -1,8 +1,8 @@ -PYTHON=python +PYTHON=python3 PACKAGE = $(shell basename `pwd`) PYFILES = $(wildcard *.py) -PYVER := $(shell $(PYTHON) -c 'import sys; print "%.3s" %(sys.version)') -PYSYSDIR := $(shell $(PYTHON) -c 'import sys; print sys.prefix') +PYVER := $(shell $(PYTHON) -c 'import sys; print("%.3s" %(sys.version))') +PYSYSDIR := $(shell $(PYTHON) -c 'import sys; print(sys.prefix)') PYLIBDIR = $(PYSYSDIR)/lib/python$(PYVER) PKGDIR = $(PYLIBDIR)/site-packages/$(PACKAGE) diff --git a/rpmUtils/arch.py b/rpmUtils/arch.py index 6082005..b3db11d 100644 --- a/rpmUtils/arch.py +++ b/rpmUtils/arch.py @@ -81,7 +81,7 @@ def legitMultiArchesInSameLib(arch=None): results = [arch] if arch == 'x86_64' or arch.startswith('sparcv9'): - for (k, v) in arches.items(): + for (k, v) in list(arches.items()): if v == arch: results.append(k) return results diff --git a/rpmUtils/miscutils.py b/rpmUtils/miscutils.py index aea4550..e33bfbf 100644 --- a/rpmUtils/miscutils.py +++ b/rpmUtils/miscutils.py @@ -26,17 +26,19 @@ import signal import rpmUtils.transaction def rpmOutToStr(arg): - if type(arg) != types.StringType: + if type(arg) != bytes: # and arg is not None: arg = str(arg) return arg -def compareEVR((e1, v1, r1), (e2, v2, r2)): +def compareEVR(xxx_todo_changeme, xxx_todo_changeme1): # return 1: a is newer than b # 0: a and b are the same version # -1: b is newer than a + (e1, v1, r1) = xxx_todo_changeme + (e2, v2, r2) = xxx_todo_changeme1 if e1 is None: e1 = '0' else: @@ -71,7 +73,7 @@ def checkSig(ts, package): fdno = os.open(package, os.O_RDONLY) try: hdr = ts.hdrFromFdno(fdno) - except rpm.error, e: + except rpm.error as e: if str(e) == "public key not availaiable": value = 1 if str(e) == "public key not available": @@ -91,7 +93,7 @@ def checkSig(ts, package): try: os.close(fdno) - except OSError, e: # if we're not opened, don't scream about it + except OSError as e: # if we're not opened, don't scream about it pass ts.setVSFlags(currentflags) # put things back like they were before @@ -265,7 +267,7 @@ def unique(s): except TypeError: del u # move on to the next method else: - return u.keys() + return list(u.keys()) # We can't hash all the elements. Second fastest is to sort, # which brings the equal elements together; then duplicates are @@ -343,8 +345,7 @@ def rpm2cpio(fdno, out=sys.stdout, bufsize=2048): # TODO: someone implement me! #el if compr != 'gzip': - raise rpmUtils.RpmUtilsError, \ - 'Unsupported payload compressor: "%s"' % compr + raise rpmUtils.RpmUtilsError('Unsupported payload compressor: "%s"' % compr) f = gzip.GzipFile(None, 'rb', None, os.fdopen(fdno, 'rb', bufsize)) while 1: tmp = f.read(bufsize) @@ -361,7 +362,7 @@ def formatRequire (name, version, flags): ''' s = name - if flags and (type(flags) == type(0) or type(flags) == type(0L)): # Flag must be set and a int (or a long, now) + if flags and (type(flags) == type(0) or type(flags) == type(0)): # Flag must be set and a int (or a long, now) if flags & (rpm.RPMSENSE_LESS | rpm.RPMSENSE_GREATER | rpm.RPMSENSE_EQUAL): s = s + " " @@ -394,7 +395,7 @@ def stringToVersion(verstring): i = verstring.find(':') if i != -1: try: - epoch = str(long(verstring[:i])) + epoch = str(int(verstring[:i])) except ValueError: # look, garbage in the epoch field, how fun, kill it epoch = '0' # this is our fallback, deal @@ -419,19 +420,19 @@ def hdrFromPackage(ts, package): """hand back the rpm header or raise an Error if the pkg is fubar""" try: fdno = os.open(package, os.O_RDONLY) - except OSError, e: - raise rpmUtils.RpmUtilsError, 'Unable to open file' + except OSError as e: + raise rpmUtils.RpmUtilsError('Unable to open file') # XXX: We should start a readonly ts here, so we don't get the options # from the other one (sig checking, etc) try: hdr = ts.hdrFromFdno(fdno) - except rpm.error, e: + except rpm.error as e: os.close(fdno) - raise rpmUtils.RpmUtilsError, "RPM Error opening Package" + raise rpmUtils.RpmUtilsError("RPM Error opening Package") if type(hdr) != rpm.hdr: os.close(fdno) - raise rpmUtils.RpmUtilsError, "RPM Error opening Package (type)" + raise rpmUtils.RpmUtilsError("RPM Error opening Package (type)") os.close(fdno) return hdr diff --git a/rpmUtils/oldUtils.py b/rpmUtils/oldUtils.py index 5f1d9ec..d8cca3c 100644 --- a/rpmUtils/oldUtils.py +++ b/rpmUtils/oldUtils.py @@ -10,7 +10,7 @@ from urlgrabber.grabber import URLGrabError from zlib import error as zlibError def log(num, msg): - print >>sys.stderr, msg + print(msg, file=sys.stderr) errorlog = log def _(msg): @@ -41,7 +41,7 @@ def checkRpmMD5(package, urlgraberror=0): fdno = os.open(package, os.O_RDONLY) try: ts.hdrFromFdno(fdno) - except rpm.error, e: + except rpm.error as e: good = 0 else: good = 1 @@ -64,7 +64,7 @@ def checkSig(package): fdno = os.open(package, os.O_RDONLY) try: hdr = ts.hdrFromFdno(fdno) - except rpm.error, e: + except rpm.error as e: if str(e) == "public key not availaiable": return 1 if str(e) == "public key not available": @@ -105,18 +105,20 @@ def getProvides(header): provides = header[rpm.RPMTAG_PROVIDENAME] if provides is None: pass - elif type(provides) is types.ListType: + elif type(provides) is list: provnames.extend(provides) else: provnames.append(provides) return provnames -def compareEVR((e1, v1, r1), (e2, v2, r2)): +def compareEVR(xxx_todo_changeme, xxx_todo_changeme1): # return 1: a is newer than b # 0: a and b are the same version # -1: b is newer than a + (e1, v1, r1) = xxx_todo_changeme + (e2, v2, r2) = xxx_todo_changeme1 def rpmOutToStr(arg): - if type(arg) != types.StringType and arg != None: + if type(arg) != bytes and arg != None: arg = str(arg) return arg e1 = rpmOutToStr(e1) @@ -147,7 +149,7 @@ def formatRequire (name, version, flags): def openrpmdb(): try: db = rpm.TransactionSet(conf.installroot) - except rpm.error, e: + except rpm.error as e: errorlog(0, _("Could not open RPM database for reading. Perhaps it is already in use?")) return db @@ -164,7 +166,7 @@ class GzipFile(gzip.GzipFile): if fname: flags = FNAME self.fileobj.write(chr(flags)) - write32u(self.fileobj, long(0)) + write32u(self.fileobj, int(0)) self.fileobj.write('\002') self.fileobj.write('\377') if fname: @@ -244,25 +246,25 @@ class Header_Work(RPM_Base_Work): if the first arg is a string then it's a filename otherwise it's an rpm hdr""" def __init__(self, header): - if type(header) is types.StringType: + if type(header) is bytes: try: fd = gzip.open(header, 'r') try: h = rpm.headerLoad(fd.read()) - except rpm.error, e: + except rpm.error as e: errorlog(0,_('Damaged Header %s') % header) h = None - except IOError,e: + except IOError as e: fd = open(header, 'r') try: h = rpm.headerLoad(fd.read()) - except rpm.error, e: + except rpm.error as e: errorlog(0,_('Damaged Header %s') % header) h = None - except ValueError, e: + except ValueError as e: errorlog(0,_('Damaged Header %s') % header) h = None - except zlibError, e: + except zlibError as e: errorlog(0,_('Damaged Header %s') % header) h = None fd.close() @@ -277,7 +279,7 @@ class RPM_Work(RPM_Base_Work): fd = os.open(rpmfn, os.O_RDONLY) try: self.hdr = ts.hdrFromFdno(fd) - except rpm.error, e: + except rpm.error as e: errorlog(0, _('Error opening rpm %s - error %s') % (rpmfn, e)) self.hdr = None os.close(fd) @@ -291,7 +293,7 @@ class Rpm_Ts_Work: if conf.installroot: if conf.installroot != '/': dbPath = conf.installroot - except NameError, e: + except NameError as e: pass self.ts = rpm.TransactionSet(dbPath) @@ -303,7 +305,7 @@ class Rpm_Ts_Work: if attribute in self.methods: return getattr(self.ts, attribute) else: - raise AttributeError, attribute + raise AttributeError(attribute) def match(self, tag = None, search = None, mire = None): """hands back a list of Header_Work objects""" @@ -348,4 +350,4 @@ class Rpm_Ts_Work: # set it back to the default self.ts.setVSFlags(rpm.RPMVSF_DEFAULT) else: - raise AttributeError, sig + raise AttributeError(sig) diff --git a/rpmUtils/tests/updates-test.py b/rpmUtils/tests/updates-test.py index 889353e..3bce12f 100644 --- a/rpmUtils/tests/updates-test.py +++ b/rpmUtils/tests/updates-test.py @@ -38,24 +38,24 @@ up.exactarch=1 #up.myarch = 'sparc64' up._is_multilib = rpmUtils.arch.isMultiLibArch(up.myarch) up._archlist = rpmUtils.arch.getArchList(up.myarch) -print up._archlist +print((up._archlist)) up._multilib_compat_arches = rpmUtils.arch.getMultiArchInfo(up.myarch) up.doUpdates() up.condenseUpdates() -for tup in up.updatesdict.keys(): +for tup in list(up.updatesdict.keys()): (old_n, old_a, old_e, old_v, old_r) = tup for (n, a, e, v, r) in up.updatesdict[tup]: - print '%s.%s %s:%s-%s updated by %s.%s %s:%s-%s' % (old_n, - old_a, old_e, old_v, old_r, n, a, e, v, r) + print(('%s.%s %s:%s-%s updated by %s.%s %s:%s-%s' % (old_n, + old_a, old_e, old_v, old_r, n, a, e, v, r))) up.rawobsoletes = obslist up.doObsoletes() -for tup in up.obsoletes.keys(): +for tup in list(up.obsoletes.keys()): (old_n, old_a, old_e, old_v, old_r) = tup for (n, a, e, v, r) in up.obsoletes[tup]: - print '%s.%s %s:%s-%s obsoletes %s.%s %s:%s-%s' % (old_n, - old_a, old_e, old_v, old_r, n, a, e, v, r) + print(('%s.%s %s:%s-%s obsoletes %s.%s %s:%s-%s' % (old_n, + old_a, old_e, old_v, old_r, n, a, e, v, r))) diff --git a/rpmUtils/transaction.py b/rpmUtils/transaction.py index 121ad5b..3d46ab4 100644 --- a/rpmUtils/transaction.py +++ b/rpmUtils/transaction.py @@ -12,7 +12,7 @@ # import rpm -import miscutils +from . import miscutils read_ts = None ts = None @@ -64,7 +64,7 @@ class TransactionWrapper: if attr in self._methods: return self.getMethod(attr) else: - raise AttributeError, attr + raise AttributeError(attr) def __iter__(self): return self.ts diff --git a/rpmUtils/updates.py b/rpmUtils/updates.py index 012d00d..8f655ff 100644 --- a/rpmUtils/updates.py +++ b/rpmUtils/updates.py @@ -70,7 +70,7 @@ class Updates: for key in keys: if key not in dict_: continue - dict_[key] = filter(value.__ne__, dict_[key]) + dict_[key] = list(filter(value.__ne__, dict_[key])) if not dict_[key]: del dict_[key] @@ -78,7 +78,7 @@ class Updates: (n, a, e, v, r) = pkgtup for aa in (a, None): if (n, aa) in dict_: - dict_[(n, aa)] = filter((e,v,r).__ne__, dict_[(n, aa)]) + dict_[(n, aa)] = list(filter((e,v,r).__ne__, dict_[(n, aa)])) if not dict_[(n, aa)]: del dict_[(n, aa)] @@ -103,7 +103,7 @@ class Updates: def debugprint(self, msg): if self.debug: - print msg + print(msg) def makeNADict(self, pkglist, Nonelists, filter=None): """return lists of (e,v,r) tuples as value of a dict keyed on (n, a) @@ -133,7 +133,7 @@ class Updates: def returnNewest(self, evrlist): """takes a list of (e, v, r) tuples and returns the newest one""" if len(evrlist)==0: - raise rpmUtils.RpmUtilsError, "Zero Length List in returnNewest call" + raise rpmUtils.RpmUtilsError("Zero Length List in returnNewest call") if len(evrlist)==1: return evrlist[0] @@ -184,7 +184,7 @@ class Updates: return an obsoleted_dict in the format of makeObsoletedDict""" if self._obsoletes_by_name is None: self._obsoletes_by_name = {} - for pkgtup, obsoletes in self.rawobsoletes.iteritems(): + for pkgtup, obsoletes in list(self.rawobsoletes.items()): for name, flag, version in obsoletes: self._obsoletes_by_name.setdefault(name, []).append( (flag, version, pkgtup) ) @@ -201,7 +201,7 @@ class Updates: if not obsdict: return {} - obslist = obsdict.keys() + obslist = list(obsdict.keys()) if newest: obslist = self._reduceListNewestByNameArch(obslist) @@ -271,7 +271,7 @@ class Updates: self.obsoleted_dict[old] = [] self.obsoleted_dict[old].append(new) self.obsoleting_dict = {} - for obsoleted, obsoletings in self.obsoleted_dict.iteritems(): + for obsoleted, obsoletings in list(self.obsoleted_dict.items()): for obsoleting in obsoletings: self.obsoleting_dict.setdefault(obsoleting, []).append(obsoleted) @@ -302,7 +302,7 @@ class Updates: newpkgs = self.availdict archlist = self._archlist - for (n, a) in newpkgs.keys(): + for (n, a) in list(newpkgs.keys()): if a not in archlist: # high log here del newpkgs[(n, a)] @@ -333,12 +333,12 @@ class Updates: pass # Now we add the (n, None) entries back... - for na in newpkgs.keys(): - all_arches = map(lambda x: (na[1], x[0], x[1], x[2]), newpkgs[na]) + for na in list(newpkgs.keys()): + all_arches = [(na[1], x[0], x[1], x[2]) for x in newpkgs[na]] newpkgs.setdefault((na[0], None), []).extend(all_arches) # get rid of all the empty dict entries: - for nakey in newpkgs.keys(): + for nakey in list(newpkgs.keys()): if len(newpkgs[nakey]) == 0: del newpkgs[nakey] @@ -575,7 +575,7 @@ class Updates: sorted, that obsolete something""" tmplist = [] - obslist = self.obsoletes.keys() + obslist = list(self.obsoletes.keys()) if newest: obslist = self._reduceListNewestByNameArch(obslist) @@ -610,7 +610,7 @@ class Updates: sorted, that obsolete something""" tmplist = [] - obslist = self.obsoletes.keys() + obslist = list(self.obsoletes.keys()) if newest: obslist = self._reduceListNewestByNameArch(obslist) @@ -644,7 +644,7 @@ class Updates: You can also specify newest=1 to get the set of newest pkgs (name, arch) sorted, that obsolete something""" - tmplist = self.obsoletes.keys() + tmplist = list(self.obsoletes.keys()) if newest: tmplist = self._reduceListNewestByNameArch(tmplist) @@ -711,7 +711,7 @@ class Updates: if not done: return tuplelist - return highdict.values() + return list(highdict.values()) # def getProblems(self): @@ -47,7 +47,7 @@ class YumShell(cmd.Cmd): self.shell_specific_commands = ['repo', 'repository', 'exit', 'quit', 'run', 'ts', 'transaction', 'config'] - self.commandlist = self.shell_specific_commands + self.base.yum_cli_commands.keys() + self.commandlist = self.shell_specific_commands + list(self.base.yum_cli_commands.keys()) self.logger = logging.getLogger("yum.cli") self.verbose_logger = logging.getLogger("yum.verbose.cli") @@ -69,10 +69,10 @@ class YumShell(cmd.Cmd): try: inputs = shlex.split(input_string) - except ValueError, e: + except ValueError as e: self.logger.critical('Script Error: %s', e) if self.from_file: - raise Errors.YumBaseError, "Fatal error in script, exiting" + raise Errors.YumBaseError("Fatal error in script, exiting") return inputs @@ -192,7 +192,7 @@ class YumShell(cmd.Cmd): elif cmd == 'solve': try: (code, msgs) = self.base.buildTransaction() - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: self.logger.critical('Error building transaction: %s', e) return False @@ -294,16 +294,16 @@ class YumShell(cmd.Cmd): # to setup the enabled one. And having some setup is bad. self.base.pkgSack changed = self.base.repos.enableRepo(repo) - except Errors.ConfigError, e: + except Errors.ConfigError as e: self.logger.critical(e) - except Errors.RepoError, e: + except Errors.RepoError as e: self.logger.critical(e) else: for repo in changed: try: self.base.doRepoSetup(thisrepo=repo) - except Errors.RepoError, e: + except Errors.RepoError as e: self.logger.critical('Disabling Repository') self.base.repos.disableRepo(repo) return False @@ -315,9 +315,9 @@ class YumShell(cmd.Cmd): for repo in repos: try: offrepos = self.base.repos.disableRepo(repo) - except Errors.ConfigError, e: + except Errors.ConfigError as e: self.logger.critical(e) - except Errors.RepoError, e: + except Errors.RepoError as e: self.logger.critical(e) else: @@ -333,9 +333,9 @@ class YumShell(cmd.Cmd): def do_test(self, line): (cmd, args, line) = self.parseline(line) - print cmd - print args - print line + print(cmd) + print(args) + print(line) def do_run(self, line): if len(self.base.tsInfo) > 0: @@ -347,11 +347,11 @@ class YumShell(cmd.Cmd): return False returnval = self.base.doTransaction() - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: self.logger.critical('Error: %s', e) - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: self.logger.critical('\n\nExiting on user cancel') - except IOError, e: + except IOError as e: if e.errno == 32: self.logger.critical('\n\nExiting on Broken Pipe') else: diff --git a/test/check-po-yes-no.py b/test/check-po-yes-no.py index e22318e..85e5b68 100755 --- a/test/check-po-yes-no.py +++ b/test/check-po-yes-no.py @@ -10,11 +10,11 @@ from yum.misc import to_utf8 def trans(msg, default): if msg == 'msgstr ""\n': - return unicode(default, encoding='utf-8') + return str(default, encoding='utf-8') if msg.startswith('msgstr "'): msg = msg[len('msgstr "'):] msg = msg[:-2] - return unicode(msg, encoding='utf-8') + return str(msg, encoding='utf-8') for fname in glob.glob("po/*.po"): next = None @@ -65,7 +65,7 @@ for fname in glob.glob("po/*.po"): y is None or no is None or n is None): - print >>sys.stderr, """\ + print("""\ ERROR: Can't find all the msg id's in %s is_this_ok %s yes %s @@ -77,7 +77,7 @@ n %s yes is None, y is None, no is None, - n is None) + n is None), file=sys.stderr) sys.exit(1) syes = trans(syes, "yes") sy = trans(sy, "y") @@ -85,7 +85,7 @@ n %s sn = trans(sn, "n") if (is_this_ok != yes or is_this_ok != no): - print >>sys.stderr, """\ + print("""\ ERROR: yes/no translations don't match in: %s is_this_ok %5s: %s yes %5s: %s @@ -95,18 +95,18 @@ n %5s: %s """ % (fname, to_utf8(is_this_ok), to_utf8(sis_this_ok), to_utf8(yes), to_utf8(syes), to_utf8(y), to_utf8(sy), - to_utf8(no), to_utf8(sno), to_utf8(n), to_utf8(sn)) + to_utf8(no), to_utf8(sno), to_utf8(n), to_utf8(sn)), file=sys.stderr) if syes[0] != sy: - print >>sys.stderr, """\ + print("""\ ERROR: yes/y translations don't match in: %s yes %5s: %s y %5s: %s """ % (fname, - yes, syes, y, sy) + yes, syes, y, sy), file=sys.stderr) if sno[0] != sn: - print >>sys.stderr, """\ + print("""\ ERROR: no/n translations don't match in: %s no %5s: %s n %5s: %s """ % (fname, - no, sno, n, sn) + no, sno, n, sn), file=sys.stderr) diff --git a/test/depsolvetests.py b/test/depsolvetests.py index 7af3f16..ff05e58 100644 --- a/test/depsolvetests.py +++ b/test/depsolvetests.py @@ -9,13 +9,13 @@ class DepsolveTests(DepsolveTests): po = FakePackage('zsh', '1', '1', None, 'i386') self.tsInfo.addInstall(po) self.tsInfo.remove(po.pkgtup) - self.assertEquals('empty', *self.resolveCode()) + self.assertEqual('empty', *self.resolveCode()) def testInstallSinglePackageNoRequires(self): po = FakePackage('zsh', '1', '1', None, 'i386') self.tsInfo.addInstall(po) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po,)) def testInstallSinglePackageRequireNotProvided(self): @@ -23,7 +23,7 @@ class DepsolveTests(DepsolveTests): po.addRequires('zip', None, (None, None, None)) self.tsInfo.addInstall(po) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireInstalled(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -33,7 +33,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1', '1', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireInstalledRequireNotProvided(self): @@ -45,7 +45,7 @@ class DepsolveTests(DepsolveTests): po.addRequires('zap', None, (None, None, None)) self.rpmdb.addPackage(ipo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireInstalledRequireInstall(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -58,7 +58,7 @@ class DepsolveTests(DepsolveTests): po.addRequires('zap', None, (None, None, None)) self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2, ipo)) @@ -70,7 +70,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.0', '2', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireVer1Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -80,7 +80,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '2', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer2NotProvided(self): @@ -91,7 +91,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '2', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireVer2Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -101,7 +101,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer3NotProvided(self): @@ -112,7 +112,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', '0', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireVer3Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -122,7 +122,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', '2', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer4NotProvided(self): @@ -133,7 +133,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', '2', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireVer4_1Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -143,7 +143,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.0', '4', '2', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer4_2Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -153,7 +153,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '3', '2', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer4_3Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -163,7 +163,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', None, 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer4_4Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -173,7 +173,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '1.3', '4', '1', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireVer4_5Installed(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -183,7 +183,7 @@ class DepsolveTests(DepsolveTests): ipo = FakePackage('zip', '0.3', '4', '2', 'i386') self.rpmdb.addPackage(ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireXtraBadVer(self): @@ -198,7 +198,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zap', '1.3', '4', '0', 'i386') self.xsack.addPackage(xpo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireXtra(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -212,7 +212,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zap', '2.6', '8', '4', 'i386') self.xsack.addPackage(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo, xpo)) def testInstallSinglePackageRequireInstalledRequireXtra(self): @@ -227,7 +227,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zap', '2.6', '8', '4', 'i386') self.xsack.addPackage(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireUpgradeRequireXtraErr(self): @@ -246,7 +246,7 @@ class DepsolveTests(DepsolveTests): xpo.addRequires('zsh', 'EQ', ('2', '4', '8')) self.xsack.addPackage(xpo) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def testInstallSinglePackageRequireUpgradeRequireXtraOk(self): po = FakePackage('zsh', '1', '1', None, 'i386') @@ -263,7 +263,7 @@ class DepsolveTests(DepsolveTests): xpo2 = FakePackage('zap', '1.3', '4', '2', 'i386') self.xsack.addPackage(xpo2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo, xpo2)) def testInstallSinglePackageRequireMultiXtra(self): @@ -278,7 +278,7 @@ class DepsolveTests(DepsolveTests): xpo2 = FakePackage('zap', '1.3', '4', '2', 'i386') self.xsack.addPackage(xpo2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo, xpo2)) def testInstallSinglePackageRequireInstalledMultiLib(self): @@ -292,7 +292,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zip', '1', '3', None, 'x86_64') self.xsack.addPackage(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, ipo)) def testInstallSinglePackageRequireXtra1MultiLib(self): @@ -302,7 +302,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zip', '1', '3', None, 'i386') self.xsack.addPackage(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo)) def testInstallSinglePackageRequireXtra2_64MultiLib(self): @@ -315,7 +315,7 @@ class DepsolveTests(DepsolveTests): xpo64 = FakePackage('zip', '1', '3', None, 'x86_64') self.xsack.addPackage(xpo64) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo64)) def testInstallSinglePackageRequireXtra2_32MultiLib(self): @@ -328,7 +328,7 @@ class DepsolveTests(DepsolveTests): xpo64 = FakePackage('zip', '1', '3', None, 'x86_64') self.xsack.addPackage(xpo64) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo64)) def testUpdateSinglePackage(self): @@ -338,7 +338,7 @@ class DepsolveTests(DepsolveTests): po = FakePackage('zsh', '1', '3', None, 'i386') self.tsInfo.addUpdate(po, oldpo=ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po,)) def testUpdateForDependency(self): @@ -352,7 +352,7 @@ class DepsolveTests(DepsolveTests): updatepo = FakePackage('zip', '2', '1', '0', 'i386') self.xsack.addPackage(updatepo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, updatepo)) def testUpdateSplitPackage(self): @@ -371,7 +371,7 @@ class DepsolveTests(DepsolveTests): updatepo2.addProvides('libzip', 'EQ', ('0', '2', '1')) self.xsack.addPackage(updatepo2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) #self.assertResult((po, updatepo, updatepo2)) # XXX obsolete needed? self.assertResult((po, installedpo, updatepo2)) @@ -386,7 +386,7 @@ class DepsolveTests(DepsolveTests): xpo = FakePackage('zip', '1', '3', None, 'x86_64') self.xsack.addPackage(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo)) def testUpdateSinglePackageOldRequires(self): @@ -401,7 +401,7 @@ class DepsolveTests(DepsolveTests): po.addRequires('zip', None, (None, None, None)) self.tsInfo.addUpdate(po, oldpo=ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo)) def testUpdateSinglePackageOldRequiresGone(self): @@ -415,7 +415,7 @@ class DepsolveTests(DepsolveTests): po = FakePackage('zsh', '1', '3', None, 'i386') self.tsInfo.addUpdate(po, oldpo=ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo)) def testUpdateSinglePackageObsoletesOldRequirement(self): @@ -434,7 +434,7 @@ class DepsolveTests(DepsolveTests): self.tsInfo.addObsoleting(po, opo) self.tsInfo.addObsoleted(opo, po) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po,)) def testUpdateForConflict(self): @@ -448,7 +448,7 @@ class DepsolveTests(DepsolveTests): updatepo = FakePackage('zip', '2', '1', '0', 'i386') self.xsack.addPackage(updatepo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, updatepo)) def testUpdateForConflict2(self): @@ -462,7 +462,7 @@ class DepsolveTests(DepsolveTests): updatepo = FakePackage('zip', '2', '1', '0', 'i386') self.xsack.addPackage(updatepo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, updatepo)) def testUpdateForConflictProvide(self): @@ -477,7 +477,7 @@ class DepsolveTests(DepsolveTests): updatepo = FakePackage('zip', '2', '1', '0', 'i386') self.xsack.addPackage(updatepo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, updatepo)) def testUpdateForConflictProvide2(self): @@ -495,7 +495,7 @@ class DepsolveTests(DepsolveTests): updatepo.addConflicts('zippy', 'LT', ('0', '2', '1')) self.xsack.addPackage(updatepo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, updatepo)) def testEraseSinglePackage(self): @@ -503,7 +503,7 @@ class DepsolveTests(DepsolveTests): self.rpmdb.addPackage(po) self.tsInfo.addErase(po) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult(()) def testEraseSinglePackageRequiredByOneInstalled(self): @@ -515,7 +515,7 @@ class DepsolveTests(DepsolveTests): self.rpmdb.addPackage(po) self.tsInfo.addErase(po) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult(()) def _setup_FakeMultilibReqs(self): @@ -550,14 +550,14 @@ class DepsolveTests(DepsolveTests): def testFakeMultilibReqsInstall(self): (po, xpo1, xpo2, ipo1, ipo2) = self._setup_FakeMultilibReqs() - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo2, ipo2)) def testFakeMultilibReqsUpdate1a(self): (po, xpo1, xpo2, ipo1, ipo2) = self._setup_FakeMultilibReqs() self.rpmdb.addPackage(xpo1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo2, ipo2)) def testFakeMultilibReqsUpdate1b(self): @@ -568,14 +568,14 @@ class DepsolveTests(DepsolveTests): # wins. po.addRequires('libxyz-1.so.0(XYZ_1.1)', None, (None, None, None)) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo2, ipo2)) def testFakeMultilibReqsUpdate2(self): (po, xpo1, xpo2, ipo1, ipo2) = self._setup_FakeMultilibReqs() self.rpmdb.addPackage(ipo1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo2, ipo2)) def testFakeMultilibReqsUpdate3(self): @@ -583,7 +583,7 @@ class DepsolveTests(DepsolveTests): self.rpmdb.addPackage(xpo1) self.rpmdb.addPackage(ipo1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, xpo2, ipo2)) def _setup_CompareProviders(self, name="libbar", arch="x86_64"): @@ -602,13 +602,13 @@ class DepsolveTests(DepsolveTests): def testCompareProvidersSameLen1_64(self): (po, po1, po2) = self._setup_CompareProviders() - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) def testCompareProvidersSameLen1_noarch(self): (po, po1, po2) = self._setup_CompareProviders(arch='noarch') - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po,), (po1,po2)) def testCompareProvidersSameLen2_64(self): @@ -624,7 +624,7 @@ class DepsolveTests(DepsolveTests): po1.addProvides('libxyz-1.so.0(64bit)', None,(None,None,None)) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) def testCompareProvidersSameLen2_noarch(self): @@ -640,7 +640,7 @@ class DepsolveTests(DepsolveTests): po1.addProvides('libxyz-1.so.0', None,(None,None,None)) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po,), (po1,po2)) def testCompareProvidersSameLen2_noarch_to_64_1(self): @@ -657,7 +657,7 @@ class DepsolveTests(DepsolveTests): po1.addProvides('libxyz-1.so.0', None,(None,None,None)) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) @@ -675,21 +675,21 @@ class DepsolveTests(DepsolveTests): po1.addProvides('libxyz-1.so.0', None,(None,None,None)) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testCompareProvidersDiffLen_64(self): (po, po1, po2) = self._setup_CompareProviders(name='libbarf') - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) def testCompareProvidersDiffLen_noarch(self): (po, po1, po2) = self._setup_CompareProviders(name='libbarf', arch='noarch') - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) def testCompareProvidersSrcRpm_64(self): @@ -697,7 +697,7 @@ class DepsolveTests(DepsolveTests): po.sourcerpm = "abcd.src.rpm" po2.sourcerpm = "abcd.src.rpm" - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testCompareProvidersSrcRpm_noarch(self): @@ -706,20 +706,20 @@ class DepsolveTests(DepsolveTests): po.sourcerpm = "abcd.src.rpm" po2.sourcerpm = "abcd.src.rpm" - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testCompareProvidersPrefix_64(self): (po, po1, po2) = self._setup_CompareProviders(name='abcd-libbarf') - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testCompareProvidersPrefix_noarch(self): (po, po1, po2) = self._setup_CompareProviders(name='abcd-libbarf', arch='noarch') - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testCompareProvidersArchVSLen(self): @@ -737,7 +737,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po3) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po1)) def testSelfObsInstall(self): @@ -746,7 +746,7 @@ class DepsolveTests(DepsolveTests): xpo.addProvides('abcd-Foo', None, (None, None, None)) self.tsInfo.addInstall(xpo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo,)) def testSelfObsUpgrade(self): @@ -760,7 +760,7 @@ class DepsolveTests(DepsolveTests): xpo.addProvides('abcd-Foo', None, (None, None, None)) self.tsInfo.addUpdate(xpo, oldpo=ipo) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo,)) @@ -782,7 +782,7 @@ class DepsolveTests(DepsolveTests): po3 = FakePackage('Foo', version='3', arch='noarch') self.xsack.addPackage(po3) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po3)) def testMultiPkgVersions2(self): @@ -803,7 +803,7 @@ class DepsolveTests(DepsolveTests): po3 = FakePackage('Foo', version='2', arch='i586') self.xsack.addPackage(po3) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po3)) def testMultiPkgVersions3(self): @@ -824,7 +824,7 @@ class DepsolveTests(DepsolveTests): po3 = FakePackage('Foo', version='2', arch='i586') self.xsack.addPackage(po3) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po2)) def testMultiPkgVersions4(self): @@ -845,7 +845,7 @@ class DepsolveTests(DepsolveTests): po3 = FakePackage('Foo', version='2', arch='i386') self.xsack.addPackage(po3) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po2)) def testMultiPkgVersions5(self): @@ -866,7 +866,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po3) self.xsack.addPackage(po2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po2)) # Test from "Real Life" because we just can't think like they do @@ -884,7 +884,7 @@ class DepsolveTests(DepsolveTests): po2.addObsoletes('unison', 'LT', ('0', '2.27.57', '3')) self.xsack.addPackage(po2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po2)) def testRL_unison2(self): @@ -901,7 +901,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((xpo, po2)) def test_min_inst_and_dep(self): @@ -921,7 +921,7 @@ class DepsolveTests(DepsolveTests): po4 = FakePackage('bar', version='4') self.xsack.addPackage(po4) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo2, po4)) def test_min_up_and_dep1(self): @@ -944,7 +944,7 @@ class DepsolveTests(DepsolveTests): po4 = FakePackage('bar', version='4') self.xsack.addPackage(po4) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo2, po4)) def test_min_up_and_dep2(self): @@ -967,7 +967,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo2, po4)) def test_min_up_and_dep3(self): @@ -1006,7 +1006,7 @@ class DepsolveTests(DepsolveTests): po7.addRequires('bar', 'EQ', ('0', '4', '1')) self.xsack.addPackage(po7) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo3, po4, po7)) def test_multi_inst_dep1(self): @@ -1024,7 +1024,7 @@ class DepsolveTests(DepsolveTests): po2.addProvides('bar-prov2', 'EQ', ('0', '2', '0')) self.xsack.addPackage(po2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def test_multi_inst_dep2(self): @@ -1042,7 +1042,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def test_multi_inst_dep3(self): @@ -1059,7 +1059,7 @@ class DepsolveTests(DepsolveTests): po2.addProvides('libbar-prov1.so.0()', None, (None, None, None)) self.xsack.addPackage(po2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def test_multi_inst_dep4(self): @@ -1076,7 +1076,7 @@ class DepsolveTests(DepsolveTests): po2.addProvides('libbar-prov1.so.0()', None, (None, None, None)) self.xsack.addPackage(po2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def test_multi_inst_dep5(self): @@ -1093,7 +1093,7 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def test_inst_require_conflict1(self): @@ -1105,7 +1105,7 @@ class DepsolveTests(DepsolveTests): po1 = FakePackage('bar') self.xsack.addPackage(po1) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def test_inst_require_conflict_me1(self): ipo1 = FakePackage('foo') @@ -1116,7 +1116,7 @@ class DepsolveTests(DepsolveTests): po1.addConflicts('foo', None, (None, None, None)) self.xsack.addPackage(po1) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) def test_inst_require_obsoletes1(self): ipo1 = FakePackage('foo') @@ -1131,7 +1131,7 @@ class DepsolveTests(DepsolveTests): # don't ignore the conflicts above? ... I'm guessing ignoring it is # by accident too? bah. # self.assertEquals('err', *self.resolveCode()) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, po1)) def testUpdate_so_req_diff_arch(self): @@ -1155,7 +1155,7 @@ class DepsolveTests(DepsolveTests): self.tsInfo.addUpdate(apo2, oldpo=rpo2) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((apo1, apo2)) def testInstalllib_oldbad_prov1(self): @@ -1175,7 +1175,7 @@ class DepsolveTests(DepsolveTests): ipo1.addRequires('libfoo.so.2()', None, (None, None, None)) self.tsInfo.addInstall(ipo1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((ipo1, apo3)) def testCompareProvidersNoarchWithHigherVer_to_64(self): @@ -1194,7 +1194,7 @@ class DepsolveTests(DepsolveTests): po1.addProvides('libxyz-1.so.0', None,(None,None,None)) self.xsack.addPackage(po1) - self.assertEquals('ok', *self.resolveCode()) + self.assertEqual('ok', *self.resolveCode()) self.assertResult((po, po2)) def testRL_dcbd1(self): @@ -1211,4 +1211,4 @@ class DepsolveTests(DepsolveTests): self.xsack.addPackage(po2) self.xsack.addPackage(po1) - self.assertEquals('err', *self.resolveCode()) + self.assertEqual('err', *self.resolveCode()) diff --git a/test/merge-history-transactions-tests.py b/test/merge-history-transactions-tests.py index 569ba8d..f6464c7 100644 --- a/test/merge-history-transactions-tests.py +++ b/test/merge-history-transactions-tests.py @@ -76,12 +76,12 @@ class MergeHistTransTests(unittest.TestCase): def assertMergedBeg(self, merged, beg): self.assertTrue(beg.tid in merged.tid) - self.assertEquals(beg.beg_timestamp, merged.beg_timestamp) - self.assertEquals(beg.beg_rpmdbversion, merged.beg_rpmdbversion) + self.assertEqual(beg.beg_timestamp, merged.beg_timestamp) + self.assertEqual(beg.beg_rpmdbversion, merged.beg_rpmdbversion) def assertMergedEnd(self, merged, end): self.assertTrue(end.tid in merged.tid) - self.assertEquals(end.end_timestamp, merged.end_timestamp) - self.assertEquals(end.end_rpmdbversion, merged.end_rpmdbversion) + self.assertEqual(end.end_timestamp, merged.end_timestamp) + self.assertEqual(end.end_rpmdbversion, merged.end_rpmdbversion) def assertMergedCodes(self, merged, trans): ret = set() uid = set() @@ -89,12 +89,12 @@ class MergeHistTransTests(unittest.TestCase): ret.add(trans.loginuid) uid.add(trans.return_code) if len(ret) == 1: - self.assertEquals(list(ret)[0], merged.return_code) + self.assertEqual(list(ret)[0], merged.return_code) else: for ret in ret: self.assertTrue(ret in merged.return_code) if len(uid) == 1: - self.assertEquals(list(uid)[0], merged.loginuid) + self.assertEqual(list(uid)[0], merged.loginuid) else: for uid in uid: self.assertTrue(uid in merged.loginuid) @@ -113,11 +113,11 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 2) - self.assertEquals(pkgs[0], pkg1) - self.assertEquals(pkgs[0].state, xstate) - self.assertEquals(pkgs[1], pkg2) - self.assertEquals(pkgs[1].state, pkg2.state) + self.assertEqual(len(pkgs), 2) + self.assertEqual(pkgs[0], pkg1) + self.assertEqual(pkgs[0].state, xstate) + self.assertEqual(pkgs[1], pkg2) + self.assertEqual(pkgs[1].state, pkg2.state) def testSimpleInMerge2(self, xstate='Install'): pkg1 = self._pkg_new('foo', state=xstate) @@ -130,15 +130,15 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], pkg2) - self.assertEquals(pkgs[0].state, pkg2.state) - self.assertEquals(pkgs[1], pkg1) - self.assertEquals(pkgs[1].state, xstate) - self.assertEquals(pkgs[2], pkg3) - self.assertEquals(pkgs[2].state, pkg3.state) - self.assertEquals(pkgs[3], pkg4) - self.assertEquals(pkgs[3].state, pkg4.state) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], pkg2) + self.assertEqual(pkgs[0].state, pkg2.state) + self.assertEqual(pkgs[1], pkg1) + self.assertEqual(pkgs[1].state, xstate) + self.assertEqual(pkgs[2], pkg3) + self.assertEqual(pkgs[2].state, pkg3.state) + self.assertEqual(pkgs[3], pkg4) + self.assertEqual(pkgs[3].state, pkg4.state) def testSimpleUpMerge1(self, xstate='Update'): opkg1 = self._pkg_new('foo', state='Updated') @@ -152,15 +152,15 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], opkg1) - self.assertEquals(pkgs[2].state, opkg1.state) - self.assertEquals(pkgs[3], npkg1) - self.assertEquals(pkgs[3].state, xstate) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], opkg1) + self.assertEqual(pkgs[2].state, opkg1.state) + self.assertEqual(pkgs[3], npkg1) + self.assertEqual(pkgs[3].state, xstate) def testSimpleUpMerge2(self, xstate='Update'): opkg1 = self._pkg_new('foo', state='Updated') @@ -176,15 +176,15 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], opkg1) - self.assertEquals(pkgs[2].state, opkg1.state) - self.assertEquals(pkgs[3], npkg3) - self.assertEquals(pkgs[3].state, xstate) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], opkg1) + self.assertEqual(pkgs[2].state, opkg1.state) + self.assertEqual(pkgs[3], npkg3) + self.assertEqual(pkgs[3].state, xstate) def testSimpleUpMerge3(self, xstate='Install'): opkg1 = self._pkg_new('foo', state=xstate) @@ -199,13 +199,13 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], npkg3) - self.assertEquals(pkgs[2].state, xstate) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], npkg3) + self.assertEqual(pkgs[2].state, xstate) def testSimpleUpMultiMerge1(self, xstate='Install'): opkg1 = self._pkg_new('foo', arch='i586', state=xstate) @@ -220,13 +220,13 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], npkg3) - self.assertEquals(pkgs[2].state, xstate) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], npkg3) + self.assertEqual(pkgs[2].state, xstate) def testUpDownMerge1(self, xstate='Update'): opkg1 = self._pkg_new('foo', version='0', state='Updated') @@ -245,16 +245,16 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[2], opkg1) - self.assertNotEquals(pkgs[3], opkg3) - self.assertNotEquals(pkgs[3], npkg3) - self.assertNotEquals(pkgs[3], opkg4) - self.assertNotEquals(pkgs[3].state, npkg4.state) - self.assertEquals(pkgs[3].pkgtup, npkg4.pkgtup) - self.assertEquals(pkgs[3].state, xstate) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[2], opkg1) + self.assertNotEqual(pkgs[3], opkg3) + self.assertNotEqual(pkgs[3], npkg3) + self.assertNotEqual(pkgs[3], opkg4) + self.assertNotEqual(pkgs[3].state, npkg4.state) + self.assertEqual(pkgs[3].pkgtup, npkg4.pkgtup) + self.assertEqual(pkgs[3].state, xstate) def testUpDownMerge2(self, xstate='Install'): opkg1 = self._pkg_new('foo') @@ -272,16 +272,16 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertNotEquals(pkgs[2], opkg1) - self.assertNotEquals(pkgs[2], opkg3) - self.assertNotEquals(pkgs[2], npkg3) - self.assertNotEquals(pkgs[2], opkg4) - self.assertNotEquals(pkgs[2].state, npkg4.state) - self.assertEquals(pkgs[2].pkgtup, npkg4.pkgtup) - self.assertEquals(pkgs[2].state, xstate) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertNotEqual(pkgs[2], opkg1) + self.assertNotEqual(pkgs[2], opkg3) + self.assertNotEqual(pkgs[2], npkg3) + self.assertNotEqual(pkgs[2], opkg4) + self.assertNotEqual(pkgs[2].state, npkg4.state) + self.assertEqual(pkgs[2].pkgtup, npkg4.pkgtup) + self.assertEqual(pkgs[2].state, xstate) def testUpDownMerge3(self): opkg1 = self._pkg_new('foo') @@ -299,18 +299,18 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[2], opkg1) - self.assertEquals(pkgs[2].state, opkg1.state) - self.assertNotEquals(pkgs[3], opkg1) - self.assertNotEquals(pkgs[3].state, opkg3.state) - self.assertNotEquals(pkgs[3], npkg3) - self.assertNotEquals(pkgs[3], opkg4) - self.assertNotEquals(pkgs[3].state, npkg4.state) - self.assertEquals(pkgs[3].pkgtup, npkg4.pkgtup) - self.assertEquals(pkgs[3].state, 'Reinstall') + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[2], opkg1) + self.assertEqual(pkgs[2].state, opkg1.state) + self.assertNotEqual(pkgs[3], opkg1) + self.assertNotEqual(pkgs[3].state, opkg3.state) + self.assertNotEqual(pkgs[3], npkg3) + self.assertNotEqual(pkgs[3], opkg4) + self.assertNotEqual(pkgs[3].state, npkg4.state) + self.assertEqual(pkgs[3].pkgtup, npkg4.pkgtup) + self.assertEqual(pkgs[3].state, 'Reinstall') def testUpDownMerge4(self, xstate='Update'): opkg2 = self._pkg_new('bar', version='4', state='Updated') @@ -327,18 +327,18 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertNotEquals(pkgs[2].state, opkg3.state) - self.assertNotEquals(pkgs[2], npkg3) - self.assertNotEquals(pkgs[2], opkg4) - self.assertNotEquals(pkgs[2].state, npkg4.state) - self.assertEquals(pkgs[2].pkgtup, opkg3.pkgtup) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertNotEqual(pkgs[2].state, opkg3.state) + self.assertNotEqual(pkgs[2], npkg3) + self.assertNotEqual(pkgs[2], opkg4) + self.assertNotEqual(pkgs[2].state, npkg4.state) + self.assertEqual(pkgs[2].pkgtup, opkg3.pkgtup) if xstate == 'Obsoleting': - self.assertEquals(pkgs[2].state, 'Obsoleting') + self.assertEqual(pkgs[2].state, 'Obsoleting') else: - self.assertEquals(pkgs[2].state, 'Reinstall') + self.assertEqual(pkgs[2].state, 'Reinstall') def testUpDownMerge5(self, xstate='Update'): opkg2 = self._pkg_new('bar', version='4', state='Updated') @@ -358,15 +358,15 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], opkg3) - self.assertEquals(pkgs[2].state, opkg3.state) - self.assertEquals(pkgs[3], npkg5) - self.assertEquals(pkgs[3].state, xstate) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], opkg3) + self.assertEqual(pkgs[2].state, opkg3.state) + self.assertEqual(pkgs[3], npkg5) + self.assertEqual(pkgs[3].state, xstate) def testDownUpMerge1(self, xstate='Downgrade'): opkg1 = self._pkg_new('foo', version='10', state='Downgraded') @@ -385,17 +385,17 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertNotEquals(pkgs[2], opkg3) - self.assertNotEquals(pkgs[2].state, npkg3.state) - self.assertNotEquals(pkgs[2], opkg4) - self.assertNotEquals(pkgs[2], npkg4) - self.assertEquals(pkgs[2].pkgtup, npkg3.pkgtup) - self.assertEquals(pkgs[2].state, xstate) - self.assertEquals(pkgs[3], opkg1) - self.assertEquals(pkgs[3].state, opkg1.state) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertNotEqual(pkgs[2], opkg3) + self.assertNotEqual(pkgs[2].state, npkg3.state) + self.assertNotEqual(pkgs[2], opkg4) + self.assertNotEqual(pkgs[2], npkg4) + self.assertEqual(pkgs[2].pkgtup, npkg3.pkgtup) + self.assertEqual(pkgs[2].state, xstate) + self.assertEqual(pkgs[3], opkg1) + self.assertEqual(pkgs[3].state, opkg1.state) def testDownUpMerge2(self, xstate='Install'): opkg1 = self._pkg_new('foo', version='7', state=xstate) @@ -413,16 +413,16 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertNotEquals(pkgs[2], opkg1) - self.assertNotEquals(pkgs[2], opkg3) - self.assertNotEquals(pkgs[2], opkg4) - self.assertNotEquals(pkgs[2], npkg4) - self.assertNotEquals(pkgs[2].state, npkg3.state) - self.assertEquals(pkgs[2].pkgtup, npkg3.pkgtup) - self.assertEquals(pkgs[2].state, xstate) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertNotEqual(pkgs[2], opkg1) + self.assertNotEqual(pkgs[2], opkg3) + self.assertNotEqual(pkgs[2], opkg4) + self.assertNotEqual(pkgs[2], npkg4) + self.assertNotEqual(pkgs[2].state, npkg3.state) + self.assertEqual(pkgs[2].pkgtup, npkg3.pkgtup) + self.assertEqual(pkgs[2].state, xstate) def testDownUpMerge3(self): opkg1 = self._pkg_new('foo') @@ -440,18 +440,18 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[2], opkg1) - self.assertEquals(pkgs[2].state, opkg1.state) - self.assertNotEquals(pkgs[3], opkg1) - self.assertNotEquals(pkgs[3], opkg3) - self.assertNotEquals(pkgs[3].state, npkg3.state) - self.assertNotEquals(pkgs[3].state, opkg4.state) - self.assertNotEquals(pkgs[3], npkg4) - self.assertEquals(pkgs[3].pkgtup, npkg3.pkgtup) - self.assertEquals(pkgs[3].state, 'Reinstall') + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[2], opkg1) + self.assertEqual(pkgs[2].state, opkg1.state) + self.assertNotEqual(pkgs[3], opkg1) + self.assertNotEqual(pkgs[3], opkg3) + self.assertNotEqual(pkgs[3].state, npkg3.state) + self.assertNotEqual(pkgs[3].state, opkg4.state) + self.assertNotEqual(pkgs[3], npkg4) + self.assertEqual(pkgs[3].pkgtup, npkg3.pkgtup) + self.assertEqual(pkgs[3].state, 'Reinstall') def testDownUpMerge4(self, xstate='Update'): opkg2 = self._pkg_new('bar', version='4', state='Updated') @@ -468,18 +468,18 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[1], npkg2) - self.assertNotEquals(pkgs[2], opkg3) - self.assertNotEquals(pkgs[2].state, 'Update') - self.assertNotEquals(pkgs[2].state, opkg4.state) - self.assertNotEquals(pkgs[2], npkg4) - self.assertEquals(pkgs[2].pkgtup, npkg3.pkgtup) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[1], npkg2) + self.assertNotEqual(pkgs[2], opkg3) + self.assertNotEqual(pkgs[2].state, 'Update') + self.assertNotEqual(pkgs[2].state, opkg4.state) + self.assertNotEqual(pkgs[2], npkg4) + self.assertEqual(pkgs[2].pkgtup, npkg3.pkgtup) if xstate == 'Obsoleting': - self.assertEquals(pkgs[2].state, 'Obsoleting') + self.assertEqual(pkgs[2].state, 'Obsoleting') else: - self.assertEquals(pkgs[2].state, 'Reinstall') + self.assertEqual(pkgs[2].state, 'Reinstall') def testDownUpMerge5(self, xstate='Downgrade'): opkg2 = self._pkg_new('bar', version='4', state='Updated') @@ -499,15 +499,15 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 4) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, opkg2.state) - self.assertEquals(pkgs[1], npkg2) - self.assertEquals(pkgs[1].state, npkg2.state) - self.assertEquals(pkgs[2], npkg5) - self.assertEquals(pkgs[2].state, xstate) - self.assertEquals(pkgs[3], opkg3) - self.assertEquals(pkgs[3].state, opkg3.state) + self.assertEqual(len(pkgs), 4) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, opkg2.state) + self.assertEqual(pkgs[1], npkg2) + self.assertEqual(pkgs[1].state, npkg2.state) + self.assertEqual(pkgs[2], npkg5) + self.assertEqual(pkgs[2].state, xstate) + self.assertEqual(pkgs[3], opkg3) + self.assertEqual(pkgs[3].state, opkg3.state) def testInRmMerge1(self, xstate='Install', estate='Erase'): npkg1 = self._pkg_new('foo', state=xstate) @@ -521,9 +521,9 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 1) - self.assertEquals(pkgs[0], npkg3) - self.assertEquals(pkgs[0].state, npkg3.state) + self.assertEqual(len(pkgs), 1) + self.assertEqual(pkgs[0], npkg3) + self.assertEqual(pkgs[0].state, npkg3.state) def testInRmMerge2(self, xstate='Install'): self.testInRmMerge1(xstate, 'Obsoleted') @@ -548,9 +548,9 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 1) - self.assertEquals(pkgs[0], npkg9) - self.assertEquals(pkgs[0].state, npkg9.state) + self.assertEqual(len(pkgs), 1) + self.assertEqual(pkgs[0], npkg9) + self.assertEqual(pkgs[0].state, npkg9.state) def testInRmInonlyMerge2(self, xstate='True-Install'): self.testInRmInonlyMerge1(xstate, 'Obsoleted') @@ -568,11 +568,11 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 2) - self.assertEquals(pkgs[0], opkg2) - self.assertEquals(pkgs[0].state, npkg3.state) - self.assertEquals(pkgs[1], npkg1) - self.assertEquals(pkgs[1].state, npkg1.state) + self.assertEqual(len(pkgs), 2) + self.assertEqual(pkgs[0], opkg2) + self.assertEqual(pkgs[0].state, npkg3.state) + self.assertEqual(pkgs[1], npkg1) + self.assertEqual(pkgs[1].state, npkg1.state) def testUpRmMerge2(self, xstate='True-Install'): npkg1 = self._pkg_new('foo') @@ -588,9 +588,9 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 1) - self.assertEquals(pkgs[0], npkg1) - self.assertEquals(pkgs[0].state, npkg1.state) + self.assertEqual(len(pkgs), 1) + self.assertEqual(pkgs[0], npkg1) + self.assertEqual(pkgs[0].state, npkg1.state) def testUpRmMerge3(self, xstate='Update'): npkg1 = self._pkg_new('foo') @@ -606,9 +606,9 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 1) - self.assertEquals(pkgs[0], npkg1) - self.assertEquals(pkgs[0].state, npkg1.state) + self.assertEqual(len(pkgs), 1) + self.assertEqual(pkgs[0], npkg1) + self.assertEqual(pkgs[0].state, npkg1.state) def testRmInMerge1(self, xstate='Install', estate='Erase'): npkg1 = self._pkg_new('foo', state=xstate) @@ -622,14 +622,14 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 2) - self.assertEquals(pkgs[0], npkg3) - self.assertEquals(pkgs[0].state, npkg3.state) - self.assertEquals(pkgs[1], npkg1) + self.assertEqual(len(pkgs), 2) + self.assertEqual(pkgs[0], npkg3) + self.assertEqual(pkgs[0].state, npkg3.state) + self.assertEqual(pkgs[1], npkg1) if xstate == 'Obsoleting': - self.assertEquals(pkgs[1].state, 'Obsoleting') + self.assertEqual(pkgs[1].state, 'Obsoleting') else: - self.assertEquals(pkgs[1].state, 'Reinstall') + self.assertEqual(pkgs[1].state, 'Reinstall') def testRmInMerge2(self, xstate='Install'): self.testRmInMerge1(xstate, 'Obsoleted') @@ -650,16 +650,16 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], npkg1) - self.assertEquals(pkgs[0].state, npkg1.state) - self.assertEquals(pkgs[1].pkgtup, npkg4.pkgtup) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], npkg1) + self.assertEqual(pkgs[0].state, npkg1.state) + self.assertEqual(pkgs[1].pkgtup, npkg4.pkgtup) if ystate == 'Obsoleting': - self.assertEquals(pkgs[1].state, "Obsoleting") + self.assertEqual(pkgs[1].state, "Obsoleting") else: - self.assertEquals(pkgs[1].state, "Downgrade") - self.assertEquals(pkgs[2].pkgtup, opkg2.pkgtup) - self.assertEquals(pkgs[2].state, "Downgraded") + self.assertEqual(pkgs[1].state, "Downgrade") + self.assertEqual(pkgs[2].pkgtup, opkg2.pkgtup) + self.assertEqual(pkgs[2].state, "Downgraded") def testUpRmInlMerge2(self, xstate='Update', ystate='Install'): self.testUpRmInlMerge1(xstate, ystate, 'Obsoleted') @@ -680,16 +680,16 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], npkg1) - self.assertEquals(pkgs[0].state, npkg1.state) - self.assertEquals(pkgs[1].pkgtup, opkg2.pkgtup) - self.assertEquals(pkgs[1].state, "Updated") - self.assertEquals(pkgs[2].pkgtup, npkg4.pkgtup) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], npkg1) + self.assertEqual(pkgs[0].state, npkg1.state) + self.assertEqual(pkgs[1].pkgtup, opkg2.pkgtup) + self.assertEqual(pkgs[1].state, "Updated") + self.assertEqual(pkgs[2].pkgtup, npkg4.pkgtup) if ystate == 'Obsoleting': - self.assertEquals(pkgs[2].state, "Obsoleting") + self.assertEqual(pkgs[2].state, "Obsoleting") else: - self.assertEquals(pkgs[2].state, "Update") + self.assertEqual(pkgs[2].state, "Update") def testUpRmInuMerge2(self, xstate='Update', ystate='Install'): self.testUpRmInuMerge1(xstate, ystate, 'Obsoleted') @@ -717,13 +717,13 @@ class MergeHistTransTests(unittest.TestCase): merged = self._merge_new(trans) self.assertMergedMain(merged, trans) pkgs = merged.trans_data - self.assertEquals(len(pkgs), 3) - self.assertEquals(pkgs[0], opkg1) - self.assertEquals(pkgs[0].state, 'Updated') - self.assertEquals(pkgs[1], opkg2) - self.assertEquals(pkgs[1].state, 'Updated') - self.assertEquals(pkgs[2], opkg3) - self.assertEquals(pkgs[2].state, estate) + self.assertEqual(len(pkgs), 3) + self.assertEqual(pkgs[0], opkg1) + self.assertEqual(pkgs[0].state, 'Updated') + self.assertEqual(pkgs[1], opkg2) + self.assertEqual(pkgs[1].state, 'Updated') + self.assertEqual(pkgs[2], opkg3) + self.assertEqual(pkgs[2].state, estate) # Obsoleting is the _painful_ one because it really should be a state, but # an attribute. So "Obsoleting" can be any of: diff --git a/test/misc-tests.py b/test/misc-tests.py index d34c161..072d6d0 100644 --- a/test/misc-tests.py +++ b/test/misc-tests.py @@ -63,7 +63,7 @@ class MiscTests(DepsolveTests): D = self.repoPackage('D', '1',arch='i386') D.addProvides('LibD') self.tsInfo.addInstall(A) - self.assertEquals('ok', *self.resolveCode(skip=False)) + self.assertEqual('ok', *self.resolveCode(skip=False)) # This one is disabled because, we no it fails, but we dont want it to bail out in the each testcase run # Just enable it to do the test # self.assertResult([A,BCD]) @@ -88,7 +88,7 @@ class MiscTests(DepsolveTests): D = self.repoPackage('LibD', '1',arch='i386') D.addProvides('LibD') self.tsInfo.addInstall(A) - self.assertEquals('ok', *self.resolveCode(skip=False)) + self.assertEqual('ok', *self.resolveCode(skip=False)) self.assertResult([A,BCD]) def resolveCode(self,skip = False): diff --git a/test/operationstests.py b/test/operationstests.py index 5a50439..076d000 100644 --- a/test/operationstests.py +++ b/test/operationstests.py @@ -15,7 +15,7 @@ class ComplicatedTests(OperationsTests): p = self.pkgs res, msg = self.runOperation(['install', 'super-zippy'], [p.installed_i386], [p.obsoletes_i386, p.obsoletes_x86_64, p.conflicts]) if new_behavior: - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.conflicts)) class CombinedUpdateObsoletesTest(OperationsTests): @@ -40,14 +40,14 @@ class CombinedUpdateObsoletesTest(OperationsTests): def testSelfObsolete(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.klibs_1_x86_64], [p.klibs_2_i386, p.klibs_2_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.klibs_2_x86_64,)) def testPackageSplitWithObsoleteAndRequiresForUpdate(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.k_1, p.kdevel_1, p.klibs_1_x86_64], [p.k_2, p.kdevel_2, p.klibs_2_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.k_2, p.kdevel_2, p.klibs_2_x86_64,)) @@ -67,7 +67,7 @@ class ComplicatedObsoletesTests(OperationsTests): def testObsoleteChain(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed], [p.obsoletes, p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if True or new_behavior: self.assertResult((p.obsoletes2,)) else: @@ -75,13 +75,13 @@ class ComplicatedObsoletesTests(OperationsTests): def testObsoleteChainNext(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.obsoletes], [p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes2,)) def testObsoleteCircle(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.obsoletecircle], [p.obsoletes, p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.obsoletecircle,)) else: @@ -89,7 +89,7 @@ class ComplicatedObsoletesTests(OperationsTests): def testObsoleteCircleNext(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.obsoletes], [p.obsoletecircle, p.obsoletes, p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.obsoletes,)) else: @@ -97,7 +97,7 @@ class ComplicatedObsoletesTests(OperationsTests): def testObsoleteCircleNextNext(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.obsoletes2], [p.obsoletecircle, p.obsoletes, p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.obsoletes2,)) else: @@ -105,7 +105,7 @@ class ComplicatedObsoletesTests(OperationsTests): def testObsoleteCircleNextNextNext(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.obsoletecircle], [p.obsoletes, p.obsoletes2]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.obsoletecircle,)) else: diff --git a/test/packagetests.py b/test/packagetests.py index 1e3302b..a1035ab 100644 --- a/test/packagetests.py +++ b/test/packagetests.py @@ -164,24 +164,24 @@ class BuildPackageDictRefTests(unittest.TestCase): def testNoPkg(self): pkgs = [] - self.assertEquals({}, packages.buildPkgRefDict(pkgs)) + self.assertEqual({}, packages.buildPkgRefDict(pkgs)) def testOnePkg(self): pkg = StubPkg("yum", "noarch", 0, "3.1.1", 2) pkgs = [pkg] pkg_dict = packages.buildPkgRefDict(pkgs) - self.assertEquals(7, len(pkg_dict)) + self.assertEqual(7, len(pkg_dict)) unseen_keys = ['yum', 'yum.noarch', 'yum-3.1.1-2.noarch', 'yum-3.1.1', 'yum-3.1.1-2', '0:yum-3.1.1-2.noarch', 'yum-0:3.1.1-2.noarch'] - for key in pkg_dict.keys(): + for key in list(pkg_dict.keys()): self.assertTrue(key in unseen_keys) unseen_keys.remove(key) - self.assertEquals(1, len(pkg_dict[key])) - self.assertEquals(pkg, pkg_dict[key][0]) + self.assertEqual(1, len(pkg_dict[key])) + self.assertEqual(pkg, pkg_dict[key][0]) - self.assertEquals(0, len(unseen_keys)) + self.assertEqual(0, len(unseen_keys)) def _perms(evr): # Magic comp. sci. stuff ... oooh e, v, r = evr @@ -205,8 +205,8 @@ class RangeCompareTests(unittest.TestCase): def testRangeCompare(self): def tst(requires, provides, result): - print requires, provides - self.assertEquals(miscutils.rangeCompare(requires, provides),result) + print(requires, provides) + self.assertEqual(miscutils.rangeCompare(requires, provides),result) def tst_lege_prov(requires, provides, result): if not result or provides[1] != 'EQ': return diff --git a/test/rpmdb-cache.py b/test/rpmdb-cache.py index 7768a93..fdfc92f 100755 --- a/test/rpmdb-cache.py +++ b/test/rpmdb-cache.py @@ -11,7 +11,7 @@ yb2 = yum.YumBase() yb2.conf.cache = True if len(sys.argv) > 1 and sys.argv[1].lower() == 'full': - print "Doing full test" + print("Doing full test") __provides_of_requires_exact__ = True assert hasattr(yb1.rpmdb, '__cache_rpmdb__') @@ -22,66 +22,66 @@ yb2.setCacheDir() ver1 = yb1.rpmdb.simpleVersion(main_only=True)[0] ver2 = yb2.rpmdb.simpleVersion(main_only=True)[0] if ver1 != ver2: - print >>sys.stderr, "Error: Version mismatch:", ver1, ver2 + print("Error: Version mismatch:", ver1, ver2, file=sys.stderr) # Conflicts cpkgs1 = yb1.rpmdb.returnConflictPackages() cpkgs2 = yb2.rpmdb.returnConflictPackages() if len(cpkgs1) != len(cpkgs2): - print >>sys.stderr, "Error: Conflict len mismatch:", len(cpkgs1),len(cpkgs2) + print("Error: Conflict len mismatch:", len(cpkgs1),len(cpkgs2), file=sys.stderr) for pkg in cpkgs1: if pkg not in cpkgs2: - print >>sys.stderr, "Error: Conflict cache missing", pkg + print("Error: Conflict cache missing", pkg, file=sys.stderr) for pkg in cpkgs2: if pkg not in cpkgs1: - print >>sys.stderr, "Error: Conflict cache extra", pkg + print("Error: Conflict cache extra", pkg, file=sys.stderr) # File Requires frd1, blah, fpd1 = yb1.rpmdb.fileRequiresData() frd2, blah, fpd2 = yb2.rpmdb.fileRequiresData() if len(frd1) != len(frd2): - print >>sys.stderr, "Error: FileReq len mismatch:", len(frd1), len(frd2) + print("Error: FileReq len mismatch:", len(frd1), len(frd2), file=sys.stderr) for pkgtup in frd1: if pkgtup not in frd2: - print >>sys.stderr, "Error: FileReq cache missing", pkgtup + print("Error: FileReq cache missing", pkgtup, file=sys.stderr) continue if len(set(frd1[pkgtup])) != len(set(frd2[pkgtup])): - print >>sys.stderr, ("Error: FileReq[%s] len mismatch:" % (pkgtup,), - len(frd1[pkgtup]), len(frd2[pkgtup])) + print(("Error: FileReq[%s] len mismatch:" % (pkgtup,), + len(frd1[pkgtup]), len(frd2[pkgtup])), file=sys.stderr) for name in frd1[pkgtup]: if name not in frd2[pkgtup]: - print >>sys.stderr, ("Error: FileReq[%s] cache missing" % (pkgtup,), - name) + print(("Error: FileReq[%s] cache missing" % (pkgtup,), + name), file=sys.stderr) for pkgtup in frd2: if pkgtup not in frd1: - print >>sys.stderr, "Error: FileReq cache extra", pkgtup + print("Error: FileReq cache extra", pkgtup, file=sys.stderr) continue for name in frd2[pkgtup]: if name not in frd1[pkgtup]: - print >>sys.stderr, ("Error: FileReq[%s] cache extra" % (pkgtup,), - name) + print(("Error: FileReq[%s] cache extra" % (pkgtup,), + name), file=sys.stderr) # File Provides (of requires) -- not exact if len(fpd1) != len(fpd2): - print >>sys.stderr, "Error: FileProv len mismatch:", len(fpd1), len(fpd2) + print("Error: FileProv len mismatch:", len(fpd1), len(fpd2), file=sys.stderr) for name in fpd1: if name not in fpd2: - print >>sys.stderr, "Error: FileProv cache missing", name + print("Error: FileProv cache missing", name, file=sys.stderr) continue if not __provides_of_requires_exact__: continue # We might be missing some providers if len(fpd1[name]) != len(fpd2[name]): - print >>sys.stderr, ("Error: FileProv[%s] len mismatch:" % (pkgtup,), - len(fpd1[name]), len(fpd2[name])) + print(("Error: FileProv[%s] len mismatch:" % (pkgtup,), + len(fpd1[name]), len(fpd2[name])), file=sys.stderr) for pkgtup in fpd1[name]: if pkgtup not in fpd2[name]: - print >>sys.stderr,"Error: FileProv[%s] cache missing" % name,pkgtup + print("Error: FileProv[%s] cache missing" % name,pkgtup, file=sys.stderr) for name in fpd2: if name not in fpd1: - print >>sys.stderr, "Error: FileProv cache extra", name + print("Error: FileProv cache extra", name, file=sys.stderr) continue for pkgtup in fpd2[name]: if pkgtup not in fpd1[name]: - print >>sys.stderr,"Error: FileProv[%s] cache extra" % name,pkgtup + print("Error: FileProv[%s] cache extra" % name,pkgtup, file=sys.stderr) diff --git a/test/simpleobsoletestests.py b/test/simpleobsoletestests.py index 97a9923..2055cd9 100644 --- a/test/simpleobsoletestests.py +++ b/test/simpleobsoletestests.py @@ -27,43 +27,43 @@ class SimpleObsoletesTests(OperationsTests): def testObsoletenoarchTonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.obsoletes_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch,)) def testObsoletenoarchTonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_noarch], [p.obsoletes_noarch, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch, p.requires_obsoletes)) def testObsoletenoarchToi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testObsoletenoarchToi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_noarch], [p.obsoletes_i386, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.requires_obsoletes)) def testObsoletenoarchTox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoletenoarchTox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_noarch], [p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes)) def testObsoletenoarchToMultiarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.obsoletes_i386, p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.obsoletes_x86_64,), (p.obsoletes_i386,)) else: @@ -72,7 +72,7 @@ class SimpleObsoletesTests(OperationsTests): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_noarch], [p.obsoletes_i386, p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes), (p.obsoletes_i386,)) # i386 to X @@ -80,46 +80,46 @@ class SimpleObsoletesTests(OperationsTests): def testObsoletei386Tonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.obsoletes_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch,)) def testObsoletei386TonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386], [p.obsoletes_noarch, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch, p.requires_obsoletes)) def testObsoletei386Toi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testObsoletei386Toi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386], [p.obsoletes_i386, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.requires_obsoletes)) def testObsoletei386Tox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoletei386Tox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386], [p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes)) def testObsoletei386ToMultiarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.obsoletes_i386, p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testObsoletei386ToMultiarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386], [p.obsoletes_i386, p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.requires_obsoletes)) # x86_64 to X @@ -127,67 +127,67 @@ class SimpleObsoletesTests(OperationsTests): def testObsoletex86_64Tonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.obsoletes_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch,)) def testObsoletex86_64TonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_x86_64], [p.obsoletes_noarch, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch, p.requires_obsoletes)) def testObsoletex86_64Toi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testObsoletex86_64Toi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_x86_64], [p.obsoletes_i386, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.requires_obsoletes)) def testObsoletex86_64Tox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoletex86_64Tox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_x86_64], [p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes)) def testObsoletex86_64ToMultiarch1(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.obsoletes_i386, p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoletex86_64ToMultiarch2(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.obsoletes_x86_64, p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testInstallObsoletex86_64ToMultiarch1(self): # Found by BZ 593349, libgfortran43/44 p = self.pkgs res, msg = self.runOperation(['install', 'zsh.x86_64'], [], [p.installed_x86_64, p.installed_i386, p.obsoletes_x86_64, p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testInstallObsoletex86_64ToMultiarch2(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh.i386'], [], [p.installed_x86_64, p.installed_i386, p.obsoletes_x86_64, p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testInstallObsoletex86_64ToMultiarch3(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh'], [], [p.installed_noarch, p.obsoletes_x86_64, p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoletex86_64ToMultiarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_x86_64], [p.obsoletes_i386, p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes)) # multiarch to X @@ -195,53 +195,53 @@ class SimpleObsoletesTests(OperationsTests): def testObsoleteMultiarchTonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch,)) def testObsoleteMultiarchTonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_noarch, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch, p.requires_obsoletes)) def testObsoleteMultiarchToi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386,)) def testObsoleteMultiarchToi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_i386, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.requires_obsoletes)) def testObsoleteMultiarchTox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64,)) def testObsoleteMultiarchTox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_x86_64, p.requires_obsoletes)) def testObsoleteMultiarchToMultiarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_i386, p.obsoletes_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.obsoletes_x86_64)) def testObsoleteMultiarchToMultiarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'superzippy'], [p.installed_i386, p.installed_x86_64], [p.obsoletes_i386, p.obsoletes_x86_64, p.requires_obsoletes]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_i386, p.obsoletes_x86_64, p.requires_obsoletes)) def testInstallObsoletenoarchTonoarch(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-ng'], [p.installed_noarch], [p.obsoletes_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.obsoletes_noarch,)) def _MultiObsHelper(self): @@ -267,21 +267,21 @@ class SimpleObsoletesTests(OperationsTests): pkgs = self._MultiObsHelper() res, msg = self.runOperation(['install', 'fish'], pkgs['pi'], pkgs['po']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['ksh'],pkgs['nash'],pkgs['fish'],)) def testMultiObs2(self): pkgs = self._MultiObsHelper() res, msg = self.runOperation(['install', 'bigfish'], pkgs['pi'], pkgs['po']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['nash'],pkgs['bigfish'],)) def testMultiObs3(self): pkgs = self._MultiObsHelper() res, msg = self.runOperation(['install', 'shark'], pkgs['pi'], pkgs['po']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['shark'],)) def testMultiObs4(self): @@ -291,7 +291,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'shark'], pkgs['pi'] + [oldshark], pkgs['po']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['shark'],)) def testMultiObs5(self): @@ -301,7 +301,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'nash'], pkgs['pi'] + [oldshark], pkgs['po']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['shark'],)) # NOTE: Do we really want to remove the old kernel-xen? ... not 100% sure @@ -317,7 +317,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'kernel'], [okern1, okernxen1, okern2, okernxen2], [nkern]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((okern1,okern2,nkern,)) def testMultiObsKern2(self): @@ -332,7 +332,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'kernel-xen'], [okern1, okernxen1, okern2, okernxen2], [nkern]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((okern1,okern2,nkern,)) def testMultiObsKern3(self): @@ -347,7 +347,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update'], [okern1, okernxen1, okern2, okernxen2], [nkern]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((okern1,okern2,nkern,)) def testIncluderObs1(self): @@ -371,7 +371,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'postfix'], [pfix1, dep], [exim, pnewfix, pfix2, dep]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((dep, pfix2, pnewfix)) def testIncluderObs2(self): @@ -395,7 +395,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update', 'postfix'], [dep, pfix1], [dep, pfix2, pnewfix, exim]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((dep, pfix2, pnewfix)) def testIncluderObs3(self): @@ -419,7 +419,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['install', 'postfix-blah'], [dep, pfix1], [dep, pfix2, pnewfix, exim]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((dep, pfix2, pnewfix)) def testConflictMultiplePkgs(self): @@ -441,7 +441,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['install', 'baz'], [rp1], [ap, aop, dep1, dep2, dep3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((ap, aop, dep1, dep2, dep3)) def testMultipleObsoleters(self): @@ -456,7 +456,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['update'], [rp1], [aop1, aop2]) - self.assert_(res=='err', msg) + self.assertTrue(res=='err', msg) # FIXME: This is really what should happen, but just sucking works too # self.assert_(res=='ok', msg) # self.assertResult((aop1,)) @@ -495,42 +495,42 @@ class SimpleObsoletesTests(OperationsTests): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess2(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update', 'dapl'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess3(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update', 'dapl-devel'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess4(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'compat-dapl'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess5(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'compat-dapl-devel'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess6(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'compat-dapl-1.2.5'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMess7(self): @@ -538,7 +538,7 @@ class SimpleObsoletesTests(OperationsTests): res, msg = self.runOperation(['install', 'compat-dapl-devel-1.2.5'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) # Now we get a bit weird, as we have obsoletes fighting with updates @@ -546,39 +546,39 @@ class SimpleObsoletesTests(OperationsTests): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'dapl-1.2.1.1-7'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMessWeirdInst2(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'dapl-2.0.15', 'dapl-devel-2.0.15'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((all['arp3'], all['arp4'])) def testRLDaplMessWeirdInst3(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['install', 'dapl-2.0.15'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((all['arp3'], all['arp4'])) def testRLDaplMessWeirdUp1(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update', 'dapl-1.2.1.1-7'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(ret) def testRLDaplMessWeirdUp2(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update', 'dapl-2.0.15', 'dapl-devel-2.0.15'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((all['arp3'], all['arp4'])) def testRLDaplMessWeirdUp3(self): rps, aps, ret, all = self._helperRLDaplMess() res, msg = self.runOperation(['update', 'dapl-2.0.15'], rps, aps) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((all['arp3'], all['arp4'])) def testRLDaplFixUpdateNotInstall(self): @@ -615,12 +615,12 @@ class GitMetapackageObsoletesTests(OperationsTests): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed], [p.new_git, p.git_all]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.new_git,)) def testGitMetapackageRenameMetapackageAndCoreInstalled(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed, p.metapackage], [p.new_git, p.git_all]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.new_git, p.git_all)) diff --git a/test/simpleremovetests.py b/test/simpleremovetests.py index be820bc..3d4a8ed 100644 --- a/test/simpleremovetests.py +++ b/test/simpleremovetests.py @@ -22,43 +22,43 @@ class SimpleRemoveTests(OperationsTests): def testRemoveSingle(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testRemoveRequired(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf, p.requires_leaf], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testRemoveRequiredMissing(self): p = self.pkgs res, msg = self.runOperation(['remove', 'bar'], [p.requires_leaf], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testRemoveRequiredProvided(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf, p.requires_leaf, p.provides_leaf], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( (p.requires_leaf, p.provides_leaf) ) def testRemoveRequiredAvailable(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf, p.requires_leaf], [p.provides_leaf]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testRemoveRequiredChain(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf, p.requires_leaf, p.rr_leaf], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testRemoveRequiredFile(self): p = self.pkgs res, msg = self.runOperation(['remove', 'foo'], [p.leaf, p.requires_file], []) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult( () ) def testShellUpRm1(self): @@ -72,7 +72,7 @@ class SimpleRemoveTests(OperationsTests): ), [pi1], [pa1], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult(()) def testShellUpRm2(self): @@ -88,7 +88,7 @@ class SimpleRemoveTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pi1, )) def testShellUpRm3(self): @@ -104,7 +104,7 @@ class SimpleRemoveTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pi2, )) def testShellUpRm4(self): @@ -120,6 +120,6 @@ class SimpleRemoveTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pi1,)) diff --git a/test/simpleupdatetests.py b/test/simpleupdatetests.py index 6177fb1..8a9d617 100644 --- a/test/simpleupdatetests.py +++ b/test/simpleupdatetests.py @@ -40,58 +40,58 @@ class SimpleUpdateTests(OperationsTests): def testUpdatenoarchTonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.update_noarch,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch,)) def testUpdatenoarchTonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_noarch], [p.update_noarch, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch, p.requires_update)) def testUpdatenoarchTonoarchForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_noarch], [p.required_updated, p.update_noarch,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_noarch,)) def testUpdatenoarchToi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.update_i386,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386,)) def testUpdatenoarchToi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_noarch], [p.update_i386, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.requires_update)) def testUpdatenoarchToi386ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_noarch], [p.required_updated, p.update_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_i386)) def testUpdatenoarchTox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.update_x86_64,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64,)) def testUpdatenoarchTox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_noarch], [p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatenoarchTox86_64ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_noarch], [p.required_updated, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_x86_64)) def testUpdatenoarchToMultilib(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_noarch], [p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if True or new_behavior: # We update from .noarch to just the .x86_64 self.assertResult((p.update_x86_64,), (p.update_i386,)) # ? else: # Updates to both... @@ -99,18 +99,18 @@ class SimpleUpdateTests(OperationsTests): def testUpdatenoarchToMultilibForDependencyRev(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_noarch], [p.update_x86_64, p.update_i386, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatenoarchToMultilibForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_noarch], [p.update_i386, p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatenoarchToMultilibForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_noarch], [p.required_updated, p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_x86_64), (p.update_i386,)) # i386 to X @@ -118,69 +118,69 @@ class SimpleUpdateTests(OperationsTests): def testUpdatei386Tonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.update_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch,)) def testUpdatei386TonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386], [p.update_noarch, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch, p.requires_update)) def testUpdatei386TonoarchForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386], [p.required_updated, p.update_noarch,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_noarch,)) def testUpdatei386Toi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.update_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386,)) def testUpdatei386Toi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386], [p.update_i386, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.requires_update)) def testUpdatei386Toi386ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386], [p.required_updated, p.update_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_i386)) def testUpdatei386Tox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64,)) def testUpdatei386Tox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386], [p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatei386Tox86_64ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386], [p.required_updated, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_x86_64)) def testUpdatei386ToMultilib(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386], [p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386,)) def testUpdatei386ToMultilibForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386], [p.update_i386, p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.requires_update)) def testUpdatei386ToMultilibForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386], [p.required_updated, p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_i386)) # x86_64 to X @@ -188,73 +188,73 @@ class SimpleUpdateTests(OperationsTests): def testUpdatex86_64Tonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.update_noarch,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch,)) def testUpdatex86_64TonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_x86_64], [p.update_noarch, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch, p.requires_update)) def testUpdatex86_64TonoarchForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_x86_64], [p.required_updated, p.update_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_noarch)) def testUpdatex86_64Toi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.update_i386,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386,)) def testUpdatex86_64Toi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_x86_64], [p.update_i386, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.requires_update)) def testUpdatex86_64Toi386ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_x86_64], [p.required_updated, p.update_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_i386)) def testUpdatex86_64Tox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.update_x86_64,]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64,)) def testUpdatex86_64Tox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_x86_64], [p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatex86_64Tox86_64ForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_x86_64], [p.required_updated, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_x86_64)) def testUpdatex86_64ToMultilib(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_x86_64], [p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64,)) def testUpdatex86_64ToMultilibForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_x86_64], [p.update_i386, p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_x86_64, p.requires_update)) def testUpdatex86_64ToMultilibForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_x86_64], [p.required_updated, p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_x86_64)) # multilib to X @@ -262,24 +262,24 @@ class SimpleUpdateTests(OperationsTests): def testUpdateMultilibTonoarch(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.update_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch,)) def testUpdateMultilibTonoarchForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386, p.installed_x86_64], [p.update_noarch, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_noarch, p.requires_update)) def testUpdateMultilibTonoarchForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386, p.installed_x86_64], [p.required_updated, p.update_noarch]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_noarch)) def testUpdateMultilibToi386(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.update_i386]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.update_i386, p.installed_x86_64)) # self.assertResult((p.update_i386,)) # XXX is this right? @@ -288,7 +288,7 @@ class SimpleUpdateTests(OperationsTests): def testUpdateMultilibToi386ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386, p.installed_x86_64], [p.update_i386, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.update_i386, p.installed_x86_64, p.requires_update)) # self.assertResult((p.update_i386, p.requires_update)) # XXX is this right? @@ -298,13 +298,13 @@ class SimpleUpdateTests(OperationsTests): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386, p.installed_x86_64], [p.required_updated, p.update_i386]) - self.assert_(res=='err', msg) + self.assertTrue(res=='err', msg) self.assertResult((p.required_updated, p.update_i386, p.installed_x86_64)) def testUpdateMultilibTox86_64(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.update_x86_64, p.installed_i386)) # self.assertResult((p.update_x86_64,)) # XXX is this right? @@ -313,7 +313,7 @@ class SimpleUpdateTests(OperationsTests): def testUpdateMultilibTox86_64ForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386, p.installed_x86_64], [p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) if new_behavior: self.assertResult((p.update_x86_64, p.installed_i386, p.requires_update)) # self.assertResult((p.update_x86_64, p.requires_update)) # XXX is this right? @@ -323,24 +323,24 @@ class SimpleUpdateTests(OperationsTests): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386, p.installed_x86_64], [p.required_updated, p.update_x86_64]) - self.assert_(res=='err', msg) + self.assertTrue(res=='err', msg) self.assertResult((p.required_updated, p.update_x86_64, p.installed_i386)) def testUpdateMultilibToMultilib(self): p = self.pkgs res, msg = self.runOperation(['update'], [p.installed_i386, p.installed_x86_64], [p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.update_x86_64)) def testUpdateMultilibToMultilibForDependency(self): p = self.pkgs res, msg = self.runOperation(['install', 'zsh-utils'], [p.installed_i386, p.installed_x86_64], [p.update_i386, p.update_x86_64, p.requires_update]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.update_i386, p.update_x86_64, p.requires_update)) def testUpdateMultilibToMultilibForDependency2(self): p = self.pkgs res, msg = self.runOperation(['update', 'bar'], [p.required, p.installed_i386, p.installed_x86_64], [p.required_updated, p.update_i386, p.update_x86_64]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p.required_updated, p.update_i386, p.update_x86_64)) def testUpdateNotLatestDep(self): @@ -352,7 +352,7 @@ class SimpleUpdateTests(OperationsTests): bar12 = FakePackage('bar', '1', '2', '0', 'i386') bar21 = FakePackage('bar', '2', '1', '0', 'i386') res, msg = self.runOperation(['install', 'foo'], [foo11, bar11], [foo12, bar12, bar21]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo12, bar12)) def testUpdateBadMultiInstall1(self): @@ -365,7 +365,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', 'foo'], [foo11, foo12, foo13], [foo20]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,)) def testUpdateBadMultiInstall2(self): @@ -378,7 +378,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foo'], [foo11, foo12, foo13], [foo20]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,)) def testUpdateBadMultiInstall3(self): @@ -391,7 +391,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update'], [foo11, foo12, foo13], [foo20]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,)) def testUpdateBadMultiInstall4(self): @@ -407,7 +407,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'bar'], [foo11, foo12, foo13, bar11], [foo20, bar12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,bar12)) def testUpdateBadMultiInstall5(self): @@ -423,7 +423,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update'], [foo11, foo12, foo13, bar11], [foo20, bar12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,bar12)) def testUpdateBadMultiInstall6(self): @@ -439,7 +439,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update'], [foo11, foo12, foo13, bar11], [foo20, bar12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((bar12,)) def testUpdateBadMultiInstall7(self): @@ -455,7 +455,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', '*'], [foo11, foo12, foo13, bar11], [foo20, bar12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((foo20,bar12)) def testUpdateBadMultiInstall8(self): @@ -471,7 +471,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', '*'], [foo11, foo12, foo13, bar11], [foo20, bar12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((bar12,)) def testUpdateMultiRequiresVersions1(self): @@ -492,7 +492,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'perl'], [pi11, pvi11], [p12, pv12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,pv12)) def testUpdateMultiRequiresVersions2(self): @@ -513,7 +513,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'perl'], [pi11, pvi11], [pr11,p12, pvr11,pv12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,pv12)) def testUpdateMultiRequiresVersions3(self): @@ -534,7 +534,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'perl-version'], [pi11, pvi11], [pr11,p12, pvr11,pv12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,pv12)) def testUpdateMultiRequiresVersions4(self): @@ -565,7 +565,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'perl-version'], [pi11, pbi11, pvi11], [pr11,p12, pbr11,pb12, pvr11,pv12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,pb12,pv12)) def testUpdateMultiRequiresVersions5(self): @@ -596,7 +596,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'perl-blah'], [pi11, pbi11, pvi11], [pr11,p12, pbr11,pb12, pvr11,pv12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,pb12,pv12)) def testUpdateMultiRequiresVersions8(self): @@ -621,7 +621,7 @@ class SimpleUpdateTests(OperationsTests): [pi11, pvi11], [pr11,p12, pvr11,pv12,pv13]) # FIXME: This fails ... it tries to install pv13 instead - self.assert_(res=='err', msg) + self.assertTrue(res=='err', msg) # self.assert_(res=='ok', msg) # self.assertResult((p12,pv12)) @@ -638,7 +638,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', '/path/to/phooy'], [pi11], [pr11,p12, py12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) # FIXME: We'd really like it to be: # self.assertResult((p12,py12)) # ...but there is no info. you can work this out with. @@ -658,7 +658,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', '/path/to/phooy'], [pi11], [pr11,p12, py12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((p12,py12)) def testInstallFilenamePkgSplit3(self): @@ -675,7 +675,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', '/path/to/phooy'], [pi12], [p11, pr12, py12]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pi12,py12)) def testUpdateMultiArchConflict(self): @@ -692,7 +692,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'B'], [pi1, pi2, pi3], [pa1, pa2, pa3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2, pa3)) # What I was trying to model here is a problem where the Fedora builders @@ -719,7 +719,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', 'A'], [], [pa1, pa2, pa3, pa4]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa3)) def testUpdateMultiAvailPkgs2(self): @@ -735,7 +735,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', 'A'], [], [pa1, pa2, pa4, pa3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa3)) def testUpdateMultiAvailPkgs3(self): @@ -748,7 +748,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', 'A'], [], [pa1, pa2, pa3, pa4]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa3)) @@ -762,7 +762,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['install', 'A'], [], [pa1, pa2, pa4, pa3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa3)) def testUpdateRLEvince1(self): @@ -784,7 +784,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'evince'], [pi1, pi2, pi3], [pa1, pa2x, pa2i, pa3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2x, pa3)) def testUpdateRLEvince2(self): @@ -807,7 +807,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'evince'], [pi1, pi2, pi3], [pa1, pa2i, pa2x, pa3]) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2x, pa3)) def testShellRmUp1(self): @@ -821,7 +821,7 @@ class SimpleUpdateTests(OperationsTests): ), [pi1], [pa1], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1,)) def testShellRmUp2(self): @@ -837,7 +837,7 @@ class SimpleUpdateTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2)) def testShellRmUp3(self): @@ -853,7 +853,7 @@ class SimpleUpdateTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2)) def testShellRmUp4(self): @@ -869,7 +869,7 @@ class SimpleUpdateTests(OperationsTests): ), [pi1, pi2], [pa1, pa2], multi_cmds=True) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pa1, pa2)) # Test how update-to != update. @@ -890,7 +890,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foo'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateTo1_2(self): @@ -898,7 +898,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update-to', 'foo'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateTo2_1(self): @@ -906,7 +906,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foo-1-2'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo12'],)) def testUpdateTo2_2(self): @@ -914,7 +914,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update-to', 'foo-1-2'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo12'],)) def testUpdateTo3_1(self): @@ -922,7 +922,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foo-1-2'], [pkgs['foo12']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateTo3_2(self): @@ -931,7 +931,7 @@ class SimpleUpdateTests(OperationsTests): [pkgs['foo12']], pkgs['all']) # Nothing to do... - self.assert_(res==0, msg) + self.assertTrue(res==0, msg) def testUpdateToProv1_1(self): @@ -939,7 +939,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foobar'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateToProv1_2(self): @@ -947,7 +947,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update-to', 'foobar'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateToProv2_1(self): @@ -964,14 +964,14 @@ class SimpleUpdateTests(OperationsTests): pkgs['all']) # self.assert_(res=='ok', msg) # self.assertResult((pkgs['foo12'],)) - self.assert_(res==0, msg) + self.assertTrue(res==0, msg) def testUpdateToProv2_2(self): pkgs = self._setupUpdateTo() res, msg = self.runOperation(['update-to', 'foobar = 1-2'], [pkgs['foo11']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo12'],)) def testUpdateToProv3_1(self): @@ -979,7 +979,7 @@ class SimpleUpdateTests(OperationsTests): res, msg = self.runOperation(['update', 'foobar = 1-2'], [pkgs['foo12']], pkgs['all']) - self.assert_(res=='ok', msg) + self.assertTrue(res=='ok', msg) self.assertResult((pkgs['foo20'],)) def testUpdateToProv3_2(self): @@ -988,5 +988,5 @@ class SimpleUpdateTests(OperationsTests): [pkgs['foo12']], pkgs['all']) # Nothing to do... - self.assert_(res==0, msg) + self.assertTrue(res==0, msg) diff --git a/test/skipbroken-tests.py b/test/skipbroken-tests.py index 812785a..075e557 100644 --- a/test/skipbroken-tests.py +++ b/test/skipbroken-tests.py @@ -64,7 +64,7 @@ class SkipBrokenTests(DepsolveTests): xpo = self.repoPackage('bar', '1') xpo.addRequires('foobar', None, (None,None,None)) - self.assertEquals('err', *self.resolveCode(skip=False)) + self.assertEqual('err', *self.resolveCode(skip=False)) self.assertResult((po,xpo)) def testMissingReqSkip(self): @@ -77,7 +77,7 @@ class SkipBrokenTests(DepsolveTests): xpo = self.repoPackage('bar', '1') xpo.addRequires('foobar', None, (None,None,None)) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([]) def testDepWithMissingReqSkip(self): @@ -95,7 +95,7 @@ class SkipBrokenTests(DepsolveTests): xpo1 = self.repoPackage('foobar', '1') xpo1.addRequires('barfoo', None, (None,None,None)) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([po2]) def testUpdateOldRequired(self): @@ -113,7 +113,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo, po1]) def testUpdateRequireOld(self): @@ -131,7 +131,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo, po1]) def testUpdateRequireBoth(self): @@ -152,7 +152,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) self.tsInfo.addInstall(por) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo, po1]) def testEraseDep(self): @@ -165,7 +165,7 @@ class SkipBrokenTests(DepsolveTests): ipo2.addRequires('foo', 'EQ', ('0', '1', '0')) self.tsInfo.addErase(ipo) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([]) def testEraseReqByUpdateNoSkip(self): @@ -182,7 +182,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addErase(ipo) self.tsInfo.addUpdate(upo2, oldpo=ipo2) - self.assertEquals('err', *self.resolveCode(skip=False)) + self.assertEqual('err', *self.resolveCode(skip=False)) def testEraseReqByUpdateSkip(self): ''' update is skipped, because a req is erased. @@ -199,7 +199,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(upo2, oldpo=ipo2) self.tsInfo.addErase(ipo) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([]) def testConflictWithInstalled(self): @@ -215,7 +215,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo, po1]) def testConflictWithInstalledButUpdateExist(self): @@ -236,7 +236,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([po1,ipo]) def testConflictWithInstalledButUpdateExist2(self): @@ -258,7 +258,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(po2, oldpo=po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([po1,ipo]) def testAlternativePackageAvailable(self): @@ -272,7 +272,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(ipo) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([ipo, provides2]) def testOnlyOneRequirementAvailable(self): @@ -284,7 +284,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(ipo) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([]) def test2PkgReqSameDep(self): @@ -299,7 +299,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(po1) self.tsInfo.addInstall(po3) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([po3,po4]) def testProvidesAndDepsGetRemoved(self): @@ -310,7 +310,7 @@ class SkipBrokenTests(DepsolveTests): po2.addRequires('nice') po2.addRequires('features') self.tsInfo.addInstall(po2) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) def testSecondStepRequiresUpdate(self): po1 = self.repoPackage('foo') @@ -324,7 +324,7 @@ class SkipBrokenTests(DepsolveTests): ipo = self.instPackage('baz') upo = self.repoPackage('baz', '2', '1') - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo]) @@ -342,7 +342,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) def testDepCycle2(self): po0 = self.repoPackage('leaf') @@ -358,7 +358,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) def testDepCycle3(self): po0 = self.repoPackage('leaf') @@ -374,7 +374,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addInstall(po1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) def testMultiLibUpdate(self): ''' @@ -389,7 +389,7 @@ class SkipBrokenTests(DepsolveTests): po2.addRequires('notfound', 'EQ', ('0', '1', '0')) self.tsInfo.addUpdate(po1, oldpo=ipo1) self.tsInfo.addUpdate(po2, oldpo=ipo2) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([ipo1,ipo2]) def testInstReqOldVer1(self): @@ -414,7 +414,7 @@ class SkipBrokenTests(DepsolveTests): #FIXME: Find out why this line is needed, it should be auto updated by the solver. self.tsInfo.addUpdate(po1, oldpo=ipo1) # why is this needed, it should work without ? self.tsInfo.addUpdate(po3, oldpo=ipo3) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([po1,po2,po3]) @@ -459,7 +459,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(d2, oldpo=d1) self.tsInfo.addUpdate(e2, oldpo=e1) self.tsInfo.addUpdate(f2, oldpo=f1) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult([a1,b1,c1,d1,e2,f2]) def testBumpedSoName2(self): @@ -509,7 +509,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(ur3, oldpo=r3) self.tsInfo.addUpdate(ur4, oldpo=r4) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([c1,d1,r1,r2,r3,r4]) def testBumpedSoName3(self): @@ -558,7 +558,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(ur3, oldpo=r3) self.tsInfo.addUpdate(ur4, oldpo=r4) - self.assertEquals('err', *self.resolveCode(skip=False)) + self.assertEqual('err', *self.resolveCode(skip=False)) def testBumpedSoNameMultiArch(self): """ @@ -612,7 +612,7 @@ class SkipBrokenTests(DepsolveTests): self.tsInfo.addUpdate(ur3, oldpo=r3) self.tsInfo.addUpdate(ur4, oldpo=r4) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([c1,d1,r1,r2,r3,r4]) def testDualPackageUpdate(self): @@ -629,7 +629,7 @@ class SkipBrokenTests(DepsolveTests): u1.addRequires("notfound") self.tsInfo.addUpdate(u1, oldpo=i1) self.tsInfo.addUpdate(u1, oldpo=i2) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([i1,i2]) def testDowngrade1(self): @@ -646,7 +646,7 @@ class SkipBrokenTests(DepsolveTests): d1 = self.repoPackage('foo', '1.1') d1.addProvides('foolib', 'EQ', ('0', '1', '0')) self.tsInfo.addDowngrade(d1, oldpo=i1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([i1, i2]) @@ -669,7 +669,7 @@ class SkipBrokenTests(DepsolveTests): u1 = self.repoPackage('iptables','1.4.6', arch='x86_64') u1.addFile("/usr/lib64/libxtables.so.4") self.tsInfo.addUpdate(u1, oldpo=i1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult([i1,i2]) def testTransactionOutput(self): @@ -700,7 +700,7 @@ class SkipBrokenTests(DepsolveTests): u7.addProvides('foo6', 'EQ', ('0', '2', '0')) self.tsInfo.addInstall(i1) self.tsInfo.addUpdate(u7, oldpo=i7) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) # uncomment this line and the test will fail and you can see the output # self.assertResult([i1]) @@ -731,7 +731,7 @@ class SkipBrokenTests(DepsolveTests): u4 = self.repoString('1:kdepim-runtime-4.4.10-2.fc15.x86_64') self.tsInfo.addUpdate(u4, oldpo=i4) members.append(u4) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult(members) def test_skipbroken_001(self): @@ -750,7 +750,7 @@ class SkipBrokenTests(DepsolveTests): ux1.addFile("/usr/lib/.libssl.so.1.0.0b.hmac") self.tsInfo.addUpdate(ux1, oldpo=ix1) members.append(ix1) - self.assertEquals('empty', *self.resolveCode(skip=True)) + self.assertEqual('empty', *self.resolveCode(skip=True)) self.assertResult(members) @@ -775,7 +775,7 @@ class SkipBrokenTests(DepsolveTests): u1 = self.repoString('afoobar-0.4.14-1.fc14.noarch') self.tsInfo.addUpdate(u1, oldpo=i1) members.append(u1) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult(members) def test_skipbroken_003(self): @@ -807,7 +807,7 @@ class SkipBrokenTests(DepsolveTests): u1 = self.repoString('zfoobar-0.4.14-1.fc14.noarch') self.tsInfo.addUpdate(u1, oldpo=i1) members.append(u1) - self.assertEquals('ok', *self.resolveCode(skip=True)) + self.assertEqual('ok', *self.resolveCode(skip=True)) self.assertResult(members) diff --git a/test/testbase.py b/test/testbase.py index d0f22be..89161a2 100644 --- a/test/testbase.py +++ b/test/testbase.py @@ -6,7 +6,7 @@ import settestpath import logging import yum.logginglevels as logginglevels -new_behavior = "NEW_BEHAVIOR" in os.environ.keys() +new_behavior = "NEW_BEHAVIOR" in list(os.environ.keys()) from yum import YumBase from yum import transactioninfo @@ -122,9 +122,9 @@ class FakePackage(packages.YumAvailablePackage): def __init__(self, name, version='1.0', release='1', epoch='0', arch='noarch', repo=None): if repo is None: repo = FakeRepo() - print "creating empty repo for %s-%s:%s-%s.%s " % (name, epoch, + print("creating empty repo for %s-%s:%s-%s.%s " % (name, epoch, version, release, - arch) + arch)) packages.YumAvailablePackage.__init__(self, repo) self.name = name @@ -326,7 +326,7 @@ class FakeRpmDb(packageSack.PackageSack): installedUnresolvedFileRequires.add(name) fileRequires = set() - for fnames in installedFileRequires.itervalues(): + for fnames in installedFileRequires.values(): fileRequires.update(fnames) installedFileProviders = {} for fname in fileRequires: @@ -361,7 +361,7 @@ class FakeRpmDb(packageSack.PackageSack): # convert flags & version for unversioned reqirements if not version: version=(None, None, None) - if type(version) in (str, type(None), unicode): + if type(version) in (str, type(None), str): version = rpmUtils.miscutils.stringToVersion(version) if flags == '0': flags=None diff --git a/test/transactiontests.py b/test/transactiontests.py index 74a7666..da2de69 100644 --- a/test/transactiontests.py +++ b/test/transactiontests.py @@ -162,4 +162,4 @@ class TransactionDataTests(unittest.TestCase): def dumpTsInfo(self): for txmbr in self.tsInfo: - print txmbr + print(txmbr) diff --git a/test/yum-leak-test.py b/test/yum-leak-test.py index 760b770..2a1933a 100755 --- a/test/yum-leak-test.py +++ b/test/yum-leak-test.py @@ -17,14 +17,14 @@ def out_mem(pid): data[1] = data[1][:-3] ps[data[0].strip().lower()] = data[1].strip() if 'vmrss' in ps and 'vmsize' in ps: - print "* Memory : %5s RSS (%5sB VSZ)" % \ + print("* Memory : %5s RSS (%5sB VSZ)" % \ (format_number(int(ps['vmrss']) * 1024), - format_number(int(ps['vmsize']) * 1024)) + format_number(int(ps['vmsize']) * 1024))) -print "Running:", yum.__version__ +print("Running:", yum.__version__) def _leak_tst_yb(): - print "Doing YumBase leak test. " + print("Doing YumBase leak test. ") out_mem(os.getpid()) while True: yb = yum.YumBase() @@ -38,41 +38,41 @@ def _leak_tst_yb(): if False: del yb - print len(gc.garbage) + print(len(gc.garbage)) if gc.garbage: - print gc.garbage[0] - print gc.get_referrers(gc.garbage[0]) + print(gc.garbage[0]) + print(gc.get_referrers(gc.garbage[0])) # print "DBG:", gc.get_referrers(yb) def _leak_tst_cl(): - print "Doing closeRpmDB and .up test. " + print("Doing closeRpmDB and .up test. ") yb = yum.YumBase() yb.preconf.debuglevel = 0 yb.preconf.errorlevel = 0 yb.repos.setCacheDir(yum.misc.getCacheDir()) while True: out_mem(os.getpid()) - print "up:", + print("up:", end=' ') yb.up - print "done" + print("done") out_mem(os.getpid()) - print "rpmdb pkgs:", + print("rpmdb pkgs:", end=' ') yb.rpmdb.returnPackages() - print "done" + print("done") out_mem(os.getpid()) - print "pkgSack pkgs:", + print("pkgSack pkgs:", end=' ') yb.pkgSack.returnPackages() - print "done" + print("done") out_mem(os.getpid()) - print "close:", + print("close:", end=' ') yb.closeRpmDB() - print "done" + print("done") def _leak_tst_ir(): - print "Doing install/remove leak test. " + print("Doing install/remove leak test. ") def _init(): yb = cli.YumBaseCli() # Need doTransaction() etc. @@ -88,14 +88,14 @@ def _leak_tst_ir(): out_mem(os.getpid()) def _run(yb): - print " Run" + print(" Run") (code, msgs) = yb.buildTransaction() if code == 1: - print "ERROR:", core, msgs + print("ERROR:", core, msgs) sys.exit(1) returnval = yb.doTransaction() if returnval != 0: # We could allow 1 too, but meh. - print "ERROR:", returnval + print("ERROR:", returnval) sys.exit(1) yb.closeRpmDB() @@ -104,14 +104,14 @@ def _leak_tst_ir(): if True: yb = _init() out_mem(os.getpid()) - print " Install:", sys.argv[1:] + print(" Install:", sys.argv[1:]) for pat in sys.argv[1:]: yb.install(pattern=pat) out_mem(os.getpid()) _run(yb) out_mem(os.getpid()) - print " Remove:", sys.argv[1:] + print(" Remove:", sys.argv[1:]) for pat in sys.argv[1:]: yb.remove(pattern=pat) out_mem(os.getpid()) @@ -60,7 +60,7 @@ def get_process_info(pid): try: pid = int(pid) - except ValueError, e: + except ValueError as e: return # Maybe true if /proc isn't mounted, or not Linux ... or something. @@ -139,7 +139,7 @@ def exception2msg(e): pass try: - return unicode(e) + return str(e) except: pass @@ -199,7 +199,7 @@ class YumUtilBase(YumBaseCli): try: self.closeRpmDB() self.doUnlock() - except Errors.LockError, e: + except Errors.LockError as e: return 200 return 0 @@ -216,7 +216,7 @@ class YumUtilBase(YumBaseCli): while True: try: self.doLock() - except Errors.LockError, e: + except Errors.LockError as e: if exception2msg(e) != lockerr: lockerr = exception2msg(e) self.logger.critical(lockerr) @@ -225,12 +225,12 @@ class YumUtilBase(YumBaseCli): show_lock_owner(e.pid, self.logger) time.sleep(2) else: - raise Errors.YumBaseError, _("Another app is currently holding the yum lock; exiting as configured by exit_on_lock") + raise Errors.YumBaseError(_("Another app is currently holding the yum lock; exiting as configured by exit_on_lock")) else: break def _printUtilVersion(self): - print "%s - %s (yum - %s)" % (self._utilName,self._utilVer,yum.__version__) + print(("%s - %s (yum - %s)" % (self._utilName,self._utilVer,yum.__version__))) def doUtilConfigSetup(self,args = sys.argv[1:],pluginsTypes=(plugins.TYPE_CORE,)): # Parse only command line options that affect basic yum setup @@ -277,16 +277,16 @@ class YumUtilBase(YumBaseCli): for opt in self.main_setopts.items: setattr(self.conf, opt, getattr(self.main_setopts, opt)) - except Errors.ConfigError, e: + except Errors.ConfigError as e: self.logger.critical(_('Config Error: %s'), exception2msg(e)) sys.exit(1) - except ValueError, e: + except ValueError as e: self.logger.critical(_('Options Error: %s'), exception2msg(e)) sys.exit(1) - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: self.logger.critical(_('PluginExit Error: %s'), exception2msg(e)) sys.exit(1) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: self.logger.critical(_('Yum Error: %s'), exception2msg(e)) sys.exit(1) @@ -314,21 +314,21 @@ class YumUtilBase(YumBaseCli): self._getRpmDB() self._getRepos(doSetup = True) self._getSacks() - except Errors.YumBaseError, msg: + except Errors.YumBaseError as msg: self.logger.critical(exception2msg(msg)) sys.exit(1) def doUtilBuildTransaction(self, unfinished_transactions_check=True): try: (result, resultmsgs) = self.buildTransaction(unfinished_transactions_check = unfinished_transactions_check) - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return self.exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: result = 1 resultmsgs = [exception2msg(e)] except KeyboardInterrupt: return self.exUserCancel() - except IOError, e: + except IOError as e: return self.exIOError(e) # Act on the depsolve result @@ -364,13 +364,13 @@ class YumUtilBase(YumBaseCli): try: return_code = self.doTransaction() - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return self.exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: return self.exFatal(e) except KeyboardInterrupt: return self.exUserCancel() - except IOError, e: + except IOError as e: return self.exIOError(e,) self.verbose_logger.log(logginglevels.INFO_2, _('Complete!')) @@ -390,9 +390,9 @@ def main(): opts = util.doUtilConfigSetup() util.logger.info("Setup Yum") util.doUtilYumSetup() - print "Command line args: %s" % " ".join(util.cmds) - print "Command line options :" - print opts + print(("Command line args: %s" % " ".join(util.cmds))) + print("Command line options :") + print(opts) util.logger.info("%s Completed" % name) if __name__ == '__main__': diff --git a/yum-updatesd.py b/yum-updatesd.py index 1ce4720..f18a7d1 100644 --- a/yum-updatesd.py +++ b/yum-updatesd.py @@ -48,7 +48,7 @@ import yum.Errors import syslog from yum.config import BaseConfig, Option, IntOption, ListOption, BoolOption from yum.parser import ConfigPreProcessor -from ConfigParser import ConfigParser, ParsingError +from configparser import ConfigParser, ParsingError from yum.constants import * from yum.update_md import UpdateMetadata @@ -257,14 +257,12 @@ class UpdateBuildTransactionThread(threading.Thread): self.updd.tsInfo.makelists() try: (result, msgs) = self.updd.buildTransaction() - except yum.Errors.RepoError, errmsg: # error downloading hdrs + except yum.Errors.RepoError as errmsg: # error downloading hdrs msgs = ["Error downloading headers"] self.updd.emitUpdateFailed(msgs) return - dlpkgs = map(lambda x: x.po, filter(lambda txmbr: - txmbr.ts_state in ("i", "u"), - self.updd.tsInfo.getMembers())) + dlpkgs = [x.po for x in [txmbr for txmbr in self.updd.tsInfo.getMembers() if txmbr.ts_state in ("i", "u")]] self.updd.downloadPkgs(dlpkgs) self.processPkgs(dlpkgs) @@ -303,7 +301,7 @@ class UpdateInstallThread(UpdateBuildTransactionThread): elif result == 1: try: self.updd.getKeyForPackage(po) - except yum.Errors.YumBaseError, errmsg: + except yum.Errors.YumBaseError as errmsg: self.failed([str(errmsg)]) del self.updd.ts @@ -317,7 +315,7 @@ class UpdateInstallThread(UpdateBuildTransactionThread): cb.tsInfo = self.updd.tsInfo try: self.updd.runTransaction(cb=cb) - except yum.Errors.YumBaseError, err: + except yum.Errors.YumBaseError as err: self.failed([str(err)]) self.success() @@ -357,7 +355,7 @@ class UpdatesDaemon(yum.YumBase): self.doRepoSetup() self.doSackSetup() self.updateCheckSetup() - except Exception, e: + except Exception as e: syslog.syslog(syslog.LOG_WARNING, "error getting update info: %s" %(e,)) self.emitCheckFailed("%s" %(e,)) @@ -445,7 +443,7 @@ class UpdatesDaemon(yum.YumBase): if not self.didSetup: try: self.doSetup() - except Exception, e: + except Exception as e: syslog.syslog(syslog.LOG_WARNING, "error initializing: %s" % e) @@ -484,7 +482,7 @@ class UpdatesDaemon(yum.YumBase): # just notify about things being available self.emitAvailable() self.releaseLocks() - except Exception, e: + except Exception as e: self.emitCheckFailed("%s" %(e,)) self.doUnlock() @@ -532,27 +530,27 @@ class UpdatesDaemon(yum.YumBase): def emitAvailable(self): """method to emit a notice about updates""" - map(lambda x: x.updatesAvailable(self.updateInfo), self.emitters) + list(map(lambda x: x.updatesAvailable(self.updateInfo), self.emitters)) def emitDownloading(self): """method to emit a notice about updates downloading""" - map(lambda x: x.updatesDownloading(self.updateInfo), self.emitters) + list(map(lambda x: x.updatesDownloading(self.updateInfo), self.emitters)) def emitUpdateApplied(self): """method to emit a notice when automatic updates applied""" - map(lambda x: x.updatesApplied(self.updateInfo), self.emitters) + list(map(lambda x: x.updatesApplied(self.updateInfo), self.emitters)) def emitUpdateFailed(self, errmsgs): """method to emit a notice when automatic updates failed""" - map(lambda x: x.updatesFailed(errmsgs), self.emitters) + list(map(lambda x: x.updatesFailed(errmsgs), self.emitters)) def emitCheckFailed(self, error): """method to emit a notice when checking for updates failed""" - map(lambda x: x.checkFailed(error), self.emitters) + list(map(lambda x: x.checkFailed(error), self.emitters)) def emitSetupFailed(self, error, translation_domain=""): """method to emit a notice when checking for updates failed""" - map(lambda x: x.setupFailed(error, translation_domain), self.emitters) + list(map(lambda x: x.setupFailed(error, translation_domain), self.emitters)) class YumDbusListener(dbus.service.Object): @@ -624,8 +622,8 @@ def main(options = None): confpp_obj = ConfigPreProcessor(config_file) try: confparser.readfp(confpp_obj) - except ParsingError, e: - print >> sys.stderr, "Error reading config file: %s" % e + except ParsingError as e: + print("Error reading config file: %s" % e, file=sys.stderr) sys.exit(1) syslog.openlog("yum-updatesd", 0, syslog.LOG_DAEMON) diff --git a/yum/Errors.py b/yum/Errors.py index c1af4ad..c51d825 100644 --- a/yum/Errors.py +++ b/yum/Errors.py @@ -18,7 +18,7 @@ Exceptions and Errors thrown by yum. """ -from i18n import to_unicode +from .i18n import to_unicode class YumBaseError(Exception): """ diff --git a/yum/Makefile b/yum/Makefile index cd469d2..39033b6 100644 --- a/yum/Makefile +++ b/yum/Makefile @@ -1,8 +1,8 @@ -PYTHON=python +PYTHON=python3 PACKAGE = $(shell basename `pwd`) PYFILES = $(wildcard *.py) -PYVER := $(shell $(PYTHON) -c 'import sys; print "%.3s" %(sys.version)') -PYSYSDIR := $(shell $(PYTHON) -c 'import sys; print sys.prefix') +PYVER := $(shell $(PYTHON) -c 'import sys; print("%.3s" %(sys.version))') +PYSYSDIR := $(shell $(PYTHON) -c 'import sys; print(sys.prefix)') PYLIBDIR = $(PYSYSDIR)/lib/python$(PYVER) PKGDIR = $(PYLIBDIR)/site-packages/$(PACKAGE) diff --git a/yum/__init__.py b/yum/__init__.py index 99039e0..fc9cf30 100644 --- a/yum/__init__.py +++ b/yum/__init__.py @@ -49,43 +49,43 @@ import yum.i18n _ = yum.i18n._ P_ = yum.i18n.P_ -import config -from config import ParsingError, ConfigParser -import Errors -import rpmsack +from . import config +from .config import ParsingError, ConfigParser +from . import Errors +from . import rpmsack import rpmUtils.updates from rpmUtils.arch import archDifference, canCoinstall, ArchStorage, isMultiLibArch from rpmUtils.miscutils import compareEVR import rpmUtils.transaction -import comps -import pkgtag_db -from repos import RepoStorage -import misc -from parser import ConfigPreProcessor, varReplace -import transactioninfo +from . import comps +from . import pkgtag_db +from .repos import RepoStorage +from . import misc +from .parser import ConfigPreProcessor, varReplace +from . import transactioninfo import urlgrabber from urlgrabber.grabber import URLGrabber, URLGrabError from urlgrabber.progress import format_number -from packageSack import packagesNewestByName, packagesNewestByNameArch, ListPackageSack -import depsolve -import plugins -import logginglevels -import yumRepo -import callbacks +from .packageSack import packagesNewestByName, packagesNewestByNameArch, ListPackageSack +from . import depsolve +from . import plugins +from . import logginglevels +from . import yumRepo +from . import callbacks import yum.history import warnings warnings.simplefilter("ignore", Errors.YumFutureDeprecationWarning) -from packages import parsePackages, comparePoEVR -from packages import YumAvailablePackage, YumLocalPackage, YumInstalledPackage -from packages import YumUrlPackage, YumNotFoundPackage -from constants import * +from .packages import parsePackages, comparePoEVR +from .packages import YumAvailablePackage, YumLocalPackage, YumInstalledPackage +from .packages import YumUrlPackage, YumNotFoundPackage +from .constants import * from yum.rpmtrans import RPMTransaction,SimpleCliCallBack from yum.i18n import to_unicode, to_str import string -import StringIO +import io from weakref import proxy as weakref @@ -390,9 +390,9 @@ class YumBase(depsolve.Depsolve): parser = ConfigParser() try: parser.readfp(confpp_obj) - except ParsingError, e: + except ParsingError as e: msg = str(e) - raise Errors.ConfigError, msg + raise Errors.ConfigError(msg) # Check sections in the .repo file that was just slurped up for section in parser.sections(): @@ -420,7 +420,7 @@ class YumBase(depsolve.Depsolve): try: thisrepo = self.readRepoConfig(parser, section) - except (Errors.RepoError, Errors.ConfigError), e: + except (Errors.RepoError, Errors.ConfigError) as e: self.logger.warning(e) continue else: @@ -444,7 +444,7 @@ class YumBase(depsolve.Depsolve): # collection try: self._repos.add(thisrepo) - except Errors.RepoError, e: + except Errors.RepoError as e: self.logger.warning(e) def getReposFromConfig(self): @@ -481,9 +481,9 @@ class YumBase(depsolve.Depsolve): repo = yumRepo.YumRepository(section) try: repo.populate(parser, section, self.conf) - except ValueError, e: + except ValueError as e: msg = _('Repository %r: Error parsing config: %s' % (section,e)) - raise Errors.ConfigError, msg + raise Errors.ConfigError(msg) # Ensure that the repo name is set if not repo.name: @@ -618,7 +618,7 @@ class YumBase(depsolve.Depsolve): continue msg = 'sslclientcert basename shared between %s and %s' - raise Errors.ConfigError, msg % (repo, cert_basenames[bn]) + raise Errors.ConfigError(msg % (repo, cert_basenames[bn])) repo_st = time.time() self._repos.doSetup(thisrepo) @@ -701,7 +701,7 @@ class YumBase(depsolve.Depsolve): self._pkgSack = None - for repo in self.repos.repos.values(): + for repo in list(self.repos.repos.values()): if hasattr(repo, '_resetSack'): repo._resetSack() else: @@ -801,10 +801,10 @@ class YumBase(depsolve.Depsolve): continue if not repo.ready(): - raise Errors.RepoError, "Repository '%s' not yet setup" % repo + raise Errors.RepoError("Repository '%s' not yet setup" % repo) try: groupremote = repo.getGroupLocation() - except Errors.RepoMDError, e: + except Errors.RepoMDError as e: pass else: reposWithGroups.append(repo) @@ -828,14 +828,14 @@ class YumBase(depsolve.Depsolve): try: self._comps.add(groupfile) - except (Errors.GroupsError,Errors.CompsException), e: + except (Errors.GroupsError,Errors.CompsException) as e: msg = _('Failed to add groups file for repository: %s - %s') % (repo, str(e)) self.logger.critical(msg) else: repo.groups_added = True if self._comps.compscount == 0: - raise Errors.GroupsError, _('No Groups Available in any repository') + raise Errors.GroupsError(_('No Groups Available in any repository')) self._comps.compile(self.rpmdb.simplePkgList()) self.verbose_logger.debug('group time: %0.3f' % (time.time() - group_st)) @@ -867,7 +867,7 @@ class YumBase(depsolve.Depsolve): cached=repo.cache) # feed it into _tags.add() self._tags.add(repo.id, tag_sqlite) - except (Errors.RepoError, Errors.PkgTagsError), e: + except (Errors.RepoError, Errors.PkgTagsError) as e: msg = _('Failed to add Pkg Tags for repository: %s - %s') % (repo, str(e)) self.logger.critical(msg) @@ -1072,7 +1072,7 @@ class YumBase(depsolve.Depsolve): if txmbr.name not in bad_togo: bad_togo[txmbr.name] = [] bad_togo[txmbr.name].append(txmbr.pkgtup) - for ipkg in self.rpmdb.searchNames(bad_togo.keys()): + for ipkg in self.rpmdb.searchNames(list(bad_togo.keys())): if (kern_pkgtup is not None and ipkg.name == kern_pkgtup[0] and kern_pkgtup in bad_togo[kern_pkgtup[0]]): continue # If "running kernel" matches, it's always bad. @@ -1081,7 +1081,7 @@ class YumBase(depsolve.Depsolve): # If there is at least one version not being removed, allow it if ipkg.pkgtup not in bad_togo[ipkg.name]: del bad_togo[ipkg.name] - for pkgname in bad_togo.keys(): + for pkgname in list(bad_togo.keys()): if (kern_pkgtup is not None and pkgname == kern_pkgtup[0] and kern_pkgtup in bad_togo[kern_pkgtup[0]]): continue # If "running kernel" matches, it's always bad. @@ -1337,10 +1337,10 @@ class YumBase(depsolve.Depsolve): return depTree def _printDepTree(self, tree): - for pkg, l in tree.iteritems(): - print pkg + for pkg, l in list(tree.items()): + print(pkg) for p in l: - print "\t", p + print(("\t", p)) def _printTransaction(self): #transaction set states @@ -1512,7 +1512,7 @@ class YumBase(depsolve.Depsolve): try: os.unlink(self._ts_save_file) - except (IOError, OSError), e: + except (IOError, OSError) as e: pass self._ts_save_file = None @@ -1553,7 +1553,7 @@ class YumBase(depsolve.Depsolve): fn = getattr(cb, i) try: misc.unlink_f(fn) - except (IOError, OSError), e: + except (IOError, OSError) as e: self.logger.critical(_('Failed to remove transaction file %s') % fn) @@ -1773,10 +1773,10 @@ class YumBase(depsolve.Depsolve): lockfile = os.path.normpath(lockfile) # get rid of silly preceding extra / mypid=str(os.getpid()) - while not self._lock(lockfile, mypid, 0644): + while not self._lock(lockfile, mypid, 0o644): try: fd = open(lockfile, 'r') - except (IOError, OSError), e: + except (IOError, OSError) as e: msg = _("Could not open lock %s: %s") % (lockfile, e) raise Errors.LockError(errno.EPERM, msg) @@ -1788,7 +1788,7 @@ class YumBase(depsolve.Depsolve): if oldpid == os.getpid(): # if we own the lock, we're fine break try: os.kill(oldpid, 0) - except OSError, e: + except OSError as e: if e[0] == errno.ESRCH: # The pid doesn't exist self._unlock(lockfile) @@ -1830,13 +1830,13 @@ class YumBase(depsolve.Depsolve): self._unlock(lockfile) self._lockfile = None - def _lock(self, filename, contents='', mode=0777): + def _lock(self, filename, contents='', mode=0o777): lockdir = os.path.dirname(filename) try: if not os.path.exists(lockdir): - os.makedirs(lockdir, mode=0755) + os.makedirs(lockdir, mode=0o755) fd = os.open(filename, os.O_EXCL|os.O_CREAT|os.O_WRONLY, mode) - except OSError, msg: + except OSError as msg: if not msg.errno == errno.EEXIST: # Whoa. What the heck happened? errmsg = _('Could not create lock at %s: %s ') % (filename, str(msg)) @@ -1875,7 +1875,7 @@ class YumBase(depsolve.Depsolve): # if the file is wrong AND it is >= what we expected then it # can't be redeemed. If we can, kill it and start over fresh cursize = os.stat(fo)[6] - totsize = long(po.size) + totsize = int(po.size) if cursize >= totsize and not po.repo.cache: # if the path to the file is NOT inside the cachedir then don't # unlink it b/c it is probably a file:// url and possibly @@ -1899,7 +1899,7 @@ class YumBase(depsolve.Depsolve): try: filesum = misc.checksum(checksumType, fo) - except Errors.MiscError, e: + except Errors.MiscError as e: raise URLGrabError(-3, _('Could not perform checksum')) if filesum != csum: @@ -1999,7 +1999,7 @@ class YumBase(depsolve.Depsolve): checkfunc = (self.verifyPkg, (po, 1), {}) dirstat = os.statvfs(po.repo.pkgdir) - if (dirstat.f_bavail * dirstat.f_bsize) <= long(po.size): + if (dirstat.f_bavail * dirstat.f_bsize) <= int(po.size): adderror(po, _('Insufficient space in download directory %s\n' " * free %s\n" " * needed %s") % @@ -2031,7 +2031,7 @@ class YumBase(depsolve.Depsolve): self.verbose_logger.warn("%s", errmsg) done_repos.add(po.repoid) - except Errors.RepoError, e: + except Errors.RepoError as e: adderror(po, str(e)) else: po.localpath = mylocal @@ -2088,7 +2088,7 @@ class YumBase(depsolve.Depsolve): if os.path.exists(local): try: result = self.verifyHeader(local, po, raiseError=1) - except URLGrabError, e: + except URLGrabError as e: # might add a check for length of file - if it is < # required doing a reget misc.unlink_f(local) @@ -2097,8 +2097,7 @@ class YumBase(depsolve.Depsolve): return else: if self.conf.cache: - raise Errors.RepoError, \ - _('Header not in local cache and caching-only mode enabled. Cannot download %s') % po.hdrpath + raise Errors.RepoError(_('Header not in local cache and caching-only mode enabled. Cannot download %s') % po.hdrpath) if self.dsCallback: self.dsCallback.downloadHeader(po.name) @@ -2109,14 +2108,14 @@ class YumBase(depsolve.Depsolve): hdrpath = repo.getHeader(po, checkfunc=checkfunc, cache=repo.http_caching != 'none', ) - except Errors.RepoError, e: + except Errors.RepoError as e: saved_repo_error = e try: misc.unlink_f(local) - except OSError, e: - raise Errors.RepoError, saved_repo_error + except OSError as e: + raise Errors.RepoError(saved_repo_error) else: - raise Errors.RepoError, saved_repo_error + raise Errors.RepoError(saved_repo_error) else: po.hdrpath = hdrpath return @@ -2210,7 +2209,7 @@ class YumBase(depsolve.Depsolve): continue try: misc.unlink_f(fn) - except OSError, e: + except OSError as e: self.logger.warning(_('Cannot remove %s'), fn) continue else: @@ -2260,7 +2259,7 @@ class YumBase(depsolve.Depsolve): for item in filelist: try: misc.unlink_f(item) - except OSError, e: + except OSError as e: self.logger.critical(_('Cannot remove %s file %s'), filetype, item) continue else: @@ -2301,7 +2300,7 @@ class YumBase(depsolve.Depsolve): key = (po.name, po.arch) if key not in ndinst or po.verGT(ndinst[key]): ndinst[key] = po - installed = dinst.values() + installed = list(dinst.values()) if showdups: avail = self.pkgSack.returnPackages(patterns=patterns, @@ -2521,7 +2520,7 @@ class YumBase(depsolve.Depsolve): critweights.setdefault(s, critweight) critweight -= 1 - for sack in self.pkgSack.sacks.values(): + for sack in list(self.pkgSack.sacks.values()): tmpres.extend(sack.searchPrimaryFieldsMultipleStrings(sql_fields, real_crit)) def results2sorted_lists(tmpres, sorted_lists): @@ -2572,9 +2571,9 @@ class YumBase(depsolve.Depsolve): del tmpres - if sorted_lists.values(): + if list(sorted_lists.values()): # do the ones we already have - for item in sorted_lists.values(): + for item in list(sorted_lists.values()): for pkg, k, v in item: if pkg not in results_by_pkg: results_by_pkg[pkg] = [] @@ -2665,7 +2664,7 @@ class YumBase(depsolve.Depsolve): for c in criteria: c = c.lower() res = self.pkgtags.search_tags(c) - for (name, taglist) in res.items(): + for (name, taglist) in list(res.items()): pkgs = self.pkgSack.searchNevra(name=name) if not pkgs: continue @@ -2800,7 +2799,7 @@ class YumBase(depsolve.Depsolve): tagdata = getattr(po, tag) if tagdata is None: continue - if type(tagdata) is types.ListType: + if type(tagdata) is list: searchlist.extend(tagdata) else: searchlist.append(tagdata) @@ -2827,7 +2826,7 @@ class YumBase(depsolve.Depsolve): available = [] if self.comps.compscount == 0: - raise Errors.GroupsError, _('No group data available for configured repositories') + raise Errors.GroupsError(_('No group data available for configured repositories')) if patterns is None: grps = self.comps.groups @@ -2858,7 +2857,7 @@ class YumBase(depsolve.Depsolve): thesegroups = self.comps.return_groups(grpid) if not thesegroups: - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) for thisgroup in thesegroups: thisgroup.toremove = True @@ -2877,7 +2876,7 @@ class YumBase(depsolve.Depsolve): thesegroups = self.comps.return_groups(grpid) if not thesegroups: - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) for thisgroup in thesegroups: thisgroup.toremove = False @@ -2908,13 +2907,13 @@ class YumBase(depsolve.Depsolve): """ if not self.comps.has_group(grpid): - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) txmbrs_used = [] thesegroups = self.comps.return_groups(grpid) if not thesegroups: - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) package_types = self.conf.group_package_types if group_package_types: @@ -2940,7 +2939,7 @@ class YumBase(depsolve.Depsolve): _('Adding package %s from group %s'), pkg, thisgroup.groupid) try: txmbrs = self.install(name = pkg) - except Errors.InstallError, e: + except Errors.InstallError as e: self.verbose_logger.debug(_('No package named %s available to be installed'), pkg) else: @@ -2954,7 +2953,7 @@ class YumBase(depsolve.Depsolve): count_cond_test = 0 if group_conditionals: - for condreq, cond in thisgroup.conditional_packages.iteritems(): + for condreq, cond in list(thisgroup.conditional_packages.items()): if self.isPackageInstalled(cond): try: txmbrs = self.install(name = condreq) @@ -3003,11 +3002,11 @@ class YumBase(depsolve.Depsolve): in the group(s) are force removed from the transaction. """ if not self.comps.has_group(grpid): - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) thesegroups = self.comps.return_groups(grpid) if not thesegroups: - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) for thisgroup in thesegroups: thisgroup.selected = False @@ -3052,7 +3051,7 @@ class YumBase(depsolve.Depsolve): self._add_not_found_a(pkgs, pkgtup) if allow_missing: # This can happen due to excludes after .up has return None # happened. - raise Errors.DepError, _('Package tuple %s could not be found in packagesack') % str(pkgtup) + raise Errors.DepError(_('Package tuple %s could not be found in packagesack') % str(pkgtup)) if len(pkgs) > 1: # boy it'd be nice to do something smarter here FIXME result = pkgs[0] @@ -3072,7 +3071,7 @@ class YumBase(depsolve.Depsolve): pkgs = self.rpmdb.searchPkgTuple(pkgtup) if len(pkgs) == 0: self._add_not_found_i(pkgs, pkgtup) - raise Errors.RpmDBError, _('Package tuple %s could not be found in rpmdb') % str(pkgtup) + raise Errors.RpmDBError(_('Package tuple %s could not be found in rpmdb') % str(pkgtup)) # Dito. FIXME from getPackageObject() for len() > 1 ... :) po = pkgs[0] # take the first one @@ -3116,7 +3115,7 @@ class YumBase(depsolve.Depsolve): # either it is 'dep (some operator) e:v-r' # or /file/dep # or packagename - if type(depstring) == types.TupleType: + if type(depstring) == tuple: (depname, depflags, depver) = depstring else: depname = depstring @@ -3129,10 +3128,10 @@ class YumBase(depsolve.Depsolve): if len(dep_split) == 3: depname, flagsymbol, depver = dep_split if not flagsymbol in SYMBOLFLAGS: - raise Errors.YumBaseError, _('Invalid version flag from: %s') % str(depstring) + raise Errors.YumBaseError(_('Invalid version flag from: %s') % str(depstring)) depflags = SYMBOLFLAGS[flagsymbol] - return self.pkgSack.getProvides(depname, depflags, depver).keys() + return list(self.pkgSack.getProvides(depname, depflags, depver).keys()) def returnPackageByDep(self, depstring): """Pass in a generic [build]require string and this function will @@ -3140,18 +3139,18 @@ class YumBase(depsolve.Depsolve): # we get all sorts of randomness here errstring = depstring - if type(depstring) not in types.StringTypes: + if type(depstring) not in (str,): errstring = str(depstring) try: pkglist = self.returnPackagesByDep(depstring) except Errors.YumBaseError: - raise Errors.YumBaseError, _('No Package found for %s') % errstring + raise Errors.YumBaseError(_('No Package found for %s') % errstring) ps = ListPackageSack(pkglist) result = self._bestPackageFromList(ps.returnNewestByNameArch()) if result is None: - raise Errors.YumBaseError, _('No Package found for %s') % errstring + raise Errors.YumBaseError(_('No Package found for %s') % errstring) return result @@ -3166,7 +3165,7 @@ class YumBase(depsolve.Depsolve): # either it is 'dep (some operator) e:v-r' # or /file/dep # or packagename - if type(depstring) == types.TupleType: + if type(depstring) == tuple: (depname, depflags, depver) = depstring else: depname = depstring @@ -3179,10 +3178,10 @@ class YumBase(depsolve.Depsolve): if len(dep_split) == 3: depname, flagsymbol, depver = dep_split if not flagsymbol in SYMBOLFLAGS: - raise Errors.YumBaseError, _('Invalid version flag from: %s') % str(depstring) + raise Errors.YumBaseError(_('Invalid version flag from: %s') % str(depstring)) depflags = SYMBOLFLAGS[flagsymbol] - return self.rpmdb.getProvides(depname, depflags, depver).keys() + return list(self.rpmdb.getProvides(depname, depflags, depver).keys()) def _bestPackageFromList(self, pkglist): """take list of package objects and return the best package object. @@ -3389,7 +3388,7 @@ class YumBase(depsolve.Depsolve): thesegroups = self.comps.return_groups(grpid) if not thesegroups: - raise Errors.GroupsError, _("No Group named %s exists") % to_unicode(grpid) + raise Errors.GroupsError(_("No Group named %s exists") % to_unicode(grpid)) pkgnames = set() for thisgroup in thesegroups: pkgnames.update(thisgroup.packages) @@ -3451,11 +3450,11 @@ class YumBase(depsolve.Depsolve): if isinstance(po, YumAvailablePackage) or isinstance(po, YumLocalPackage): pkgs.append(po) else: - raise Errors.InstallError, _('Package Object was not a package object instance') + raise Errors.InstallError(_('Package Object was not a package object instance')) else: if not kwargs: - raise Errors.InstallError, _('Nothing specified to install') + raise Errors.InstallError(_('Nothing specified to install')) if 'pattern' in kwargs: if kwargs['pattern'] and kwargs['pattern'][0] == '-': @@ -3479,7 +3478,7 @@ class YumBase(depsolve.Depsolve): try: mypkgs = self.returnPackagesByDep(arg) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: self.logger.critical(_('No Match for argument: %s') % to_unicode(arg)) else: # install MTA* == fail, because provides don't do globs @@ -3537,7 +3536,7 @@ class YumBase(depsolve.Depsolve): pkgbyname[pkg.name].append(pkg) lst = [] - for pkgs in pkgbyname.values(): + for pkgs in list(pkgbyname.values()): lst.extend(self.bestPackagesFromList(pkgs)) pkgs = lst @@ -3560,7 +3559,7 @@ class YumBase(depsolve.Depsolve): self.verbose_logger.warning(_('Package %s installed and not available'), pkg) if pkgs: return [] - raise Errors.InstallError, _('No package(s) available to install') + raise Errors.InstallError(_('No package(s) available to install')) # FIXME - lots more checking here # - install instead of erase @@ -3802,7 +3801,7 @@ class YumBase(depsolve.Depsolve): depmatches = self.returnPackagesByDep(arg) else: depmatches = self.returnInstalledPackagesByDep(arg) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: self.logger.critical(_('%s') % e) if update_to: @@ -3841,7 +3840,7 @@ class YumBase(depsolve.Depsolve): self._add_not_found_a(availpkgs, nevra_dict) if len(availpkgs) > 1: availpkgs = self._compare_providers(availpkgs, requiringPo) - availpkgs = map(lambda x: x[0], availpkgs) + availpkgs = [x[0] for x in availpkgs] elif not availpkgs: self.logger.warning(_("No package matched to upgrade: %s"), self._ui_nevra_dict(nevra_dict)) @@ -3991,7 +3990,7 @@ class YumBase(depsolve.Depsolve): if no po then look at kwargs, if neither then raise an exception""" if not po and not kwargs: - raise Errors.RemoveError, 'Nothing specified to remove' + raise Errors.RemoveError('Nothing specified to remove') tx_return = [] pkgs = [] @@ -4015,7 +4014,7 @@ class YumBase(depsolve.Depsolve): arg = u[0] try: depmatches = self.returnInstalledPackagesByDep(arg) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: self.logger.critical(_('%s') % e) if not depmatches: @@ -4228,7 +4227,7 @@ class YumBase(depsolve.Depsolve): else: tx_mbrs.extend(self.remove(**kwargs)) if not tx_mbrs: - raise Errors.ReinstallRemoveError, _("Problem in reinstall: no package matched to remove") + raise Errors.ReinstallRemoveError(_("Problem in reinstall: no package matched to remove")) templen = len(tx_mbrs) # this is a reinstall, so if we can't reinstall exactly what we uninstalled # then we really shouldn't go on @@ -4317,7 +4316,7 @@ class YumBase(depsolve.Depsolve): EOL """ if not po and not kwargs: - raise Errors.DowngradeError, 'Nothing specified to downgrade' + raise Errors.DowngradeError('Nothing specified to downgrade') doing_group_pkgs = False if po: @@ -4339,7 +4338,7 @@ class YumBase(depsolve.Depsolve): try: apkgs = self.returnPackagesByDep(arg) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: self.logger.critical(_('No Match for argument: %s') % to_unicode(arg)) else: @@ -4362,7 +4361,7 @@ class YumBase(depsolve.Depsolve): pkgs = self.rpmdb.searchNevra(name=kwargs['name']) if pkgs: return [] - raise Errors.DowngradeError, _('No package(s) available to downgrade') + raise Errors.DowngradeError(_('No package(s) available to downgrade')) warned_nas = set() # Skip kernel etc. @@ -4614,7 +4613,7 @@ class YumBase(depsolve.Depsolve): text = repo.id + '/gpgkey' rawkey = urlgrabber.urlread(url, **opts) - except urlgrabber.grabber.URLGrabError, e: + except urlgrabber.grabber.URLGrabError as e: raise Errors.YumBaseError(_('GPG key retrieval failed: ') + to_unicode(str(e))) @@ -4630,12 +4629,12 @@ class YumBase(depsolve.Depsolve): text = repo.id + '/gpgkeysig' sigfile = urlgrabber.urlopen(url, **opts) - except urlgrabber.grabber.URLGrabError, e: + except urlgrabber.grabber.URLGrabError as e: sigfile = None if sigfile: if not misc.valid_detached_sig(sigfile, - StringIO.StringIO(rawkey), repo.gpgcadir): + io.StringIO(rawkey), repo.gpgcadir): #if we decide we want to check, even though the sig failed # here is where we would do that raise Errors.YumBaseError(_('GPG key signature on key %s does not match CA Key for repo: %s') % (url, repo.id)) @@ -4647,7 +4646,7 @@ class YumBase(depsolve.Depsolve): # Parse the key try: keys_info = misc.getgpgkeyinfo(rawkey, multiple=True) - except ValueError, e: + except ValueError as e: raise Errors.YumBaseError(_('Invalid GPG Key from %s: %s') % (url, to_unicode(str(e)))) keys = [] @@ -4656,8 +4655,7 @@ class YumBase(depsolve.Depsolve): for info in ('keyid', 'timestamp', 'userid', 'fingerprint', 'raw_key'): if info not in keyinfo: - raise Errors.YumBaseError, \ - _('GPG key parsing failed: key does not have value %s') + info + raise Errors.YumBaseError(_('GPG key parsing failed: key does not have value %s') + info) thiskey[info] = keyinfo[info] thiskey['hexkeyid'] = misc.keyIdToRPMVer(keyinfo['keyid']).upper() thiskey['valid_sig'] = valid_sig @@ -4751,27 +4749,25 @@ class YumBase(depsolve.Depsolve): ts = self.rpmdb.readOnlyTS() result = ts.pgpImportPubkey(misc.procgpgkey(info['raw_key'])) if result != 0: - raise Errors.YumBaseError, \ - _('Key import failed (code %d)') % result + raise Errors.YumBaseError(_('Key import failed (code %d)') % result) self.logger.info(_('Key imported successfully')) key_installed = True if not key_installed and user_cb_fail: - raise Errors.YumBaseError, _("Didn't install any keys") + raise Errors.YumBaseError(_("Didn't install any keys")) if not key_installed: - raise Errors.YumBaseError, \ - _('The GPG keys listed for the "%s" repository are ' \ + raise Errors.YumBaseError(_('The GPG keys listed for the "%s" repository are ' \ 'already installed but they are not correct for this ' \ 'package.\n' \ 'Check that the correct key URLs are configured for ' \ - 'this repository.') % (repo.name) + 'this repository.') % (repo.name)) # Check if the newly installed keys helped result, errmsg = self.sigCheckPkg(po) if result != 0: self.logger.info(_("Import of key(s) didn't help, wrong key(s)?")) - raise Errors.YumBaseError, errmsg + raise Errors.YumBaseError(errmsg) def _getAnyKeyForRepo(self, repo, destdir, keyurl_list, is_cakey=False, callback=None): """ @@ -4835,7 +4831,7 @@ class YumBase(depsolve.Depsolve): # Import the key result = misc.import_key_to_pubring(info['raw_key'], info['hexkeyid'], gpgdir=destdir) if not result: - raise Errors.YumBaseError, _('Key import failed') + raise Errors.YumBaseError(_('Key import failed')) self.logger.info(_('Key imported successfully')) key_installed = True # write out the key id to imported_cakeys in the repos basedir @@ -4851,14 +4847,13 @@ class YumBase(depsolve.Depsolve): pass if not key_installed and user_cb_fail: - raise Errors.YumBaseError, _("Didn't install any keys for repo %s") % repo + raise Errors.YumBaseError(_("Didn't install any keys for repo %s") % repo) if not key_installed: - raise Errors.YumBaseError, \ - _('The GPG keys listed for the "%s" repository are ' \ + raise Errors.YumBaseError(_('The GPG keys listed for the "%s" repository are ' \ 'already installed but they are not correct.\n' \ 'Check that the correct key URLs are configured for ' \ - 'this repository.') % (repo.name) + 'this repository.') % (repo.name)) def getKeyForRepo(self, repo, callback=None): """ @@ -4993,9 +4988,7 @@ class YumBase(depsolve.Depsolve): def _downloadPackages(self,callback): ''' Download the need packages in the Transaction ''' # This can be overloaded by a subclass. - dlpkgs = map(lambda x: x.po, filter(lambda txmbr: - txmbr.ts_state in ("i", "u"), - self.tsInfo.getMembers())) + dlpkgs = [x.po for x in [txmbr for txmbr in self.tsInfo.getMembers() if txmbr.ts_state in ("i", "u")]] # Check if there is something to do if len(dlpkgs) == 0: return None @@ -5005,7 +4998,7 @@ class YumBase(depsolve.Depsolve): probs = self.downloadPkgs(dlpkgs) except IndexError: - raise Errors.YumBaseError, [_("Unable to find a suitable mirror.")] + raise Errors.YumBaseError([_("Unable to find a suitable mirror.")]) if len(probs) > 0: errstr = [_("Errors were encountered while downloading packages.")] for key in probs: @@ -5013,7 +5006,7 @@ class YumBase(depsolve.Depsolve): for error in errors: errstr.append("%s: %s" % (key, error)) - raise Errors.YumDownloadError, errstr + raise Errors.YumDownloadError(errstr) return dlpkgs def _checkSignatures(self,pkgs,callback): @@ -5027,7 +5020,7 @@ class YumBase(depsolve.Depsolve): elif result == 1: self.getKeyForPackage(po, self._askForGPGKeyImport) else: - raise Errors.YumGPGCheckError, errmsg + raise Errors.YumGPGCheckError(errmsg) return 0 @@ -5059,12 +5052,12 @@ class YumBase(depsolve.Depsolve): if rpmlib_only: retmsgs = [_("ERROR You need to update rpm to handle:")] retmsgs.extend(msgs) - raise Errors.YumRPMCheckError, retmsgs + raise Errors.YumRPMCheckError(retmsgs) retmsgs = [_('ERROR with transaction check vs depsolve:')] retmsgs.extend(msgs) retmsgs.append(_('Please report this error at %s') % self.conf.bugtracker_url) - raise Errors.YumRPMCheckError,retmsgs + raise Errors.YumRPMCheckError(retmsgs) tsConf = {} for feature in ['diskspacecheck']: # more to come, I'm sure @@ -5082,7 +5075,7 @@ class YumBase(depsolve.Depsolve): errstring = _('Test Transaction Errors: ') for descr in tserrors: errstring += ' %s\n' % descr - raise Errors.YumTestTransactionError, errstring + raise Errors.YumTestTransactionError(errstring) del self.ts # put back our depcheck callback @@ -5155,7 +5148,7 @@ class YumBase(depsolve.Depsolve): newrepo.basecachedir = self.conf.cachedir newrepo.base_persistdir = self.conf._repos_persistdir - for key in kwargs.keys(): + for key in list(kwargs.keys()): if not hasattr(newrepo, key): continue # skip the ones which aren't vars setattr(newrepo, key, kwargs[key]) @@ -5178,7 +5171,7 @@ class YumBase(depsolve.Depsolve): tmpdir = '/var/tmp' try: cachedir = misc.getCacheDir(tmpdir, reuse) - except (IOError, OSError), e: + except (IOError, OSError) as e: self.logger.critical(_('Could not set cachedir: %s') % str(e)) cachedir = None @@ -5257,7 +5250,7 @@ class YumBase(depsolve.Depsolve): try: f.write(msg) f.close() - except (IOError, OSError), e: + except (IOError, OSError) as e: self._ts_save_file = None if auto: self.logger.critical(_("Could not save transaction file %s: %s") % (filename, str(e))) @@ -5275,7 +5268,7 @@ class YumBase(depsolve.Depsolve): # return txmbrs loaded try: data = open(filename, 'r').readlines() - except (IOError, OSError), e: + except (IOError, OSError) as e: raise Errors.YumBaseError(_("Could not access/read saved transaction %s : %s") % (filename, str(e))) @@ -5308,7 +5301,7 @@ class YumBase(depsolve.Depsolve): # so someone can add --nogpgcheck or --nodocs or --nodiskspace or some nonsense and have it work try: tsflags = int(data[1].strip()) - except (ValueError, IndexError), e: + except (ValueError, IndexError) as e: msg = _("cannot find tsflags or tsflags not integer.") raise Errors.YumBaseError(msg) @@ -5350,7 +5343,7 @@ class YumBase(depsolve.Depsolve): else: msg = _("Found txmbr in unknown current state: %s" % current_state) raise Errors.YumBaseError(msg) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: missingany = True msg = _("Could not find txmbr: %s in state %s" % (str(pkgtup), current_state)) if not ignoremissing: @@ -5387,7 +5380,7 @@ class YumBase(depsolve.Depsolve): po = self.getInstalledPackageObject(tuple(pkgtup.split(','))) else: po = self.getPackageObject(tuple(pkgtup.split(','))) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: msg = _("Could not find txmbr: %s from origin: %s" % (str(pkgtup), origin)) self.logger.critical(msg) missingany = True @@ -5404,7 +5397,7 @@ class YumBase(depsolve.Depsolve): po = self.getInstalledPackageObject(tuple(pkgtup.split(','))) else: po = self.getPackageObject(tuple(pkgtup.split(','))) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: msg = _("Could not find txmbr: %s from origin: %s" % (str(pkgtup), origin)) self.logger.critical(msg) missingany = True @@ -5472,12 +5465,12 @@ class YumBase(depsolve.Depsolve): # go through the stuff in the ts to be installed - make sure none of that needs the required pkg, either. for (provn,provf,provevr) in required.provides: - if self.tsInfo.getNewRequires(provn, provf, provevr).keys(): + if list(self.tsInfo.getNewRequires(provn, provf, provevr).keys()): still_needed = True okay_to_remove[required] = False break for fn in required.filelist + required.dirlist: - if self.tsInfo.getNewRequires(fn, None,(None,None,None)).keys(): + if list(self.tsInfo.getNewRequires(fn, None,(None,None,None)).keys()): okay_to_remove[required] = False still_needed = True break @@ -5489,7 +5482,7 @@ class YumBase(depsolve.Depsolve): # break if not still_needed: - print '---> Marking %s to be removed - no longer needed by %s' % (required.name, pkg.name) + print(('---> Marking %s to be removed - no longer needed by %s' % (required.name, pkg.name))) txmbrs = self.remove(po=required) for txmbr in txmbrs: diff --git a/yum/callbacks.py b/yum/callbacks.py index 7ad25ce..f8ca2a9 100644 --- a/yum/callbacks.py +++ b/yum/callbacks.py @@ -40,7 +40,7 @@ class ProcessTransBaseCallback: self.logger = logging.getLogger('yum.verbose.ProcessTrasactionBaseCallback') def event(self,state,data=None): - if state in PT_MESSAGES.keys(): + if state in list(PT_MESSAGES.keys()): self.logger.info(PT_MESSAGES[state]) class ProcessTransNoOutputCallback: diff --git a/yum/comps.py b/yum/comps.py index 65f6d5e..b8c0075 100755 --- a/yum/comps.py +++ b/yum/comps.py @@ -16,14 +16,14 @@ import types import sys -from constants import * -from Errors import CompsException +from .constants import * +from .Errors import CompsException #FIXME - compsexception isn't caught ANYWHERE so it's pointless to raise it # switch all compsexceptions to grouperrors after api break import fnmatch import re from yum.i18n import to_unicode -from misc import get_my_lang_code +from .misc import get_my_lang_code from yum.misc import cElementTree_iterparse as iterparse lang_attr = '{http://www.w3.org/XML/1998/namespace}lang' @@ -119,10 +119,10 @@ class Group(CompsObj): def _packageiter(self): # Gah, FIXME: real iterator/class - lst = self.mandatory_packages.keys() + \ - self.optional_packages.keys() + \ - self.default_packages.keys() + \ - self.conditional_packages.keys() + lst = list(self.mandatory_packages.keys()) + \ + list(self.optional_packages.keys()) + \ + list(self.default_packages.keys()) + \ + list(self.conditional_packages.keys()) return lst @@ -184,7 +184,7 @@ class Group(CompsObj): if child.tag == 'packagereq': genre = child.attrib.get('type') if not genre: - genre = u'mandatory' + genre = 'mandatory' if genre not in ('mandatory', 'default', 'optional', 'conditional'): # just ignore bad package lines @@ -288,7 +288,7 @@ class Category(CompsObj): self.parse(elem) def _groupiter(self): - return self._groups.keys() + return list(self._groups.keys()) groups = property(_groupiter) @@ -357,11 +357,11 @@ class Category(CompsObj): <display_order>%s</display_order>\n""" % (self.categoryid, self.display_order) msg +=""" <name>%s</name>\n""" % self.name - for (lang, val) in self.translated_name.items(): + for (lang, val) in list(self.translated_name.items()): msg += """ <name xml:lang="%s">%s</name>\n""" % (lang, val) msg += """ <description>%s</description>\n""" % self.description - for (lang, val) in self.translated_description.items(): + for (lang, val) in list(self.translated_description.items()): msg += """ <description xml:lang="%s">%s</description>\n""" % (lang, val) msg += """ <grouplist>\n""" @@ -384,12 +384,12 @@ class Comps(object): def get_groups(self): - grps = self._groups.values() + grps = list(self._groups.values()) grps.sort(key=lambda x: (x.display_order, x.name)) return grps def get_categories(self): - cats = self._categories.values() + cats = list(self._categories.values()) cats.sort(key=lambda x: (x.display_order, x.name)) return cats @@ -440,12 +440,12 @@ class Comps(object): # If we didn't match to anything in the current locale, try others for group in self.groups: - for name in group.translated_name.values(): + for name in list(group.translated_name.values()): if match(name): returns[group.groupid] = group break - return returns.values() + return list(returns.values()) # This is close to returnPackages() etc. API ... need to std. these names # the above return_groups uses different, but equal, API. @@ -476,12 +476,12 @@ class Comps(object): continue for cat in self.categories: - for name in cat.translated_name.values(): + for name in list(cat.translated_name.values()): if match(name): returns[cat.categoryid] = cat break - return returns.values() + return list(returns.values()) def add_group(self, group): if group.groupid in self._groups: @@ -501,12 +501,12 @@ class Comps(object): if not srcfile: raise CompsException - if type(srcfile) in types.StringTypes: + if type(srcfile) in (str,): # srcfile is a filename string try: infile = open(srcfile, 'rt') - except IOError, e: - raise CompsException, 'open(%s): #%u %s' % (srcfile, e.errno, e.strerror) + except IOError as e: + raise CompsException('open(%s): #%u %s' % (srcfile, e.errno, e.strerror)) else: # srcfile is a file object infile = srcfile @@ -523,8 +523,8 @@ class Comps(object): if elem.tag == "category": category = Category(elem) self.add_category(category) - except SyntaxError, e: - raise CompsException, "comps file is empty/damaged" + except SyntaxError as e: + raise CompsException("comps file is empty/damaged") del parser @@ -551,7 +551,7 @@ class Comps(object): # optional/default packages installed. # If so - then the group is installed else: - check_pkgs = group.optional_packages.keys() + group.default_packages.keys() + group.conditional_packages.keys() + check_pkgs = list(group.optional_packages.keys()) + list(group.default_packages.keys()) + list(group.conditional_packages.keys()) group.installed = False for pkgname in check_pkgs: if pkgname in inst_pkg_names: @@ -585,23 +585,23 @@ class Comps(object): def main(): try: - print sys.argv[1] + print(sys.argv[1]) p = Comps() for srcfile in sys.argv[1:]: p.add(srcfile) for group in p.groups: - print group + print(group) for pkg in group.packages: - print ' ' + pkg + print(' ' + pkg) for category in p.categories: - print category.name + print(category.name) for group in category.groups: - print ' ' + group + print(' ' + group) except IOError: - print >> sys.stderr, "newcomps.py: No such file:\'%s\'" % sys.argv[1] + print("newcomps.py: No such file:\'%s\'" % sys.argv[1], file=sys.stderr) sys.exit(1) if __name__ == '__main__': diff --git a/yum/config.py b/yum/config.py index d09511f..52f60ec 100644 --- a/yum/config.py +++ b/yum/config.py @@ -25,9 +25,9 @@ import sys import warnings import rpm import copy -import urlparse +import urllib.parse import shlex -from parser import ConfigPreProcessor, varReplace +from .parser import ConfigPreProcessor, varReplace try: from iniparse import INIConfig from iniparse.compat import NoSectionError, NoOptionError, ParsingError @@ -35,12 +35,12 @@ try: except ImportError: _use_iniparse = False if not _use_iniparse: - from ConfigParser import NoSectionError, NoOptionError, ParsingError - from ConfigParser import ConfigParser + from configparser import NoSectionError, NoOptionError, ParsingError + from configparser import ConfigParser import rpmUtils.transaction -import Errors +from . import Errors import types -from misc import get_uuid, read_in_items_from_dot_dir +from .misc import get_uuid, read_in_items_from_dot_dir # Alter/patch these to change the default checking... __pkgs_gpgcheck_default__ = False @@ -90,10 +90,10 @@ class Option(object): @return: Nothing. ''' # Only try to parse if it's a string - if isinstance(value, basestring): + if isinstance(value, str): try: value = self.parse(value) - except ValueError, e: + except ValueError as e: # Add the field name onto the error raise ValueError('Error parsing "%s = %r": %s' % (self._optname, value, str(e))) @@ -207,7 +207,7 @@ class UrlOption(Option): raise ValueError('"_none_" is not a valid value') # Check that scheme is valid - (s,b,p,q,f,o) = urlparse.urlparse(url) + (s,b,p,q,f,o) = urllib.parse.urlparse(url) if s not in self.schemes: raise ValueError('URL must be %s not "%s"' % (self._schemelist(), s)) @@ -267,7 +267,7 @@ class IntOption(Option): def parse(self, s): try: val = int(s) - except (ValueError, TypeError), e: + except (ValueError, TypeError) as e: raise ValueError('invalid integer value') if self._range_max is not None and val > self._range_max: raise ValueError('out of range integer value') @@ -326,7 +326,7 @@ class SecondsOption(Option): try: n = float(n) - except (ValueError, TypeError), e: + except (ValueError, TypeError) as e: raise ValueError('invalid value') if n < 0: @@ -487,14 +487,14 @@ class BaseConfig(object): def __init__(self): self._section = None - for name in self.iterkeys(): + for name in list(self.keys()): option = self.optionobj(name) option.setup(self, name) def __str__(self): out = [] out.append('[%s]' % self._section) - for name, value in self.iteritems(): + for name, value in list(self.items()): out.append('%s: %r' % (name, value)) return '\n'.join(out) @@ -513,7 +513,7 @@ class BaseConfig(object): opts = set(parser.options(section)) else: opts = set() - for name in self.iterkeys(): + for name in list(self.keys()): option = self.optionobj(name) value = None if name in opts: @@ -557,7 +557,7 @@ class BaseConfig(object): The value returned is the parsed, validated option value. ''' # Use dir() so that we see inherited options too - for name in self.iterkeys(): + for name in list(self.keys()): yield (name, getattr(self, name)) def write(self, fileobj, section=None, always=()): @@ -578,7 +578,7 @@ class BaseConfig(object): # Updated the ConfigParser with the changed values cfgOptions = self.cfg.options(section) - for name,value in self.iteritems(): + for name,value in list(self.items()): option = self.optionobj(name) if always is None or name in always or option.default != value or name in cfgOptions : self.cfg.set(section,name, option.tostring(value)) @@ -600,7 +600,7 @@ class BaseConfig(object): if hasattr(self, option): setattr(self, option, value) else: - raise Errors.ConfigError, 'No such option %s' % option + raise Errors.ConfigError('No such option %s' % option) class StartupConf(BaseConfig): ''' @@ -771,7 +771,7 @@ class YumConf(StartupConf): res = getattr(self, attr) if not res and type(res) not in (type(False), type(0)): res = '' - if type(res) == types.ListType: + if type(res) == list: res = ',\n '.join(res) output = output + '%s = %s\n' % (attr, res) @@ -866,7 +866,7 @@ def readStartupConfig(configfile, root): confpp_obj = ConfigPreProcessor(configfile) try: parser.readfp(confpp_obj) - except ParsingError, e: + except ParsingError as e: raise Errors.ConfigError("Parsing file failed: %s" % e) startupconf.populate(parser, 'main') @@ -960,7 +960,7 @@ def readVersionGroupsConfig(configfile="/etc/yum/version-groups.conf"): confpp_obj = ConfigPreProcessor(configfile) try: parser.readfp(confpp_obj) - except ParsingError, e: + except ParsingError as e: raise Errors.ConfigError("Parsing file failed: %s" % e) ret = {} for section in parser.sections(): @@ -1011,7 +1011,7 @@ def _getsysver(installroot, distroverpkg): ts.pushVSFlags(~(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)) try: idx = ts.dbMatch('provides', distroverpkg) - except TypeError, e: + except TypeError as e: # This is code for "cannot open rpmdb" # this is for pep 352 compliance on python 2.6 and above :( if sys.hexversion < 0x02050000: @@ -1020,7 +1020,7 @@ def _getsysver(installroot, distroverpkg): else: raise Errors.YumBaseError("Error: " + str(e)) raise Errors.YumBaseError("Error: " + str(e)) - except rpm.error, e: + except rpm.error as e: # This is the "new" code for "cannot open rpmdb", 4.8.0 ish raise Errors.YumBaseError("Error: " + str(e)) # we're going to take the first one - if there is more than one of these @@ -1028,7 +1028,7 @@ def _getsysver(installroot, distroverpkg): if idx.count() == 0: releasever = '$releasever' else: - hdr = idx.next() + hdr = next(idx) releasever = hdr['version'] del hdr del idx @@ -1051,13 +1051,13 @@ def writeRawRepoFile(repo,only=None): # out which one is which section_id = repo.id if repo.id not in ini._sections: - for sect in ini._sections.keys(): + for sect in list(ini._sections.keys()): if varReplace(sect, repo.yumvar) == repo.id: section_id = sect # Updated the ConfigParser with the changed values cfgOptions = repo.cfg.options(repo.id) - for name,value in repo.iteritems(): + for name,value in list(repo.items()): if value is None: # Proxy continue diff --git a/yum/depsolve.py b/yum/depsolve.py index 6d744c0..c8eafa3 100644 --- a/yum/depsolve.py +++ b/yum/depsolve.py @@ -25,16 +25,16 @@ import logging import rpmUtils.transaction import rpmUtils.miscutils from rpmUtils.arch import archDifference, canCoinstall -import misc -from misc import unique, version_tuple_to_string -from transactioninfo import TransactionMember +from . import misc +from .misc import unique, version_tuple_to_string +from .transactioninfo import TransactionMember import rpm -from packageSack import ListPackageSack -from constants import * -import packages -import logginglevels -import Errors +from .packageSack import ListPackageSack +from .constants import * +from . import packages +from . import logginglevels +from . import Errors import warnings warnings.simplefilter("ignore", Errors.YumFutureDeprecationWarning) @@ -96,7 +96,7 @@ class Depsolve(object): return if not self.conf.installroot: - raise Errors.YumBaseError, _('Setting up TransactionSets before config class is up') + raise Errors.YumBaseError(_('Setting up TransactionSets before config class is up')) self._getTsInfo(remove_only) self.initActionTs() @@ -282,7 +282,7 @@ class Depsolve(object): self.po_with_problems.add((po,self._working_po,errormsgs[-1])) - except Errors.DepError,e: + except Errors.DepError as e: # FIXME: This is a hack, it don't solve the problem # of tries to update to a package the have been removed from the # pkgSack because of dep problems. @@ -369,8 +369,7 @@ class Depsolve(object): # if this package is being obsoleted, it's just like if it's # being upgraded as far as checking for other providers if thismode is None: - if filter(lambda x: x.obsoleted_by, - self.tsInfo.matchNaevr(i_n, i_a, i_e, i_v, i_r)): + if [x for x in self.tsInfo.matchNaevr(i_n, i_a, i_e, i_v, i_r) if x.obsoleted_by]: thismode = 'u' if thismode is not None: @@ -433,7 +432,7 @@ class Depsolve(object): # If the requirement is still there, try and solve it again # so we don't lose it for pkg in txmbrs[0].updated_by: - if requirement in map(self._prco_req2req, pkg.returnPrco('requires')): + if requirement in list(map(self._prco_req2req, pkg.returnPrco('requires'))): return True, missingdep + self._requiringFromTransaction(pkg, requirement, errorlist)[1] checkdeps = True return checkdeps, missingdep @@ -460,9 +459,9 @@ class Depsolve(object): if flags == 0: flags = None - if type(version) in (types.StringType, types.NoneType, types.UnicodeType): + if type(version) in (bytes, type(None), str): (r_e, r_v, r_r) = rpmUtils.miscutils.stringToVersion(version) - elif type(version) in (types.TupleType, types.ListType): # would this ever be a ListType? + elif type(version) in (tuple, list): # would this ever be a ListType? (r_e, r_v, r_r) = version # Quick lookup, lots of reqs for one pkg: @@ -626,7 +625,7 @@ class Depsolve(object): # before, they're not going to be installed anymore, so we # should mark them to be re-checked if txmbr.pkgtup in upgraded: - map(self.tsInfo.remove, upgraded[txmbr.pkgtup]) + list(map(self.tsInfo.remove, upgraded[txmbr.pkgtup])) if not txmbrs: missingdep = 1 checkdeps = 0 @@ -701,7 +700,7 @@ class Depsolve(object): prof = hotshot.Profile(fn) rc = prof.runcall(self.resolveDeps) prof.close() - print "done running depcheck" + print("done running depcheck") stats = hotshot.stats.load(fn) stats.strip_dirs() stats.sort_stats('time', 'calls') @@ -713,7 +712,7 @@ class Depsolve(object): prof = cProfile.Profile() rc = prof.runcall(self.resolveDeps) prof.dump_stats("yumprof") - print "done running depcheck" + print("done running depcheck") p = pstats.Stats('yumprof') p.strip_dirs() @@ -973,7 +972,7 @@ class Depsolve(object): continue # FIXME: This is probably the best place to fix the postfix rename # problem long term (post .21) ... see compare_providers. - for pkg, hits in self.tsInfo.getRequires(*prov).iteritems(): + for pkg, hits in list(self.tsInfo.getRequires(*prov).items()): # See the docs, this is to make groupremove "more useful". if (self.conf.groupremove_leaf_only and txmbr.groups and txmbr.output_state == TS_ERASE): @@ -1019,7 +1018,7 @@ class Depsolve(object): # get file requirements from packages not deleted todel = [] - for pkgtup, files in self.installedFileRequires.iteritems(): + for pkgtup, files in list(self.installedFileRequires.items()): if self._tsInfo.getMembersWithState(pkgtup, output_states=TS_REMOVE_STATES): todel.append(pkgtup) else: @@ -1219,7 +1218,7 @@ class Depsolve(object): unique_nevra_pkgs[pkg.pkgtup].repo <= pkg.repo): continue unique_nevra_pkgs[pkg.pkgtup] = pkg - pkgs = unique_nevra_pkgs.values() + pkgs = list(unique_nevra_pkgs.values()) pkgresults = {} @@ -1230,7 +1229,7 @@ class Depsolve(object): self.plugins.run("compare_providers", providers_dict=pkgresults, reqpo=reqpo) - for pkg in pkgresults.keys(): + for pkg in list(pkgresults.keys()): rpmdbpkgs = self.rpmdb.searchNevra(name=pkg.name) if rpmdbpkgs: # We only want to count things as "installed" if they are @@ -1258,7 +1257,7 @@ class Depsolve(object): # be ignored entirely. Just not preferred pass - pkgs = pkgresults.keys() + pkgs = list(pkgresults.keys()) # go through each pkg and compare to others # if it is same skip it @@ -1382,7 +1381,7 @@ class Depsolve(object): pkgresults[po] += 1000 pkgresults[po] += (len(po.name)*-1) - bestorder = sorted(pkgresults.items(), + bestorder = sorted(list(pkgresults.items()), key=lambda x: (x[1], x[0]), reverse=True) self.verbose_logger.log(logginglevels.DEBUG_4, _('Best Order: %s' % str(bestorder))) diff --git a/yum/history.py b/yum/history.py index 5385bd1..a5fef73 100644 --- a/yum/history.py +++ b/yum/history.py @@ -22,7 +22,7 @@ import os, os.path import glob from weakref import proxy as weakref -from sqlutils import sqlite, executeSQL, sql_esc_glob +from .sqlutils import sqlite, executeSQL, sql_esc_glob import yum.misc as misc import yum.constants from yum.constants import * @@ -410,7 +410,7 @@ class YumMergedHistoryTransaction(YumHistoryTransaction): if xstate != 'Obsoleting': _move_pkg_n(npkg, 'Reinstall') - sametups = set(npkgtup2pkg.keys()).intersection(fpkgtup2pkg.keys()) + sametups = set(npkgtup2pkg.keys()).intersection(list(fpkgtup2pkg.keys())) for pkgtup in sametups: if pkgtup not in fpkgtup2pkg or pkgtup not in npkgtup2pkg: continue @@ -571,7 +571,7 @@ class YumHistory: if not os.path.exists(self.conf.db_path): try: os.makedirs(self.conf.db_path) - except (IOError, OSError), e: + except (IOError, OSError) as e: # some sort of useful thing here? A warning? return self.conf.writable = True @@ -588,7 +588,7 @@ class YumHistory: if len(pieces) != 3: continue try: - map(int, pieces) + list(map(int, pieces)) except ValueError: continue @@ -605,7 +605,7 @@ class YumHistory: if not os.path.exists(self.conf.addon_path): try: os.makedirs(self.conf.addon_path) - except (IOError, OSError), e: + except (IOError, OSError) as e: # some sort of useful thing here? A warning? return else: @@ -785,7 +785,7 @@ class YumHistory: if problem.problem == 'duplicates': pkgs[problem.duplicate.pkgtup] = problem.duplicate - for pkg in pkgs.values(): + for pkg in list(pkgs.values()): pid = self.pkg2pid(pkg) if pkg.pkgtup == problem.pkg.pkgtup: main = 'TRUE' @@ -938,8 +938,8 @@ class YumHistory: if self.conf.writable and not os.path.exists(tid_dir): try: - os.makedirs(tid_dir, mode=0700) - except (IOError, OSError), e: + os.makedirs(tid_dir, mode=0o700) + except (IOError, OSError) as e: # emit a warning/raise an exception? return False @@ -954,7 +954,7 @@ class YumHistory: # flush data fo.flush() fo.close() - except (IOError, OSError), e: + except (IOError, OSError) as e: return False # return return True @@ -1110,7 +1110,7 @@ class YumHistory: trans_end.rpmdb_version AS end_rv, return_code FROM trans_end""" - params = tid2obj.keys() + params = list(tid2obj.keys()) if len(params) > yum.constants.PATTERNS_INDEXED_MAX: executeSQL(cur, sql) else: @@ -1325,7 +1325,7 @@ class YumHistory: if self.conf.writable and not os.path.exists(self._db_file): # make them default to 0600 - sysadmin can change it later # if they want - fo = os.open(self._db_file, os.O_CREAT, 0600) + fo = os.open(self._db_file, os.O_CREAT, 0o600) os.close(fo) cur = self._get_cursor() diff --git a/yum/i18n.py b/yum/i18n.py index 9889bf6..9ac1ed9 100755 --- a/yum/i18n.py +++ b/yum/i18n.py @@ -175,15 +175,15 @@ def __utf8_iter_ucs(msg): if byte0 < 0x80: # 0xxxxxxx yield (byte0, 1) elif (byte0 & 0xe0) == 0xc0: # 110XXXXx 10xxxxxx - byte1 = uiter.next() + byte1 = next(uiter) if (((byte1 & 0xc0) != 0x80) or ((byte0 & 0xfe) == 0xc0)): # overlong? yield (None, 2) return yield ((((byte0 & 0x1f) << 6) | (byte1 & 0x3f)), 2) elif (byte0 & 0xf0) == 0xe0: # 1110XXXX 10Xxxxxx 10xxxxxx - byte1 = uiter.next() - byte2 = uiter.next() + byte1 = next(uiter) + byte2 = next(uiter) if (((byte1 & 0xc0) != 0x80) or ((byte2 & 0xc0) != 0x80) or ((byte0 == 0xe0) and ((byte1 & 0xe0) == 0x80)) or # overlong? ((byte0 == 0xed) and ((byte1 & 0xe0) == 0xa0)) or # surrogate? @@ -194,9 +194,9 @@ def __utf8_iter_ucs(msg): yield ((((byte0 & 0x0f) << 12) | ((byte1 & 0x3f) << 6) | (byte2 & 0x3f)), 3) elif (byte0 & 0xf8) == 0xf0: # 11110XXX 10XXxxxx 10xxxxxx 10xxxxxx - byte1 = uiter.next() - byte2 = uiter.next() - byte3 = uiter.next() + byte1 = next(uiter) + byte2 = next(uiter) + byte3 = next(uiter) if (((byte1 & 0xc0) != 0x80) or ((byte2 & 0xc0) != 0x80) or ((byte3 & 0xc0) != 0x80) or @@ -232,7 +232,7 @@ def utf8_width_chop(msg, chop=None): return utf8_width(msg), msg ret = 0 - passed_unicode = isinstance(msg, unicode) + passed_unicode = isinstance(msg, str) msg_bytes = 0 msg = to_utf8(msg) for (ucs, bytes) in __utf8_iter_ucs(msg): @@ -284,7 +284,7 @@ def utf8_width_fill(msg, fill, chop=None, left=True, prefix='', suffix=''): else: msg = ''.join([extra, prefix, msg, suffix]) - if isinstance(passed_msg, unicode): + if isinstance(passed_msg, str): return to_unicode(msg) return msg @@ -337,7 +337,7 @@ def utf8_text_wrap(text, width=70, initial_indent='', subsequent_indent=''): # alsa-plugins-jack, setools*, dblatex, uisp, "perl-Getopt-GUI-Long", # suitesparse, "synce-serial", writer2latex, xenwatch, ltsp-utils - passed_unicode = isinstance(text, unicode) + passed_unicode = isinstance(text, str) def _indent_at_beg(line): count = 0 @@ -414,7 +414,7 @@ def utf8_text_wrap(text, width=70, initial_indent='', subsequent_indent=''): ret.append(indent.rstrip(' ')) if passed_unicode: - return map(to_unicode, ret) + return list(map(to_unicode, ret)) return ret def utf8_text_fill(text, *args, **kwargs): @@ -425,14 +425,14 @@ def utf8_text_fill(text, *args, **kwargs): def to_unicode(obj, encoding='utf-8', errors='replace'): ''' convert a 'str' to 'unicode' ''' - if isinstance(obj, basestring): - if not isinstance(obj, unicode): - obj = unicode(obj, encoding, errors) + if isinstance(obj, str): + if not isinstance(obj, str): + obj = str(obj, encoding, errors) return obj def to_utf8(obj, errors='replace'): '''convert 'unicode' to an encoded utf-8 byte string ''' - if isinstance(obj, unicode): + if isinstance(obj, str): obj = obj.encode('utf-8', errors) return obj @@ -448,13 +448,13 @@ def to_str(obj): """ Convert something to a string, if it isn't one. """ # NOTE: unicode counts as a string just fine. We just want objects to call # their __str__ methods. - if not isinstance(obj, basestring): + if not isinstance(obj, str): obj = str(obj) return obj def str_eq(a, b): """ convert between unicode and not and compare them, w/o warning or being annoying""" - if isinstance(a, unicode) == isinstance(b, unicode): + if isinstance(a, str) == isinstance(b, str): if a == b: # stupid python... return True elif to_utf8(a) == to_utf8(b): @@ -485,29 +485,29 @@ if __name__ == "__main__": def out(arg): arg = to_utf8(arg) - print "UTF8 :", arg - print "len :", len(arg) + print(("UTF8 :", arg)) + print(("len :", len(arg))) arg = to_unicode(arg) - print "USC :", arg - print "len :", len(arg) - print "valid:", utf8_valid(arg) - print "width:", utf8_width(arg) - print "4.8 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 8), '>') - print "4.3 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 3), '>') - print "4.2 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 2), '>') - print "4.1 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 1), '>') - print "3.3 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 3), '>') - print "3.2 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 2), '>') - print "3.1 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 1), '>') - print "40.79:", "%s%s%s" % ('<', utf8_width_fill(arg, 40, 79), '>') - print "40.20:", "%s%s%s" % ('<', utf8_width_fill(arg, 40, 20), '>') - print '' - - print " ---- Arguments/str ---- " + print(("USC :", arg)) + print(("len :", len(arg))) + print(("valid:", utf8_valid(arg))) + print(("width:", utf8_width(arg))) + print(("4.8 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 8), '>'))) + print(("4.3 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 3), '>'))) + print(("4.2 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 2), '>'))) + print(("4.1 :", "%s%s%s" % ('<', utf8_width_fill(arg, 4, 1), '>'))) + print(("3.3 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 3), '>'))) + print(("3.2 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 2), '>'))) + print(("3.1 :", "%s%s%s" % ('<', utf8_width_fill(arg, 3, 1), '>'))) + print(("40.79:", "%s%s%s" % ('<', utf8_width_fill(arg, 40, 79), '>'))) + print(("40.20:", "%s%s%s" % ('<', utf8_width_fill(arg, 40, 20), '>'))) + print('') + + print(" ---- Arguments/str ---- ") for arg in sys.argv[1:]: out(arg) - print " ---- Arguments/gettext ---- " + print(" ---- Arguments/gettext ---- ") for arg in sys.argv[1:]: try: arg = _(arg) @@ -516,12 +516,12 @@ if __name__ == "__main__": out(arg) if len(sys.argv) > 2: - print " ---- Arguments/str/all ---- " + print(" ---- Arguments/str/all ---- ") out(sys.argv[1] % sys.argv[2:]) - print " ---- Arguments/gettext/all ---- " + print(" ---- Arguments/gettext/all ---- ") try: - arg = _(sys.argv[1]) % map(_, sys.argv[2:]) + arg = _(sys.argv[1]) % list(map(_, sys.argv[2:])) except UnicodeDecodeError: sys.exit(0) out(arg) diff --git a/yum/logginglevels.py b/yum/logginglevels.py index 14c5e73..55da8f3 100644 --- a/yum/logginglevels.py +++ b/yum/logginglevels.py @@ -98,7 +98,7 @@ def __convertLevel(level, table): try: new_level = table[level] except KeyError: - keys = table.keys() + keys = list(table.keys()) # We didn't find the level in the table, check if it's smaller # than the smallest level if level < keys[0]: @@ -195,11 +195,11 @@ def setFileLog(uid, logfile, cleanup=None): # For installroot etc. logdir = os.path.dirname(logfile) if not os.path.exists(logdir): - os.makedirs(logdir, mode=0755) + os.makedirs(logdir, mode=0o755) if not os.path.exists(logfile): f = open(logfile, 'w') - os.chmod(logfile, 0600) # making sure umask doesn't catch us up + os.chmod(logfile, 0o600) # making sure umask doesn't catch us up f.close() filelogger = logging.getLogger("yum.filelogging") diff --git a/yum/mdparser.py b/yum/mdparser.py index 8631f06..db51d16 100644 --- a/yum/mdparser.py +++ b/yum/mdparser.py @@ -22,10 +22,10 @@ except ImportError: import cElementTree iterparse = cElementTree.iterparse -from cStringIO import StringIO +from io import StringIO import warnings -import Errors +from . import Errors #TODO: document everything here @@ -50,7 +50,7 @@ class MDParser: else: fh = open(filename, 'r') parser = iterparse(fh, events=('start', 'end')) self.reader = parser.__iter__() - event, elem = self.reader.next() + event, elem = next(self.reader) self._handlercls = handlers.get(elem.tag, None) if not self._handlercls: raise ValueError('Unknown repodata type "%s" in %s' % ( @@ -61,7 +61,7 @@ class MDParser: def __iter__(self): return self - def next(self): + def __next__(self): for event, elem in self.reader: if event == 'end' and elem.tag[-7:] == 'package': self.count += 1 @@ -77,10 +77,10 @@ class BaseEntry: return self._p[k] def keys(self): - return self._p.keys() + return list(self._p.keys()) def values(self): - return self._p.values() + return list(self._p.values()) def has_key(self, k): warnings.warn('has_key() will go away in a future version of Yum.\n', @@ -92,10 +92,10 @@ class BaseEntry: def __str__(self): out = StringIO() - keys = self.keys() + keys = list(self.keys()) keys.sort() for k in keys: - line = u'%s=%s\n' % (k, self[k]) + line = '%s=%s\n' % (k, self[k]) out.write(line.encode('utf8')) return out.getvalue() @@ -207,10 +207,10 @@ def test(): parser = MDParser(sys.argv[1]) for pkg in parser: - print '-' * 40 - print pkg + print(('-' * 40)) + print(pkg) - print 'read: %s packages (%s suggested)' % (parser.count, parser.total) + print(('read: %s packages (%s suggested)' % (parser.count, parser.total))) if __name__ == '__main__': test() diff --git a/yum/metalink.py b/yum/metalink.py index aaa4f25..8876e3f 100755 --- a/yum/metalink.py +++ b/yum/metalink.py @@ -24,7 +24,7 @@ import os import time from urlgrabber.progress import format_number -import Errors +from . import Errors from yum.misc import cElementTree_xmlparse as xmlparse @@ -68,11 +68,11 @@ class MetaLinkFile: self.chksums[helem.get("type").lower()] = helem.text if not hasattr(self, 'timestamp'): - raise MetaLinkRepoErrorParseFail, "No timestamp for file" + raise MetaLinkRepoErrorParseFail("No timestamp for file") if not hasattr(self, 'size'): - raise MetaLinkRepoErrorParseFail, "No size for file" + raise MetaLinkRepoErrorParseFail("No size for file") if not hasattr(self, 'chksums'): - raise MetaLinkRepoErrorParseFail, "No verifications for file" + raise MetaLinkRepoErrorParseFail("No verifications for file") def __str__(self): return """\ @@ -181,11 +181,11 @@ class MetaLinkRepoMD: self.old_repomds = [] self.mirrors = [] if not os.path.exists(filename): - raise MetaLinkRepoErrorParseFail, "File %s does not exist" %filename + raise MetaLinkRepoErrorParseFail("File %s does not exist" %filename) try: root = xmlparse(filename) except SyntaxError: - raise MetaLinkRepoErrorParseFail, "File %s is not XML" % filename + raise MetaLinkRepoErrorParseFail("File %s is not XML" % filename) for elem in root.findall(__ML_FILE_ELEMENT__): name = elem.get('name') @@ -193,13 +193,13 @@ class MetaLinkRepoMD: continue if self.name is not None and self.name != name: - raise MetaLinkRepoErrorParseFail, "Different paths for repomd file" + raise MetaLinkRepoErrorParseFail("Different paths for repomd file") self.name = name repomd = MetaLinkFile(elem) if self.repomd is not None and self.repomd != repomd: - raise MetaLinkRepoErrorParseFail, "Different data for repomd file" + raise MetaLinkRepoErrorParseFail("Different data for repomd file") self.repomd = repomd for celem in elem.findall(__ML_OLD_FILE_ELEMENTS__): @@ -215,9 +215,9 @@ class MetaLinkRepoMD: self.mirrors.sort() if self.repomd is None: - raise MetaLinkRepoErrorParseFail, "No repomd file" + raise MetaLinkRepoErrorParseFail("No repomd file") if len(self.mirrors) < 1: - raise MetaLinkRepoErrorParseFail, "No mirror" + raise MetaLinkRepoErrorParseFail("No mirror") def urls(self): """ Iterate plain urls for the mirrors, like the old mirrorlist. """ @@ -271,7 +271,7 @@ def main(): """ MetaLinkRepoMD test function. """ def usage(): - print >> sys.stderr, "Usage: %s <metalink> ..." % sys.argv[0] + print("Usage: %s <metalink> ..." % sys.argv[0], file=sys.stderr) sys.exit(1) if len(sys.argv) < 2: @@ -279,12 +279,12 @@ def main(): for filename in sys.argv[1:]: if not os.path.exists(filename): - print "No such file:", filename + print("No such file:", filename) continue - print "File:", filename - print MetaLinkRepoMD(filename) - print '' + print("File:", filename) + print(MetaLinkRepoMD(filename)) + print('') if __name__ == '__main__': main() diff --git a/yum/misc.py b/yum/misc.py index 2f6ddfe..6904c27 100644 --- a/yum/misc.py +++ b/yum/misc.py @@ -6,14 +6,14 @@ Assorted utility functions for yum. import types import os import os.path -from cStringIO import StringIO +from io import StringIO import base64 import struct import re import errno -import Errors -import constants -import pgpmsg +from . import Errors +from . import constants +from . import pgpmsg import tempfile import glob import pwd @@ -53,12 +53,12 @@ except ImportError: return md5.new() if algo == 'sha1': return sha.new() - raise ValueError, "Bad checksum type" + raise ValueError("Bad checksum type") -from Errors import MiscError +from .Errors import MiscError # These are API things, so we can't remove them even if they aren't used here. # pylint: disable-msg=W0611 -from i18n import to_utf8, to_unicode +from .i18n import to_utf8, to_unicode # pylint: enable-msg=W0611 _share_data_store = {} @@ -70,12 +70,12 @@ def share_data(value): # and hash('a') == hash(u'a') ... so use different stores. # In theory eventaully we'll have all of one type, but don't hold breath. store = _share_data_store - if isinstance(value, unicode): + if isinstance(value, str): store = _share_data_store_u # hahahah, of course the above means that: # hash(('a', 'b')) == hash((u'a', u'b')) # ...which we have in deptuples, so just screw sharing those atm. - if type(value) == types.TupleType: + if type(value) == tuple: return value return store.setdefault(value, value) @@ -242,12 +242,12 @@ class Checksums: elif ignore_missing: continue else: - raise MiscError, 'Error Checksumming, bad checksum type %s' % sumtype + raise MiscError('Error Checksumming, bad checksum type %s' % sumtype) done.add(sumtype) self._sumtypes.append(sumtype) self._sumalgos.append(sumalgo) if not done and not ignore_none: - raise MiscError, 'Error Checksumming, no valid checksum type' + raise MiscError('Error Checksumming, no valid checksum type') def __len__(self): return self._len @@ -319,7 +319,7 @@ def checksum(sumtype, file, CHUNK=2**16, datasize=None): # chunking brazenly lifted from Ryan Tomayko try: - if type(file) not in types.StringTypes: + if type(file) not in (str,): fo = file # assume it's a file-like-object else: fo = open(file, 'r', CHUNK) @@ -329,7 +329,7 @@ def checksum(sumtype, file, CHUNK=2**16, datasize=None): if datasize is not None and data.length > datasize: break - if type(file) is types.StringType: + if type(file) is bytes: fo.close() del fo @@ -339,8 +339,8 @@ def checksum(sumtype, file, CHUNK=2**16, datasize=None): return '!%u!%s' % (datasize, data.hexdigest(sumtype)) return data.hexdigest(sumtype) - except (IOError, OSError), e: - raise MiscError, 'Error opening file for checksum: %s' % file + except (IOError, OSError) as e: + raise MiscError('Error opening file for checksum: %s' % file) def getFileList(path, ext, filelist): """Return all files in path matching ext, store them in filelist, @@ -349,8 +349,8 @@ def getFileList(path, ext, filelist): extlen = len(ext) try: dir_list = os.listdir(path) - except OSError, e: - raise MiscError, ('Error accessing directory %s, %s') % (path, e) + except OSError as e: + raise MiscError(('Error accessing directory %s, %s') % (path, e)) for d in dir_list: if os.path.isdir(path + '/' + d): @@ -379,7 +379,7 @@ class GenericHolder: if hasattr(self, item): return getattr(self, item) else: - raise KeyError, item + raise KeyError(item) def procgpgkey(rawkey): '''Convert ASCII armoured GPG key to binary @@ -421,7 +421,7 @@ def getgpgkeyinfo(rawkey, multiple=False): key_info_objs = [] try: keys = pgpmsg.decode_multiple_keys(rawkey) - except Exception, e: + except Exception as e: raise ValueError(str(e)) if len(keys) == 0: raise ValueError('No key found in given key data') @@ -464,7 +464,7 @@ def keyIdToRPMVer(keyid): '''Convert an integer representing a GPG key ID to the hex version string used by RPM ''' - return "%08x" % (keyid & 0xffffffffL) + return "%08x" % (keyid & 0xffffffff) def keyInstalled(ts, keyid, timestamp): @@ -528,13 +528,13 @@ def import_key_to_pubring(rawkey, keyid, cachedir=None, gpgdir=None, make_ro_cop rodir = gpgdir + '-ro' if not os.path.exists(rodir): - os.makedirs(rodir, mode=0755) + os.makedirs(rodir, mode=0o755) for f in glob.glob(gpgdir + '/*'): basename = os.path.basename(f) ro_f = rodir + '/' + basename shutil.copy(f, ro_f) - os.chmod(ro_f, 0755) - fp = open(rodir + '/gpg.conf', 'w', 0755) + os.chmod(ro_f, 0o755) + fp = open(rodir + '/gpg.conf', 'w', 0o755) # yes it is this stupid, why do you ask? opts="""lock-never no-auto-check-trustdb @@ -587,7 +587,7 @@ def valid_detached_sig(sig_file, signed_file, gpghome=None): try: sigs = ctx.verify(sig, signed_text, plaintext) - except gpgme.GpgmeError, e: + except gpgme.GpgmeError as e: return False else: if not sigs: @@ -681,7 +681,7 @@ def prco_tuple_to_string(prcoTuple): def string_to_prco_tuple(prcoString): """returns a prco tuple (name, flags, (e, v, r)) for a string""" - if type(prcoString) == types.TupleType: + if type(prcoString) == tuple: (n, f, v) = prcoString else: n = prcoString @@ -700,14 +700,14 @@ def string_to_prco_tuple(prcoString): if f not in constants.SYMBOLFLAGS: try: f = flagToString(int(f)) - except (ValueError,TypeError), e: - raise Errors.MiscError, 'Invalid version flag: %s' % f + except (ValueError,TypeError) as e: + raise Errors.MiscError('Invalid version flag: %s' % f) else: f = constants.SYMBOLFLAGS[f] - if type(v) in (types.StringType, types.NoneType, types.UnicodeType): + if type(v) in (bytes, type(None), str): (prco_e, prco_v, prco_r) = stringToVersion(v) - elif type(v) in (types.TupleType, types.ListType): + elif type(v) in (tuple, list): (prco_e, prco_v, prco_r) = v #now we have (n, f, (e, v, r)) for the thing specified @@ -729,7 +729,7 @@ def _decompress_chunked(source, dest, ztype): if ztype not in _available_compression: msg = "%s compression not available" % ztype - raise Errors.MiscError, msg + raise Errors.MiscError(msg) if ztype == 'bz2': s_fn = bz2.BZ2File(source, 'r') @@ -751,9 +751,9 @@ def _decompress_chunked(source, dest, ztype): try: destination.write(data) - except (OSError, IOError), e: + except (OSError, IOError) as e: msg = "Error writing to file %s: %s" % (dest, str(e)) - raise Errors.MiscError, msg + raise Errors.MiscError(msg) destination.close() s_fn.close() @@ -847,9 +847,9 @@ def find_ts_remaining(timestamp, yumlibpath='/var/lib/yum'): continue try: (action, pkgspec) = item.split() - except ValueError, e: + except ValueError as e: msg = "Transaction journal file %s is corrupt." % (tsallpath) - raise Errors.MiscError, msg + raise Errors.MiscError(msg) to_complete_items.append((action, pkgspec)) return to_complete_items @@ -877,26 +877,26 @@ def _ugly_utf8_string_hack(item): # if we're anything obvious - do them first if item is None: return '' - elif isinstance(item, unicode): + elif isinstance(item, str): return item # this handles any bogon formats we see du = False try: - x = unicode(item, 'ascii') + x = str(item, 'ascii') du = True except UnicodeError: encodings = ['utf-8', 'iso-8859-1', 'iso-8859-15', 'iso-8859-2'] for enc in encodings: try: - x = unicode(item, enc) + x = str(item, enc) except UnicodeError: pass else: if x.encode(enc) == item: if enc != 'utf-8': - print '\n%s encoding on %s\n' % (enc, item) + print('\n%s encoding on %s\n' % (enc, item)) return x.encode('utf-8') @@ -905,7 +905,7 @@ def _ugly_utf8_string_hack(item): # we allow high bytes, if it passed the utf8 check above. Eg. # good chars = #x9 | #xA | #xD | [#x20-...] newitem = '' - bad_small_bytes = range(0, 8) + [11, 12] + range(14, 32) + bad_small_bytes = list(range(0, 8)) + [11, 12] + list(range(14, 32)) for char in item: if ord(char) in bad_small_bytes: pass # Just ignore these bytes... @@ -936,7 +936,7 @@ def unlink_f(filename): difference between "rm -f" and plain "rm". """ try: os.unlink(filename) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -944,7 +944,7 @@ def stat_f(filename): """ Call os.stat(), but don't die if the file isn't there. Returns None. """ try: return os.stat(filename) - except OSError, e: + except OSError as e: if e.errno not in (errno.ENOENT, errno.ENOTDIR): raise return None @@ -985,9 +985,9 @@ def setup_locale(override_codecs=True, override_time=False): # set time to C so that we output sane things in the logs (#433091) if override_time: locale.setlocale(locale.LC_TIME, 'C') - except locale.Error, e: + except locale.Error as e: # default to C locale if we get a failure. - print >> sys.stderr, 'Failed to set locale, defaulting to C' + print('Failed to set locale, defaulting to C', file=sys.stderr) os.environ['LC_ALL'] = 'C' locale.setlocale(locale.LC_ALL, 'C') @@ -1000,7 +1000,7 @@ def setup_locale(override_codecs=True, override_time=False): def get_my_lang_code(): try: mylang = locale.getlocale(locale.LC_MESSAGES) - except ValueError, e: + except ValueError as e: # This is RHEL-5 python crack, Eg. en_IN can't be parsed properly mylang = (None, None) if mylang == (None, None): # odd :) @@ -1026,7 +1026,7 @@ def get_open_files(pid): maps_f = '/proc/%s/maps' % pid try: maps = open(maps_f, 'r') - except (IOError, OSError), e: + except (IOError, OSError) as e: return files for line in maps: @@ -1043,7 +1043,7 @@ def get_open_files(pid): cli_f = '/proc/%s/cmdline' % pid try: cli = open(cli_f, 'r') - except (IOError, OSError), e: + except (IOError, OSError) as e: return files cmdline = cli.read() @@ -1073,7 +1073,7 @@ def get_uuid(savepath): sf.write(myid) sf.flush() sf.close() - except (IOError, OSError), e: + except (IOError, OSError) as e: pass return myid @@ -1126,7 +1126,7 @@ def repo_gen_decompress(filename, generated_name, cached=False): dest = os.path.dirname(filename) dest += '/gen' if not os.path.exists(dest): - os.makedirs(dest, mode=0755) + os.makedirs(dest, mode=0o755) dest += '/' + generated_name return decompress(filename, dest=dest, check_timestamps=True,fn_only=cached) diff --git a/yum/packageSack.py b/yum/packageSack.py index 4af563a..05c9101 100644 --- a/yum/packageSack.py +++ b/yum/packageSack.py @@ -18,12 +18,12 @@ Classes for manipulating and querying groups of packages. """ -from Errors import PackageSackError +from .Errors import PackageSackError import warnings import re import fnmatch -import misc -from packages import parsePackages +from . import misc +from .packages import parsePackages import rpmUtils.miscutils from rpmUtils.miscutils import compareEVR @@ -37,7 +37,7 @@ class PackageSackVersion: def __eq__(self, other): if other is None: return False - if type(other) in (type(''), type(u'')): + if type(other) in (type(''), type('')): return str(self) == other if self._num != other._num: return False if self._chksum.digest() != other._chksum.digest(): return False @@ -303,7 +303,7 @@ class PackageSackBase(object): '%s-%s:%s-%s.%s' % (n, e, v, r, a), )) - for (term,query) in specs.items(): + for (term,query) in list(specs.items()): if term == query: if query in names: exactmatch.append(self.searchPkgTuple(pkgtup)[0]) @@ -379,7 +379,7 @@ class MetaSack(PackageSackBase): return ret def dropCachedData(self): - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): if hasattr(sack, 'dropCachedData'): sack.dropCachedData() @@ -394,7 +394,7 @@ class MetaSack(PackageSackBase): self.sacks[repo.id].populate(repo, mdtype, callback, cacheOnly) def setCompatArchs(self, compatArchs): - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): sack.setCompatArchs(compatArchs) def packagesByTuple(self, pkgtup): @@ -480,7 +480,7 @@ class MetaSack(PackageSackBase): """builds the useful indexes for searching/querying the packageSack This should be called after all the necessary packages have been added/deleted""" - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): sack.buildIndexes() def delPackage(self, obj): @@ -525,7 +525,7 @@ class MetaSack(PackageSackBase): pkgs = packagesNewestByNameArch(pkgs) if not pkgs and (naTup or patterns): ui_pats = ", ".join(patterns or []) - raise PackageSackError, 'No Package Matching %s' % ui_pats + raise PackageSackError('No Package Matching %s' % ui_pats) return pkgs def returnNewestByName(self, name=None, patterns=None, ignore_case=False): @@ -540,7 +540,7 @@ class MetaSack(PackageSackBase): ui_pats = name else: ui_pats = ", ".join(patterns or []) - raise PackageSackError, 'No Package Matching %s' % ui_pats + raise PackageSackError('No Package Matching %s' % ui_pats) return pkgs def simplePkgList(self, patterns=None, ignore_case=False): @@ -549,12 +549,12 @@ class MetaSack(PackageSackBase): patterns, ignore_case) def printPackages(self): - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): sack.printPackages() def excludeArchs(self, archlist): """exclude incompatible arches. archlist is a list of compatible arches""" - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): sack.excludeArchs(archlist) def searchPackages(self, fields, criteria_re, callback): @@ -567,7 +567,7 @@ class MetaSack(PackageSackBase): matched = [] exactmatch = [] unmatched = None - for sack in self.sacks.values(): + for sack in list(self.sacks.values()): if hasattr(sack, "matchPackageNames"): e, m, u = [], [], [] try: @@ -596,7 +596,7 @@ class MetaSack(PackageSackBase): if hasattr(sack, methodName): method = getattr(sack, methodName) try: - sackResult = apply(method, args) + sackResult = method(*args) except PackageSackError: continue @@ -611,7 +611,7 @@ class MetaSack(PackageSackBase): if hasattr(sack, methodName): method = getattr(sack, methodName) try: - sackResult = apply(method, args) + sackResult = method(*args) except PackageSackError: continue @@ -652,7 +652,7 @@ class PackageSack(PackageSackBase): if not self.indexesBuilt: if failure == 'error': - raise PackageSackError, 'Indexes not yet built, cannot search' + raise PackageSackError('Indexes not yet built, cannot search') elif failure == 'build': self.buildIndexes() @@ -672,7 +672,7 @@ class PackageSack(PackageSackBase): pkgs = self.nevra.get((name, None, None, None, None), []) else: pkgs = [] - for pkgsbyRepo in self.pkgsByRepo.itervalues(): + for pkgsbyRepo in list(self.pkgsByRepo.values()): pkgs.extend(pkgsbyRepo) result = [ ] @@ -705,7 +705,7 @@ class PackageSack(PackageSackBase): self._checkIndexes(failure='build') if version is None: version = (None, None, None) - elif type(version) in (str, type(None), unicode): + elif type(version) in (str, type(None), str): version = rpmUtils.miscutils.stringToVersion(version) result = { } for po in self.provides.get(name, []): @@ -723,7 +723,7 @@ class PackageSack(PackageSackBase): self._checkIndexes(failure='build') if version is None: version = (None, None, None) - elif type(version) in (str, type(None), unicode): + elif type(version) in (str, type(None), str): version = rpmUtils.miscutils.stringToVersion(version) result = { } for po in self.requires.get(name, []): @@ -947,7 +947,7 @@ class PackageSack(PackageSackBase): self._checkIndexes(failure='build') where = self.nevra.get((naTup[0],None,None,None,None)) if (not where): - raise PackageSackError, 'No Package Matching %s.%s' % naTup + raise PackageSackError('No Package Matching %s.%s' % naTup) else: where = self.returnPackages(patterns=patterns, ignore_case=ignore_case) @@ -964,9 +964,9 @@ class PackageSack(PackageSackBase): if naTup in highdict: return [highdict[naTup]] else: - raise PackageSackError, 'No Package Matching %s.%s' % naTup + raise PackageSackError('No Package Matching %s.%s' % naTup) - return highdict.values() + return list(highdict.values()) def returnNewestByName(self, name=None, patterns=None, ignore_case=False): """return list of newest packages based on name matching @@ -994,11 +994,11 @@ class PackageSack(PackageSackBase): if name in highdict: return highdict[name] else: - raise PackageSackError, 'No Package Matching %s' % name + raise PackageSackError('No Package Matching %s' % name) #this is a list of lists - break it back out into a single list returnlist = [] - for polst in highdict.values(): + for polst in list(highdict.values()): for po in polst: returnlist.append(po) @@ -1013,7 +1013,7 @@ class PackageSack(PackageSackBase): def printPackages(self): for pkg in self.returnPackages(): - print pkg + print(pkg) def excludeArchs(self, archlist): """exclude incompatible arches. archlist is a list of compatible arches""" @@ -1054,7 +1054,7 @@ def packagesNewestByName(pkgs): elif cval == 0: newest[key].append(pkg) ret = [] - for vals in newest.itervalues(): + for vals in list(newest.values()): ret.extend(vals) return ret def packagesNewestByNameArch(pkgs): @@ -1066,7 +1066,7 @@ def packagesNewestByNameArch(pkgs): if key in newest and pkg.verLE(newest[key]): continue newest[key] = pkg - return newest.values() + return list(newest.values()) class ListPackageSack(PackageSack): """Derived class from PackageSack to build new Sack from list of diff --git a/yum/packages.py b/yum/packages.py index 5ef9951..b0cc071 100644 --- a/yum/packages.py +++ b/yum/packages.py @@ -22,8 +22,8 @@ Classes and functions dealing with rpm package representations. import rpm import os import os.path -import misc -import i18n +from . import misc +from . import i18n import re import fnmatch import stat @@ -32,14 +32,14 @@ from subprocess import Popen, PIPE from rpmUtils import RpmUtilsError import rpmUtils.miscutils from rpmUtils.miscutils import flagToString, stringToVersion, compareVerOnly -import Errors +from . import Errors import errno import struct -from constants import * +from .constants import * from operator import itemgetter -import urlparse -urlparse.uses_fragment.append("media") +import urllib.parse +urllib.parse.uses_fragment.append("media") from urlgrabber.grabber import URLGrabber, URLGrabError try: @@ -127,7 +127,7 @@ def parsePackages(pkgs, usercommands, casematch=0, # anything we couldn't find a match for # could mean it's not there, could mean it's a wildcard if misc.re_glob(command): - trylist = pkgdict.keys() + trylist = list(pkgdict.keys()) # command and pkgdict are already lowered if not casematch # so case sensitive is always fine restring = fnmatch.translate(command) @@ -155,11 +155,11 @@ def parsePackages(pkgs, usercommands, casematch=0, for pkg in pkgs: mark = "%s%s" % (pkg.repo.id, pkg.pkgKey) u[mark] = pkg - return u.values() + return list(u.values()) matched = pkgunique(matched) exactmatch = pkgunique(exactmatch) else: - raise ValueError, "Bad value for unique: %s" % unique + raise ValueError("Bad value for unique: %s" % unique) return exactmatch, matched, unmatched class FakeSack: @@ -571,7 +571,7 @@ class RpmBase(object): primary_only=True to limit to those files in the primary repodata""" if primary_only: ret = [] # We only return the types for the primary files. - for ftype in self.files.keys(): + for ftype in list(self.files.keys()): if ftype == 'dir': match = misc.re_primary_dirname else: @@ -586,7 +586,7 @@ class RpmBase(object): ret.append(ftype) return ret - return self.files.keys() + return list(self.files.keys()) def returnPrcoNames(self, prcotype): if not hasattr(self, '_cache_prco_names_' + prcotype): @@ -784,8 +784,8 @@ class YumAvailablePackage(PackageObject, RpmBase): # urljoin sucks in the reverse way that os.path.join sucks :) if base[-1] != '/': base = base + '/' - return urlparse.urljoin(base, self.remote_path) - return urlparse.urljoin(self.repo.urls[0], self.remote_path) + return urllib.parse.urljoin(base, self.remote_path) + return urllib.parse.urljoin(self.repo.urls[0], self.remote_path) size = property(fget=lambda self: self._size()) remote_path = property(_remote_path) @@ -846,7 +846,7 @@ class YumAvailablePackage(PackageObject, RpmBase): def getDiscNum(self): if self.basepath is None: return None - (scheme, netloc, path, query, fragid) = urlparse.urlsplit(self.basepath) + (scheme, netloc, path, query, fragid) = urllib.parse.urlsplit(self.basepath) if scheme == "media": if len(fragid) == 0: return 0 @@ -859,7 +859,7 @@ class YumAvailablePackage(PackageObject, RpmBase): try: hdr = rpmUtils.miscutils.hdrFromPackage(ts, rpmfile) except rpmUtils.RpmUtilsError: - raise Errors.RepoError, 'Package Header %s: RPM Cannot open' % self + raise Errors.RepoError('Package Header %s: RPM Cannot open' % self) return hdr def returnLocalHeader(self): @@ -871,9 +871,9 @@ class YumAvailablePackage(PackageObject, RpmBase): hlist = rpm.readHeaderListFromFile(self.localHdr()) hdr = hlist[0] except (rpm.error, IndexError): - raise Errors.RepoError, 'Package Header %s: Cannot open' % self + raise Errors.RepoError('Package Header %s: Cannot open' % self) else: - raise Errors.RepoError, 'Package Header %s: Not Available' % self + raise Errors.RepoError('Package Header %s: Not Available' % self) return hdr @@ -904,7 +904,7 @@ class YumAvailablePackage(PackageObject, RpmBase): # read+checksum "large" datasets multiple times per. transaction. try: nst = os.stat(self.localPkg()) - except OSError, e: + except OSError as e: return False if (hasattr(self, '_verify_local_pkg_cache') and self._verify_local_pkg_cache): @@ -1182,7 +1182,7 @@ class YumAvailablePackage(PackageObject, RpmBase): if mylist: msg = "\n <rpm:requires>\n" if hasattr(self, '_collapse_libc_requires') and self._collapse_libc_requires: - libc_requires = filter(lambda x: x[0].startswith('libc.so.6'), mylist) + libc_requires = [x for x in mylist if x[0].startswith('libc.so.6')] if libc_requires: rest = sorted(libc_requires, cmp=compareVerOnly, key=itemgetter(0)) best = rest.pop() @@ -1348,21 +1348,21 @@ class YumHeaderPackage(YumAvailablePackage): hdr = self._get_hdr() for tag in tag2prco: name = hdr[getattr(rpm, 'RPMTAG_%sNAME' % tag)] - name = map(misc.share_data, name) + name = list(map(misc.share_data, name)) if not name: # empty or none or whatever, doesn't matter continue lst = hdr[getattr(rpm, 'RPMTAG_%sFLAGS' % tag)] - flag = map(rpmUtils.miscutils.flagToString, lst) - flag = map(misc.share_data, flag) + flag = list(map(rpmUtils.miscutils.flagToString, lst)) + flag = list(map(misc.share_data, flag)) lst = hdr[getattr(rpm, 'RPMTAG_%sVERSION' % tag)] - vers = map(rpmUtils.miscutils.stringToVersion, lst) - vers = map(lambda x: (misc.share_data(x[0]), misc.share_data(x[1]), - misc.share_data(x[2])), vers) + vers = list(map(rpmUtils.miscutils.stringToVersion, lst)) + vers = [(misc.share_data(x[0]), misc.share_data(x[1]), + misc.share_data(x[2])) for x in vers] prcotype = tag2prco[tag] - self.prco[prcotype] = map(misc.share_data, zip(name,flag,vers)) + self.prco[prcotype] = list(map(misc.share_data, list(zip(name,flag,vers)))) def tagByName(self, tag): warnings.warn("tagByName() will go away in a furture version of Yum.\n", @@ -1370,7 +1370,7 @@ class YumHeaderPackage(YumAvailablePackage): try: return getattr(self, tag) except AttributeError: - raise Errors.MiscError, "Unknown header tag %s" % tag + raise Errors.MiscError("Unknown header tag %s" % tag) def __getattr__(self, thing): #FIXME - if an error - return AttributeError, not KeyError @@ -1378,17 +1378,17 @@ class YumHeaderPackage(YumAvailablePackage): if thing.startswith('__') and thing.endswith('__'): # If these existed, then we wouldn't get here ... # So these are missing. - raise AttributeError, "%s has no attribute %s" % (self, thing) + raise AttributeError("%s has no attribute %s" % (self, thing)) try: return self.hdr[thing] except KeyError: # Note above, API break to fix this ... this at least is a nicer # msg. so we know what we accessed that is bad. - raise KeyError, "%s has no attribute %s" % (self, thing) + raise KeyError("%s has no attribute %s" % (self, thing)) except ValueError: # Note above, API break to fix this ... this at least is a nicer # msg. so we know what we accessed that is bad. - raise ValueError, "%s has no attribute %s" % (self, thing) + raise ValueError("%s has no attribute %s" % (self, thing)) def doepoch(self): tmpepoch = self.hdr['epoch'] @@ -1407,7 +1407,7 @@ class YumHeaderPackage(YumAvailablePackage): files = self.hdr['filenames'] fileflags = self.hdr['fileflags'] filemodes = self.hdr['filemodes'] - filetuple = zip(files, filemodes, fileflags) + filetuple = list(zip(files, filemodes, fileflags)) if not self._loadedfiles: for (fn, mode, flag) in filetuple: #garbage checks @@ -1438,9 +1438,9 @@ class YumHeaderPackage(YumAvailablePackage): # then create a _loadChangelog() method to put them into the # self._changelog attr if len(self.hdr['changelogname']) > 0: - return zip(misc.to_unicode(self.hdr['changelogtime'], errors='replace'), + return list(zip(misc.to_unicode(self.hdr['changelogtime'], errors='replace'), misc.to_unicode(self.hdr['changelogname'], errors='replace'), - misc.to_unicode(self.hdr['changelogtext'], errors='replace')) + misc.to_unicode(self.hdr['changelogtext'], errors='replace'))) return [] def returnChecksums(self): @@ -1466,12 +1466,12 @@ class YumHeaderPackage(YumAvailablePackage): """returns requires with pre-require bit""" name = self.hdr[rpm.RPMTAG_REQUIRENAME] lst = self.hdr[rpm.RPMTAG_REQUIREFLAGS] - flag = map(flagToString, lst) - pre = map(self._is_pre_req, lst) + flag = list(map(flagToString, lst)) + pre = list(map(self._is_pre_req, lst)) lst = self.hdr[rpm.RPMTAG_REQUIREVERSION] - vers = map(stringToVersion, lst) + vers = list(map(stringToVersion, lst)) if name is not None: - lst = zip(name, flag, vers, pre) + lst = list(zip(name, flag, vers, pre)) mylist = misc.unique(lst) return mylist @@ -1819,11 +1819,11 @@ class YumInstalledPackage(YumHeaderPackage): my_st_size = my_st.st_size try: my_user = pwd.getpwuid(my_st[stat.ST_UID])[0] - except KeyError, e: + except KeyError as e: my_user = 'uid %s not found' % my_st[stat.ST_UID] try: my_group = grp.getgrgid(my_st[stat.ST_GID])[0] - except KeyError, e: + except KeyError as e: my_group = 'gid %s not found' % my_st[stat.ST_GID] my_ftype = YUMVerifyPackageFile._ftype(my_st.st_mode) @@ -1892,7 +1892,7 @@ class YumInstalledPackage(YumHeaderPackage): my_mode = my_st.st_mode if 'ghost' in ftypes: # This is what rpm does, although it - my_mode &= 0777 # doesn't usually get here. + my_mode &= 0o777 # doesn't usually get here. if check_perms and pf.verify_mode and my_mode != pf.mode: prob = _PkgVerifyProb('mode', 'mode does not match', ftypes) prob.database_value = pf.mode @@ -1964,7 +1964,7 @@ class YumInstalledPackage(YumHeaderPackage): try: os.stat(pf.filename) perms_ok = True # Shouldn't happen - except OSError, e: + except OSError as e: perms_ok = True if e.errno == errno.EACCES: perms_ok = False @@ -1998,8 +1998,7 @@ class YumLocalPackage(YumHeaderPackage): ts = rpmUtils.transaction.initReadOnlyTransaction() if filename is None: - raise Errors.MiscError, \ - 'No Filename specified for YumLocalPackage instance creation' + raise Errors.MiscError('No Filename specified for YumLocalPackage instance creation') self.pkgtype = 'local' self.localpath = filename @@ -2008,9 +2007,8 @@ class YumLocalPackage(YumHeaderPackage): try: hdr = rpmUtils.miscutils.hdrFromPackage(ts, self.localpath) - except RpmUtilsError, e: - raise Errors.MiscError, \ - 'Could not open local rpm file: %s: %s' % (self.localpath, e) + except RpmUtilsError as e: + raise Errors.MiscError('Could not open local rpm file: %s: %s' % (self.localpath, e)) fakerepo = FakeRepository(filename) fakerepo.cost = 0 @@ -2167,6 +2165,6 @@ class YumUrlPackage(YumLocalPackage): if ua is not None: ug.opts.user_agent = ua result = ug.urlgrab(url, local, text=fname) - except URLGrabError, e: + except URLGrabError as e: raise Errors.MiscError("Cannot download %s: %s" % (url, e)) YumLocalPackage.__init__(self, ts, result) diff --git a/yum/parser.py b/yum/parser.py index fccf528..f1debb6 100644 --- a/yum/parser.py +++ b/yum/parser.py @@ -1,10 +1,10 @@ #! /usr/bin/python -tt import re -import urlparse +import urllib.parse import urlgrabber import os.path -import Errors +from . import Errors _KEYCRE = re.compile(r"\$(\w+)") @@ -69,7 +69,7 @@ class ConfigPreProcessor: # first make configfile a url even if it points to # a local file - scheme = urlparse.urlparse(configfile)[0] + scheme = urllib.parse.urlparse(configfile)[0] if scheme == '': # check it to make sure it's not a relative file url if configfile[0] != '/': @@ -86,7 +86,7 @@ class ConfigPreProcessor: # _pushfile will return None if he couldn't open the file fo = self._pushfile( url ) if fo is None: - raise Errors.ConfigError, 'Error accessing file: %s' % url + raise Errors.ConfigError('Error accessing file: %s' % url) def readline( self, size=0 ): """ @@ -127,8 +127,7 @@ class ConfigPreProcessor: if m: url = m.group('url') if len(url) == 0: - raise Errors.ConfigError, \ - 'Error parsing config %s: include must specify file to include.' % (self.name) + raise Errors.ConfigError('Error parsing config %s: include must specify file to include.' % (self.name)) else: # whooohoo a valid include line.. push it on the stack fo = self._pushfile( url ) @@ -168,7 +167,7 @@ class ConfigPreProcessor: # it's the initial config file. No base url to resolve against. return url else: - return urlparse.urljoin( self.geturl(), url ) + return urllib.parse.urljoin( self.geturl(), url ) def _pushfile( self, url ): """ @@ -190,15 +189,14 @@ class ConfigPreProcessor: return None try: fo = urlgrabber.grabber.urlopen(absurl) - except urlgrabber.grabber.URLGrabError, e: + except urlgrabber.grabber.URLGrabError as e: fo = None if fo is not None: self.name = absurl self._incstack.append( fo ) self._alreadyincluded.append(includetuple) else: - raise Errors.ConfigError, \ - 'Error accessing file for config %s' % (absurl) + raise Errors.ConfigError('Error accessing file for config %s' % (absurl)) return fo diff --git a/yum/pgpmsg.py b/yum/pgpmsg.py index ee825c6..3afef24 100644 --- a/yum/pgpmsg.py +++ b/yum/pgpmsg.py @@ -14,7 +14,7 @@ ##You should have received a copy of the GNU General Public License ##along with this program; if not, write to the Free Software ##Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -import struct, time, cStringIO, base64, types +import struct, time, io, base64, types # We use this so that we can work on python-2.4 and python-2.6, and thus. # use import md5/import sha on the older one and import hashlib on the newer. @@ -38,7 +38,7 @@ except ImportError: return md5.new() if algo == 'sha1': return sha.new() - raise ValueError, "Bad checksum type" + raise ValueError("Bad checksum type") debug = None @@ -316,10 +316,10 @@ def get_whole_number(msg, idx, numlen) : extracts a "whole number" field of length numlen from msg at index idx returns (<whole number>, new_idx) where the whole number is a long integer and new_idx is the index of the next element in the message""" - n = 0L + n = 0 while numlen > 0 : b = (struct.unpack("B", msg[idx:idx+1]))[0] - n = n * 256L + long(b) + n = n * 256 + int(b) idx = idx + 1 numlen = numlen - 1 return (n, idx) @@ -385,7 +385,7 @@ the index of the next element in the message""" return (l[1], l[2]) def str_to_hex(s) : - return ''.join(map(lambda x : hex(ord(x))[2:].zfill(2), list(s))) + return ''.join([hex(ord(x))[2:].zfill(2) for x in list(s)]) def duration_to_str(s) : if s == 0 : @@ -402,7 +402,7 @@ def duration_to_str(s) : def map_to_str(m, vals) : slist = [] # change to a list if it's a single value - if type(vals) != types.ListType and type(vals) != types.TupleType : + if type(vals) != list and type(vals) != tuple : vals = list((vals,)) for i in vals : if i in m : @@ -454,7 +454,7 @@ class public_key(pgp_packet) : def key_id(self) : if self.version == 3 : - return pack_long(self.pk_rsa_mod & 0xffffffffffffffffL) + return pack_long(self.pk_rsa_mod & 0xffffffffffffffff) elif self.version == 4 : return self.fingerprint()[-8:] @@ -511,7 +511,7 @@ class public_key(pgp_packet) : raise RuntimeError("unknown public key algorithm %d at %d" % (self.pk_algo, idx_save)) def __str__(self) : - sio = cStringIO.StringIO() + sio = io.StringIO() sio.write(pgp_packet.__str__(self) + "\n") sio.write("version: " + str(self.version) + "\n") sio.write("timestamp: " + time.ctime(self.timestamp) + "\n") @@ -626,7 +626,7 @@ class signature(pgp_packet) : idx = idx + sublen - 1 return (subtype, expr), idx if subtype == SIG_SUB_TYPE_PREF_SYMM_ALGO or subtype == SIG_SUB_TYPE_PREF_HASH_ALGO or subtype == SIG_SUB_TYPE_PREF_COMP_ALGO or subtype == SIG_SUB_TYPE_KEY_FLAGS : - algo_list = map(lambda x : ord(x), list(msg[idx:idx+sublen-1])) + algo_list = [ord(x) for x in list(msg[idx:idx+sublen-1])] idx = idx + sublen - 1 return (subtype, algo_list), idx if subtype == SIG_SUB_TYPE_REVOKE_KEY : # revocation key @@ -846,7 +846,7 @@ class signature(pgp_packet) : return idx def __str__(self) : - sio = cStringIO.StringIO() + sio = io.StringIO() sio.write(pgp_packet.__str__(self) + "\n") sio.write("version: " + str(self.version) + "\n") sio.write("type: " + sig_type_to_str[self.sig_type] + "\n") @@ -885,7 +885,7 @@ class pgp_certificate(object): self.primary_user_id = -1 # index of the primary user id def __str__(self) : - sio = cStringIO.StringIO() + sio = io.StringIO() sio.write("PGP Public Key Certificate v%d\n" % self.version) sio.write("Cert ID: %s\n" % str_to_hex(self.public_key.key_id())) sio.write("Primary ID: %s\n" % self.user_id) @@ -1136,9 +1136,9 @@ in the message""" plen, idx = get_whole_int(msg, idx, 4) return b & CTB_PKT_MASK, plen, idx else : - raise Exception, 'partial message bodies are not supported by this version (%d)', b + raise Exception('partial message bodies are not supported by this version (%d)').with_traceback(b) else : - raise Exception, "unknown (not \"normal\") cypher type bit %d at byte %d" % (b, idx) + raise Exception("unknown (not \"normal\") cypher type bit %d at byte %d" % (b, idx)) def crc24(msg) : crc24_init = 0xb704ce @@ -1198,13 +1198,13 @@ a PGP "certificate" includes a public key, user id(s), and signature. """ # first we'll break the block up into lines and trim each line of any # carriage return chars - pgpkey_lines = map(lambda x : x.rstrip(), msg.split('\n')) + pgpkey_lines = [x.rstrip() for x in msg.split('\n')] # check out block in_block = 0 in_data = 0 - block_buf = cStringIO.StringIO() + block_buf = io.StringIO() for l in pgpkey_lines : if not in_block : if l == '-----BEGIN PGP PUBLIC KEY BLOCK-----' : @@ -1230,7 +1230,7 @@ a PGP "certificate" includes a public key, user id(s), and signature. # check the checksum if csum != crc24(cert_msg) : - raise Exception, 'bad checksum on pgp message' + raise Exception('bad checksum on pgp message') # ok, the sum looks ok so we'll actually decode the thing pkt_list = decode(cert_msg) @@ -1260,7 +1260,7 @@ def decode_multiple_keys(msg): #ditto of above - but handling multiple certs/keys per file certs = [] - pgpkey_lines = map(lambda x : x.rstrip(), msg.split('\n')) + pgpkey_lines = [x.rstrip() for x in msg.split('\n')] in_block = 0 block = '' for l in pgpkey_lines : @@ -1284,4 +1284,4 @@ def decode_multiple_keys(msg): if __name__ == '__main__' : import sys for pgp_cert in decode_msg(open(sys.argv[1]).read()) : - print pgp_cert + print(pgp_cert) diff --git a/yum/pkgtag_db.py b/yum/pkgtag_db.py index afcc28d..1172717 100644 --- a/yum/pkgtag_db.py +++ b/yum/pkgtag_db.py @@ -17,26 +17,26 @@ # parse sqlite tag database # return pkgnames and tag that was matched -from sqlutils import sqlite, executeSQL, sql_esc -from Errors import PkgTagsError -import sqlutils +from .sqlutils import sqlite, executeSQL, sql_esc +from .Errors import PkgTagsError +from . import sqlutils import sys -import misc +from . import misc def catchSqliteException(func): """This decorator converts sqlite exceptions into PkgTagsError""" def newFunc(*args, **kwargs): try: return func(*args, **kwargs) - except sqlutils.sqlite.Error, e: + except sqlutils.sqlite.Error as e: # 2.4.x requires this, but 2.6.x complains about even hasattr() # of e.message ... *sigh* if sys.hexversion < 0x02050000: if hasattr(e,'message'): - raise PkgTagsError, str(e.message) + raise PkgTagsError(str(e.message)) else: - raise PkgTagsError, str(e) - raise PkgTagsError, str(e) + raise PkgTagsError(str(e)) + raise PkgTagsError(str(e)) newFunc.__name__ = func.__name__ newFunc.__doc__ = func.__doc__ @@ -105,7 +105,7 @@ class PackageTags(object): def add(self, repoid, sqlite_file): if repoid in self.db_objs: - raise PkgTagsError, "Already added tags from %s" % repoid + raise PkgTagsError("Already added tags from %s" % repoid) dbobj = PackageTagDB(repoid, sqlite_file) self.db_objs[repoid] = dbobj @@ -114,30 +114,30 @@ class PackageTags(object): if repoid in self.db_objs: del self.db_objs[repoid] else: - raise PkgTagsError, "No tag db for %s" % repoid + raise PkgTagsError("No tag db for %s" % repoid) def search_names(self, name): res = {} - for ptd in self.db_objs.values(): - for (name, taglist) in ptd.search_names(name).items(): + for ptd in list(self.db_objs.values()): + for (name, taglist) in list(ptd.search_names(name).items()): if not name in res: res[name] = [] res[name].extend(taglist) out = {} - for (name, taglist) in res.items(): + for (name, taglist) in list(res.items()): out[name] = misc.unique(taglist) return out def search_tags(self, tagname): res = {} - for ptd in self.db_objs.values(): - for (name, taglist) in ptd.search_tags(tagname).items(): + for ptd in list(self.db_objs.values()): + for (name, taglist) in list(ptd.search_tags(tagname).items()): if not name in res: res[name] = [] res[name].extend(taglist) out = {} - for (name, taglist) in res.items(): + for (name, taglist) in list(res.items()): out[name] = misc.unique(taglist) return out diff --git a/yum/plugins.py b/yum/plugins.py index bfc49b7..1f4bb39 100644 --- a/yum/plugins.py +++ b/yum/plugins.py @@ -21,12 +21,12 @@ import warnings import atexit import gettext import logging -import logginglevels -from constants import * -import config -from config import ParsingError, ConfigParser -import Errors -from parser import ConfigPreProcessor +from . import logginglevels +from .constants import * +from . import config +from .config import ParsingError, ConfigParser +from . import Errors +from .parser import ConfigPreProcessor from textwrap import fill import fnmatch @@ -350,7 +350,7 @@ class YumPlugins: confpp_obj = ConfigPreProcessor(conffilename) try: parser.readfp(confpp_obj) - except ParsingError, e: + except ParsingError as e: raise Errors.ConfigError("Couldn't parse %s: %s" % (conffilename, str(e))) return parser diff --git a/yum/repoMDObject.py b/yum/repoMDObject.py index 31b1080..a1d5919 100755 --- a/yum/repoMDObject.py +++ b/yum/repoMDObject.py @@ -15,11 +15,11 @@ # Copyright 2006 Duke University from yum.misc import cElementTree_iterparse as iterparse -from Errors import RepoMDError +from .Errors import RepoMDError import sys import types -from misc import AutoFileChecksums, to_xml +from .misc import AutoFileChecksums, to_xml def ns_cleanup(qn): if qn.find('}') == -1: return qn @@ -124,12 +124,12 @@ class RepoMD: self.parse(srcfile) def parse(self, srcfile): - if type(srcfile) in types.StringTypes: + if type(srcfile) in (str,): # srcfile is a filename string try: infile = open(srcfile, 'rt') except IOError: - raise RepoMDError, "Unable to open %s" %(srcfile,) + raise RepoMDError("Unable to open %s" %(srcfile,)) else: # srcfile is a file object infile = srcfile @@ -166,47 +166,47 @@ class RepoMD: self.checksums = infile.checksums.hexdigests() self.length = len(infile.checksums) - except SyntaxError, e: - raise RepoMDError, "Damaged repomd.xml file" + except SyntaxError as e: + raise RepoMDError("Damaged repomd.xml file") def fileTypes(self): """return list of metadata file types available""" - return self.repoData.keys() + return list(self.repoData.keys()) def getData(self, type): if type in self.repoData: return self.repoData[type] else: - raise RepoMDError, "requested datatype %s not available" % type + raise RepoMDError("requested datatype %s not available" % type) def dump(self): """dump fun output""" - print "file timestamp: %s" % self.timestamp - print "file length : %s" % self.length + print("file timestamp: %s" % self.timestamp) + print("file length : %s" % self.length) for csum in sorted(self.checksums): - print "file checksum : %s/%s" % (csum, self.checksums[csum]) + print("file checksum : %s/%s" % (csum, self.checksums[csum])) if self.revision is not None: - print 'revision: %s' % self.revision + print('revision: %s' % self.revision) if self.tags['content']: - print 'tags content: %s' % ", ".join(sorted(self.tags['content'])) + print('tags content: %s' % ", ".join(sorted(self.tags['content']))) if self.tags['distro']: for distro in sorted(self.tags['distro']): - print 'tags distro: %s' % distro + print('tags distro: %s' % distro) tags = self.tags['distro'][distro] - print ' tags: %s' % ", ".join(sorted(tags)) - print '\n---- Data ----' + print(' tags: %s' % ", ".join(sorted(tags))) + print('\n---- Data ----') for ft in sorted(self.fileTypes()): thisdata = self.repoData[ft] - print ' datatype: %s' % thisdata.type - print ' location : %s %s' % thisdata.location - print ' timestamp : %s' % thisdata.timestamp - print ' size : %s' % thisdata.size - print ' open size : %s' % thisdata.opensize - print ' checksum : %s - %s' % thisdata.checksum - print ' open checksum: %s - %s' % thisdata.openchecksum - print ' dbversion : %s' % thisdata.dbversion - print '' + print(' datatype: %s' % thisdata.type) + print(' location : %s %s' % thisdata.location) + print(' timestamp : %s' % thisdata.timestamp) + print(' size : %s' % thisdata.size) + print(' open size : %s' % thisdata.opensize) + print(' checksum : %s - %s' % thisdata.checksum) + print(' open checksum: %s - %s' % thisdata.openchecksum) + print(' dbversion : %s' % thisdata.dbversion) + print('') def dump_xml(self): msg = "" @@ -236,7 +236,7 @@ class RepoMD: tags += """ </tags>\n""" msg += tags - for md in self.repoData.values(): + for md in list(self.repoData.values()): msg += md.dump_xml() msg += """</repomd>\n""" @@ -246,12 +246,12 @@ class RepoMD: def main(): try: - print "file : %s" % sys.argv[1] + print("file : %s" % sys.argv[1]) p = RepoMD('repoid', sys.argv[1]) p.dump() except IOError: - print >> sys.stderr, "newcomps.py: No such file:\'%s\'" % sys.argv[1] + print("newcomps.py: No such file:\'%s\'" % sys.argv[1], file=sys.stderr) sys.exit(1) if __name__ == '__main__': diff --git a/yum/repos.py b/yum/repos.py index 3793bad..d0db82c 100644 --- a/yum/repos.py +++ b/yum/repos.py @@ -18,10 +18,10 @@ import re import fnmatch import types import logging -import misc +from . import misc -import Errors -from packageSack import MetaSack +from . import Errors +from .packageSack import MetaSack from weakref import proxy as weakref @@ -92,18 +92,18 @@ class RepoStorage: self.ayum.plugins.run('postreposetup') def __str__(self): - return str(self.repos.keys()) + return str(list(self.repos.keys())) def __del__(self): self.close() def close(self): - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.close() def add(self, repoobj): if repoobj.id in self.repos: - raise Errors.DuplicateRepoError, 'Repository %s is listed more than once in the configuration' % (repoobj.id) + raise Errors.DuplicateRepoError('Repository %s is listed more than once in the configuration' % (repoobj.id)) self.repos[repoobj.id] = repoobj if hasattr(repoobj, 'quick_enable_disable'): self.quick_enable_disable.update(repoobj.quick_enable_disable) @@ -124,16 +124,15 @@ class RepoStorage: del self.repos[repoid] def sort(self): - repolist = self.repos.values() + repolist = list(self.repos.values()) repolist.sort() return repolist def getRepo(self, repoid): try: return self.repos[repoid] - except KeyError, e: - raise Errors.RepoError, \ - 'Error getting repository data for %s, repository not found' % (repoid) + except KeyError as e: + raise Errors.RepoError('Error getting repository data for %s, repository not found' % (repoid)) def findRepos(self,pattern): """find all repositories matching fnmatch `pattern`""" @@ -143,7 +142,7 @@ class RepoStorage: for item in pattern.split(','): item = item.strip() match = re.compile(fnmatch.translate(item)).match - for name,repo in self.repos.items(): + for name,repo in list(self.repos.items()): if match(name): result.append(repo) return result @@ -192,7 +191,7 @@ class RepoStorage: return self._cache_enabled_repos returnlist = [] - for repo in self.repos.values(): + for repo in list(self.repos.values()): if repo.isEnabled(): returnlist.append(repo) @@ -215,14 +214,14 @@ class RepoStorage: def setCache(self, cacheval): """sets cache value in all repos""" self.cache = cacheval - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.cache = cacheval def setCacheDir(self, cachedir): """sets the cachedir value in all repos""" self._cachedir = cachedir - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.old_base_cache_dir = repo.basecachedir repo.basecachedir = cachedir @@ -230,23 +229,23 @@ class RepoStorage: def setProgressBar(self, obj): """sets the progress bar for downloading files from repos""" - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.setCallback(obj) def setFailureCallback(self, obj): """sets the failure callback for all repos""" - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.setFailureObj(obj) def setMirrorFailureCallback(self, obj): """sets the failure callback for all mirrors""" - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.setMirrorFailureObj(obj) def setInterruptCallback(self, callback): - for repo in self.repos.values(): + for repo in list(self.repos.values()): repo.setInterruptCallback(callback) def getPackageSack(self): @@ -270,16 +269,16 @@ class RepoStorage: if which == 'enabled': myrepos = self.listEnabled() elif which == 'all': - myrepos = self.repos.values() + myrepos = list(self.repos.values()) else: - if type(which) == types.ListType: + if type(which) == list: for repo in which: if isinstance(repo, Repository): myrepos.append(repo) else: repobj = self.getRepo(repo) myrepos.append(repobj) - elif type(which) == types.StringType: + elif type(which) == bytes: repobj = self.getRepo(which) myrepos.append(repobj) @@ -292,7 +291,7 @@ class RepoStorage: sack = repo.getPackageSack() try: sack.populate(repo, mdtype, callback, cacheonly) - except Errors.RepoError, e: + except Errors.RepoError as e: if mdtype in ['all', 'metadata'] and repo.skip_if_unavailable: self.disableRepo(repo.id) else: diff --git a/yum/rpmsack.py b/yum/rpmsack.py index e289a7a..d2635c4 100644 --- a/yum/rpmsack.py +++ b/yum/rpmsack.py @@ -23,24 +23,24 @@ import os.path from rpmUtils import miscutils from rpmUtils import arch from rpmUtils.transaction import initReadOnlyTransaction -import misc -import Errors -from packages import YumInstalledPackage, parsePackages -from packageSack import PackageSackBase, PackageSackVersion +from . import misc +from . import Errors +from .packages import YumInstalledPackage, parsePackages +from .packageSack import PackageSackBase, PackageSackVersion # For returnPackages(patterns=) import fnmatch import re from yum.i18n import to_unicode, _ -import constants +from . import constants import yum.depsolve def _open_no_umask(*args): """ Annoying people like to set umask's for root, which screws everything up for user readable stuff. """ - oumask = os.umask(022) + oumask = os.umask(0o22) try: ret = open(*args) finally: @@ -52,7 +52,7 @@ def _iopen(*args): """ IOError wrapper BS for open, stupid exceptions. """ try: ret = open(*args) - except IOError, e: + except IOError as e: return None, e return ret, None @@ -77,15 +77,15 @@ class RPMInstalledPackage(YumInstalledPackage): ts = self.rpmdb.readOnlyTS() mi = ts.dbMatch(0, self.idx) try: - return mi.next() + return next(mi) except StopIteration: - raise Errors.PackageSackError, 'Rpmdb changed underneath us' + raise Errors.PackageSackError('Rpmdb changed underneath us') def __getattr__(self, varname): # If these existed, then we wouldn't get here... # Prevent access of __foo__, _cached_foo etc from loading the header if varname.startswith('_'): - raise AttributeError, "%s has no attribute %s" % (self, varname) + raise AttributeError("%s has no attribute %s" % (self, varname)) if varname != 'hdr': # Don't cache the hdr, unless explicitly requested # Note that we don't even cache the .blah value, but looking up the @@ -252,7 +252,7 @@ class RPMDBPackageSack(PackageSackBase): if not self._simple_pkgtup_list: csumpkgtups = self.preloadPackageChecksums(load_packages=False) if csumpkgtups is not None: - self._simple_pkgtup_list = csumpkgtups.keys() + self._simple_pkgtup_list = list(csumpkgtups.keys()) if not self._simple_pkgtup_list: for (hdr, mi) in self._get_packages(): @@ -424,7 +424,7 @@ class RPMDBPackageSack(PackageSackBase): for pkg in fileresults: result.setdefault(pkg.pkgid, pkg) - return result.values() + return list(result.values()) def searchFiles(self, name): """search the filelists in the rpms for anything matching name""" @@ -440,7 +440,7 @@ class RPMDBPackageSack(PackageSackBase): pkg = self._makePackageObject(hdr, idx) result.setdefault(pkg.pkgid, pkg) - return result.values() + return list(result.values()) def searchPrco(self, name, prcotype): @@ -469,7 +469,7 @@ class RPMDBPackageSack(PackageSackBase): for pkg in fileresults: result[pkg.pkgid] = pkg - result = result.values() + result = list(result.values()) self._cache[prcotype][name] = result return result @@ -507,7 +507,7 @@ class RPMDBPackageSack(PackageSackBase): allpkg = self._search(name=name, arch=arch) if not allpkg: - raise Errors.PackageSackError, 'No Package Matching %s' % name + raise Errors.PackageSackError('No Package Matching %s' % name) return [ po.pkgtup for po in misc.newestInList(allpkg) ] @@ -518,7 +518,7 @@ class RPMDBPackageSack(PackageSackBase): allpkgs = self._search(name=name) if not allpkgs: - raise Errors.PackageSackError, 'No Package Matching %s' % name + raise Errors.PackageSackError('No Package Matching %s' % name) return misc.newestInList(allpkgs) @@ -618,7 +618,7 @@ class RPMDBPackageSack(PackageSackBase): self._makePackageObject(hdr, idx) self._completely_loaded = patterns is None - pkgobjlist = self._idx2pkg.values() + pkgobjlist = list(self._idx2pkg.values()) # Remove gpg-pubkeys, as no sane callers expects/likes them... if self._loaded_gpg_keys: pkgobjlist = [pkg for pkg in pkgobjlist if pkg.name != 'gpg-pubkey'] @@ -658,7 +658,7 @@ class RPMDBPackageSack(PackageSackBase): po.conflicts po._has_hdr = False del po.hdr - self._cached_conflicts_data = result.values() + self._cached_conflicts_data = list(result.values()) return self._cached_conflicts_data @@ -699,7 +699,7 @@ class RPMDBPackageSack(PackageSackBase): # . Always throw - but at least it shouldn't happen again. # if __debug__: - raise Errors.PackageSackError, 'Rpmdb checksum is invalid: %s' % caller + raise Errors.PackageSackError('Rpmdb checksum is invalid: %s' % caller) def _read_conflicts(self): if not self.__cache_rpmdb__: @@ -877,7 +877,7 @@ class RPMDBPackageSack(PackageSackBase): installedUnresolvedFileRequires.add(name) fileRequires = set() - for fnames in installedFileRequires.itervalues(): + for fnames in list(installedFileRequires.values()): fileRequires.update(fnames) installedFileProviders = {} for fname in fileRequires: @@ -1089,7 +1089,7 @@ class RPMDBPackageSack(PackageSackBase): try: os.makedirs(self._cachedir) - except (IOError, OSError), e: + except (IOError, OSError) as e: return fo = _open_no_umask(rpmdbvfname + ".tmp", "w") @@ -1167,7 +1167,7 @@ class RPMDBPackageSack(PackageSackBase): def searchPrimaryFieldsMultipleStrings(self, fields, searchstrings, lowered=False): if not lowered: - searchstrings = map(lambda x: x.lower(), searchstrings) + searchstrings = [x.lower() for x in searchstrings] ret = [] for hdr, idx in self._get_packages(): n = self._find_search_fields(fields, searchstrings, hdr) @@ -1364,10 +1364,10 @@ class RPMDBPackageSack(PackageSackBase): if flags == 0: flags = None - if type(version) is types.StringType: + if type(version) is bytes: (r_e, r_v, r_r) = miscutils.stringToVersion(version) # would this ever be a ListType? - elif type(version) in (types.TupleType, types.ListType): + elif type(version) in (tuple, list): (r_e, r_v, r_r) = version else: # FIXME: This isn't always type(version) is types.NoneType: @@ -1563,7 +1563,7 @@ class RPMDBAdditionalData(object): if not os.path.exists(self.conf.db_path): try: os.makedirs(self.conf.db_path) - except (IOError, OSError), e: + except (IOError, OSError) as e: # some sort of useful thing here? A warning? return self.conf.writable = True @@ -1599,7 +1599,7 @@ class RPMDBAdditionalData(object): elif pkgtup and pkgid: thisdir = self._get_dir_name(pkgtup, pkgid) else: - raise ValueError,"Pass something to RPMDBAdditionalData.get_package" + raise ValueError("Pass something to RPMDBAdditionalData.get_package") return RPMDBAdditionalDataPackage(self.conf, thisdir, yumdb_cache=self.yumdb_cache) @@ -1689,7 +1689,7 @@ class RPMDBAdditionalDataPackage(object): assert self._yumdb_cache['attr'][value][2] try: - lfn = iter(self._yumdb_cache['attr'][value][2]).next() + lfn = next(iter(self._yumdb_cache['attr'][value][2])) misc.unlink_f(fn + '.tmp') os.link(lfn, fn + '.tmp') os.rename(fn + '.tmp', fn) @@ -1716,7 +1716,7 @@ class RPMDBAdditionalDataPackage(object): fn = self._attr2fn(attr) if attr.endswith('.tmp'): - raise AttributeError, "Cannot set attribute %s on %s" % (attr, self) + raise AttributeError("Cannot set attribute %s on %s" % (attr, self)) # These two are special, as they have an index and are used as our # cache-breaker. @@ -1733,8 +1733,8 @@ class RPMDBAdditionalDataPackage(object): fo = _open_no_umask(fn + '.tmp', 'w') try: fo.write(value) - except (OSError, IOError), e: - raise AttributeError, "Cannot set attribute %s on %s" % (attr, self) + except (OSError, IOError) as e: + raise AttributeError("Cannot set attribute %s on %s" % (attr, self)) fo.flush() fo.close() @@ -1751,11 +1751,11 @@ class RPMDBAdditionalDataPackage(object): fn = self._attr2fn(attr) if attr.endswith('.tmp'): - raise AttributeError, "%s has no attribute %s" % (self, attr) + raise AttributeError("%s has no attribute %s" % (self, attr)) info = misc.stat_f(fn) if info is None: - raise AttributeError, "%s has no attribute %s" % (self, attr) + raise AttributeError("%s has no attribute %s" % (self, attr)) if info.st_nlink > 1 and self._yumdb_cache is not None: key = (info.st_dev, info.st_ino) @@ -1788,7 +1788,7 @@ class RPMDBAdditionalDataPackage(object): try: os.unlink(fn) except (IOError, OSError): - raise AttributeError, "Cannot delete attribute %s on %s " % (attr, self) + raise AttributeError("Cannot delete attribute %s on %s " % (attr, self)) def __getattr__(self, attr): return self._read(attr) @@ -1847,7 +1847,7 @@ class RPMDBAdditionalDataPackage(object): def main(): sack = RPMDBPackageSack('/') for p in sack.simplePkgList(): - print p + print(p) if __name__ == '__main__': main() diff --git a/yum/rpmtrans.py b/yum/rpmtrans.py index 9b265f9..8a3e9e9 100644 --- a/yum/rpmtrans.py +++ b/yum/rpmtrans.py @@ -26,7 +26,7 @@ import sys from yum.constants import * from yum import _ from yum.transactioninfo import TransactionMember -import misc +from . import misc import tempfile class NoOutputCallBack: @@ -109,7 +109,7 @@ class RPMBaseCallback: def errorlog(self, msg): # FIXME this should probably dump to the filelog, too - print >> sys.stderr, msg + print(msg, file=sys.stderr) def filelog(self, package, action): # If the action is not in the fileaction list then dump it as a string @@ -132,13 +132,13 @@ class SimpleCliCallBack(RPMBaseCallback): msg = '%s: %s %s/%s [%s/%s]' % (self.action[action], package, te_current, te_total, ts_current, ts_total) if msg != self.lastmsg: - print msg + print(msg) self.lastmsg = msg self.lastpackage = package def scriptout(self, package, msgs): if msgs: - print msgs, + print(msgs, end=' ') # This is ugly, but atm. rpm can go insane and run the "cleanup" phase # without the "install" phase if it gets an exception in it's callback. The @@ -267,7 +267,7 @@ class RPMTransaction: # if this is not one, somebody screwed up assert len(txmbrs) == 1 return (txmbrs[0].name, txmbrs[0]) - elif isinstance(cbkey, basestring): + elif isinstance(cbkey, str): ret = None # If we don't have a tuple, it's because this is an erase txmbr and # rpm doesn't provide one in that case. So we can "cheat" and look @@ -313,7 +313,7 @@ class RPMTransaction: try: self._ts_done = open(ts_done_fn, 'w') - except (IOError, OSError), e: + except (IOError, OSError) as e: self.display.errorlog('could not open ts_done file: %s' % e) self._ts_done = None return False @@ -328,7 +328,7 @@ class RPMTransaction: try: self._ts_done.write(msg) self._ts_done.flush() - except (IOError, OSError), e: + except (IOError, OSError) as e: # Having incomplete transactions is probably worse than having # nothing. self.display.errorlog('could not write to ts_done file: %s' % e) @@ -363,7 +363,7 @@ class RPMTransaction: self.display.filelog(package, msg) # check the pkg name out to make sure it matches - if type(package) in types.StringTypes: + if type(package) in (str,): name = package else: name = package.name @@ -413,7 +413,7 @@ class RPMTransaction: if not os.path.exists(os.path.dirname(tsfn)): os.makedirs(os.path.dirname(tsfn)) # make the dir, fo = open(tsfn, 'w') - except (IOError, OSError), e: + except (IOError, OSError) as e: self.display.errorlog('could not open ts_all file: %s' % e) self._ts_done = None return @@ -424,7 +424,7 @@ class RPMTransaction: fo.write(msg) fo.flush() fo.close() - except (IOError, OSError), e: + except (IOError, OSError) as e: # Having incomplete transactions is probably worse than having # nothing. self.display.errorlog('could not write to ts_all file: %s' % e) @@ -485,7 +485,7 @@ class RPMTransaction: rpmloc = txmbr.po.localPkg() try: self.fd = file(rpmloc) - except IOError, e: + except IOError as e: self.display.errorlog("Error: Cannot open file %s: %s" % (rpmloc, e)) else: if self.trans_running: diff --git a/yum/sqlitesack.py b/yum/sqlitesack.py index 8a6f6f3..3039381 100644 --- a/yum/sqlitesack.py +++ b/yum/sqlitesack.py @@ -23,15 +23,15 @@ import os import os.path import fnmatch -import yumRepo -from packages import PackageObject, RpmBase, YumAvailablePackage, parsePackages -import Errors -import misc +from . import yumRepo +from .packages import PackageObject, RpmBase, YumAvailablePackage, parsePackages +from . import Errors +from . import misc -from sqlutils import executeSQL, sql_esc, sql_esc_glob +from .sqlutils import executeSQL, sql_esc, sql_esc_glob import rpmUtils.miscutils -import sqlutils -import constants +from . import sqlutils +from . import constants import operator from yum.misc import seq_max_split from yum.i18n import to_utf8, to_unicode @@ -44,15 +44,15 @@ def catchSqliteException(func): def newFunc(*args, **kwargs): try: return func(*args, **kwargs) - except sqlutils.sqlite.Error, e: + except sqlutils.sqlite.Error as e: # 2.4.x requires this, but 2.6.x complains about even hasattr() # of e.message ... *sigh* if sys.hexversion < 0x02050000: if hasattr(e,'message'): - raise Errors.RepoError, str(e.message) + raise Errors.RepoError(str(e.message)) else: - raise Errors.RepoError, str(e) - raise Errors.RepoError, str(e) + raise Errors.RepoError(str(e)) + raise Errors.RepoError(str(e)) newFunc.__name__ = func.__name__ newFunc.__doc__ = func.__doc__ @@ -257,17 +257,17 @@ class YumAvailablePackageSqlite(YumAvailablePackage, PackageObject, RpmBase): # If these existed, then we wouldn't get here ... and nothing in the DB # starts and ends with __'s. So these are missing. if varname.startswith('__') and varname.endswith('__'): - raise AttributeError, varname + raise AttributeError(varname) dbname = db2simplemap.get(varname, varname) try: r = self._sql_MD('primary', "SELECT %s FROM packages WHERE pkgId = ?" % dbname, (self.pkgId,)).fetchone() - except Errors.RepoError, e: + except Errors.RepoError as e: if str(e).startswith('no such column'): #FIXME - after API break make this an AttributeError Raise - raise KeyError, str(e) + raise KeyError(str(e)) raise value = r[0] if varname == 'epoch' and value is None: @@ -356,7 +356,7 @@ class YumAvailablePackageSqlite(YumAvailablePackage, PackageObject, RpmBase): if primary_only and not self._loadedfiles: sql = "SELECT name as fname FROM files WHERE pkgKey = ? and type = ?" cur = self._sql_MD('primary', sql, (self.pkgKey, ftype)) - return map(lambda x: x['fname'], cur) + return [x['fname'] for x in cur] self._loadFiles() return RpmBase.returnFileEntries(self,ftype,primary_only) @@ -367,7 +367,7 @@ class YumAvailablePackageSqlite(YumAvailablePackage, PackageObject, RpmBase): if primary_only and not self._loadedfiles: sql = "SELECT DISTINCT type as ftype FROM files WHERE pkgKey = ?" cur = self._sql_MD('primary', sql, (self.pkgKey,)) - return map(lambda x: x['ftype'], cur) + return [x['ftype'] for x in cur] self._loadFiles() return RpmBase.returnFileTypes(self) @@ -378,7 +378,7 @@ class YumAvailablePackageSqlite(YumAvailablePackage, PackageObject, RpmBase): Errors.YumDeprecationWarning, stacklevel=2) sql = "SELECT name as fname FROM files WHERE pkgKey = ? and type = ?" cur = self._sql_MD('primary', sql, (self.pkgKey, ftype)) - return map(lambda x: x['fname'], cur) + return [x['fname'] for x in cur] def returnPrco(self, prcotype, printable=False): prcotype = _share_data(prcotype) @@ -464,7 +464,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): assert hasattr(self, 'pkgobjlist') if self._pkgobjlist_dirty: - pol = filter(lambda x: not self._pkgExcluded(x), self.pkgobjlist) + pol = [x for x in self.pkgobjlist if not self._pkgExcluded(x)] self.pkgobjlist = pol self._pkgobjlist_dirty = False @@ -473,7 +473,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): def __len__(self): # First check if everything is excluded all_excluded = True - for (repo, cache) in self.primarydb.items(): + for (repo, cache) in list(self.primarydb.items()): if repo not in self._all_excludes: all_excluded = False break @@ -515,9 +515,9 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): def close(self): self.dropCachedData() - for dataobj in self.primarydb.values() + \ - self.filelistsdb.values() + \ - self.otherdb.values(): + for dataobj in list(self.primarydb.values()) + \ + list(self.filelistsdb.values()) + \ + list(self.otherdb.values()): dataobj.close() self.primarydb = {} self.filelistsdb = {} @@ -549,7 +549,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): po = self._key2pkg[repo].pop(pkgKey, None) if po is not None: # Will also be in the pkgtup2pkgs cache... pos = self._pkgtup2pkgs[po.pkgtup] - pos = filter(lambda x: id(x) == id(po), pos) + pos = [x for x in pos if id(x) == id(po)] self._pkgtup2pkgs[po.pkgtup] = pos # Remove a package @@ -729,7 +729,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): data = self._sql_MD('primary', repo, sql, (pkgKey,)).fetchone() if data is None: msg = "pkgKey %s doesn't exist in repo %s" % (pkgKey, repo) - raise Errors.RepoError, msg + raise Errors.RepoError(msg) if exclude and self._pkgExcludedRKD(repo, pkgKey, data): return None po = self.pc(repo, data) @@ -798,7 +798,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): self.excludes[repo] = {} if dataobj is None: - raise Errors.RepoError, "Tried to add None %s to %s" % (datatype, repo) + raise Errors.RepoError("Tried to add None %s to %s" % (datatype, repo)) if datatype == 'metadata': self.primarydb[repo] = dataobj @@ -808,7 +808,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): self.otherdb[repo] = dataobj else: # We can not handle this yet... - raise Errors.RepoError, "Sorry sqlite does not support %s in %s" % (datatype, repo) + raise Errors.RepoError("Sorry sqlite does not support %s in %s" % (datatype, repo)) self.added[repo].append(datatype) @@ -850,7 +850,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): querytype = '=' results = [] - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): if rep in self._all_excludes: continue cur = cache.cursor() @@ -864,7 +864,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): """ Return true if pkg.returnFileEntries(primary_only=True) is fast. basically does "CREATE INDEX pkgfiles ON files (pkgKey);" exist. """ - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): if rep in self._all_excludes: continue cur = cache.cursor() @@ -923,7 +923,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): if len(self.filelistsdb) == 0: # grab repo object from primarydb and force filelists population in this sack using repo # sack.populate(repo, mdtype, callback, cacheonly) - for (repo,cache) in self.primarydb.items(): + for (repo,cache) in list(self.primarydb.items()): if repo in self._all_excludes: continue @@ -955,7 +955,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): sql_params.append('%' + pattern + '%') elif filename == '*': # We only care about matching on dirname... - for (rep,cache) in self.filelistsdb.items(): + for (rep,cache) in list(self.filelistsdb.items()): if rep in self._all_excludes: continue @@ -968,7 +968,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): return misc.unique(pkgs) - for (rep,cache) in self.filelistsdb.items(): + for (rep,cache) in list(self.filelistsdb.items()): if rep in self._all_excludes: continue @@ -993,7 +993,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): if not file_glob: return int(filename in files) - fns = map(lambda f: '%s/%s' % (sql_dirname, f), files) + fns = ['%s/%s' % (sql_dirname, f) for f in files] for match in fns: if name_re.match(match): return 1 @@ -1029,7 +1029,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): for f in fields[1:]: sql = "%s or %s like '%%%s%%'%s " % (sql, f, searchstring, esc) - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, sql) self._sql_pkgKey2po(rep, cur, result) @@ -1077,7 +1077,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): totalstring = unionstring + " UNION ALL ".join(selects) + endunionstring - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, totalstring) for ob in cur: @@ -1096,7 +1096,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): raise NotImplementedError() obsoletes = {} - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select packages.name as name,\ packages.pkgKey as pkgKey,\ @@ -1127,7 +1127,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): @catchSqliteException def getPackageDetails(self,pkgId): - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select * from packages where pkgId = ?", (pkgId,)) for ob in cur: @@ -1140,7 +1140,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): return pkgs pkgid_query = str(tuple(pkgId_list)) - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select * from packages where pkgId in %s" %(pkgid_query,)) for ob in cur: @@ -1153,7 +1153,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): if not hasattr(self, '_memoize_' + prcotype): memoize = {} - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): if rep in self._all_excludes: continue @@ -1180,7 +1180,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): name = to_unicode(name) if flags == 0: flags = None - if type(version) in (str, type(None), unicode): + if type(version) in (str, type(None), str): req = (name, flags, rpmUtils.miscutils.stringToVersion( version)) elif type(version) in (tuple, list): # would this ever be a list? @@ -1199,13 +1199,13 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): # fixed something with later change? ... maybe I was on crack? # Speed seems to depend on _search_cache. if True: # prcotype != 'requires': - primarydb_items = self.primarydb.items() + primarydb_items = list(self.primarydb.items()) preload = False else: primarydb_items = [] preload = True memoize = self._search_get_memoize(prcotype) - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): if rep in self._all_excludes: continue @@ -1214,7 +1214,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): pkgkey, val = x if rpmUtils.miscutils.rangeCompare(req, val): tmp.setdefault(pkgkey, []).append(val) - for pkgKey, hits in tmp.iteritems(): + for pkgKey, hits in list(tmp.items()): pkg = self._packageByKey(rep, pkgKey) if pkg is None: continue @@ -1235,7 +1235,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): val = _share_data(val) if rpmUtils.miscutils.rangeCompare(req, val): tmp.setdefault(x['pkgKey'], []).append(val) - for pkgKey, hits in tmp.iteritems(): + for pkgKey, hits in list(tmp.items()): pkg = self._packageByKey(rep, pkgKey) if pkg is None: continue @@ -1308,7 +1308,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): pat_sqls.append("name = ?") qsql = qsql + " OR ".join(pat_sqls) - for (repo, cache) in self.primarydb.items(): + for (repo, cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, qsql, names) @@ -1339,8 +1339,8 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): return [] try: (n,f,(e,v,r)) = misc.string_to_prco_tuple(name) - except Errors.MiscError, e: - raise Errors.PackageSackError, to_unicode(e) + except Errors.MiscError as e: + raise Errors.PackageSackError(to_unicode(e)) # The _b means this is a byte string # The _u means this is a unicode string @@ -1358,7 +1358,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): basic_results = [] results = [] - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select DISTINCT pkgKey from %s where name %s ?" % (prcotype,querytype), (n,)) self._sql_pkgKey2po(rep, cur, basic_results) @@ -1416,7 +1416,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): def db2class(self, db, nevra_only=False): - print 'die die die die die db2class' + print('die die die die die db2class') class tmpObject: pass y = tmpObject() @@ -1451,14 +1451,14 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): # First find all packages that fulfill naTup allpkg = [] - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select pkgId,pkgKey,name,epoch,version,release,arch from packages where name=? and arch=?", naTup) self._sql_pkgKey2po(rep, cur, allpkg, have_data=True) # if we've got zilch then raise if not allpkg: - raise Errors.PackageSackError, 'No Package Matching %s.%s' % naTup + raise Errors.PackageSackError('No Package Matching %s.%s' % naTup) return misc.newestInList(allpkg) @catchSqliteException @@ -1480,14 +1480,14 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): # First find all packages that fulfill name allpkg = [] - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, "select pkgId,pkgKey,name,epoch,version,release,arch from packages where name=?", (name,)) self._sql_pkgKey2po(rep, cur, allpkg, have_data=True) # if we've got zilch then raise if not allpkg: - raise Errors.PackageSackError, 'No Package Matching %s' % name + raise Errors.PackageSackError('No Package Matching %s' % name) return misc.newestInList(allpkg) # Do what packages.matchPackageNames does, but query the DB directly @@ -1508,7 +1508,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): query = PARSE_QUERY % ({ "op": "=", "q": p }) matchres = exactmatch - for (rep, db) in self.primarydb.items(): + for (rep, db) in list(self.primarydb.items()): cur = db.cursor() executeSQL(cur, query) pmatches = self._sql_pkgKey2po(rep, cur) @@ -1586,7 +1586,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): qsql = """select pkgId, pkgKey, name,epoch,version,release,arch from packages""" - for (repo,cache) in self.primarydb.items(): + for (repo,cache) in list(self.primarydb.items()): if (repoid == None or repoid == repo.id): cur = cache.cursor() executeSQL(cur, qsql, pat_data) @@ -1735,7 +1735,7 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): q = q + ' %s = "%s"' % (col, var) # Search all repositories - for (rep,cache) in self.primarydb.items(): + for (rep,cache) in list(self.primarydb.items()): cur = cache.cursor() executeSQL(cur, q) self._sql_pkgKey2po(rep, cur, returnList, have_data=True) @@ -1749,10 +1749,10 @@ class YumSqlitePackageSack(yumRepo.YumPackageSack): self._arch_allowed = set(archlist) else: self._arch_allowed = self._arch_allowed.intersection(archlist) - sarchlist = map(lambda x: "'%s'" % x , archlist) + sarchlist = ["'%s'" % x for x in archlist] arch_query = ",".join(sarchlist) - for (rep, cache) in self.primarydb.items(): + for (rep, cache) in list(self.primarydb.items()): cur = cache.cursor() # This is a minor hack opt. for source repos. ... if they are diff --git a/yum/sqlutils.py b/yum/sqlutils.py index 4d7e36e..3e4cfde 100644 --- a/yum/sqlutils.py +++ b/yum/sqlutils.py @@ -89,10 +89,10 @@ def Tokenize(str, whitespace=" \t\r\n", quotes="\"", escapes="\\"): buffer=buffer[1:] except IndexError: - raise TokenizeError, "Unexpected end of string" + raise TokenizeError("Unexpected end of string") if quote: - raise TokenizeError, "Unexpected end of string in quoted text" + raise TokenizeError("Unexpected end of string in quoted text") if curtoken!=None: tokens.append(curtoken) diff --git a/yum/transactioninfo.py b/yum/transactioninfo.py index 4d89d83..785750f 100644 --- a/yum/transactioninfo.py +++ b/yum/transactioninfo.py @@ -26,13 +26,13 @@ Classes and functions for manipulating a transaction to be passed to rpm. """ -from constants import * -from packageSack import PackageSack, PackageSackVersion -from packages import YumInstalledPackage -from sqlitesack import YumAvailablePackageSqlite -import Errors +from .constants import * +from .packageSack import PackageSack, PackageSackVersion +from .packages import YumInstalledPackage +from .sqlitesack import YumAvailablePackageSqlite +from . import Errors import warnings -import misc +from . import misc class GetProvReqOnlyPackageSack(PackageSack): def __init__(self, need_files=False): @@ -117,11 +117,10 @@ class TransactionData: def debugprint(self, msg): if self.debug: - print msg + print(msg) def getMembersWithState(self, pkgtup=None, output_states=None): - return filter(lambda p: p.output_state in output_states, - self.getMembers(pkgtup)) + return [p for p in self.getMembers(pkgtup) if p.output_state in output_states] def getMembers(self, pkgtup=None): """takes an optional package tuple and returns all transaction members @@ -130,7 +129,7 @@ class TransactionData: returnlist = [] if pkgtup is None: - for members in self.pkgdict.itervalues(): + for members in list(self.pkgdict.values()): returnlist.extend(members) elif pkgtup in self.pkgdict: returnlist.extend(self.pkgdict[pkgtup]) @@ -219,7 +218,7 @@ class TransactionData: txmbrs.extend(self.getMembers(pkg.pkgtup)) # Now we need to do conditional group packages, so they don't # get added later on. This is hacky :( - for req, cpkgs in self.conditionals.iteritems(): + for req, cpkgs in list(self.conditionals.items()): if pkg in cpkgs: cpkgs.remove(pkg) self.conditionals[req] = cpkgs @@ -245,7 +244,7 @@ class TransactionData: return True provides = po.provides_names - if filter (lambda prov: prov in self.installonlypkgs, provides): + if [prov for prov in provides if prov in self.installonlypkgs]: return True return False @@ -558,11 +557,11 @@ class TransactionData: if not self.pkgSackPackages: pass elif self._inSack is None: - for pkg, hits in self.pkgSack.getProvides(name, flag, version).iteritems(): + for pkg, hits in list(self.pkgSack.getProvides(name, flag, version).items()): if self.getMembersWithState(pkg.pkgtup, TS_INSTALL_STATES): result[pkg] = hits else: - for pkg, hits in self._inSack.getProvides(name, flag, version).iteritems(): + for pkg, hits in list(self._inSack.getProvides(name, flag, version).items()): result[pkg] = hits result.update(self.localSack.getProvides(name, flag, version)) return result @@ -571,7 +570,7 @@ class TransactionData: """return dict { packages -> list of matching provides } searches in packages already installed and not going to be removed""" result = { } - for pkg, hits in self.rpmdb.getProvides(name, flag, version).iteritems(): + for pkg, hits in list(self.rpmdb.getProvides(name, flag, version).items()): if not self.getMembersWithState(pkg.pkgtup, TS_REMOVE_STATES): result[pkg] = hits return result @@ -589,11 +588,11 @@ class TransactionData: if not self.pkgSackPackages: pass elif self._inSack is None: - for pkg, hits in self.pkgSack.getRequires(name, flag, version).iteritems(): + for pkg, hits in list(self.pkgSack.getRequires(name, flag, version).items()): if self.getMembersWithState(pkg.pkgtup, TS_INSTALL_STATES): result[pkg] = hits else: - for pkg, hits in self._inSack.getRequires(name, flag, version).iteritems(): + for pkg, hits in list(self._inSack.getRequires(name, flag, version).items()): result[pkg] = hits result.update(self.localSack.getRequires(name, flag, version)) @@ -604,7 +603,7 @@ class TransactionData: """return dict { packages -> list of matching provides } searches in packages already installed and not going to be removed""" result = { } - for pkg, hits in self.rpmdb.getRequires(name, flag, version).iteritems(): + for pkg, hits in list(self.rpmdb.getRequires(name, flag, version).items()): if not self.getMembersWithState(pkg.pkgtup, TS_REMOVE_STATES): result[pkg] = hits return result diff --git a/yum/update_md.py b/yum/update_md.py index 2cb1acb..fe94080 100644 --- a/yum/update_md.py +++ b/yum/update_md.py @@ -28,7 +28,7 @@ from yum.yumRepo import YumRepository from yum.packages import FakeRepository from yum.misc import to_xml, decompress, repo_gen_decompress from yum.misc import cElementTree_iterparse as iterparse -import Errors +from . import Errors import rpmUtils.miscutils @@ -39,7 +39,7 @@ def safe_iterparse(filename): for event, elem in iterparse(filename): yield event, elem except SyntaxError: # Bad XML - print >> sys.stderr, "File is not valid XML:", filename + print("File is not valid XML:", filename, file=sys.stderr) class UpdateNoticeException(Exception): """ An exception thrown for bad UpdateNotice data. """ @@ -100,7 +100,7 @@ class UpdateNotice(object): head += " Updated : %s" % self._md['updated'] # Add our bugzilla references - bzs = filter(lambda r: r['type'] == 'bugzilla', self._md['references']) + bzs = [r for r in self._md['references'] if r['type'] == 'bugzilla'] if len(bzs) and 'bugs' not in skip_data: buglist = " Bugs :" for bz in bzs: @@ -109,7 +109,7 @@ class UpdateNotice(object): head += buglist[: - 1].rstrip() + '\n' # Add our CVE references - cves = filter(lambda r: r['type'] == 'cve', self._md['references']) + cves = [r for r in self._md['references'] if r['type'] == 'cve'] if len(cves) and 'cves' not in skip_data: cvelist = " CVEs :" for cve in cves: @@ -374,7 +374,7 @@ class UpdateMetadata(object): def get_notices(self, name=None): """ Return all notices. """ if name is None: - return self._notices.values() + return list(self._notices.values()) return name in self._no_cache and self._no_cache[name] or [] notices = property(get_notices) @@ -439,7 +439,7 @@ class UpdateMetadata(object): """ Parse a metadata from a given YumRepository, file, or filename. """ if not obj: raise UpdateNoticeException - if type(obj) in (type(''), type(u'')): + if type(obj) in (type(''), type('')): unfile = decompress(obj) infile = open(unfile, 'rt') @@ -452,7 +452,7 @@ class UpdateMetadata(object): unfile = repo_gen_decompress(md, 'updateinfo.xml') infile = open(unfile, 'rt') elif isinstance(obj, FakeRepository): - raise Errors.RepoMDError, "No updateinfo for local pkg" + raise Errors.RepoMDError("No updateinfo for local pkg") else: # obj is a file object infile = obj @@ -460,16 +460,16 @@ class UpdateMetadata(object): if elem.tag == 'update': try: un = UpdateNotice(elem) - except UpdateNoticeException, e: - print >> sys.stderr, "An update notice is broken, skipping." + except UpdateNoticeException as e: + print("An update notice is broken, skipping.", file=sys.stderr) # what else should we do? continue self.add_notice(un) def __unicode__(self): - ret = u'' + ret = '' for notice in self.notices: - ret += unicode(notice) + ret += str(notice) return ret def __str__(self): return to_utf8(self.__unicode__()) @@ -479,7 +479,7 @@ class UpdateMetadata(object): if fileobj: fileobj.write(msg) - for notice in self._notices.values(): + for notice in list(self._notices.values()): if fileobj: fileobj.write(notice.xml()) else: @@ -503,21 +503,21 @@ def main(): yum.misc.setup_locale() def usage(): - print >> sys.stderr, "Usage: %s <update metadata> ..." % sys.argv[0] + print("Usage: %s <update metadata> ..." % sys.argv[0], file=sys.stderr) sys.exit(1) if len(sys.argv) < 2: usage() try: - print sys.argv[1] + print(sys.argv[1]) um = UpdateMetadata() for srcfile in sys.argv[1:]: um.add(srcfile) - print unicode(um) + print(str(um)) except IOError: - print >> sys.stderr, "%s: No such file:\'%s\'" % (sys.argv[0], - sys.argv[1:]) + print("%s: No such file:\'%s\'" % (sys.argv[0], + sys.argv[1:]), file=sys.stderr) usage() if __name__ == '__main__': diff --git a/yum/yumRepo.py b/yum/yumRepo.py index e5e9ece..aca45e9 100644 --- a/yum/yumRepo.py +++ b/yum/yumRepo.py @@ -18,28 +18,28 @@ import os import re import time import types -import urlparse -urlparse.uses_fragment.append("media") +import urllib.parse +urllib.parse.uses_fragment.append("media") -import Errors +from . import Errors from urlgrabber.grabber import URLGrabber from urlgrabber.grabber import default_grabber import urlgrabber.mirror from urlgrabber.grabber import URLGrabError -import repoMDObject -import packageSack -from repos import Repository -import parser +from . import repoMDObject +from . import packageSack +from .repos import Repository +from . import parser import sqlitecachec -import sqlitesack +from . import sqlitesack from yum import config from yum import misc from yum import comps -from constants import * -import metalink +from .constants import * +from . import metalink import logging -import logginglevels +from . import logginglevels import warnings @@ -103,8 +103,8 @@ class YumPackageSack(packageSack.PackageSack): elif datatype in ['filelists', 'otherdata']: if repo in self.added: if 'metadata' not in self.added[repo]: - raise Errors.RepoError, '%s md for %s imported before primary' \ - % (datatype, repo.id) + raise Errors.RepoError('%s md for %s imported before primary' \ + % (datatype, repo.id)) current = 0 for pkgid in dataobj: current += 1 @@ -360,10 +360,10 @@ class YumRepository(Repository, config.RepoConf): CHUNK=65536 by default""" try: return misc.checksum(sumtype, file, CHUNK, datasize) - except (Errors.MiscError, EnvironmentError), e: + except (Errors.MiscError, EnvironmentError) as e: if checksum_can_fail: return None - raise Errors.RepoError, 'Error opening file for checksum: %s' % e + raise Errors.RepoError('Error opening file for checksum: %s' % e) def dump(self): output = '[%s]\n' % self.id @@ -389,7 +389,7 @@ class YumRepository(Repository, config.RepoConf): res = getattr(self, attr) if not res and type(res) not in (type(False), type(0)): res = '' - if type(res) == types.ListType: + if type(res) == list: res = ',\n '.join(res) output = output + '%s = %s\n' % (attr, res) @@ -400,29 +400,28 @@ class YumRepository(Repository, config.RepoConf): self.enable() try: config.writeRawRepoFile(self,only=['enabled']) - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: logger.warning(e) else: - raise IOError, str(e) + raise IOError(str(e)) def disablePersistent(self): """Persistently disables this repository.""" self.disable() try: config.writeRawRepoFile(self,only=['enabled']) - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: logger.warning(e) else: - raise IOError, str(e) + raise IOError(str(e)) def check(self): """self-check the repo information - if we don't have enough to move on then raise a repo error""" if len(self._urls) < 1 and not self.mediaid: - raise Errors.RepoError, \ - 'Cannot find a valid baseurl for repo: %s' % self.id + raise Errors.RepoError('Cannot find a valid baseurl for repo: %s' % self.id) def doProxyDict(self): if self._proxy_dict: @@ -434,7 +433,7 @@ class YumRepository(Repository, config.RepoConf): if self.proxy not in empty: proxy_string = '%s' % self.proxy if self.proxy_username not in empty: - proxy_parsed = urlparse.urlsplit(self.proxy, allow_fragments=0) + proxy_parsed = urllib.parse.urlsplit(self.proxy, allow_fragments=0) proxy_proto = proxy_parsed[0] proxy_host = proxy_parsed[1] # http://foo:123 == ('http', 'foo:123', '', '', '') @@ -532,14 +531,14 @@ class YumRepository(Repository, config.RepoConf): return if self.cache: - raise Errors.RepoError, "Cannot access repository dir %s" % dpath + raise Errors.RepoError("Cannot access repository dir %s" % dpath) try: - os.makedirs(dpath, mode=0755) - except OSError, e: + os.makedirs(dpath, mode=0o755) + except OSError as e: msg = "%s: %s %s: %s" % ("Error making cache directory", dpath, "error was", e) - raise Errors.RepoError, msg + raise Errors.RepoError(msg) def dirSetup(self): """make the necessary dirs, if possible, raise on failure""" @@ -569,7 +568,7 @@ class YumRepository(Repository, config.RepoConf): for dir in [self.persistdir]: try: self._dirSetupMkdir_p(dir) - except Errors.RepoError, e: + except Errors.RepoError as e: pass # if we're using a cachedir that's not the system one, copy over these @@ -661,10 +660,10 @@ class YumRepository(Repository, config.RepoConf): if not self.cache: try: misc.unlink_f(self.mirrorlist_file) - except (IOError, OSError), e: - print 'Could not delete bad mirrorlist file: %s - %s' % (self.mirrorlist_file, e) + except (IOError, OSError) as e: + print(('Could not delete bad mirrorlist file: %s - %s' % (self.mirrorlist_file, e))) else: - print 'removing mirrorlist with no valid mirrors: %s' % self.mirrorlist_file + print(('removing mirrorlist with no valid mirrors: %s' % self.mirrorlist_file)) # store them all back in baseurl for compat purposes self.baseurl = self._urls self.check() @@ -681,8 +680,8 @@ class YumRepository(Repository, config.RepoConf): url= url + '/' try: # This started throwing ValueErrors, BZ 666826 - (s,b,p,q,f,o) = urlparse.urlparse(url) - except (ValueError, IndexError, KeyError), e: + (s,b,p,q,f,o) = urllib.parse.urlparse(url) + except (ValueError, IndexError, KeyError) as e: s = 'blah' if s not in ['http', 'ftp', 'file', 'https']: @@ -694,9 +693,9 @@ class YumRepository(Repository, config.RepoConf): if skipped is not None: # Caller cleans up for us. if goodurls: - print 'YumRepo Warning: Some mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped) + print(('YumRepo Warning: Some mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped))) else: # And raises in this case - print 'YumRepo Error: All mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped) + print(('YumRepo Error: All mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped))) return goodurls def _geturls(self): @@ -719,23 +718,23 @@ class YumRepository(Repository, config.RepoConf): ug = URLGrabber(progress_obj = self.callback, **ugopts) result = ug.urlgrab(url, local, text=self.id + "/metalink") - except urlgrabber.grabber.URLGrabError, e: + except urlgrabber.grabber.URLGrabError as e: if not os.path.exists(self.metalink_filename): msg = ("Cannot retrieve metalink for repository: %s. " "Please verify its path and try again" % self ) - raise Errors.RepoError, msg + raise Errors.RepoError(msg) # Now, we have an old usable metalink, so we can't move to # a newer repomd.xml ... or checksums won't match. - print "Could not get metalink %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])) + print(("Could not get metalink %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])))) self._metadataCurrent = True if not self._metadataCurrent: try: self._metalink = metalink.MetaLinkRepoMD(result) shutil.move(result, self.metalink_filename) - except metalink.MetaLinkRepoErrorParseFail, e: + except metalink.MetaLinkRepoErrorParseFail as e: # Downloaded file failed to parse, revert (dito. above): - print "Could not parse metalink %s error was \n%s"%(url, e) + print(("Could not parse metalink %s error was \n%s"%(url, e))) self._metadataCurrent = True misc.unlink_f(result) @@ -767,21 +766,19 @@ class YumRepository(Repository, config.RepoConf): copy_local = self.copy_local if local is None or relative is None: - raise Errors.RepoError, \ - "get request for Repo %s, gave no source or dest" % self.id + raise Errors.RepoError("get request for Repo %s, gave no source or dest" % self.id) if self.cache == 1: if os.path.exists(local): # FIXME - we should figure out a way return local # to run the checkfunc from here else: # ain't there - raise - raise Errors.RepoError, \ - "Caching enabled but no local cache of %s from %s" % (local, + raise Errors.RepoError("Caching enabled but no local cache of %s from %s" % (local, - self) + self)) if url: - (scheme, netloc, path, query, fragid) = urlparse.urlsplit(url) + (scheme, netloc, path, query, fragid) = urllib.parse.urlsplit(url) if self.mediaid and self.mediafunc: discnum = 1 @@ -793,7 +790,7 @@ class YumRepository(Repository, config.RepoConf): # pass to the media grabber function here result = self.mediafunc(local = local, checkfunc = checkfunc, relative = relative, text = text, copy_local = copy_local, url = url, mediaid = self.mediaid, name = self.name, discnum = discnum, range = (start, end)) return result - except Errors.MediaError, e: + except Errors.MediaError as e: verbose_logger.log(logginglevels.DEBUG_2, "Error getting package from media; falling back to url %s" %(e,)) if url and scheme != "media": @@ -814,15 +811,15 @@ class YumRepository(Repository, config.RepoConf): text=misc.to_utf8(text), range=(start, end), ) - except URLGrabError, e: + except URLGrabError as e: errstr = "failed to retrieve %s from %s\nerror was %s" % (relative, self.id, e) if self.mirrorurls: errstr +="\n You could try running: yum clean expire-cache" errstr +="\n To get a new set of mirrors." if e.errno == 256: - raise Errors.NoMoreMirrorsRepoError, errstr + raise Errors.NoMoreMirrorsRepoError(errstr) else: - raise Errors.RepoError, errstr + raise Errors.RepoError(errstr) else: @@ -837,12 +834,12 @@ class YumRepository(Repository, config.RepoConf): http_headers=headers, size=size ) - except URLGrabError, e: + except URLGrabError as e: errstr = "failure: %s from %s: %s" % (relative, self.id, e) if e.errno == 256: - raise Errors.NoMoreMirrorsRepoError, errstr + raise Errors.NoMoreMirrorsRepoError(errstr) else: - raise Errors.RepoError, errstr + raise Errors.RepoError(errstr) return result __get = _getFile @@ -921,7 +918,7 @@ class YumRepository(Repository, config.RepoConf): return self._metadataCurrent if self.cache and not os.path.exists(self.metalink_filename): - raise Errors.RepoError, 'Cannot find metalink.xml file for %s' %self + raise Errors.RepoError('Cannot find metalink.xml file for %s' %self) if self.cache: self._metadataCurrent = True @@ -981,7 +978,7 @@ class YumRepository(Repository, config.RepoConf): self.gpg_import_func = gpg_import_func self.gpgca_import_func = gpgca_import_func self.confirm_func = confirm_func - except Errors.RepoError, e: + except Errors.RepoError as e: raise if not self.mediafunc and self.mediaid and not self.mirrorlist and not self.baseurl: verbose_logger.log(logginglevels.DEBUG_2, "Disabling media repo for non-media-aware frontend") @@ -991,7 +988,7 @@ class YumRepository(Repository, config.RepoConf): def _cachingRepoXML(self, local): """ Should we cache the current repomd.xml """ if self.cache and not os.path.exists(local): - raise Errors.RepoError, 'Cannot find repomd.xml file for %s' % self + raise Errors.RepoError('Cannot find repomd.xml file for %s' % self) if self.cache or self.metadataCurrent(): return True return False @@ -1015,11 +1012,11 @@ class YumRepository(Repository, config.RepoConf): cache=self.http_caching == 'all', size=102400) # setting max size as 100K - except URLGrabError, e: + except URLGrabError as e: misc.unlink_f(tfname) if grab_can_fail: return None - raise Errors.RepoError, 'Error downloading file %s: %s' % (local, e) + raise Errors.RepoError('Error downloading file %s: %s' % (local, e)) except (Errors.NoMoreMirrorsRepoError, Errors.RepoError): misc.unlink_f(tfname) if grab_can_fail: @@ -1034,20 +1031,20 @@ class YumRepository(Repository, config.RepoConf): misc.unlink_f(tfname) if grab_can_fail: return None - raise Errors.RepoError, 'Error renaming file %s to %s' % (result, - local) + raise Errors.RepoError('Error renaming file %s to %s' % (result, + local)) return local def _parseRepoXML(self, local, parse_can_fail=None): """ Parse the repomd.xml file. """ try: return repoMDObject.RepoMD(self.id, local) - except Errors.RepoMDError, e: + except Errors.RepoMDError as e: if parse_can_fail is None: parse_can_fail = 'old_repo_XML' in self._oldRepoMDData if parse_can_fail: return None - raise Errors.RepoError, 'Error importing repomd.xml from %s: %s' % (self, e) + raise Errors.RepoError('Error importing repomd.xml from %s: %s' % (self, e)) def _saveOldRepoXML(self, local): """ If we have an older repomd.xml file available, save it out. """ @@ -1074,7 +1071,7 @@ class YumRepository(Repository, config.RepoConf): # We still want the old data, so we don't download twice. So we # pretend everything is good until the revert. if not self.timestamp_check: - raise Errors.RepoError, "Can't download or revert repomd.xml" + raise Errors.RepoError("Can't download or revert repomd.xml") if 'old_repo_XML' not in self._oldRepoMDData: self._oldRepoMDData = {} @@ -1320,7 +1317,7 @@ class YumRepository(Repository, config.RepoConf): return False return True - all_mdtypes = self.retrieved.keys() + all_mdtypes = list(self.retrieved.keys()) if mdtypes is None: mdtypes = all_mdtypes @@ -1427,7 +1424,7 @@ class YumRepository(Repository, config.RepoConf): 'group:main' : ["primary", "group", "filelists", "updateinfo", "prestodelta"]} mdtypes = set() - if type(self.mdpolicy) in types.StringTypes: + if type(self.mdpolicy) in (str,): mdtypes.update(md_groups.get(self.mdpolicy, [self.mdpolicy])) else: for mdpolicy in self.mdpolicy: @@ -1446,17 +1443,17 @@ class YumRepository(Repository, config.RepoConf): except KeyboardInterrupt: self._revertOldRepoXML() # Undo metadata cookie? raise - raise Errors.RepoError, 'Bad loadRepoXML policy: %s' % (self.mdpolicy) + raise Errors.RepoError('Bad loadRepoXML policy: %s' % (self.mdpolicy)) def _getRepoXML(self): if self._repoXML: return self._repoXML try: self._loadRepoXML(text=self) - except Errors.RepoError, e: + except Errors.RepoError as e: msg = ("Cannot retrieve repository metadata (repomd.xml) for repository: %s. " "Please verify its path and try again" % self ) - raise Errors.RepoError, msg + raise Errors.RepoError(msg) return self._repoXML @@ -1485,13 +1482,13 @@ class YumRepository(Repository, config.RepoConf): checkfunc=None, cache=self.http_caching == 'all', size=102400) - except URLGrabError, e: + except URLGrabError as e: raise URLGrabError(-1, 'Error finding signature for repomd.xml for %s: %s' % (self, e)) valid = misc.valid_detached_sig(result, filepath, self.gpgdir) if not valid and self.gpg_import_func: try: self.gpg_import_func(self, self.confirm_func) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: raise URLGrabError(-1, 'Gpg Keys not imported, cannot verify repomd.xml for repo %s' % (self)) valid = misc.valid_detached_sig(result, filepath, self.gpgdir) @@ -1500,7 +1497,7 @@ class YumRepository(Repository, config.RepoConf): try: repoXML = repoMDObject.RepoMD(self.id, filepath) - except Errors.RepoMDError, e: + except Errors.RepoMDError as e: raise URLGrabError(-1, 'Error importing repomd.xml for %s: %s' % (self, e)) self._hack_mirrorlist_for_anaconda() @@ -1539,7 +1536,7 @@ class YumRepository(Repository, config.RepoConf): try: # get the local checksum l_csum = self._checksum(r_ctype, file, datasize=size) - except Errors.RepoError, e: + except Errors.RepoError as e: if check_can_fail: return None raise URLGrabError(-3, 'Error performing checksum') @@ -1579,16 +1576,14 @@ class YumRepository(Repository, config.RepoConf): if os.path.exists(local): try: self.checkMD(local, mdtype) - except URLGrabError, e: - raise Errors.RepoError, \ - "Caching enabled and local cache: %s does not match checksum" % local + except URLGrabError as e: + raise Errors.RepoError("Caching enabled and local cache: %s does not match checksum" % local) else: return local else: # ain't there - raise - raise Errors.RepoError, \ - "Caching enabled but no local cache of %s from %s" % (local, - self) + raise Errors.RepoError("Caching enabled but no local cache of %s from %s" % (local, + self)) if (os.path.exists(local) or self._preload_md_from_system_cache(os.path.basename(local))): @@ -1618,11 +1613,10 @@ class YumRepository(Repository, config.RepoConf): if retrieve_can_fail: return None raise - except URLGrabError, e: + except URLGrabError as e: if retrieve_can_fail: return None - raise Errors.RepoError, \ - "Could not retrieve %s matching remote checksum from %s" % (local, self) + raise Errors.RepoError("Could not retrieve %s matching remote checksum from %s" % (local, self)) else: self.retrieved[mdtype] = 1 return local @@ -1675,10 +1669,10 @@ class YumRepository(Repository, config.RepoConf): if fo is not None: try: content = fo.readlines() - except Exception, e: + except Exception as e: if url is None: # Shouldn't happen url = "<unknown>" - print "Could not read mirrorlist %s, error was \n%s" %(url, e) + print(("Could not read mirrorlist %s, error was \n%s" %(url, e))) content = [] for line in content: if re.match('\s*(#|$)', line): @@ -1707,14 +1701,14 @@ class YumRepository(Repository, config.RepoConf): url = 'file://' + self.mirrorlist_file # just to keep self._readMirrorList(fo,url) happy else: url = self.mirrorlist - scheme = urlparse.urlparse(url)[0] + scheme = urllib.parse.urlparse(url)[0] if scheme == '': url = 'file://' + url ugopts = self._default_grabopts() try: fo = urlgrabber.grabber.urlopen(url, **ugopts) - except urlgrabber.grabber.URLGrabError, e: - print "Could not retrieve mirrorlist %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])) + except urlgrabber.grabber.URLGrabError as e: + print(("Could not retrieve mirrorlist %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])))) fo = None (returnlist, content) = self._readMirrorList(fo, url) @@ -1788,19 +1782,19 @@ class YumRepository(Repository, config.RepoConf): def _verify_md(self): problems = [] - print 'verifying md' + print('verifying md') try: md_types = self.repoXML.fileTypes() - except Errors.RepoError, e: + except Errors.RepoError as e: prb = RepoVerifyProblem(1, "failed to load repomd.xml", str(e)) problems.append(prb) return problems for md_type in md_types: - print 'verifying %s' % md_type + print(('verifying %s' % md_type)) try: self.retrieveMD(md_type) - except Errors.RepoError, e: + except Errors.RepoError as e: msg = "%s metadata missing or does not match checksum" % md_type prb = RepoVerifyProblem(2, msg, str(e)) problems.append(prb) @@ -1808,7 +1802,7 @@ class YumRepository(Repository, config.RepoConf): return problems def _verify_comps(self): - print 'verifying comps' + print('verifying comps') problems = [] # grab the comps for this repo # run the xmllint on it @@ -1823,7 +1817,7 @@ class YumRepository(Repository, config.RepoConf): try: c = comps.Comps() c.add(grpfile) - except (Errors.GroupsError, Errors.CompsException), e: + except (Errors.GroupsError, Errors.CompsException) as e: msg = "comps file failed to add" prb = RepoVerifyProblem(REPO_PROBLEM_COMPS, msg, str(e)) problems.add(prb) @@ -1866,10 +1860,10 @@ def getMirrorList(mirrorlist, pdict = None): if hasattr(urlgrabber.grabber, 'urlopen'): urlresolver = urlgrabber.grabber else: - import urllib + import urllib.request, urllib.parse, urllib.error urlresolver = urllib - scheme = urlparse.urlparse(mirrorlist)[0] + scheme = urllib.parse.urlparse(mirrorlist)[0] if scheme == '': url = 'file://' + mirrorlist else: @@ -1877,8 +1871,8 @@ def getMirrorList(mirrorlist, pdict = None): try: fo = urlresolver.urlopen(url, proxies=pdict) - except urlgrabber.grabber.URLGrabError, e: - print "Could not retrieve mirrorlist %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])) + except urlgrabber.grabber.URLGrabError as e: + print(("Could not retrieve mirrorlist %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])))) fo = None if fo is not None: diff --git a/yumcommands.py b/yumcommands.py index 4dcbea7..7205d62 100644 --- a/yumcommands.py +++ b/yumcommands.py @@ -212,7 +212,7 @@ class InstallCommand(YumCommand): self.doneCommand(base, _("Setting up Install Process")) try: return base.installPkgs(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] class UpdateCommand(YumCommand): @@ -234,7 +234,7 @@ class UpdateCommand(YumCommand): self.doneCommand(base, _("Setting up Update Process")) try: return base.updatePkgs(extcmds, update_to=(basecmd == 'update-to')) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] class DistroSyncCommand(YumCommand): @@ -257,7 +257,7 @@ class DistroSyncCommand(YumCommand): try: base.conf.obsoletes = 1 return base.distroSyncPkgs(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def _add_pkg_simple_list_lens(data, pkg, indent=''): @@ -302,7 +302,7 @@ class InfoCommand(YumCommand): try: highlight = base.term.MODE['bold'] ypl = base.returnPkgLists(extcmds, installed_available=highlight) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] else: update_pkgs = {} @@ -369,7 +369,7 @@ class InfoCommand(YumCommand): if len(ypl.obsoletes) > 0 and basecmd == 'list': # if we've looked up obsolete lists and it's a list request rop = [0, ''] - print _('Obsoleting Packages') + print((_('Obsoleting Packages'))) # The tuple is (newPkg, oldPkg) ... so sort by new for obtup in sorted(ypl.obsoletesTuples, key=operator.itemgetter(0)): @@ -421,7 +421,7 @@ class EraseCommand(YumCommand): self.doneCommand(base, _("Setting up Remove Process")) try: return base.erasePkgs(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def needTs(self, base, basecmd, extcmds): @@ -442,7 +442,7 @@ class GroupsCommand(YumCommand): 'groupinfo' : 'info'} def getNames(self): - return ['groups', 'group'] + self.direct_commands.keys() + return ['groups', 'group'] + list(self.direct_commands.keys()) def getUsage(self): return "[list|info|summary|install|upgrade|remove|mark] [GROUP]" @@ -458,7 +458,7 @@ class GroupsCommand(YumCommand): base.doGroupSetup() except yum.Errors.GroupsError: return 1, [_('No Groups on which to run command')] - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def _grp_cmd(self, basecmd, extcmds): @@ -524,7 +524,7 @@ class GroupsCommand(YumCommand): if cmd == 'remove': return base.removeGroups(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] @@ -577,7 +577,7 @@ class MakeCacheCommand(YumCommand): base.repos.populateSack(mdtype='otherdata', cacheonly=1) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] return 0, [_('Metadata Cache Created')] @@ -623,7 +623,7 @@ class ProvidesCommand(YumCommand): base.logger.debug("Searching Packages: ") try: return base.provides(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] class CheckUpdateCommand(YumCommand): @@ -668,14 +668,14 @@ class CheckUpdateCommand(YumCommand): highlight_modes={'=' : cul, 'not in' : cur}) result = 100 if len(ypl.obsoletes) > 0: # This only happens in verbose mode - print _('Obsoleting Packages') + print((_('Obsoleting Packages'))) # The tuple is (newPkg, oldPkg) ... so sort by new for obtup in sorted(ypl.obsoletesTuples, key=operator.itemgetter(0)): base.updatesObsoletesList(obtup, 'obsoletes', columns=columns) result = 100 - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] else: return result, [] @@ -697,7 +697,7 @@ class SearchCommand(YumCommand): base.logger.debug(_("Searching Packages: ")) try: return base.search(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def needTs(self, base, basecmd, extcmds): @@ -723,7 +723,7 @@ class UpgradeCommand(YumCommand): self.doneCommand(base, _("Setting up Upgrade Process")) try: return base.updatePkgs(extcmds, update_to=(basecmd == 'upgrade-to')) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] class LocalInstallCommand(YumCommand): @@ -751,7 +751,7 @@ class LocalInstallCommand(YumCommand): updateonly = basecmd == 'localupdate' try: return base.localInstall(filelist=extcmds, updateonly=updateonly) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def needTs(self, base, basecmd, extcmds): @@ -771,7 +771,7 @@ class ResolveDepCommand(YumCommand): base.logger.debug(_("Searching Packages for Dependency:")) try: return base.resolveDepCli(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] class ShellCommand(YumCommand): @@ -791,7 +791,7 @@ class ShellCommand(YumCommand): self.doneCommand(base, _('Setting up Yum Shell')) try: return base.doShell() - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def needTs(self, base, basecmd, extcmds): @@ -815,7 +815,7 @@ class DepListCommand(YumCommand): self.doneCommand(base, _("Finding dependencies: ")) try: return base.deplist(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] @@ -855,7 +855,7 @@ class RepoListCommand(YumCommand): extcmds = extcmds[1:] else: arg = 'enabled' - extcmds = map(lambda x: x.lower(), extcmds) + extcmds = [x.lower() for x in extcmds] verbose = base.verbose_logger.isEnabledFor(logginglevels.DEBUG_3) if arg != 'disabled' or extcmds: @@ -867,7 +867,7 @@ class RepoListCommand(YumCommand): if verbose: raise - repos = base.repos.repos.values() + repos = list(base.repos.repos.values()) repos.sort() enabled_repos = base.repos.listEnabled() on_ehibeg = base.term.FG_COLOR['green'] + base.term.MODE['bold'] @@ -1173,7 +1173,7 @@ class ReInstallCommand(YumCommand): try: return base.reinstallPkgs(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [to_unicode(e)] def getSummary(self): @@ -1199,7 +1199,7 @@ class DowngradeCommand(YumCommand): self.doneCommand(base, _("Setting up Downgrade Process")) try: return base.downgradePkgs(extcmds) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] def getSummary(self): @@ -1256,9 +1256,9 @@ class VersionCommand(YumCommand): groups[group].update(base.run_with_package_names) if vcmd == 'grouplist': - print _(" Yum version groups:") + print((_(" Yum version groups:"))) for group in sorted(groups): - print " ", group + print((" ", group)) return 0, ['version grouplist'] @@ -1266,11 +1266,11 @@ class VersionCommand(YumCommand): for group in groups: if group not in extcmds[1:]: continue - print _(" Group :"), group - print _(" Packages:") + print((_(" Group :"), group)) + print((_(" Packages:"))) if not verbose: for pkgname in sorted(groups[group]): - print " ", pkgname + print((" ", pkgname)) else: data = {'envra' : {}, 'rid' : {}} pkg_names = groups[group] @@ -1307,7 +1307,7 @@ class VersionCommand(YumCommand): cols.append(("%s %s" % (_("Group-Installed:"), grp), str(data[2][grp]))) _append_repos(cols, data[3][grp]) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] if vcmd in ('available', 'all', 'group-available', 'group-all'): try: @@ -1326,7 +1326,7 @@ class VersionCommand(YumCommand): str(data[2][grp]))) if verbose: _append_repos(cols, data[3][grp]) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [str(e)] data = {'rid' : {}, 'ver' : {}} @@ -1339,7 +1339,7 @@ class VersionCommand(YumCommand): columns = (-columns[0], columns[1]) for line in cols: - print base.fmtColumns(zip(line, columns)) + print((base.fmtColumns(list(zip(line, columns))))) return 0, ['version'] @@ -1368,7 +1368,7 @@ class HistoryCommand(YumCommand): if old is None: return 1, ['Failed history redo'] tm = time.ctime(old.beg_timestamp) - print "Repeating transaction %u, from %s" % (old.tid, tm) + print(("Repeating transaction %u, from %s" % (old.tid, tm))) base.historyInfoCmdPkgsAltered(old) if base.history_redo(old): return 2, ["Repeating transaction %u" % (old.tid,)] @@ -1378,7 +1378,7 @@ class HistoryCommand(YumCommand): if old is None: return 1, ['Failed history undo'] tm = time.ctime(old.beg_timestamp) - print "Undoing transaction %u, from %s" % (old.tid, tm) + print(("Undoing transaction %u, from %s" % (old.tid, tm))) base.historyInfoCmdPkgsAltered(old) if base.history_undo(old): return 2, ["Undoing transaction %u" % (old.tid,)] @@ -1400,14 +1400,14 @@ class HistoryCommand(YumCommand): return 0, ['Rollback to current, nothing to do'] mobj = None - for tid in base.history.old(range(old.tid + 1, last.tid + 1)): + for tid in base.history.old(list(range(old.tid + 1, last.tid + 1))): if not force and (tid.altered_lt_rpmdb or tid.altered_gt_rpmdb): if tid.altered_lt_rpmdb: msg = "Transaction history is incomplete, before %u." else: msg = "Transaction history is incomplete, after %u." - print msg % tid.tid - print " You can use 'history rollback force', to try anyway." + print((msg % tid.tid)) + print(" You can use 'history rollback force', to try anyway.") return 1, ['Failed history rollback, incomplete'] if mobj is None: @@ -1416,9 +1416,9 @@ class HistoryCommand(YumCommand): mobj.merge(tid) tm = time.ctime(old.beg_timestamp) - print "Rollback to transaction %u, from %s" % (old.tid, tm) - print base.fmtKeyValFill(" Undoing the following transactions: ", - ", ".join((str(x) for x in mobj.tid))) + print(("Rollback to transaction %u, from %s" % (old.tid, tm))) + print((base.fmtKeyValFill(" Undoing the following transactions: ", + ", ".join((str(x) for x in mobj.tid))))) base.historyInfoCmdPkgsAltered(mobj) if base.history_undo(mobj): return 2, ["Rollback to transaction %u" % (old.tid,)] @@ -1496,7 +1496,7 @@ class CheckRpmdbCommand(YumCommand): chkcmd = extcmds def _out(x): - print to_unicode(x.__str__()) + print((to_unicode(x.__str__()))) rc = 0 if base._rpmdb_warn_checks(out=_out, warn=False, chkcmd=chkcmd, @@ -1527,7 +1527,7 @@ class LoadTransactionCommand(YumCommand): try: base.load_ts(load_file) - except yum.Errors.YumBaseError, e: + except yum.Errors.YumBaseError as e: return 1, [to_unicode(e)] return 2, [_('Transaction loaded from %s with %s members') % (load_file, len(base.tsInfo.getMembers()))] @@ -72,14 +72,14 @@ def main(args): try: base.closeRpmDB() base.doUnlock() - except Errors.LockError, e: + except Errors.LockError as e: return 200 return 0 def rpmdb_warn_checks(): try: probs = base._rpmdb_warn_checks(out=verbose_logger.info, warn=False) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: # This is mainly for PackageSackError from rpmdb. verbose_logger.info(_(" Yum checks failed: %s"), exception2msg(e)) probs = [] @@ -96,16 +96,16 @@ def main(args): # also sanity check the things being passed on the cli try: base.getOptionsConfig(args) - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: return exFatal(e) # Try to open the current directory to see if we have # read and write access. If not, chdir to / try: f = open(".") - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: logger.critical(_('No read/write access in current directory, moving to /')) os.chdir("/") @@ -116,7 +116,7 @@ def main(args): while True: try: base.doLock() - except Errors.LockError, e: + except Errors.LockError as e: if exception2msg(e) != lockerr: lockerr = exception2msg(e) logger.critical(lockerr) @@ -138,14 +138,14 @@ def main(args): try: result, resultmsgs = base.doCommands() - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: result = 1 resultmsgs = [exception2msg(e)] except KeyboardInterrupt: return exUserCancel() - except IOError, e: + except IOError as e: return exIOError(e) # Act on the command/shell result @@ -179,14 +179,14 @@ def main(args): try: (result, resultmsgs) = base.buildTransaction() - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: result = 1 resultmsgs = [exception2msg(e)] except KeyboardInterrupt: return exUserCancel() - except IOError, e: + except IOError as e: return exIOError(e) # Act on the depsolve result @@ -221,13 +221,13 @@ def main(args): # Run the transaction try: return_code = base.doTransaction() - except plugins.PluginYumExit, e: + except plugins.PluginYumExit as e: return exPluginExit(e) - except Errors.YumBaseError, e: + except Errors.YumBaseError as e: return exFatal(e) except KeyboardInterrupt: return exUserCancel() - except IOError, e: + except IOError as e: return exIOError(e) # rpm ts.check() failed. @@ -295,6 +295,6 @@ suppress_keyboard_interrupt_message() if __name__ == "__main__": try: user_main(sys.argv[1:], exit_code=True) - except KeyboardInterrupt, e: - print >> sys.stderr, _("\n\nExiting on user cancel.") + except KeyboardInterrupt as e: + print(_("\n\nExiting on user cancel."), file=sys.stderr) sys.exit(1) |