diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ee013bd1..16659541 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.7, 3.8, 3.9, "3.10", "3.11"] + python-version: [3.7, 3.8, 3.9, "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v3 diff --git a/.gitignore b/.gitignore index 2df594df..47cc69e9 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,6 @@ bin/setups.zsh TAGS autom4te.cache eups_impl.py -eups +bin/eups bin/eups_setup bin/eups_setup_impl.py diff --git a/Makefile.in b/Makefile.in index cd9b4b8f..183d1096 100644 --- a/Makefile.in +++ b/Makefile.in @@ -127,7 +127,7 @@ configure : configure.ac tests : test test : @ echo "Running tests" - "$(EUPS_PYTHON)" tests/testAll.py + "$(EUPS_PYTHON)" -Wd tests/testAll.py @ echo "Running server tests (requires network)" "$(EUPS_PYTHON)" tests/testServerAll.py clean : diff --git a/bin/eups.in b/bin/eups.in index 9c2d2491..9e4e13b5 100644 --- a/bin/eups.in +++ b/bin/eups.in @@ -2,7 +2,6 @@ # # The main eups programme # -from __future__ import print_function import sys import os diff --git a/bin/eups_setup.in b/bin/eups_setup.in index e6f3508d..8393b446 100644 --- a/bin/eups_setup.in +++ b/bin/eups_setup.in @@ -2,7 +2,6 @@ # # The EUPS setup programme # -from __future__ import print_function import sys, os, re sys.argv[0] = "eups" diff --git a/bin/mksetup b/bin/mksetup index 95ffb5f5..0dc85161 100755 --- a/bin/mksetup +++ b/bin/mksetup @@ -1,6 +1,5 @@ #!/usr/bin/env python # -from __future__ import print_function import os, re, sys sys.argv.pop(0) # remove script name @@ -27,7 +26,6 @@ setup = os.path.join('$EUPS_DIR',"bin","eups_setup"); # Keep only one copy of each directory in sys.argv[1], but make sure that sys.argv[2] is present unique_path=""" -from __future__ import print_function import sys pp = [] for d in sys.argv[1].split(":"): diff --git a/callbacks/distribInstallPostHook.py b/callbacks/distribInstallPostHook.py index ef11a684..d38a4589 100644 --- a/callbacks/distribInstallPostHook.py +++ b/callbacks/distribInstallPostHook.py @@ -5,10 +5,7 @@ be critical (e.g. to patch up os/x's SIP protection) """ -from __future__ import absolute_import, print_function - from distutils.spawn import find_executable -import io import locale import mmap import re @@ -98,7 +95,7 @@ def fix_shebang(path, build_python, verbose=0): return prefenc = locale.getpreferredencoding() - with io.open(path, encoding=prefenc, mode='r+') as fi: + with open(path, encoding=prefenc, mode='r+') as fi: try: data = fi.read(100) fi.seek(0) @@ -139,7 +136,7 @@ def fix_shebang(path, build_python, verbose=0): # save original file mode mode = os.stat(path).st_mode - with io.open(path, 'w', encoding=encoding) as fo: + with open(path, 'w', encoding=encoding) as fo: fo.write(new_data.decode(encoding)) # restore file mode os.chmod(path, mode) diff --git a/python/eups/Eups.py b/python/eups/Eups.py index 7a98abb2..aba733ad 100644 --- a/python/eups/Eups.py +++ b/python/eups/Eups.py @@ -1,7 +1,6 @@ """ The Eups class """ -from __future__ import absolute_import, print_function import glob import re import os @@ -23,7 +22,7 @@ from .utils import cmp_or_key, xrange, cmp from . import hooks -class Eups(object): +class Eups: """ An application interface to EUPS functionality. @@ -45,7 +44,7 @@ class Eups(object): # managed software stack ups_db = "ups_db" - # staticmethod; would use a decorator if we knew we had a new enough python + @staticmethod def setEupsPath(path=None, dbz=None): if not path: path = os.environ.get("EUPS_PATH", []) @@ -71,9 +70,7 @@ def setEupsPath(path=None, dbz=None): os.environ["EUPS_PATH"] = ":".join(eups_path) return eups_path - setEupsPath = staticmethod(setEupsPath) - - # staticmethod; would use a decorator if we knew we had a new enough python + @staticmethod def _processDefaultTags(opts): """Handle any default tags defined as hooks""" if opts.tag in (["None"], [""]): @@ -104,8 +101,6 @@ def _processDefaultTags(opts): if not (hasattr(opts, "unsetup") and opts.unsetup): print(msg, "; ".join(tagMsg), file=utils.stdinfo) - _processDefaultTags = staticmethod(_processDefaultTags) - def __init__(self, flavor=None, path=None, dbz=None, root=None, readCache=True, shell=None, verbose=0, quiet=0, noaction=False, force=False, ignore_versions=False, @@ -513,14 +508,11 @@ def _userStackCache(self, eupsPathDir): def _makeUserCacheDir(self, eupsPathDir): cachedir = self._userStackCache(eupsPathDir) if cachedir and not os.path.exists(cachedir): - os.makedirs(cachedir) + os.makedirs(cachedir, exist_ok=True) try: - readme = open(os.path.join(cachedir,"README"), "w") - try: + with open(os.path.join(cachedir,"README"), "w") as readme: print("User cache directory for", eupsPathDir, file=readme) - finally: - readme.close() - except: + except Exception: pass return cachedir @@ -1220,7 +1212,7 @@ def _findTaggedProductFromFile(self, name, fileName, eupsPathDirs=None, flavor=N try: fd = open(fileName, "r") - except IOError: + except OSError: raise TagNotRecognized(str(fileName)) version = None @@ -1459,7 +1451,7 @@ def getUpsDB(self, eupsPathDir, create=False, noRaise=False): if not os.path.isdir(upsDB): if create: - os.makedirs(upsDB) + os.makedirs(upsDB, exist_ok=True) if not os.path.isdir(upsDB): if noRaise: @@ -2414,7 +2406,7 @@ def declare(self, productName, versionName, productDir=None, eupsPathDir=None, t if self.isUserTag(tag): ups_db = self.getUpsDB(self.userDataDir) if not os.path.isdir(ups_db): - os.makedirs(ups_db) + os.makedirs(ups_db, exist_ok=True) eupsPathDir = self.userDataDir if not eupsPathDir: @@ -2469,7 +2461,7 @@ def cleanup(*args): umask = os.umask(0o02); os.umask(umask) try: perms = os.fstat(tfd.fileno()).st_mode - except: + except Exception: perms = 0 perms |= (0o666 & ~umask) # set read/write for everyone (modulu umask) @@ -2580,8 +2572,10 @@ def cleanup(*args): if not os.path.exists(pathOut): differences += ["Adding %s" % pathOut] else: - crcOld = zlib.crc32(open(fileNameIn, "rb").read()) - crcNew = zlib.crc32(open(pathOut, "rb").read()) + with open(fileNameIn, "rb") as fd: + crcOld = zlib.crc32(fd.read()) + with open(pathOut, "rb") as fd: + crcNew = zlib.crc32(fd.read()) if crcOld != crcNew: differences += ["%s's CRC32 changed" % pathOut] @@ -2719,7 +2713,7 @@ def cleanup(*args): else: if self.verbose > 1: print("mkdir -p %s" % (dirName), file=utils.stdinfo) - os.makedirs(dirName) + os.makedirs(dirName, exist_ok=True) if not (os.path.exists(pathOut) and os.path.samefile(fileNameIn, pathOut)): if self.noaction: @@ -3272,7 +3266,7 @@ def remove(self, productName, versionName, recursive=False, checkRecursive=False if interactive: yn = default_yn while yn != "!": - yn = raw_input("Remove %s %s: (ynq!) [%s] " % (product.name, product.version, default_yn)) + yn = input("Remove %s %s: (ynq!) [%s] " % (product.name, product.version, default_yn)) if yn == "": yn = default_yn @@ -3724,7 +3718,7 @@ def selectVRO(self, tag=None, productDir=None, versionName=None, dbz=None, inexa self._vro = self.preferredTags # we should get rid of preferredTags; it's left over from Ray Plante - # staticmethod; would use a decorator if we knew we had a new enough python + @staticmethod def __mergeWarnings(vro): """Replace consecutive sequences of warn:X by warn:min (otherwise we may get repeated warnings); such sequences can be generated while rewriting the VRO""" @@ -3756,8 +3750,6 @@ def __mergeWarnings(vro): return cleanedVro - __mergeWarnings = staticmethod(__mergeWarnings) - def makeVroExact(self): """Modify the VRO to support setup --exact even if the table files don't have an if(type == exact) { block }""" @@ -3822,7 +3814,7 @@ def getVRO(self): _ClassEups = Eups # so we can say, "isinstance(Eups, _ClassEups)" -class _TagSet(object): +class _TagSet: def __init__(self, eups, tags): self.eups = eups self.lu = {} diff --git a/python/eups/Product.py b/python/eups/Product.py index 5935f74a..e81092ce 100644 --- a/python/eups/Product.py +++ b/python/eups/Product.py @@ -1,11 +1,8 @@ # from Table import * -from __future__ import absolute_import, print_function import os import re -try: - from configparser import ConfigParser -except ImportError: - from ConfigParser import ConfigParser +from configparser import ConfigParser + from . import table as mod_table from . import utils from .exceptions import ProductNotFound, TableFileNotFound @@ -16,7 +13,7 @@ "UPS_DIR": re.compile(r"^\$UPS_DIR\b"), "UPS_DB": re.compile(r"^\$UPS_DB\b") } -class Product(object): +class Product: """ a description of a Product as stored in the stack database. @@ -464,7 +461,7 @@ def getConfig(self, section="DEFAULT", option=None, getType=None): return config # this replaces from initFromDirectory() - # @staticmethod # requires python 2.4 + @staticmethod def createLocal(productName, productDir, flavor=None, checkForTable=True, tablefile=None): localDir = Product._decode_dir(productDir) if localDir: @@ -482,8 +479,6 @@ def createLocal(productName, productDir, flavor=None, checkForTable=True, tablef if not os.path.exists(out.tablefile): out.tablefile = "none" return out - createLocal = staticmethod(createLocal) # should work as of python 2.2 - def envarDirName(self): return utils.dirEnvNameFor(self.name) diff --git a/python/eups/Uses.py b/python/eups/Uses.py index 046c78fe..4f5980b8 100644 --- a/python/eups/Uses.py +++ b/python/eups/Uses.py @@ -8,13 +8,13 @@ # # Cache for the Uses tree # -class Props(object): +class Props: def __init__(self, version, optional, depth): self.version = version self.optional = optional self.depth = depth -class Uses(object): +class Uses: """ a class for tracking product dependencies. Typically an instance of this class is created via a call to Eups.uses(). This class is used diff --git a/python/eups/VersionCompare.py b/python/eups/VersionCompare.py index c3b6b4cc..2d4220a1 100644 --- a/python/eups/VersionCompare.py +++ b/python/eups/VersionCompare.py @@ -2,7 +2,7 @@ from .utils import cmp -class VersionCompare(object): +class VersionCompare: """ A comparison function class that compares two product versions. """ diff --git a/python/eups/VersionParser.py b/python/eups/VersionParser.py index f33c5ed5..1e28c0d3 100644 --- a/python/eups/VersionParser.py +++ b/python/eups/VersionParser.py @@ -3,7 +3,7 @@ import os import re -class VersionParser(object): +class VersionParser: """Evaluate a logical expression, returning a Bool. The grammar is: expr : term diff --git a/python/eups/__init__.py b/python/eups/__init__.py index 05225994..04834ff5 100644 --- a/python/eups/__init__.py +++ b/python/eups/__init__.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import from .exceptions import * from .tags import Tags, Tag, TagNotRecognized from .Product import Product diff --git a/python/eups/app.py b/python/eups/app.py index 38501571..cae3fdb0 100644 --- a/python/eups/app.py +++ b/python/eups/app.py @@ -2,14 +2,10 @@ common high-level EUPS functions appropriate for calling from an application. """ -from __future__ import absolute_import, print_function import fnmatch import re import os -try: - import cPickle as pickle -except ImportError: - import pickle +import pickle from .distrib import builder from .Eups import Eups from .exceptions import ProductNotFound @@ -19,7 +15,7 @@ from .stack import ProductStack, persistVersionName as cacheVersion from . import utils, table, hooks from .exceptions import EupsException -from .utils import cmp_or_key, cmp +from .utils import cmp_or_key def printProducts(ostrm, productName=None, versionName=None, eupsenv=None, tags=None, setup=False, tablefile=False, directory=False, diff --git a/python/eups/cmd.py b/python/eups/cmd.py index fdb05c2f..d26d6e13 100644 --- a/python/eups/cmd.py +++ b/python/eups/cmd.py @@ -31,7 +31,6 @@ # ######################################################################## -from __future__ import absolute_import, print_function import re import os import sys @@ -47,7 +46,7 @@ _errstrm = utils.stderr -class EupsCmd(object): +class EupsCmd: """ A class for defining and executing the EUPS command-line tool. @@ -170,7 +169,7 @@ def execute(self): try: return ecmd.run() - except: + except Exception: raise finally: lock.giveLocks(locks, ecmd.opts.verbose) @@ -348,7 +347,7 @@ def createEups(self, opts=None, versionName=None, readCache=None, quiet=0): #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -class CommandCallbacks(object): +class CommandCallbacks: """Callback to allow users to customize behaviour by defining hooks in EUPS_STARTUP and calling eups.commandCallbacks.add(hook)""" @@ -943,7 +942,7 @@ def execute(self): return 6 try: ifd = open(inFile) - except IOError as e: + except OSError as e: self.err('Failed to open file "%s" for read: %s' % (inFile, str(e))) return 6 @@ -955,7 +954,7 @@ def execute(self): try: ofd = open(outfile, "w") - except IOError as e: + except OSError as e: self.err('Failed to open file "%s" for write: %s' % (outfile, str(e))) return 6 @@ -965,7 +964,7 @@ def execute(self): "."+os.path.basename(inFile)+".tmp") try: ofd = open(tmpout, "w") - except IOError as e: + except OSError as e: outfile = os.path.dirname(tmpout) if not outfile: outfile = "." self.err('Failed to temporary file in "%s" for write: %s' % @@ -1086,7 +1085,7 @@ def execute(self): return 6 try: ifd = open(inFile) - except IOError as e: + except OSError as e: self.err('Failed to open file "%s" for read: %s' % (inFile, str(e))) return 6 @@ -1098,7 +1097,7 @@ def execute(self): try: ofd = open(outfile, "w") - except IOError as e: + except OSError as e: self.err('Failed to open file "%s" for write: %s' % (outfile, str(e))) return 6 @@ -1108,7 +1107,7 @@ def execute(self): "."+os.path.basename(inFile)+".tmp") try: ofd = open(tmpout, "w") - except IOError as e: + except OSError as e: outfile = os.path.dirname(tmpout) if not outfile: outfile = "." self.err('Failed to temporary file in "%s" for write: %s' % @@ -1278,7 +1277,7 @@ def execute(self): else: try: tablefile = open(self.opts.externalTablefile, "r") - except IOError as e: + except OSError as e: self.err("Error opening %s: %s" % (self.opts.externalTablefile, e)) return 4 @@ -1653,7 +1652,7 @@ def execute(self): try: lock.clearLocks(path, self.opts.verbose, self.opts.noaction) - except IOError: + except OSError: pass return 0 @@ -1687,7 +1686,7 @@ def execute(self): try: lock.listLocks(path, self.opts.verbose, self.opts.noaction) - except IOError: + except OSError: pass return 0 @@ -2615,7 +2614,7 @@ def execute(self): break elif not os.path.exists(self.opts.serverDir): self.err("Server directory %s does not exist; creating " % self.opts.serverDir) - os.makedirs(self.opts.serverDir) + os.makedirs(self.opts.serverDir, exist_ok=True) elif not utils.isDbWritable(self.opts.serverDir): self.err("Server directory %s is not writable: " % self.opts.serverDir) return 3 @@ -2729,7 +2728,7 @@ def isDependent(product, searchList): doRebuild = True try: doRebuild = not p.getConfig("distrib", "binary", getType=bool) - except: + except Exception: pass if doRebuild: if self.opts.verbose: @@ -2982,7 +2981,7 @@ def execute(self): try: isatty = os.isatty(sys.stdout.fileno()) - except: + except Exception: isatty = False if isatty: diff --git a/python/eups/db/ChainFile.py b/python/eups/db/ChainFile.py index 2f68df54..711fa68c 100644 --- a/python/eups/db/ChainFile.py +++ b/python/eups/db/ChainFile.py @@ -1,4 +1,3 @@ -from __future__ import print_function import os import re import errno @@ -6,7 +5,7 @@ who = getUserName(full=True) -class ChainFile(object): +class ChainFile: """ a representation of the data contained in a product tag chain file. This file records which version of a product a particular tag is @@ -43,7 +42,7 @@ def __init__(self, file, productName=None, tag=None, verbosity=0, if readFile: try: self._read(self.file, verbosity) - except IOError as e: + except OSError as e: # It's not an error if the file didn't exist if e.errno != errno.ENOENT: raise diff --git a/python/eups/db/Database.py b/python/eups/db/Database.py index 5e811986..a439b60c 100644 --- a/python/eups/db/Database.py +++ b/python/eups/db/Database.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import os import re from .VersionFile import VersionFile @@ -54,7 +52,7 @@ def Database(dbpath, userTagRoot=None, defStackRoot=None, owner=None): return _databases[key] -class _Database(object): +class _Database: """ An interface to the product database recorded on disk. This interface will enforce restrictions on product names, flavors, and versions. @@ -460,7 +458,7 @@ def declare(self, product): # seal the deal if not os.path.exists(pdir): - os.mkdir(pdir) + os.makedirs(pdir, exist_ok=True) if prod.dir: trimDir = prod.stackRoot() @@ -514,7 +512,7 @@ def undeclare(self, product): if not os.path.exists(vfile): try: os.rmdir(pdir) - except: + except Exception: pass return changed @@ -618,7 +616,7 @@ def assignTag(self, tag, productName, version, flavors=None, writeableDB=None): pdir = self._productDir(productName, writeableDB) if not os.path.exists(pdir): - os.makedirs(pdir) + os.makedirs(pdir, exist_ok=True) else: pdir = self._productDir(productName) @@ -727,5 +725,3 @@ def _cmp_str(a, b): if a < b: return -1 if a > b: return 1 return 0 - - diff --git a/python/eups/db/VersionFile.py b/python/eups/db/VersionFile.py index 8266b5ff..5dd2de61 100644 --- a/python/eups/db/VersionFile.py +++ b/python/eups/db/VersionFile.py @@ -1,4 +1,3 @@ -from __future__ import print_function import os import re from eups.Product import Product @@ -9,7 +8,7 @@ who = eups.utils.getUserName(full=True) defaultProductUpsDir = "ups" -class VersionFile(object): +class VersionFile: """ A representation of the declaration information stored in a version file for a particular product declared in an EUPS database. @@ -179,21 +178,6 @@ def makeProduct(self, flavor, eupsPathDir=None, dbpath=None): return out - def _resolve(self, value, data, skip=None): - if not value: return value - - dosub = list(data.keys()) - if skip: - if eups.utils.is_string(skip): - skip = skip.split() - dosub = [n for n in dosub if n not in skip] - - for name in dosub: - if name in macrore and data[name]: - value = macrore[name].sub(data[name], value) - - return value - def makeProducts(self): """ return Product instances for all of the flavors declared in the file. @@ -529,6 +513,3 @@ def write(self, trimDir=None, file=None): print("End:", file=fd) fd.close() - - - diff --git a/python/eups/debug.py b/python/eups/debug.py index 268ae892..a56dd56f 100644 --- a/python/eups/debug.py +++ b/python/eups/debug.py @@ -3,7 +3,6 @@ N.b. can't go in utils.py as utils is imported be eups, and we need to import eups.Eups here """ -from __future__ import print_function import re import sys import eups.Eups diff --git a/python/eups/distrib/Distrib.py b/python/eups/distrib/Distrib.py index 0b6dc5eb..0c34863c 100755 --- a/python/eups/distrib/Distrib.py +++ b/python/eups/distrib/Distrib.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package # -from __future__ import absolute_import, print_function import sys import os import re @@ -15,7 +14,7 @@ from eups.exceptions import EupsException from . import server -class Distrib(object): +class Distrib: """A class to encapsulate product distribution This class is an abstract base class with some default implementation. @@ -135,7 +134,7 @@ def __init__(self, Eups, distServ, flavor=None, tag="current", options=None, self._alwaysExpandTableFiles = True # returned by self.alwaysExpandTableFiles() - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only we recognize the given distribution identifier @@ -144,8 +143,6 @@ def parseDistID(distID): """ return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def checkInit(self, forserver=True): """Check that self is properly initialised; this matters for subclasses with special needs""" @@ -157,7 +154,7 @@ def initServerTree(self, serverDir): @param serverDir the directory to initialize """ if not os.path.exists(serverDir): - os.makedirs(serverDir) + os.makedirs(serverDir, exist_ok=True) def createPackage(self, serverDir, product, version, flavor=None, overwrite=False): """Write a package distribution into server directory tree and @@ -418,7 +415,7 @@ def getDependencies(productName, version): product = self.Eups.getProduct(productName, version) dependencies = self.Eups.getDependentProducts(product, productDictionary={}, topological=True) - except: + except Exception: return None return dependencies @@ -524,7 +521,7 @@ def lookupProduct(product, version): else: try: (baseDir, productDir) = re.search(r"^(\S+)/(%s/\S*)$" % (product), pinfo.dir).groups() - except: + except Exception: if self.verbose > 1: print("Split of \"%s\" at \"%s\" failed; proceeding" \ % (pinfo.dir, product), file=self.log) @@ -536,7 +533,7 @@ def lookupProduct(product, version): if self.verbose > 1: print("Guessing \"%s\" has productdir \"%s\"" \ % (pinfo.dir, productDir), file=self.log) - except: + except Exception: if self.verbose: print("Again failed to split \"%s\" into baseDir and productdir" \ % (pinfo.dir), file=self.log) @@ -648,7 +645,7 @@ def initServerTree(self, serverDir): for dir in "manifests tables".split(): dir = os.path.join(serverDir, dir) if not os.path.exists(dir): - os.makedirs(dir) + os.makedirs(dir, exist_ok=True) # set group owner ship and permissions, if desired self.setGroupPerms(dir) @@ -764,7 +761,7 @@ def writeManifest(self, serverDir, productDeps, product, version, out = self.getManifestPath(serverDir, product, version, self.flavor) mandir = os.path.dirname(out) if not os.path.exists(mandir): - os.makedirs(mandir) + os.makedirs(mandir, exist_ok=True) man = server.Manifest(product, version, self.Eups, verbosity=self.verbose-1, log=self.log) @@ -919,7 +916,7 @@ def findTableFile(self, product, version, flavor): # except KeyboardInterrupt: # raise RuntimeError, ("You hit ^C while looking for %s %s's table file" % # (product, version)) - # except: + # except Exception: # pass # return tablefile diff --git a/python/eups/distrib/DistribFactory.py b/python/eups/distrib/DistribFactory.py index acc8ad2c..ab1937b4 100644 --- a/python/eups/distrib/DistribFactory.py +++ b/python/eups/distrib/DistribFactory.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package: a specialization for Pacman # -from __future__ import absolute_import import sys import re import copy @@ -211,7 +210,7 @@ class NoneDistrib(Distrib): def __init__(self, *args, **kwargs): Distrib.__init__(self, *args, **kwargs) - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only if we recognize the given distribution identifier""" if distID == 'None': @@ -219,8 +218,6 @@ def parseDistID(distID): return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def installPackage(self, *args, **kwargs): """Install a package with a given server location into a given product directory tree. """ diff --git a/python/eups/distrib/Repositories.py b/python/eups/distrib/Repositories.py index 88f0a4b2..0059fffc 100644 --- a/python/eups/distrib/Repositories.py +++ b/python/eups/distrib/Repositories.py @@ -2,7 +2,6 @@ the Repositories class -- a set of distribution servers from which distribution packages can be received and installed. """ -from __future__ import absolute_import, print_function import sys import os import re @@ -19,7 +18,7 @@ from .server import Manifest, ServerError, RemoteFileInvalid import eups.hooks as hooks -class Repositories(object): +class Repositories: DEPS_NONE = 0 DEPS_ALL = 1 @@ -773,7 +772,7 @@ def _recordDistID(self, pkgroot, distId, installDir): print(pkgroot, file=fd) finally: fd.close() - except: + except Exception: if self.verbose >= 0: print("Warning: Failed to write distID to %s: %s" % (file, traceback.format_exc(0)), file=self.log) @@ -859,7 +858,7 @@ def expandTableFile(tablefile): tablefile = open(tablefile, "r") else: if upsdir and not os.path.exists(upsdir): - os.makedirs(upsdir) + os.makedirs(upsdir, exist_ok=True) tablefile = \ repos.distServer.getFileForProduct(mprod.tablefile, mprod.product, @@ -909,7 +908,7 @@ def getBuildDirFor(self, productRoot, product, version, options=None, # Can we write to that directory? # try: - os.makedirs(buildRoot) # make sure it exists if we have the power to do so + os.makedirs(buildRoot, exist_ok=True) # make sure it exists if we have the power to do so except OSError: # already exists, or failed; we don't care which pass @@ -927,7 +926,7 @@ def getBuildDirFor(self, productRoot, product, version, options=None, buildRoot = bd else: try: - os.makedirs(bd) + os.makedirs(bd, exist_ok=True) except Exception as e: pass else: @@ -954,7 +953,7 @@ def makeBuildDirFor(self, productRoot, product, version, options=None, """ dir = self.getBuildDirFor(productRoot, product, version, options, flavor) if not os.path.exists(dir): - os.makedirs(dir) + os.makedirs(dir, exist_ok=True) return dir def cleanBuildDirFor(self, productRoot, product, version, options=None, diff --git a/python/eups/distrib/Repository.py b/python/eups/distrib/Repository.py index 0d372e03..bbe3d4d5 100644 --- a/python/eups/distrib/Repository.py +++ b/python/eups/distrib/Repository.py @@ -2,18 +2,17 @@ the Repository class -- An interface into a distribution server for installing and deploying distribution packages. """ -from __future__ import absolute_import, print_function import sys import eups from eups.tags import Tag, TagNotRecognized -from eups.utils import Flavor, isDbWritable, cmp_or_key, xrange, is_string +from eups.utils import Flavor, isDbWritable, cmp_or_key, is_string from eups.exceptions import EupsException, ProductNotFound from .server import ServerConf, Manifest, Mapping, TaggedProductList from .server import LocalTransporter from .DistribFactory import DistribFactory from .Distrib import Distrib, DefaultDistrib -class Repository(object): +class Repository: """ an interface into a distribution server for handling package installation and creation requests. diff --git a/python/eups/distrib/__init__.py b/python/eups/distrib/__init__.py index e43aea0b..477d8a42 100644 --- a/python/eups/distrib/__init__.py +++ b/python/eups/distrib/__init__.py @@ -27,7 +27,6 @@ above concrete implementations use these assumptions and thus inherit from DefaultDistrib. """ -from __future__ import absolute_import from .Repositories import Repositories from .Repository import Repository from .Distrib import Distrib, DefaultDistrib, findInstallableRoot diff --git a/python/eups/distrib/builder.py b/python/eups/distrib/builder.py index cda97107..173c077d 100755 --- a/python/eups/distrib/builder.py +++ b/python/eups/distrib/builder.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package: a specialization for the "Builder" mechanism # -from __future__ import absolute_import, print_function import sys import os, re from . import Distrib as eupsDistrib @@ -66,7 +65,7 @@ def __init__(self, Eups, distServ, flavor, tag="current", options=None, - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only we recognize the given distribution identifier @@ -81,8 +80,6 @@ def parseDistID(distID): return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def checkInit(self, forserver=True): """Check that self is properly initialised; this matters for subclasses with special needs""" @@ -214,8 +211,8 @@ def createPackage(self, serverDir, product, version, flavor=None, overwrite=Fals builderDir = os.path.join(serverDir, "builds") if not os.path.isdir(builderDir): try: - os.makedirs(builderDir) - except: + os.makedirs(builderDir, exist_ok=True) + except Exception: raise RuntimeError("Failed to create %s" % (builderDir)) full_builder = os.path.join(builderDir, builder) @@ -234,11 +231,11 @@ def createPackage(self, serverDir, product, version, flavor=None, overwrite=Fals else: try: ifd = open(buildFile) - except IOError as e: + except OSError as e: raise RuntimeError("Failed to open file \"%s\" for read" % buildFile) try: ofd = open(full_builder, "w") - except IOError as e: + except OSError as e: raise RuntimeError("Failed to open file \"%s\" for write" % full_builder) builderVars = eups.hooks.config.distrib["builder"]["variables"] @@ -255,7 +252,7 @@ def createPackage(self, serverDir, product, version, flavor=None, overwrite=Fals raise RuntimeError("Failed to expand build file \"%s\": %s" % (full_builder, e)) del ifd; del ofd - except IOError as param: + except OSError as param: try: os.unlink(full_builder) except OSError: @@ -353,7 +350,7 @@ def installPackage(self, location, product, version, productRoot, else: try: fd = open(tfile) - except IOError as e: + except OSError as e: raise RuntimeError("Failed to open %s: %s" % (tfile, e)) for line in fd: @@ -396,7 +393,8 @@ def installPackage(self, location, product, version, productRoot, print("Issuing commands:") print("\t", str.join("\n\t", cmd)) - print(str.join("\n\t", cmd), file=file(logfile, "w")) + with open(logfile, "w") as fd: + print(str.join("\n\t", cmd), file=fd) if False: cmd = "(%s) 2>&1 | tee >> %s" % (str.join("\n", cmd), logfile) @@ -411,7 +409,7 @@ def installPackage(self, location, product, version, productRoot, try: print("BUILD ERROR! From build log:", file=self.log) eupsServer.system("tail -20 %s 1>&2" % logfile) - except: + except Exception: pass raise RuntimeError("Failed to build %s: %s" % (builder, str(e))) @@ -466,7 +464,7 @@ def find_file_on_path(self, fileName, auxDir = None): #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -class BuildfilePatchCallbacks(object): +class BuildfilePatchCallbacks: """Callbacks to modify build files. E.g. we can define a callback to rewrite SVN root to recognise a tagname @@ -551,7 +549,7 @@ def guess_cvsroot(cvsroot): rfd = open("CVS/Root") cvsroot = re.sub(r"\n$", "", rfd.readline()) del rfd - except IOError as e: + except OSError as e: print("Tried to read \"CVS/Root\" but failed: %s" % e, file=sys.stderr) return cvsroot @@ -581,7 +579,7 @@ def guess_svnroot(svnroot): break del rfd - except IOError as e: + except OSError as e: print("Tried to read \".svn\" but failed: %s" % e, file=sys.stderr) return svnroot diff --git a/python/eups/distrib/dream.py b/python/eups/distrib/dream.py index 5e13e9a9..d053825d 100644 --- a/python/eups/distrib/dream.py +++ b/python/eups/distrib/dream.py @@ -1,6 +1,5 @@ #!/usr/bin/env python -from __future__ import absolute_import import re import os.path import eups diff --git a/python/eups/distrib/eupspkg.py b/python/eups/distrib/eupspkg.py index 10016827..63b341d2 100755 --- a/python/eups/distrib/eupspkg.py +++ b/python/eups/distrib/eupspkg.py @@ -670,7 +670,6 @@ """ -from __future__ import absolute_import, print_function import sys, os, shutil, tempfile, shlex, stat from . import Distrib as eupsDistrib from . import server as eupsServer @@ -705,7 +704,7 @@ def __init__(self, Eups, distServ, flavor=None, tag="current", options=None, knownopts = set(['config', 'nobuild', 'noclean', 'noaction', 'exact', 'allowIncomplete', 'buildDir', 'noeups', 'installCurrent']); self.qopts = " ".join( "%s=%s" % (k.upper(), shlex.quote(str(v))) for k, v in self.options.items() if k not in knownopts ) - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only we recognize the given distribution identifier @@ -720,8 +719,6 @@ def parseDistID(distID): return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def initServerTree(self, serverDir): """initialize the given directory to serve as a package distribution tree. @@ -747,7 +744,7 @@ def initServerTree(self, serverDir): # Create the tags storage directory tagsDir = os.path.join(serverDir, 'tags') if not os.path.exists(tagsDir): - os.mkdir(tagsDir) + os.makedirs(tagsDir, exist_ok=True) def getTaggedReleasePath(self, tag, flavor=None): @@ -833,8 +830,8 @@ def createPackage(self, serverDir, product, version, flavor=None, overwrite=Fals productsDir = os.path.join(serverDir, "products") if not os.path.isdir(productsDir): try: - os.makedirs(productsDir) - except: + os.makedirs(productsDir, exist_ok=True) + except Exception: raise RuntimeError("Failed to create %s" % (productsDir)) tfn = os.path.join(productsDir, "%s-%s.eupspkg" % (product, version)) @@ -1071,7 +1068,7 @@ def installPackage(self, location, product, version, productRoot, try: print("\n\n***** error: from %s:" % logfile, file=self.log) eupsServer.system("tail -20 %s 1>&2" % q(logfile)) - except: + except Exception: pass raise RuntimeError("Failed to build %s: %s" % (pkg, str(e))) diff --git a/python/eups/distrib/pacman.py b/python/eups/distrib/pacman.py index 93635bed..f176c9b8 100644 --- a/python/eups/distrib/pacman.py +++ b/python/eups/distrib/pacman.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package: a specialization for Pacman # -from __future__ import print_function import sys, os from . import Distrib as eupsDistrib from . import server as eupsServer @@ -43,7 +42,7 @@ def __init__(self, Eups, distServ, flavor, tag="current", options=None, self.distServer is not None: self.options['pacmanCache'] = self.distServer.base + "/pm" - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only we recognize the given distribution identifier @@ -58,8 +57,6 @@ def parseDistID(distID): return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def checkInit(self, forserver=True): """Check that self is properly initialised; this matters for subclasses with special needs""" @@ -207,7 +204,7 @@ def createPacmanDir(self, pacmanDir): pacman -install http://dev.lsstcorp.org/pkgs/pm:LSSTinit """ if not os.path.isdir(pacmanDir): - os.mkdir(pacmanDir) + os.makedirs(pacmanDir, exist_ok=True) def cleanPackage(self, product, version, productRoot, location): """remove any distribution-specific remnants of a package installation. diff --git a/python/eups/distrib/server.py b/python/eups/distrib/server.py index 772c7c03..05a569fc 100644 --- a/python/eups/distrib/server.py +++ b/python/eups/distrib/server.py @@ -3,7 +3,6 @@ """ classes for communicating with a remote package server """ -from __future__ import print_function import sys import os import re @@ -28,7 +27,7 @@ BASH = "/bin/bash" # see end of this module where we look for bash dirCache = dict() # cache listDir results -class DistribServer(object): +class DistribServer: """a class that encapsulates the communication with a package server. This class allows the mechanisms (e.g. the URLs) used to retrieve @@ -391,7 +390,7 @@ def cacheFile(self, filename, source, noaction=False): # make sure we can write to destination parent = os.path.dirname(filename) if parent and not os.path.isdir(parent): - os.makedirs(parent) + os.makedirs(parent, exist_ok=True) trx.cacheToFile(filename, noaction=noaction) # this is not a cache! It's "copy to local file" @@ -953,20 +952,18 @@ def __init__(self, message, exc=None): """ TransporterError.__init__(self, message, exc) -class Transporter(object): +class Transporter: """a class that understands how to operate a particular transport mechanism. This is an abstract class with an implementation that raises exeptions """ - # @staticmethod # requires python 2.4 + @staticmethod def canHandle(source): """return True if this source location is recognized as one that can be handled by this Transporter class""" return False; - canHandle = staticmethod(canHandle) # should work as of python 2.2 - def __init__(self, source, verbosity=0, log=sys.stderr): """create the transporter. @param source the location of the source file @@ -1000,9 +997,9 @@ def unimplemented(self, name): class WebTransporter(Transporter): """a class that can return files via an HTTP or FTP URL""" - # @staticmethod # requires python 2.4 global poolManager + @staticmethod def canHandle(source): """return True if this source location is recognized as one that can be handled by this Transporter class""" @@ -1010,8 +1007,6 @@ def canHandle(source): bool(re.search(r'^https://', source)) or \ bool(re.search(r'^ftp://', source)) - canHandle = staticmethod(canHandle) # should work as of python 2.2 - def cacheToFile(self, filename, noaction=False): """cache the source to a local file @param filename the name of the file to cache to @@ -1153,14 +1148,12 @@ def __init__(self, source, verbosity=0, log=sys.stderr): Transporter.__init__(self, source, verbosity, log); self.remfile = re.sub(r'^scp:', '', self.loc) - # @staticmethod # requires python 2.4 + @staticmethod def canHandle(source): """return True if this source location is recognized as one that can be handled by this Transporter class""" return bool(re.search(r'^scp:', source)) - canHandle = staticmethod(canHandle) # should work as of python 2.2 - def cacheToFile(self, filename, noaction=False): """cache the source to a local file @param filename the name of the file to cache to @@ -1172,7 +1165,7 @@ def cacheToFile(self, filename, noaction=False): try: system("scp -q %s %s 2>/dev/null" % (self.remfile, filename), noaction, self.verbose) - except IOError as e: + except OSError as e: if e.errno == 2: raise RemoteFileNotFound("%s: file not found" % self.loc) else: @@ -1230,15 +1223,13 @@ class LocalTransporter(Transporter): def __init__(self, source, verbosity=0, log=sys.stderr): Transporter.__init__(self, source, verbosity, log); - # @staticmethod # requires python 2.4 + @staticmethod def canHandle(source): """return True if this source location is recognized as one that can be handled by this Transporter class""" return os.path.isabs(source) or os.path.exists(source) or \ not re.match(r'^\w\w+:', source) - canHandle = staticmethod(canHandle) # should work as of python 2.2 - def cacheToFile(self, filename, noaction=False): """cache the source to a local file @param filename the name of the file to cache to @@ -1256,7 +1247,7 @@ def cacheToFile(self, filename, noaction=False): copyfile(self.loc, filename) if self.verbose > 0: print("cp from", self.loc, file=self.log) - except IOError as e: + except OSError as e: if e.errno == 2: dir = os.path.dirname(filename) if dir and not os.path.exists(dir): @@ -1291,11 +1282,11 @@ class DreamTransporter(Transporter): dream:/path/to/buildFiles """ + @staticmethod def canHandle(source): # We only want to handle the configuration file, as that involves the set up # Everything else can be shoved off to another transport return bool(source.startswith("dream:") and source.endswith("config.txt")) - canHandle = staticmethod(canHandle) # should work as of python 2.2 def cacheToFile(self, filename, noaction=False): # We know we're getting the configuration file, because that's all we handle. @@ -1314,7 +1305,7 @@ def listDir(self, noaction=False): pass -class TransporterFactory(object): +class TransporterFactory: def __init__(self): self.classes = [] @@ -1365,7 +1356,7 @@ def defaultMakeTransporter(source, verbosity, log): makeTransporter = defaultMakeTransporter -class TaggedProductList(object): +class TaggedProductList: """ a listing of all versions of products that has been assigned a particular tag. @@ -1438,7 +1429,7 @@ def read(self, filename): try: info = wordsre.findall(line) - except: + except Exception: raise RuntimeError("Failed to parse line:" + line) productName, versionName, flavor, info = info[0], info[2], info[1], info[3:] @@ -1526,7 +1517,7 @@ def getProducts(self, sort=False): return out - # @staticmethod # requires python 2.4 + @staticmethod def fromFile(filename, tag="current", flavor=None, verbosity=0, log=sys.stderr): """create a TaggedProductList from the contents of a product list file @param filename the file to read @@ -1537,9 +1528,8 @@ def fromFile(filename, tag="current", flavor=None, verbosity=0, log=sys.stderr): out.read(filename) return out - fromFile = staticmethod(fromFile) # should work as of python 2.2 -class Dependency(object): +class Dependency: """a container for information about a product required by another product. Users should use the attribute data directly. """ @@ -1576,7 +1566,7 @@ def __repr__(self): return repr(out) -class Mapping(object): +class Mapping: """a mapping between product,version pairs for different flavors""" def __init__(self): self._mapping = {} @@ -1695,7 +1685,7 @@ def __repr__(self): return "Mapping(" + self.__str__() + ")" -class Manifest(object): +class Manifest: """a list of product dependencies that must be installed in order to install a particular product.""" @@ -1899,7 +1889,7 @@ def write(self, filename, noOptional=True, flavor=None, noaction=False): if not noaction: ofd.close() - # @staticmethod # requires python 2.4 + @staticmethod def fromFile(filename, eupsenv=None, shouldRecurse=None, verbosity=0, log=sys.stderr): """ @@ -1919,8 +1909,6 @@ def fromFile(filename, eupsenv=None, shouldRecurse=None, out.remapEntries() return out - fromFile = staticmethod(fromFile) # should work as of python 2.2 - def remapEntries(self, mapping=Mapping(), mode=None): """Allow the user to modify entries in the Manifest @@ -2065,7 +2053,7 @@ def _readRemapFile(self, dirname, mapping=Mapping(), overwrite=True, mode=None, return mapping -class ServerConf(object): +class ServerConf: """a factory class for creating DistribServer classes based on the servers configuration data """ @@ -2112,7 +2100,7 @@ def __init__(self, packageBase, save=False, configFile=None, # make sure the cache directory exists pdir = os.path.dirname(cached) if not os.path.exists(pdir): - os.makedirs(pdir) + os.makedirs(pdir, exist_ok=True) if self.verbose > 1 and self.base != "/dev/null" and not os.path.exists(cached): print("Caching configuration for %s as %s" % (self.base, cached), file=self.log) @@ -2188,7 +2176,7 @@ def cachedConfigFile(self, packageBase): configDir = os.path.dirname(configFile) try: if not os.path.exists(configDir): - os.makedirs(configDir) + os.makedirs(configDir, exist_ok=True) if os.access(configDir, os.W_OK): defaultConfigFile = configFile # we can create it if we need to except OSError: @@ -2207,7 +2195,7 @@ def readConfFile(self, file): try: fd = open(file); - except IOError as e: + except OSError as e: raise RuntimeError("%s: %s" % (file, str(e))) if self.verbose > 1: print("Reading configuration data from", file, file=self.log) @@ -2252,7 +2240,7 @@ def writeConfFile(self, file): finally: fd.close() - # @staticmethod # requires python 2.4 + @staticmethod def clearConfigCache(eups, servers=None, verbosity=0, log=sys.stderr): """clear the cached configuration data for each of the server URLs provided, or all of them if none are provided @@ -2298,9 +2286,6 @@ def clearConfigCache(eups, servers=None, verbosity=0, log=sys.stderr): pkgroot, "in %s: %s" % (stack, str(e)), file=log) pass - clearConfigCache = staticmethod(clearConfigCache) - - def createDistribServer(self, verbosity=0, log=sys.stderr): """ create a DistribServer instance based on this configuration @@ -2328,7 +2313,7 @@ def importServerClass(self, classname): """ return importClass(classname) - # @staticmethod # requires python 2.4 + @staticmethod def makeServer(packageBase, save=True, eupsenv=None, override=None, verbosity=0, log=sys.stderr): """create a DistribServer class for a give package base @@ -2349,7 +2334,6 @@ def makeServer(packageBase, save=True, eupsenv=None, override=None, verbosity=verbosity, log=log) return conf.createDistribServer(verbosity=verbosity, log=log) - makeServer = staticmethod(makeServer) # should work as of python 2.2 def makeTempFile(prefix): (fd, filename) = tempfile.mkstemp("", prefix, utils.createTempDir("distrib")) @@ -2371,7 +2355,7 @@ def importClass(classname): def system(cmd, noaction=False, verbosity=0, log=sys.stderr): """Run BASH shell commands in a EUPS-aware environment. This will make sure the EUPS environment is properly setup before running the commands. - The currently environment is passed in except: + The current environment is passed in except: o the SHELL environment is set to /bin/bash o the BASH_ENV environment is set to setup EUPS o the setting up of EUPS will tweak EUPS_PATH & PYTHONPATH (in good ways). diff --git a/python/eups/distrib/tarball.py b/python/eups/distrib/tarball.py index 9b428314..7c678519 100644 --- a/python/eups/distrib/tarball.py +++ b/python/eups/distrib/tarball.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package: : a specialization for binary tar-balls # -from __future__ import absolute_import, print_function import sys, os, re from . import Distrib as eupsDistrib from . import server as eupsServer @@ -42,7 +41,7 @@ def __init__(self, Eups, distServ, flavor, tag="current", options=None, self._alwaysExpandTableFiles = False # expand table files after installation - # @staticmethod # requires python 2.4 + @staticmethod def parseDistID(distID): """Return a valid package location if and only if we recognize the given distribution identifier @@ -57,8 +56,6 @@ def parseDistID(distID): return None - parseDistID = staticmethod(parseDistID) # should work as of python 2.2 - def initServerTree(self, serverDir): """initialize the given directory to serve as a package distribution tree. @@ -135,19 +132,19 @@ def createPackage(self, serverDir, product, version, flavor=None, except Exception as e: try: os.unlink(pwdFile) - except: + except Exception: pass try: os.unlink(fullTarball) - except: + except Exception: pass raise OSError("Failed to write '%s': %s" % (tarball, str(e))) try: os.unlink(pwdFile) - except: + except Exception: pass self.setGroupPerms(os.path.join(serverDir, tarball)) @@ -219,7 +216,7 @@ def installPackage(self, location, product, version, productRoot, pass if not os.path.exists(unpackDir): - os.makedirs(unpackDir) + os.makedirs(unpackDir, exist_ok=True) if self.verbose > 0: print("installing %s into %s" % (tarball, unpackDir), file=self.log) @@ -248,7 +245,7 @@ def installPackage(self, location, product, version, productRoot, try: # "try ... except ... finally" and "with" are too new-fangled to use fd = open(pwdFile) originalDir = fd.readline().strip() - except: + except Exception: originalDir = None if originalDir and installDir != originalDir: diff --git a/python/eups/hooks.py b/python/eups/hooks.py index 7f136bb8..5203aa4b 100644 --- a/python/eups/hooks.py +++ b/python/eups/hooks.py @@ -1,7 +1,6 @@ """ Module that enables user configuration and hooks. """ -from __future__ import absolute_import, print_function import os import re from . import utils @@ -232,9 +231,6 @@ def loadCustomization(verbose=0, log=utils.stdinfo, execute=True, quiet=True, pa return customisationFiles def execute_file(startupFile): - import eups - from eups import hooks - from .VersionCompare import VersionCompare _globals = {} for key in globals().keys(): diff --git a/python/eups/lock.py b/python/eups/lock.py index 9810532b..81697f10 100644 --- a/python/eups/lock.py +++ b/python/eups/lock.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, print_function import errno import glob import os @@ -39,7 +38,7 @@ def getLockPath(dirName, create=False): if create: if not os.path.exists(dirName): - os.makedirs(dirName) + os.makedirs(dirName, exist_ok=True) return dirName diff --git a/python/eups/setupcmd.py b/python/eups/setupcmd.py index b747b5c4..34ac5d44 100644 --- a/python/eups/setupcmd.py +++ b/python/eups/setupcmd.py @@ -13,7 +13,6 @@ The output of run() is a status code appropriate for passing to sys.exit(). """ -from __future__ import absolute_import, print_function import os import sys from .cmd import EupsOptionParser @@ -30,7 +29,7 @@ def append_current(option, opt_str, value, parser): parser.values.postTag.append("current") -class EupsSetup(object): +class EupsSetup: """ A class for executing the EUPS command-line setup tool. diff --git a/python/eups/stack/ProductFamily.py b/python/eups/stack/ProductFamily.py index 24529335..306ce8f6 100644 --- a/python/eups/stack/ProductFamily.py +++ b/python/eups/stack/ProductFamily.py @@ -5,7 +5,7 @@ from eups.exceptions import ProductNotFound, TableFileNotFound from eups.table import Table -class ProductFamily(object): +class ProductFamily: """ a set of different versions of a named product. When this refers to installed products, it is assumed that all versions are of the same flavor. diff --git a/python/eups/stack/ProductStack.py b/python/eups/stack/ProductStack.py index c7550165..0896a5e2 100644 --- a/python/eups/stack/ProductStack.py +++ b/python/eups/stack/ProductStack.py @@ -1,9 +1,5 @@ -from __future__ import absolute_import, print_function import re, os, sys -try: - import cPickle as pickle -except ImportError: - import pickle +import pickle from eups import utils from eups import Product from .ProductFamily import ProductFamily @@ -25,7 +21,7 @@ dotre = re.compile(r'\.') who = utils.getUserName() -class ProductStack(object): +class ProductStack: """ a lookup for products installed into a software "stack" managed by EUPS via a single ups_db database. @@ -75,7 +71,7 @@ def __init__(self, dbpath, persistDir=None, autosave=True): raise RuntimeError("Empty/None given as EUPS database path: " + str(dbpath)) if not os.path.exists(self.dbpath): - raise IOError(dbpath + ": EUPS database directory not found") + raise OSError(dbpath + ": EUPS database directory not found") # a hierarchical dictionary for looking up products. The dimensions # of the hierarchy (from left to right, general to specific) are: @@ -104,7 +100,7 @@ def __init__(self, dbpath, persistDir=None, autosave=True): self.persistDir = persistDir if self.persistDir is not None and self.autosave and \ not os.path.exists(self.persistDir): - os.makedirs(self.persistDir) + os.makedirs(self.persistDir, exist_ok=True) # raise IOError("Directory not found: " + self.persistDir) # user tag assignments stored a hierarchical dictionary. The @@ -219,10 +215,9 @@ def getProduct(self, name, version, flavor): except KeyError: raise ProductNotFound(name, version, flavor) - # @staticmethod # requires python 2.4 + @staticmethod def persistFilename(flavor): return "%s.%s" % (flavor, ProductStack.persistFileExt) - persistFilename = staticmethod(persistFilename) # works since python 2.2 def save(self, flavors=None, dir=None): """ @@ -299,7 +294,7 @@ def persist(self, flavor, file=None): dir = self.persistDir if not dir: dir = self.dbpath - file = os.path.join(dir, persistFilename(flavor)) + file = os.path.join(dir, self.persistFilename(flavor)) if flavor not in self.lookup: self.lookup[flavor] = {} @@ -743,7 +738,7 @@ def _loadUserTags(self, userTagDir=None): self.assignTag(tag, pname, version, flavor) - # @staticmethod # requires python 2.4 + @staticmethod def fromDatabase(dbpath, persistDir=None, userTagDir=None, autosave=True): """ return a ProductStack that has all products loaded in from an EUPS @@ -759,9 +754,8 @@ def fromDatabase(dbpath, persistDir=None, userTagDir=None, autosave=True): out = ProductStack(dbpath, persistDir, autosave) out.refreshFromDatabase(userTagDir) return out - fromDatabase = staticmethod(fromDatabase) # works since python2.2 - # @staticmethod # requires python 2.4 + @staticmethod def fromCache(dbpath, flavors, persistDir=None, userTagDir=None, updateCache=True, autosave=True, verbose=0): """ @@ -813,8 +807,6 @@ def fromCache(dbpath, flavors, persistDir=None, userTagDir=None, out.autosave = autosave return out - fromCache = staticmethod(fromCache) # works since python2.2 - def _tryCache(self, dbpath, cacheDir, flavors, verbose=0): if not cacheDir or not os.path.exists(cacheDir): return False diff --git a/python/eups/table.py b/python/eups/table.py index 7ffe260e..13e75dbb 100644 --- a/python/eups/table.py +++ b/python/eups/table.py @@ -4,7 +4,6 @@ # Export a product and its dependencies as a package, or install a # product from a package # -from __future__ import absolute_import, print_function import os import re @@ -15,7 +14,7 @@ from . import utils from . import hooks -class Table(object): +class Table: """A class that represents a eups table file""" def __init__(self, tableFile, topProduct=None, addDefaultProduct=None, verbose=0): @@ -259,7 +258,7 @@ def _read(self, tableFile, addDefaultProduct, verbose=0, topProduct=None): try: fd = open(tableFile) - except IOError as e: + except OSError as e: raise TableError(tableFile, msg=str(e)) contents = fd.readlines() @@ -706,7 +705,7 @@ def getDeclareOptions(self, flavor, setupType): #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -class Action(object): +class Action: """ An action in a table file @@ -1442,7 +1441,7 @@ def subSetup(match): if recurse: try: NVOL += eups.getDependencies(productName, version, Eups, setup=True, shouldRaise=True) - except: + except Exception: if not optional: if not force: raise diff --git a/python/eups/tags.py b/python/eups/tags.py index 35b3bba2..588d7524 100644 --- a/python/eups/tags.py +++ b/python/eups/tags.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, print_function import fnmatch import os import re @@ -12,7 +11,7 @@ tagListFileRe = re.compile(r"^(\w\S*).%s$" % tagListFileExt) commRe = re.compile(r"\s*#.*$") -class Tags(object): +class Tags: """ a manager of a set of known tag names. Tags are organized into groups; however, the same name may not be allowed in more than one @@ -202,12 +201,11 @@ def registerUserTag(self, name, force=False): """ return self.registerTag(name, self.user, force) - # @staticmethod # requires python 2.4 + @staticmethod def persistFilename(group): if group in (Tags.global_, Tags.pseudo): group = "global" if group == Tags.user: group = "user" return tagListFileTmpl % group - persistFilename = staticmethod(persistFilename) #should work as'f python 2.2 def load(self, group, file): """ @@ -253,7 +251,7 @@ def save(self, group, file): finally: try: fd.close() - except: + except Exception: pass def loadFromEupsPath(self, eupsPath, verbosity=0): @@ -303,7 +301,7 @@ def loadFromEupsPath(self, eupsPath, verbosity=0): print("Reading tags from", file, file=utils.stdinfo) try: loaded = self.load(group, file) - except IOError as e: + except OSError as e: if verbosity >= 0: print("Skipping troublesome tag file (%s): %s" % \ (str(e), file), file=utils.stdwarn) @@ -320,7 +318,7 @@ def loadUserTags(self, userPersistDir): containing the user tags. """ if not os.path.isdir(userPersistDir): - raise IOError("Tag cache not an existing directory: " + + raise OSError("Tag cache not an existing directory: " + userPersistDir) fileName = os.path.join(userPersistDir, self.persistFilename("user")) if not os.path.exists(fileName): @@ -340,7 +338,7 @@ def saveGroup(self, group, dir): if group == self.user: group = "user" if not os.path.isdir(dir): - raise IOError("Tag cache not an existing directory: " + dir) + raise OSError("Tag cache not an existing directory: " + dir) file = os.path.join(dir, self.persistFilename(group)) if group == "global": @@ -365,7 +363,7 @@ def saveGlobalTags(self, persistDir): taken from the EUPS_PATH). """ if not os.path.isdir(persistDir): - raise IOError("Tag cache not an existing directory: " + + raise OSError("Tag cache not an existing directory: " + persistDir) dir = os.path.join(persistDir, "ups_db") @@ -375,7 +373,7 @@ def saveGlobalTags(self, persistDir): self.save(self.global_, file) -class Tag(object): +class Tag: """ a representation of a Tag. This implementation supports == and != with @@ -445,7 +443,7 @@ def __eq__(self, that): def __ne__(self, that): return not (self == that) - # @staticmethod # requires python 2.4 + @staticmethod def parse(name, defGroup=Tags.global_): """ create a Tag instance from a fully specified tag name string. @@ -454,16 +452,7 @@ def parse(name, defGroup=Tags.global_): there is not group name, it is assumed to be of the group given by defGroup (which defaults to global). """ - # This is requires python 2.4 - # parts = name.rsplit(':', 1) - # replaced with: - parts = name.split(':') - if len(parts) > 2: - try: - parts = ":".join(parts[:-1], parts[-1]) - except Exception as e: - import eups; eups.debug(e) - + parts = name.rsplit(':', 1) if len(parts) == 1: return Tag(name, defGroup) else: @@ -475,7 +464,6 @@ def parse(name, defGroup=Tags.global_): return Tag(parts[1]) # unknown tag, probably from a version name return Tag(parts[1], parts[0]) - parse = staticmethod(parse) #should work as of python 2.2 def UserTag(name): """ diff --git a/python/eups/utils.py b/python/eups/utils.py index 49b18063..89f68a01 100644 --- a/python/eups/utils.py +++ b/python/eups/utils.py @@ -1,7 +1,6 @@ """ Utility functions used across EUPS classes. """ -from __future__ import print_function import time import os import sys @@ -11,66 +10,39 @@ import tempfile import pwd -#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -# Python 2/3 compatibility layer - -# load the correct StringIO module (StringIO in 2, io in 3) -if sys.version_info[0] == 2: - # Python 2.x versions - import cStringIO as StringIO - - xrange = xrange - - def cmp_or_key(cmp): - return { 'cmp': cmp } - - reload = reload - - cmp = cmp - reduce = reduce +# Python 3.x versions +import io as StringIO - def get_content_charset(response): - return "ascii" +xrange = range - def decode(string, encoding): - return string +import functools +def cmp_or_key(cmp): + return { 'key': functools.cmp_to_key(cmp) } - def is_string(string): - return isinstance(string, basestring) -else: - # Python 3.x versions - import io as StringIO +import importlib +try: + # Python 3.4 and newer + reload = importlib.reload +except AttributeError: + # Python 3.3 and older + import imp + reload = imp.reload - xrange = range +def cmp(a, b): + return (a > b) - (a < b) - import functools - def cmp_or_key(cmp): - return { 'key': functools.cmp_to_key(cmp) } +import functools +reduce = functools.reduce - import importlib - try: - # Python 3.4 and newer - reload = importlib.reload - except AttributeError: - # Python 3.3 and older - import imp - reload = imp.reload - - def cmp(a, b): - return (a > b) - (a < b) - - import functools - reduce = functools.reduce +def get_content_charset(response): + return response.headers.get_content_charset(failobj='utf-8') - def get_content_charset(response): - return response.headers.get_content_charset(failobj='utf-8') +def decode(string, encoding): + return string.decode(encoding) - def decode(string, encoding): - return string.decode(encoding) - - def is_string(string): - return isinstance(string, str) +def is_string(string): + return isinstance(string, str) #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -322,7 +294,7 @@ def isDbWritable(dbpath, create=False): if not dbExists and create: try: - os.makedirs(dbpath) + os.makedirs(dbpath, exist_ok=True) except Exception as e: pass else: @@ -431,7 +403,7 @@ def decodePath(encodedPath): """Decode a directory path that was encoded by encodePath().""" return encodedPath.replace(SPACE_TO_STRING, " ") -class Flavor(object): +class Flavor: """A class to handle flavors""" def __init__(self): @@ -474,7 +446,7 @@ def getFallbackFlavors(self, flavor=None, includeMe=False): # # setFallbackFlavors = Flavor().setFallbackFlavors -class Quiet(object): +class Quiet: """A class whose members, while they exist, make Eups quieter""" def __init__(self, Eups): @@ -484,7 +456,7 @@ def __init__(self, Eups): def __del__(self): self.Eups.quiet -= 1 -class ConfigProperty(object): +class ConfigProperty: """ This class emulates a properties used in configuration files. It represents a set of defined property names that are accessible as @@ -559,10 +531,7 @@ def canPickle(): cache product info. """ try: - try: - import cPickle as pickle - except ImportError: - import pickle + import pickle return pickle.HIGHEST_PROTOCOL >= 2 except (ImportError, AttributeError): return False @@ -595,7 +564,7 @@ def createTempDir(path): dir = os.path.join(dir, d) if not os.path.isdir(dir): - os.mkdir(dir) + os.makedirs(dir, exist_ok=True) os.chmod(dir, 0o777) return path @@ -626,7 +595,7 @@ def copyfile(file1, file2): #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -class Color(object): +class Color: classes = dict( OK = "green", WARN = "yellow", @@ -665,6 +634,7 @@ def __init__(self, text, color): if bold: self._code += ";1" + @staticmethod def colorize(val=None): """Should I colour strings? With an argument, set the value""" if val is not None: @@ -687,8 +657,6 @@ def colorize(val=None): return Color._colorize - colorize = staticmethod(colorize) - def __str__(self): if not self.colorize(): return self.rawText @@ -700,7 +668,7 @@ def __str__(self): return prefix + self.rawText + suffix -class coloredFile(object): +class coloredFile: """Like sys.stderr, but colourize text first""" def __init__(self, fileObj, cclass): @@ -709,7 +677,7 @@ def __init__(self, fileObj, cclass): self._class = cclass try: self._isatty = os.isatty(fileObj.fileno()) - except: + except Exception: self._isatty = False def write(self, text): @@ -915,7 +883,7 @@ def cmp_prods_and_none(a, b): raise RuntimeError("A cyclic dependency exists amongst %s" % " ".join(sorted([name([x for x in p]) for p in graph.keys()]))) -class AtomicFile(object): +class AtomicFile: """ A file to which all the changes (writes) are committed all at once, or not at all. Useful for avoiding race conditions where a reader diff --git a/tests/checkVersionFile.py b/tests/checkVersionFile.py index 8251f23b..8f9cf7ef 100644 --- a/tests/checkVersionFile.py +++ b/tests/checkVersionFile.py @@ -3,17 +3,13 @@ Check a Version file for parsability and macro substitution """ -from __future__ import print_function import os import sys -import shutil import re import unittest -import time from optparse import OptionParser import testCommon -from eups import ProductNotFound, Product from eups.db import VersionFile defaultFile = os.path.join(testCommon.testEupsStack, "fw.version") @@ -75,26 +71,26 @@ def assertPathOK(self, path, what): self.assertPathExists(path, what) def assertPathExists(self, path, what): - self.assert_(os.path.exists(path), + self.assertTrue(os.path.exists(path), "Path %s does not exist: %s" % (what, path)) def assertResolvedMacros(self, path, what): - self.assert_(path.find('$') < 0, + self.assertTrue(path.find('$') < 0, "Unresolved macro in %s: %s" % (what, path)) def assertAbs(self, path, what): - self.assert_(path == "none" or os.path.isabs(path), + self.assertTrue(path == "none" or os.path.isabs(path), "Relative path in %s: %s" % (what, path)) def shortDescription(self): return self.file -class VersionFileTestResult(unittest._TextTestResult): +class VersionFileTestResult(unittest.TextTestResult): def __init__(self, stream=None): if not stream: stream = sys.stderr - strm = unittest._WritelnDecorator(stream) - unittest._TextTestResult.__init__(self, strm, True, 1) + strm = unittest.runner._WritelnDecorator(stream) + unittest.TextTestResult.__init__(self, strm, True, 1) def findVersionFiles(dir): out = [] diff --git a/tests/python26compat.py b/tests/python26compat.py deleted file mode 100644 index a5a11d46..00000000 --- a/tests/python26compat.py +++ /dev/null @@ -1,96 +0,0 @@ -#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -# -# Some Python 2.6 compatibility hacks, that allows us to write Python 2.7/3.x -# compatible code. This code monkey-patches some parts of 2.6 standard library -# with a few useful functions introduced in 2.7 -# -# Most of this code was lifted straight from the Python 2.7 standard library. -# Remove it once we don't have a requirement to be Python 2.6 compatible. -# - -import unittest -try: - safe_repr -except NameError: - safe_repr = repr - -class TestCase27(unittest.TestCase): - def assertIn(self, member, container, msg=None): - """Just like self.assertTrue(a in b), but with a nicer default message.""" - if member not in container: - standardMsg = '%s not found in %s' % (safe_repr(member), - safe_repr(container)) - self.fail(self._formatMessage(msg, standardMsg)) - - def assertNotIn(self, member, container, msg=None): - """Just like self.assertTrue(a not in b), but with a nicer default message.""" - if member in container: - standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), - safe_repr(container)) - self.fail(self._formatMessage(msg, standardMsg)) - - def assertIsNone(self, obj, msg=None): - """Same as self.assertTrue(obj is None), with a nicer default message.""" - if obj is not None: - standardMsg = '%s is not None' % (safe_repr(obj),) - self.fail(self._formatMessage(msg, standardMsg)) - - def assertIsNotNone(self, obj, msg=None): - """Included for symmetry with assertIsNone.""" - if obj is None: - standardMsg = 'unexpectedly None' - self.fail(self._formatMessage(msg, standardMsg)) - -unittest.TestCase = TestCase27 - - -# Exception classes used by this module. -class _CalledProcessError(Exception): - """This exception is raised when a process run by check_call() or - check_output() returns a non-zero exit status. - The exit status will be stored in the returncode attribute; - check_output() will also store the output in the output attribute. - """ - def __init__(self, returncode, cmd, output=None): - self.returncode = returncode - self.cmd = cmd - self.output = output - def __str__(self): - return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) - -def _check_output(*popenargs, **kwargs): - r"""Run command with arguments and return its output as a byte string. - - If the exit code was non-zero it raises a CalledProcessError. The - CalledProcessError object will have the return code in the returncode - attribute and output in the output attribute. - - The arguments are the same as for the Popen constructor. Example: - - >>> check_output(["ls", "-l", "/dev/null"]) - 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' - - The stdout argument is not allowed as it is used internally. - To capture standard error in the result, use stderr=STDOUT. - - >>> check_output(["/bin/sh", "-c", - ... "ls -l non_existent_file ; exit 0"], - ... stderr=STDOUT) - 'ls: non_existent_file: No such file or directory\n' - """ - if 'stdout' in kwargs: - raise ValueError('stdout argument not allowed, it will be overridden.') - process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) - output, unused_err = process.communicate() - retcode = process.poll() - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise subprocess.CalledProcessError(retcode, cmd, output=output) - return output - -# Do the monkeypatching -import subprocess -subprocess.CalledProcessError = _CalledProcessError -subprocess.check_output = _check_output diff --git a/tests/testApp.py b/tests/testApp.py index 5338a0e2..e463d670 100644 --- a/tests/testApp.py +++ b/tests/testApp.py @@ -33,8 +33,7 @@ def testProductDir(self): if "SETUP_PYTHON" in os.environ: del os.environ["SETUP_PYTHON"] - self.assertTrue(eups.productDir("python") is None, - "found unsetup product") + self.assertIsNone(eups.productDir("python"), "found unsetup product") pdir = os.path.join(testEupsStack, os.environ["EUPS_FLAVOR"], "python", "2.5.2") @@ -109,7 +108,7 @@ def testDefPrefTag(self): # setup the preferred (tagged current) version eups.setup("python") prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "2.5.2") self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") @@ -117,7 +116,7 @@ def testDefPrefTag(self): # check for dependent product prod = self.eups.findSetupProduct("tcltk") - self.assert_(prod is not None, "tcltk not setup") + self.assertIsNotNone(prod, "tcltk not setup") self.assertEqual(prod.version, "8.5a4") self.assertIn("SETUP_TCLTK", os.environ, "SETUP_TCLTK not set") self.assertIn("TCLTK_DIR", os.environ, "TCLTK_DIR not set") @@ -125,18 +124,18 @@ def testDefPrefTag(self): eups.unsetup("python") prod = self.eups.findSetupProduct("python") - self.assert_(prod is None, "python is still setup") + self.assertIsNone(prod, "python is still setup") self.assertNotIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON is still set") self.assertNotIn("PYTHON_DIR", os.environ, "PYTHON_DIR is still set") prod = self.eups.findSetupProduct("tcltk") - self.assert_(prod is None, "tcltk is still setup") + self.assertIsNone(prod, "tcltk is still setup") self.assertNotIn("SETUP_TCLTK", os.environ, "SETUP_TCLTK is still set") self.assertNotIn("TCLTK_DIR", os.environ, "TCLTK_DIR is still set") # set up an explicit version eups.setup("python", "2.5.2") prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "2.5.2") self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") @@ -144,7 +143,7 @@ def testDefPrefTag(self): # check for dependent product prod = self.eups.findSetupProduct("tcltk") - self.assert_(prod is not None, "tcltk not setup") + self.assertIsNotNone(prod, "tcltk not setup") self.assertEqual(prod.version, "8.5a4") self.assertIn("SETUP_TCLTK", os.environ, "SETUP_TCLTK not set") self.assertIn("TCLTK_DIR", os.environ, "TCLTK_DIR not set") @@ -152,11 +151,11 @@ def testDefPrefTag(self): eups.unsetup("python") prod = self.eups.findSetupProduct("python") - self.assert_(prod is None, "python is still setup") + self.assertIsNone(prod, "python is still setup") self.assertNotIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON is still set") self.assertNotIn("PYTHON_DIR", os.environ, "PYTHON_DIR is still set") prod = self.eups.findSetupProduct("tcltk") - self.assert_(prod is None, "tcltk is still setup") + self.assertIsNone(prod, "tcltk is still setup") self.assertNotIn("SETUP_TCLTK", os.environ, "SETUP_TCLTK is still set") self.assertNotIn("TCLTK_DIR", os.environ, "TCLTK_DIR is still set") @@ -179,14 +178,14 @@ def testTaggedTarget(self): setupRequired(python) """ self.eups.declare("newprod", "1.0", pdir10, testEupsStack, - tablefile=StringIO(newprodtable)) + tablefile=StringIO.StringIO(newprodtable)) self.eups.declare("newprod", "2.0", pdir20, testEupsStack, - tablefile=StringIO(newprodtable), tag="beta") + tablefile=StringIO.StringIO(newprodtable), tag="beta") # test the setup - self.assert_(self.eups.findProduct("newprod", "1.0") is not None, "newprod 1.0 not declared") - self.assert_(self.eups.findProduct("newprod", "2.0") is not None, "newprod 2.0 not declared") - self.assert_(os.path.exists(ptble10), "Can't find newprod 1.0's table file") - self.assert_(os.path.exists(ptble20), "Can't find newprod 2.0's table file") + self.assertIsNotNone(self.eups.findProduct("newprod", "1.0"), "newprod 1.0 not declared") + self.assertIsNotNone(self.eups.findProduct("newprod", "2.0"), "newprod 2.0 not declared") + self.assertTrue(os.path.exists(ptble10), "Can't find newprod 1.0's table file") + self.assertTrue(os.path.exists(ptble20), "Can't find newprod 2.0's table file") self.assertEqual(len(p for p in self.eups.uses("python") if p[0] == "newprod"), 2, "newprod does not depend on python") @@ -195,14 +194,14 @@ def testTaggedTarget(self): eups.setup("newprod", prefTags="beta") prod = self.eups.findSetupProduct("newprod") - self.assert_(prod is not None, "newprod not setup") + self.assertIsNotNone(prod, "newprod not setup") self.assertEqual(prod.version, "2.0") self.assertIn("SETUP_NEWPROD", os.environ, "SETUP_NEWPROD not set") self.assertIn("NEWPROD_DIR", os.environ, "NEWPROD_DIR not set") self.assertEqual(os.environ["NEWPROD_DIR"], pdir20) prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "2.5.2") # tagged current self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") @@ -210,11 +209,11 @@ def testTaggedTarget(self): eups.unsetup("newprod") prod = self.eups.findSetupProduct("newprod") - self.assert_(prod is None, "newprod is still setup") + self.assertIsNone(prod, "newprod is still setup") self.assertNotIn("SETUP_NEWPROD", os.environ, "SETUP_NEWPROD not set") self.assertNotIn("NEWPROD_DIR", os.environ, "NEWPROD_DIR not set") prod = self.eups.findSetupProduct("python") - self.assert_(prod is None, "python is still setup") + self.assertIsNone(prod, "python is still setup") self.assertNotIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON is still set") self.assertNotIn("PYTHON_DIR", os.environ, "PYTHON_DIR is still set") @@ -223,14 +222,14 @@ def testTaggedTarget(self): eups.setup("newprod", prefTags="beta") prod = self.eups.findSetupProduct("newprod") - self.assert_(prod is not None, "newprod not setup") + self.assertIsNotNone(prod, "newprod not setup") self.assertEqual(prod.version, "2.0") self.assertIn("SETUP_NEWPROD", os.environ, "SETUP_NEWPROD not set") self.assertIn("NEWPROD_DIR", os.environ, "NEWPROD_DIR not set") self.assertEqual(os.environ["NEWPROD_DIR"], pdir20) prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "2.6") # tagged beta self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") @@ -256,16 +255,16 @@ def testTaggedDeps(self): setupRequired(python) """ self.eups.declare("newprod", "1.0", pdir10, testEupsStack, - tablefile=StringIO(newprodtable), tag="current") + tablefile=StringIO.StringIO(newprodtable), tag="current") self.eups.declare("newprod", "2.0", pdir20, testEupsStack, - tablefile=StringIO(newprodtable)) + tablefile=StringIO.StringIO(newprodtable)) self.eups.assignTag("beta", "python", "2.6") # test the setup - self.assert_(self.eups.findProduct("newprod", "1.0") is not None, "newprod 1.0 not declared") - self.assert_(self.eups.findProduct("newprod", "2.0") is not None, "newprod 2.0 not declared") - self.assert_(os.path.exists(ptble10), "Can't find newprod 1.0's table file") - self.assert_(os.path.exists(ptble20), "Can't find newprod 2.0's table file") + self.assertIsNotNone(self.eups.findProduct("newprod", "1.0"), "newprod 1.0 not declared") + self.assertIsNotNone(self.eups.findProduct("newprod", "2.0"), "newprod 2.0 not declared") + self.assertTrue(os.path.exists(ptble10), "Can't find newprod 1.0's table file") + self.assertTrue(os.path.exists(ptble20), "Can't find newprod 2.0's table file") self.assertEqual(len(p for p in self.eups.uses("python") if p[0] == "newprod"), 2, "newprod does not depend on python") @@ -276,14 +275,14 @@ def testTaggedDeps(self): del q prod = self.eups.findSetupProduct("newprod") - self.assert_(prod is not None, "newprod not setup") + self.assertIsNotNone(prod, "newprod not setup") self.assertEqual(prod.version, "1.0") self.assertIn("SETUP_NEWPROD", os.environ, "SETUP_NEWPROD not set") self.assertIn("NEWPROD_DIR", os.environ, "NEWPROD_DIR not set") self.assertEqual(os.environ["NEWPROD_DIR"], pdir20) prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "2.6") # tagged beta self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") @@ -309,18 +308,18 @@ def testTaggedDeps2(self): pytdir = pyprod.dir self.eups.declare("newprod", "1.0", pdir10, testEupsStack, - tablefile=StringIO(newprodtable), tag="current") + tablefile=StringIO.StringIO(newprodtable), tag="current") self.eups.declare("newprod", "2.0", pdir20, testEupsStack, - tablefile=StringIO(newprodtable)) + tablefile=StringIO.StringIO(newprodtable)) self.eups.declare("python", "test", pytdir, testEupsStack) self.eups.assignTag("rhl", "python", "test") # test the setup - self.assert_(self.eups.findProduct("newprod", "1.0") is not None, "newprod 1.0 not declared") - self.assert_(self.eups.findProduct("newprod", "2.0") is not None, "newprod 2.0 not declared") - self.assert_(os.path.exists(ptble10), "Can't find newprod 1.0's table file") - self.assert_(os.path.exists(ptble20), "Can't find newprod 2.0's table file") - self.assert_(self.eups.findProduct("python", "test") is not None, "python test not declared") + self.assertIsNotNone(self.eups.findProduct("newprod", "1.0"), "newprod 1.0 not declared") + self.assertIsNotNone(self.eups.findProduct("newprod", "2.0"), "newprod 2.0 not declared") + self.assertTrue(os.path.exists(ptble10), "Can't find newprod 1.0's table file") + self.assertTrue(os.path.exists(ptble20), "Can't find newprod 2.0's table file") + self.assertIsNotNone(self.eups.findProduct("python", "test"), "python test not declared") self.assertEqual(len(p for p in self.eups.uses("python") if p[0] == "newprod"), 2, "newprod does not depend on python") @@ -331,14 +330,14 @@ def testTaggedDeps2(self): del q prod = self.eups.findSetupProduct("newprod") - self.assert_(prod is not None, "newprod not setup") + self.assertIsNotNone(prod, "newprod not setup") self.assertEqual(prod.version, "1.0") self.assertIn("SETUP_NEWPROD", os.environ, "SETUP_NEWPROD not set") self.assertIn("NEWPROD_DIR", os.environ, "NEWPROD_DIR not set") self.assertEqual(os.environ["NEWPROD_DIR"], pdir20) prod = self.eups.findSetupProduct("python") - self.assert_(prod is not None, "python not setup") + self.assertIsNotNone(prod, "python not setup") self.assertEqual(prod.version, "test") # tagged rhl self.assertIn("SETUP_PYTHON", os.environ, "SETUP_PYTHON not set") self.assertIn("PYTHON_DIR", os.environ, "PYTHON_DIR not set") diff --git a/tests/testCmd.py b/tests/testCmd.py index 0dd40443..149616d2 100644 --- a/tests/testCmd.py +++ b/tests/testCmd.py @@ -357,7 +357,7 @@ def testDistribList(self): def testDistrib(self): cmd = eups.cmd.EupsCmd(args="distrib".split(), toolname=prog) self.assertNotEqual(cmd.run(), 0) - self.assertNotEquals(self.err.getvalue(), "") + self.assertNotEqual(self.err.getvalue(), "") import eups.setupcmd @@ -403,7 +403,7 @@ def testNoTable(self): self.assertEqual(cmd.run(), 0) -class Stdout(object): +class Stdout: def __init__(self, newstdout=None): self.oldstdout = sys.stdout diff --git a/tests/testCommon.py b/tests/testCommon.py index 97d2706a..42988e17 100644 --- a/tests/testCommon.py +++ b/tests/testCommon.py @@ -3,9 +3,6 @@ import subprocess import glob -# This will activate Python 2.6 compatibility hacks -if sys.version_info[:2] == (2, 6): - import python26compat testEupsStack = os.path.dirname(__file__) @@ -94,12 +91,7 @@ def _shouldSkip(self, testFn): skipMarkerFn = testFn + ".skip"; if os.path.isfile(skipMarkerFn): - if sys.version_info[:2] > (2, 6): - self.skipTest(open(skipMarkerFn).read()) - else: - # On Python 2.6 we'll just pretend the test succeeded - print("Skipping test %s" % testFn) - return True + self.skipTest(open(skipMarkerFn).read()) return False @@ -171,7 +163,7 @@ def makeSuite(testCases, makeSuite=True): tests = [] for t in testCases: - tests += unittest.makeSuite(t) + tests += unittest.defaultTestLoader.loadTestsFromTestCase(t) if makeSuite: return unittest.TestSuite(tests) diff --git a/tests/testDb.py b/tests/testDb.py index a94faf81..fcf218af 100644 --- a/tests/testDb.py +++ b/tests/testDb.py @@ -84,7 +84,7 @@ def testAddFlavor(self): self.assertEqual(len(flavors), 2) self.vf.removeFlavor(flavors) self.assertEqual(len(self.vf.getFlavors()), 0) - self.assert_(self.vf.isEmpty()) + self.assertTrue(self.vf.isEmpty()) def testMakeProduct(self): prod = self.vf.makeProduct("Darwin") @@ -94,7 +94,7 @@ def testMakeProduct(self): self.assertEqual(prod.flavor, "Darwin") self.assertEqual(prod.tablefile, "DarwinX86/fw/1.2/ups/fw.table") self.assertEqual(len(prod.tags), 0) - self.assert_(prod.db is None) + self.assertIsNone(prod.db) self.vf.addFlavor("Linux:rhel", "/opt/sw/Linux/fw/1.2", "/opt/sw/Linux/fw/1.2/ups/fw.table", "ups") @@ -105,14 +105,14 @@ def testMakeProduct(self): self.assertEqual(prod.flavor, "Linux:rhel") self.assertEqual(prod.tablefile, "/opt/sw/Linux/fw/1.2/ups/fw.table") self.assertEqual(len(prod.tags), 0) - self.assert_(prod.db is None) + self.assertIsNone(prod.db) self.assertRaises(ProductNotFound, self.vf.makeProduct, "goober") prod = self.vf.makeProducts() self.assertEqual(len(prod), 3) for p in prod: - self.assert_(isinstance(p, Product)) + self.assertTrue(isinstance(p, Product)) def testWrite(self): self.vf.addFlavor("Linux:rhel", "/opt/sw/Linux/fw/1.2", @@ -270,7 +270,7 @@ def testUPS_DB(self): vf = VersionFile(None, readFile=False) vf.addFlavor("Linux", "$UPS_DB/Linux/fw/1.0", "fw.table") prod = vf.makeProduct("Linux") - self.assert_(prod.db is None) + self.assertIsNone(prod.db) self.assertEqual(prod.dir, "$UPS_DB/Linux/fw/1.0") self.assertEqual(prod.tablefile, "$UPS_DB/Linux/fw/1.0/fw.table") @@ -399,8 +399,8 @@ def testSetVersion(self): flavor = self.cf.info["Linux"] self.assertEqual(flavor['version'], '2.0') - self.assert_(bool(flavor['declarer'])) - self.assert_(bool(flavor['declared'])) + self.assertTrue(bool(flavor['declarer'])) + self.assertTrue(bool(flavor['declared'])) self.assertNotIn('modifier', flavor) self.assertNotIn('modified', flavor) who = flavor['declarer'] @@ -414,7 +414,7 @@ def testSetVersion(self): flavor = self.cf.info["Linux64"] self.assertEqual(flavor['version'], '2.1') self.assertEqual(flavor['declarer'], who) - self.assert_(bool(flavor['declared'])) + self.assertTrue(bool(flavor['declared'])) self.assertNotIn('modifier', flavor) self.assertNotIn('modified', flavor) @@ -430,7 +430,7 @@ def testSetVersion(self): self.assertEqual(flavor['declarer'], 'rhl') self.assertEqual(flavor['declared'], 'Thu Jan 24 23:43:35 2008') self.assertEqual(flavor['modifier'], who) - self.assert_(bool(flavor['modified'])) + self.assertTrue(bool(flavor['modified'])) self.cf.removeVersion("Linux64") flavors = self.cf.getFlavors() @@ -442,7 +442,7 @@ def testSetVersion(self): flavors = self.cf.getFlavors() self.assertEqual(len(flavors), 0) - self.assert_(self.cf.hasNoAssignments()) + self.assertTrue(self.cf.hasNoAssignments()) def testWrite(self): self.cf.setVersion("2.0", "Linux:rhel") @@ -475,8 +475,7 @@ class DatabaseTestCase(unittest.TestCase): def setUp(self): self.dbpath = os.path.join(testEupsStack, "ups_db") self.userdb = os.path.join(testEupsStack, "user_ups_db") - if not os.path.exists(self.userdb): - os.makedirs(self.userdb) + os.makedirs(self.userdb, exist_ok=True) self.db = Database(self.dbpath, self.userdb) @@ -490,7 +489,7 @@ def tearDown(self): if os.path.exists(self.userdb) and self.userdb.endswith("user_ups_db"): - os.system("rm -rf " + self.userdb) + shutil.rmtree(self.userdb, ignore_errors=True) def testFindProductNames(self): prods = self.db.findProductNames() @@ -541,16 +540,16 @@ def testFindTags(self): def testFindProduct(self): prod = self.db.findProduct("doxygen", "1.5.9", "Linux") - self.assert_(prod is None) + self.assertIsNone(prod) prod = self.db.findProduct("doxygen", "1.5.10", "Linux") - self.assert_(prod is None) + self.assertIsNone(prod) prod = self.db.findProduct("goober", "1.5.10", "Linux") - self.assert_(prod is None) + self.assertIsNone(prod) prod = self.db.findProduct("doxygen", "1.5.9", "Linux64") - self.assert_(prod is not None) + self.assertIsNotNone(prod) self.assertEqual(prod.name, "doxygen") self.assertEqual(prod.version, "1.5.9") self.assertEqual(prod.flavor, "Linux64") @@ -561,7 +560,7 @@ def testFindProduct(self): self.assertEqual(len(prod.tags), 0) prod = self.db.findProduct("doxygen", "1.5.7.1", "Linux") - self.assert_(prod is not None) + self.assertIsNotNone(prod) self.assertEqual(prod.name, "doxygen") self.assertEqual(prod.version, "1.5.7.1") self.assertEqual(prod.flavor, "Linux") @@ -578,14 +577,14 @@ def testFindProduct(self): self.assertEqual(prod.version, "2.5.2") self.assertEqual(prod.flavor, "Linux") self.assertEqual(prod.db, os.path.join(testEupsStack, "ups_db")) - self.assert_(prod.tablefile.endswith("Linux/python/2.5.2/ups/python.table")) - self.assert_(os.path.exists(prod.tablefile)) + self.assertTrue(prod.tablefile.endswith("Linux/python/2.5.2/ups/python.table")) + self.assertTrue(os.path.exists(prod.tablefile)) # test autonormalization of product install directories. # The install directory (PROD_DIR) for this python is given # as a relative directory prod = self.db.findProduct("python", "2.5.2", "Linux") - self.assert_(prod is not None) + self.assertIsNotNone(prod) self.assertEqual(prod.name, "python") self.assertEqual(prod.version, "2.5.2") self.assertEqual(prod.flavor, "Linux") @@ -613,25 +612,25 @@ def testFindProducts(self): self.assertEqual(len(prods), 1) def testIsDeclared(self): - self.assert_(self.db.isDeclared("doxygen")) - self.assert_(self.db.isDeclared("doxygen", "1.5.9")) - self.assert_(self.db.isDeclared("doxygen", "1.5.7.1")) - self.assert_(self.db.isDeclared("doxygen", "1.5.9", "Linux64")) - self.assert_(self.db.isDeclared("doxygen", flavor="Linux64")) - self.assert_(self.db.isDeclared("doxygen", flavor="Linux")) - self.assert_(not self.db.isDeclared("goober")) - self.assert_(not self.db.isDeclared("goober", "1.0")) - self.assert_(not self.db.isDeclared("doxygen", "1.5.10")) - self.assert_(not self.db.isDeclared("doxygen", "1.5.9", "Linux")) + self.assertTrue(self.db.isDeclared("doxygen")) + self.assertTrue(self.db.isDeclared("doxygen", "1.5.9")) + self.assertTrue(self.db.isDeclared("doxygen", "1.5.7.1")) + self.assertTrue(self.db.isDeclared("doxygen", "1.5.9", "Linux64")) + self.assertTrue(self.db.isDeclared("doxygen", flavor="Linux64")) + self.assertTrue(self.db.isDeclared("doxygen", flavor="Linux")) + self.assertFalse(self.db.isDeclared("goober")) + self.assertFalse(self.db.isDeclared("goober", "1.0")) + self.assertFalse(self.db.isDeclared("doxygen", "1.5.10")) + self.assertFalse(self.db.isDeclared("doxygen", "1.5.9", "Linux")) def testUserTag(self): vers = self.db.getTaggedVersion("user:my", "python", "Linux")[1] - self.assert_(vers is None) + self.assertIsNone(vers) self.db.assignTag("user:my", "python", "2.5.2") vers = self.db.getTaggedVersion("user:my", "python", "Linux")[1] self.assertEqual(vers, "2.5.2") - self.assert_(os.path.exists(os.path.join(self.userdb, + self.assertTrue(os.path.exists(os.path.join(self.userdb, "python","my.chain"))) tags = self.db.findTags("python", "2.5.2", "Linux") @@ -648,8 +647,8 @@ def testUserTag(self): self.db.unassignTag("user:my", "python") vers = self.db.getTaggedVersion("user:my", "python", "Linux")[1] - self.assert_(vers is None) - self.assert_(not os.path.exists(os.path.join(self.userdb, + self.assertIsNone(vers) + self.assertFalse(os.path.exists(os.path.join(self.userdb, "python","my.chain"))) def testAssignTag(self): @@ -676,9 +675,9 @@ def testAssignTag(self): "Linux"), ("python", "2.6")) self.db.unassignTag("stable", "python", "Linux") - self.assert_(not os.path.exists(tfile)) - except: - if os.path.exists(tfile): os.remove(file) + self.assertFalse(os.path.exists(tfile)) + except Exception: + if os.path.exists(tfile): os.remove(tfile) raise tfile = self.db._tagFile("doxygen", "beta") @@ -709,8 +708,8 @@ def testAssignTag(self): None) self.db.assignTag("beta", "doxygen", "1.5.7.1") self.db.unassignTag("beta", "doxygen") - self.assert_(not os.path.exists(tfile)) - except: + self.assertFalse(os.path.exists(tfile)) + except Exception: if os.path.exists(tfile): os.remove(tfile) raise @@ -725,15 +724,15 @@ def testDeclare(self): os.remove(f) os.removedirs(pdir) try: - self.assert_(not os.path.exists(pdir)) + self.assertFalse(os.path.exists(pdir)) baseidir = os.path.join(testEupsStack,"Linux/base/1.0") base = Product("base", "1.0", "Linux", baseidir, os.path.join(baseidir, "ups/base.table"), tags=["current"]) self.db.declare(base) - self.assert_(os.path.isdir(pdir)) - self.assert_(os.path.isfile(os.path.join(pdir,"1.0.version"))) - self.assert_(os.path.isfile(os.path.join(pdir,"current.chain"))) + self.assertTrue(os.path.isdir(pdir)) + self.assertTrue(os.path.isfile(os.path.join(pdir,"1.0.version"))) + self.assertTrue(os.path.isfile(os.path.join(pdir,"current.chain"))) prods = self.db.findProducts("base") self.assertEqual(len(prods), 1) self.assertEqual(prods[0].name, "base") @@ -764,21 +763,21 @@ def testDeclare(self): self.db.undeclare(base) self.assertEqual(self.db.findProduct("base","1.0","Linux"), None) self.assertEqual(len(self.db.findProducts("base")), 2) - self.assert_(not os.path.exists(os.path.join(pdir,"1.0.version"))) + self.assertFalse(os.path.exists(os.path.join(pdir,"1.0.version"))) self.db.undeclare(base3) self.assertEqual(self.db.findProduct("base","3.0","Linux"), None) self.assertEqual(len(self.db.findProducts("base")), 1) - self.assert_(not os.path.exists(os.path.join(pdir,"3.0.version"))) + self.assertFalse(os.path.exists(os.path.join(pdir,"3.0.version"))) self.assertEqual(self.db.getTaggedVersion("current", "base", "Linux")[1], None) - self.assert_(not os.path.exists(os.path.join(pdir,"current.chain"))) + self.assertFalse(os.path.exists(os.path.join(pdir,"current.chain"))) self.db.undeclare(base2) self.assertEqual(len(self.db.findProducts("base")), 0) - self.assert_(not os.path.exists(pdir)) + self.assertFalse(os.path.exists(pdir)) - except: + except Exception: if False: if os.path.isdir(pdir): for p in os.listdir(pdir): diff --git a/tests/testDeprecated.py b/tests/testDeprecated.py index 587fa139..4f2b7767 100644 --- a/tests/testDeprecated.py +++ b/tests/testDeprecated.py @@ -45,8 +45,8 @@ def tearDown(self): def testDeprecatedProduct(self): prod = Product(Eups(), "newprod", noInit=True) - self.assert_(prod is not None) - self.assert_(newerr.getvalue().find("deprecated") >= 0) + self.assertIsNotNone(prod) + self.assertTrue(newerr.getvalue().find("deprecated") >= 0) self.assertEqual(prod.envarDirName(), "NEWPROD_DIR") self.assertEqual(prod.envarSetupName(), "SETUP_NEWPROD") diff --git a/tests/testEups.py b/tests/testEups.py index b286e762..19f9ffa5 100644 --- a/tests/testEups.py +++ b/tests/testEups.py @@ -3,8 +3,6 @@ Tests for eups.Eups """ -from __future__ import print_function - # Import this first, as it will set up the environment import testCommon @@ -46,7 +44,7 @@ def tearDown(self): usercachedir = os.path.join(testEupsStack,"_userdata_","_caches_") if os.path.exists(usercachedir): - os.system('rm -rf "%s"' % usercachedir) + shutil.rmtree(usercachedir, ignore_errors=True) if os.path.exists(self.betachain): os.remove(self.betachain) @@ -75,7 +73,7 @@ def testInit(self): self.assertEqual(self.eups.getUpsDB(testEupsStack), self.dbpath) self.assertEqual(len(self.eups.versions), 2) self.assertIn(testEupsStack, self.eups.versions) - self.assert_(self.eups.versions[testEupsStack] is not None) + self.assertIsNotNone(self.eups.versions[testEupsStack]) flavors = self.eups.versions[testEupsStack].getFlavors() self.assertEqual(len(flavors), 3) @@ -96,7 +94,7 @@ def testInit(self): for flav in flavors: cache = os.path.join(self.eups._userStackCache(testEupsStack), ProductStack.persistFilename(flav)) - self.assert_(os.path.exists(cache), + self.assertTrue(os.path.exists(cache), "Cache file for %s not written" % flav) def testPrefTags(self): @@ -121,31 +119,31 @@ def testFindProduct(self): # look for non-existent flavor prod = self.eups.findProduct("eigen", "2.0.0", flavor="Darwin") - self.assert_(prod is None, "Found non-existent flavor") + self.assertIsNone(prod, "Found non-existent flavor") prod = self.eups.findProduct("eigen", "2.0.1", flavor="Linux") - self.assert_(prod is None, "Found non-existent version") + self.assertIsNone(prod, "Found non-existent version") # find by name, version, flavor prod = self.eups.findProduct("eigen", "2.0.0", flavor="Linux") - self.assert_(prod is not None, "Failed to find product") + self.assertIsNotNone(prod, "Failed to find product") self.assertEqual(prod.name, "eigen") self.assertEqual(prod.version, "2.0.0") self.assertEqual(prod.flavor, "Linux") # look for non-existent name-version combo prod = self.eups.findProduct("eigen", "2.0.1") - self.assert_(prod is None, "Found non-existent version") + self.assertIsNone(prod, "Found non-existent version") # find by name, version prod = self.eups.findProduct("eigen", "2.0.0") - self.assert_(prod is not None, "Failed to find product") + self.assertIsNotNone(prod, "Failed to find product") self.assertEqual(prod.name, "eigen") self.assertEqual(prod.version, "2.0.0") self.assertEqual(prod.flavor, "Linux") # find by name prod = self.eups.findProduct("eigen") - self.assert_(prod is not None, "Failed to find product") + self.assertIsNotNone(prod, "Failed to find product") self.assertEqual(prod.name, "eigen") self.assertEqual(prod.version, "2.0.0") self.assertEqual(prod.flavor, "Linux") @@ -153,7 +151,7 @@ def testFindProduct(self): # find by name, preferring tagged version prod = self.eups.findProduct("python") - self.assert_(prod is not None, "Failed to find python product") + self.assertIsNotNone(prod, "Failed to find python product") self.assertEqual(prod.name, "python") self.assertEqual(prod.version, "2.5.2") self.assertEqual(prod.flavor, "Linux") @@ -162,7 +160,7 @@ def testFindProduct(self): # find by name, preferring latest version tag = self.eups.tags.getTag("latest") prod = self.eups.findProduct("python", tag) - self.assert_(prod is not None, "Failed to find python product") + self.assertIsNotNone(prod, "Failed to find python product") self.assertEqual(prod.name, "python") self.assertEqual(prod.version, "2.6") self.assertEqual(prod.flavor, "Linux") @@ -205,16 +203,16 @@ def testFindProduct(self): # look for a setup version tag = self.eups.tags.getTag("setup") prod = self.eups.findProduct("python", tag) - self.assert_(prod is None, "Found unsetup product") + self.assertIsNone(prod, "Found unsetup product") def testAssignTags(self): prod = self.eups.getProduct("python", "2.6") - self.assert_(prod is not None, "Failed to find python 2.6") + self.assertIsNotNone(prod, "Failed to find python 2.6") if "beta" in prod.tags: print("Warning: python 2.6 is already tagged beta", file=sys.stderr) self.eups.assignTag("beta", "python", "2.6") - self.assert_(os.path.exists(self.betachain), + self.assertTrue(os.path.exists(self.betachain), "Failed to create beta tag file for python") prod = self.eups.getProduct("python", "2.6", noCache=True) self.assertIn("beta", prod.tags) @@ -229,23 +227,23 @@ def testAssignTags(self): q = Quiet(self.eups) self.eups.unassignTag("beta", "python", "2.5.2") del q - self.assert_(os.path.exists(self.betachain), + self.assertTrue(os.path.exists(self.betachain), "Incorrectly removed beta tag file for python") # test unassign, specifying version self.eups.unassignTag("beta", "python", "2.6") - self.assert_(not os.path.exists(self.betachain), + self.assertFalse(os.path.exists(self.betachain), "Failed to remove beta tag file for python") # test unassign to any version self.eups.assignTag("beta", "python", "2.6") - self.assert_(os.path.exists(self.betachain), + self.assertTrue(os.path.exists(self.betachain), "Failed to create beta tag file for python") self.eups.unassignTag("beta", "python") - self.assert_(not os.path.exists(self.betachain), + self.assertFalse(os.path.exists(self.betachain), "Failed to remove beta tag file for python") prod = self.eups.findProduct("python", self.eups.tags.getTag("beta")) - self.assert_(prod is None, "Failed to untag beta from %s" % prod) + self.assertIsNone(prod, "Failed to untag beta from %s" % prod) def testDeclare(self): pdir = os.path.join(testEupsStack, "Linux", "newprod") @@ -257,7 +255,7 @@ def testDeclare(self): # test declare. Note: "current" is now a default tag assignment self.eups.declare("newprod", "1.0", pdir10, testEupsStack, table) prod = self.eups.findProduct("newprod") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(prod.name, "newprod") self.assertEqual(prod.version, "1.0") self.assertEqual(len(prod.tags), 1) @@ -267,22 +265,22 @@ def testDeclare(self): self.assertEqual(prod.version, "1.0") self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], 'current') - self.assert_(os.path.exists(os.path.join(self.dbpath, + self.assertTrue(os.path.exists(os.path.join(self.dbpath, "newprod", "1.0.version"))) # test undeclare self.eups.undeclare("newprod", "1.0", testEupsStack) prod = self.eups.findProduct("newprod") - self.assert_(prod is None, "Found undeclared product") + self.assertIsNone(prod, "Found undeclared product") prod = self.eups.findProduct("newprod", noCache=True) - self.assert_(prod is None, "Found undeclared product") - self.assert_(not os.path.exists(os.path.join(self.dbpath, + self.assertIsNone(prod, "Found undeclared product") + self.assertFalse(os.path.exists(os.path.join(self.dbpath, "newprod", "1.0.version"))) # test declaring with tag (+ without eupsPathDir) self.eups.declare("newprod", "1.0", pdir10, None, table, tag="beta") prod = self.eups.findProduct("newprod", eupsPathDirs=testEupsStack) - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "beta") @@ -303,12 +301,12 @@ def testDeclare(self): # test 2nd declare, w/ transfer of tag self.eups.declare("newprod", "1.1", pdir11, None, table, tag="beta") prod = self.eups.findProduct("newprod", "1.1") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(prod.dir, pdir11) self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "beta") prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(len(prod.tags), 0) # test redeclare w/change of product dir @@ -321,7 +319,7 @@ def testDeclare(self): self.eups.force = True self.eups.declare("newprod", "1.1", pdir10, None, table, tag="beta") prod = self.eups.findProduct("newprod", "1.1") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(prod.dir, pdir10) self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "beta") @@ -332,60 +330,60 @@ def testDeclare(self): # test tagging via declare (install dir determined on fly) self.eups.declare("newprod", "1.0", tag="current") chainfile = os.path.join(self.dbpath, "newprod", "current.chain") - self.assert_(os.path.exists(chainfile)) + self.assertTrue(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "current") # test unassign of tag via undeclare self.eups.undeclare("newprod", "1.0", tag="current") - self.assert_(not os.path.exists(chainfile)) + self.assertFalse(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Unintentionally undeclared product") + self.assertIsNotNone(prod, "Unintentionally undeclared product") self.assertEqual(len(prod.tags), 0) # test deprecated declareCurrent q = Quiet(self.eups) self.eups.declare ("newprod", "1.0", declareCurrent=True) - self.assert_(os.path.exists(chainfile)) + self.assertTrue(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "current") self.eups.undeclare("newprod", "1.0", undeclareCurrent=True) - self.assert_(not os.path.exists(chainfile)) + self.assertFalse(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Unintentionally undeclared product") + self.assertIsNotNone(prod, "Unintentionally undeclared product") self.assertEqual(len(prod.tags), 0) # test deprecated declareCurrent self.eups.declare("newprod", "1.0", pdir10, testEupsStack, table, True) - self.assert_(os.path.exists(chainfile)) + self.assertTrue(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") self.assertEqual(len(prod.tags), 1) self.assertEqual(prod.tags[0], "current") self.eups.undeclare("newprod", "1.0", testEupsStack, True) - self.assert_(not os.path.exists(chainfile)) + self.assertFalse(os.path.exists(chainfile)) prod = self.eups.findProduct("newprod", "1.0") - self.assert_(prod is not None, "Unintentionally undeclared product") + self.assertIsNotNone(prod, "Unintentionally undeclared product") self.assertEqual(len(prod.tags), 0) del q # test undeclare of tagged product self.eups.undeclare("newprod", "1.1") chainfile = os.path.join(self.dbpath, "newprod", "beta.chain") - self.assert_(not os.path.exists(chainfile), + self.assertFalse(os.path.exists(chainfile), "undeclared tag file still exists") prod = self.eups.findTaggedProduct("newprod", "beta") - self.assert_(prod is None, "removed tag still assigned") + self.assertIsNone(prod, "removed tag still assigned") prod = self.eups.findProduct("newprod") - self.assert_(prod is not None, "all products removed") + self.assertIsNotNone(prod, "all products removed") # needs listProducts() self.eups.undeclare("newprod") - self.assert_(not os.path.exists(os.path.join(self.dbpath,"newprod")), + self.assertFalse(os.path.exists(os.path.join(self.dbpath,"newprod")), "product not fully removed") def testDeclareStdinTable(self): @@ -393,17 +391,17 @@ def testDeclareStdinTable(self): pdir11 = os.path.join(pdir, "1.1") tableStrm = StringIO.StringIO('setupRequired("python")\n') prod = self.eups.findProduct("newprod", "1.1") - self.assert_(prod is None, "newprod is already declared") + self.assertIsNone(prod, "newprod is already declared") # declare with table coming from input stream self.eups.declare("newprod", "1.1", pdir11, testEupsStack, tableStrm) prod = self.eups.findProduct("newprod", "1.1") - self.assert_(prod is not None, "failed to declare newprod 1.1") + self.assertIsNotNone(prod, "failed to declare newprod 1.1") self.assertEqual(prod.tablefile, os.path.join(self.dbpath, "Linux","newprod","1.1", "ups", "newprod.table")) def testUserTags(self): - self.assert_(self.eups.tags.isRecognized("mine"), + self.assertTrue(self.eups.tags.isRecognized("mine"), "user:mine not recognized") prod = self.eups.getProduct("python", "2.5.2") self.assertNotIn("user:mine", prod.tags, "user:mine already assigned") @@ -521,16 +519,16 @@ def testRemove(self): pdir10 = os.path.join(pdir, "1.0") pdir20 = os.path.join(pdir, "2.0") shutil.copytree(pdir10, pdir20) - self.assert_(os.path.isdir(pdir20)) + self.assertTrue(os.path.isdir(pdir20)) self.eups.declare("newprod", "2.0", pdir20) - self.assert_(os.path.exists(os.path.join(self.dbpath,"newprod","2.0.version"))) + self.assertTrue(os.path.exists(os.path.join(self.dbpath,"newprod","2.0.version"))) # self.eups.verbose=1 # self.eups.remove("newprod", "2.0", False, interactive=True) self.eups.remove("newprod", "2.0", False) - self.assert_(not os.path.exists(os.path.join(self.dbpath,"newprod","2.0.version")), + self.assertFalse(os.path.exists(os.path.join(self.dbpath,"newprod","2.0.version")), "Failed to undeclare newprod") - self.assert_(not os.path.exists(pdir20), "Failed to remove newprod") + self.assertFalse(os.path.exists(pdir20), "Failed to remove newprod") # need to test for recursion @@ -552,7 +550,7 @@ def setUp(self): def tearDown(self): usercachedir = os.path.join(testEupsStack,"_userdata_","_caches_") if os.path.exists(usercachedir): - os.system("rm -rf " + usercachedir) + shutil.rmtree(usercachedir, ignore_errors=True) newprod = os.path.join(self.dbpath,"newprod") if os.path.exists(newprod): @@ -574,24 +572,24 @@ def testDetectOutOfSync(self): time.sleep(1) prod = e1.findProduct("newprod") - self.assert_(prod is None, "Found not-yet declared product") + self.assertIsNone(prod, "Found not-yet declared product") prod = e2.findProduct("newprod") - self.assert_(prod is None, "Found not-yet declared product") + self.assertIsNone(prod, "Found not-yet declared product") pdir = os.path.join(testEupsStack, "Linux", "newprod") pdir10 = os.path.join(pdir, "1.0") table = os.path.join(pdir10, "ups", "newprod.table") e1.declare("newprod", "1.0", pdir10, testEupsStack, table) prod = e1.findProduct("newprod") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") # Eups now keeps things in sync # prod = e2.findProduct("newprod") - # self.assert_(prod is None, "Failed to consult out-of-sync cache") + # self.assertIsNone(prod, "Failed to consult out-of-sync cache") e2.assignTag("beta", "python", "2.5.2") prod = e2.findProduct("newprod") - self.assert_(prod is not None, "Failed to declare product") + self.assertIsNotNone(prod, "Failed to declare product") #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- diff --git a/tests/testProduct.py b/tests/testProduct.py index c6a414df..99eb4aac 100644 --- a/tests/testProduct.py +++ b/tests/testProduct.py @@ -23,10 +23,10 @@ def testInit(self): self.assertEqual(self.prod.name, "eups") self.assertEqual(self.prod.version, "1.0") self.assertEqual(self.prod.dir, testEupsStack) - self.assert_(self.prod.db is None) - self.assert_(self.prod._table is None) - self.assert_(self.prod.tablefile is None) - self.assert_(self.prod._prodStack is None) + self.assertIsNone(self.prod.db) + self.assertIsNone(self.prod._table) + self.assertIsNone(self.prod.tablefile) + self.assertIsNone(self.prod._prodStack) db = os.path.join(os.environ["PWD"], "ups_db") p = Product("eups", "1.0", dir=os.environ["PWD"], @@ -37,7 +37,7 @@ def testInit(self): self.assertIn("mine", p.tags) def testStackRoot(self): - self.assert_(self.prod.stackRoot() is None) + self.assertIsNone(self.prod.stackRoot()) self.prod.db = os.path.join(self.prod.dir, "ups_db") self.assertEqual(self.prod.stackRoot(), self.prod.dir) @@ -46,20 +46,20 @@ def testTableFileName(self): self.assertEqual(path, os.path.join(testEupsStack,"ups","eups.table")) self.prod.tablefile = "none" - self.assert_(self.prod.tableFileName() is None) + self.assertIsNone(self.prod.tableFileName()) self.prod.tablefile = "/tmp/eups.table" self.assertEqual(self.prod.tableFileName(), "/tmp/eups.table") def testTableFileName2(self): self.prod.name = None - self.assert_(self.prod.tableFileName() is None) + self.assertIsNone(self.prod.tableFileName()) def testTableFileName3(self): self.prod.dir = None - self.assert_(self.prod.tableFileName() is None) + self.assertIsNone(self.prod.tableFileName()) self.prod.dir = "none" - self.assert_(self.prod.tableFileName() is None) + self.assertIsNone(self.prod.tableFileName()) def testGetTable(self): self.assertRaises(TableFileNotFound, self.prod.getTable) @@ -85,8 +85,8 @@ def testProd1(self): self.assertEqual(prod.dir, pdir) self.assertEqual(prod.db, self.dbpath) - self.assert_(prod.ups_dir is None) - self.assert_(prod.tablefile is None) + self.assertIsNone(prod.ups_dir) + self.assertIsNone(prod.tablefile) self.assertEqual(prod.tableFileName(), os.path.join(pdir,"ups",pname+".table")) @@ -94,8 +94,8 @@ def testProd1(self): clone = prod.clone() self.assertEqual(clone.dir, pdir) self.assertEqual(clone.db, self.dbpath) - self.assert_(clone.ups_dir is None) - self.assert_(clone.tablefile is None) + self.assertIsNone(clone.ups_dir) + self.assertIsNone(clone.tablefile) self.assertEqual(clone.tableFileName(), os.path.join(pdir,"ups",pname+".table")) @@ -162,7 +162,7 @@ def testProd2(self): self.assertEqual(prod.db, self.dbpath) self.assertEqual(prod.tablefile, os.path.join(self.dbpath,"newprod/Linux/2.0.table")) - self.assert_(prod.ups_dir is None) + self.assertIsNone(prod.ups_dir) self.assertEqual(prod.tableFileName(), os.path.join(self.dbpath,"newprod/Linux/2.0.table")) @@ -172,7 +172,7 @@ def testProd2(self): self.assertEqual(clone.db, self.dbpath) self.assertEqual(clone.tablefile, os.path.join(self.dbpath,"newprod/Linux/2.0.table")) - self.assert_(clone.ups_dir is None) + self.assertIsNone(clone.ups_dir) self.assertEqual(clone.tableFileName(), os.path.join(self.dbpath,"newprod/Linux/2.0.table")) @@ -180,7 +180,7 @@ def testProd2(self): prod.resolvePaths() self.assertEqual(prod.dir, pdir) self.assertEqual(prod.db, self.dbpath) - self.assert_(prod.ups_dir is None) + self.assertIsNone(prod.ups_dir) self.assertEqual(prod.tablefile, os.path.join(self.dbpath,"newprod/Linux/2.0.table")) self.assertEqual(prod.tableFileName(), diff --git a/tests/testServerAll.py b/tests/testServerAll.py index da308d9c..8c0f910a 100644 --- a/tests/testServerAll.py +++ b/tests/testServerAll.py @@ -2,7 +2,6 @@ """ A master script for running all tests. """ -from __future__ import print_function import sys, unittest from testServerLocal import * diff --git a/tests/testServerLSST.py b/tests/testServerLSST.py index deddf6ec..91c14c7b 100644 --- a/tests/testServerLSST.py +++ b/tests/testServerLSST.py @@ -33,7 +33,7 @@ def tearDown(self): def testGetConfigFile(self): ds = DistribServer(self.base) configFile = ds.getConfigFile(self.configFile) - self.assert_(os.path.exists(configFile)) + self.assertTrue(os.path.exists(configFile)) @@ -63,7 +63,7 @@ def setUp(self): # an empty config file self.configFile = os.path.join(testEupsStack,"testserver","s2", "config.txt") - self.assert_(os.path.isfile(self.configFile)) + self.assertTrue(os.path.isfile(self.configFile)) conf = ServerConf(self.pkgroot, configFile=self.configFile) self.ds = conf.createDistribServer() @@ -72,13 +72,13 @@ def tearDown(self): pass def testInit(self): - self.assert_(isinstance(self.ds, ConfigurableDistribServer), + self.assertTrue(isinstance(self.ds, ConfigurableDistribServer), "factory did not return ConfigurableDistribServer") self.assertEqual(self.ds.getConfigProperty("PREFER_GENERIC",""), '') def testListAvailProds(self): prods = self.ds.listAvailableProducts() - self.assert_(len(prods) > 300) + self.assertTrue(len(prods) > 300) def testGetTagNames(self): # test default implementation @@ -96,7 +96,7 @@ def testGetTagNames(self): def testGetManifest(self): man = self.ds.getManifest("doxygen", "1.5.9", "generic") - self.assert_(man is not None) + self.assertIsNotNone(man) self.assertEqual(man.product, "doxygen") self.assertEqual(man.version, "1.5.9") self.assertEqual(len(man.getProducts()), 1) @@ -138,20 +138,20 @@ def tearDown(self): pass def testInit(self): - self.assert_(self.repos.distServer, DistribServer) + self.assertTrue(self.repos.distServer, DistribServer) def testIsWritable(self): - self.assert_(not self.repos.isWritable()) + self.assertFalse(self.repos.isWritable()) def testGetManifest(self): man = self.repos.getManifest("doxygen", "1.5.9", "generic") - self.assert_(man is not None) + self.assertIsNotNone(man) def testListPackages(self): pkgs = self.repos.listPackages() - self.assert_(pkgs is not None) - self.assert_(isinstance(pkgs, list)) - self.assert_(len(pkgs) > 300) + self.assertIsNotNone(pkgs) + self.assertTrue(isinstance(pkgs, list)) + self.assertTrue(len(pkgs) > 300) def testGetSupportedTags(self): tags = self.repos.getSupportedTags() @@ -162,32 +162,32 @@ def testGetSupportedTags(self): def testFindPackage(self): pkg = self.repos.findPackage("doxygen") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.4") self.assertEqual(pkg[2], "generic") pkg = self.repos.findPackage("doxygen", "1.5.9") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") pkg = self.repos.findPackage("doxygen", "1.5.0") - self.assert_(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.9", "Linux") - self.assert_(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.9", "generic") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") tag = Tag("latest") pkg = self.repos.findPackage("doxygen", tag) - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") @@ -215,34 +215,34 @@ def testFindPackage1(self): self.assertEqual(len(self.repos.pkgroots), 2) pkg = self.repos.findPackage("doxygen") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") self.assertEqual(pkg[3], self.lsstroot) pkg = self.repos.findPackage("doxygen", "1.5.9") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") self.assertEqual(pkg[3], self.lsstroot) pkg = self.repos.findPackage("doxygen", "1.5.8") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") self.assertEqual(pkg[3], self.localroot) pkg = self.repos.findPackage("doxygen", "1.5.0") - self.assert_(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.9", "Linux") - self.assert_(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.9", "generic") - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") @@ -250,7 +250,7 @@ def testFindPackage1(self): tag = Tag("latest") pkg = self.repos.findPackage("doxygen", tag) - self.assert_(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.9") self.assertEqual(pkg[2], "generic") @@ -262,8 +262,8 @@ def testListPackages(self): self.assertEqual(len(self.repos.pkgroots), 2) pkgs = self.repos.listPackages() - self.assert_(pkgs is not None) - self.assert_(isinstance(pkgs, list)) + self.assertIsNotNone(pkgs) + self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) # the # of repositories self.assertEqual(len(pkgs[0]), 2) # (pkgroot, pkg-list) self.assertEqual(len(pkgs[1]), 2) # (pkgroot, pkg-list) @@ -272,12 +272,12 @@ def testListPackages(self): self.assertEqual(pkgs[0][1][0][0], "doxygen") self.assertEqual(pkgs[0][1][0][1], "1.5.8") self.assertEqual(pkgs[0][1][0][2], "generic") - self.assert_(len(pkgs[1][1]) > 300) # # of products per repos. + self.assertTrue(len(pkgs[1][1]) > 300) # # of products per repos. pkgs = self.repos.listPackages("doxygen") pkgs = self.repos.listPackages("doxygen") - self.assert_(pkgs is not None) - self.assert_(isinstance(pkgs, list)) + self.assertIsNotNone(pkgs) + self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) self.assertEqual(len(pkgs[0][1]), 1) # # of products per repos. self.assertEqual(pkgs[0][1][0][0], "doxygen") @@ -318,17 +318,17 @@ def tearDown(self): def testInstall(self): prod = Eups().findProduct("lssteups") - self.assert_(prod is None) + self.assertIsNone(prod) cmd = "distrib install lssteups 1.1 -q -r " + self.lsstroot cmd = eups.cmd.EupsCmd(args=cmd.split(), toolname=prog) self.assertEqual(cmd.run(), 0) prod = Eups().findProduct("lssteups") - self.assert_(prod is not None) + self.assertIsNotNone(prod) self.assertEqual(prod.version, "1.1") - self.assert_(prod.dir.endswith("lssteups/1.1")) - self.assert_(os.path.exists(prod.dir)) + self.assertTrue(prod.dir.endswith("lssteups/1.1")) + self.assertTrue(os.path.exists(prod.dir)) pdir = prod.dir cmd = "remove lssteups 1.1" @@ -336,30 +336,30 @@ def testInstall(self): self.assertEqual(cmd.run(), 0) prod = Eups().findProduct("lssteups") - self.assert_(prod is None) + self.assertIsNone(prod) cmd = "distrib install lssteups 1.1 --noclean -q -r " + self.lsstroot cmd = eups.cmd.EupsCmd(args=cmd.split(), toolname=prog) self.assertEqual(cmd.run(), 0) prod = Eups().findProduct("lssteups") - self.assert_(prod is not None) + self.assertIsNotNone(prod) bdir = os.path.join(testEupsStack,"EupsBuildDir",self.flavor,"lssteups-1.1") - self.assert_(os.path.exists(bdir), "%s does not exist" % bdir) + self.assertTrue(os.path.exists(bdir), "%s does not exist" % bdir) cmd = "distrib clean lssteups 1.1 -r " + self.lsstroot cmd = eups.cmd.EupsCmd(args=cmd.split(), toolname=prog) self.assertEqual(cmd.run(), 0) - self.assert_(not os.path.exists(bdir), "%s still exists" % bdir) + self.assertFalse(os.path.exists(bdir), "%s still exists" % bdir) cmd = "distrib clean lssteups 1.1 -q -R -r " + self.lsstroot cmd = eups.cmd.EupsCmd(args=cmd.split(), toolname=prog) self.assertEqual(cmd.run(), 0) - self.assert_(not os.path.exists(bdir), "%s still exists" % bdir) + self.assertFalse(os.path.exists(bdir), "%s still exists" % bdir) prod = Eups().findProduct("lssteups") - self.assert_(prod is None) - self.assert_(not os.path.exists(pdir)) + self.assertIsNone(prod) + self.assertFalse(os.path.exists(pdir)) __all__ = "LsstConfigFileTestCase LsstServerConfTestCase LsstDistribServerTestCase LsstRepositoryTestCase LsstRepositoriesTestCase".split() diff --git a/tests/testServerLocal.py b/tests/testServerLocal.py index 08cee9d5..004164d7 100644 --- a/tests/testServerLocal.py +++ b/tests/testServerLocal.py @@ -20,13 +20,13 @@ def setUp(self): def testGenericTransporter(self): loc = self.base+"s1/config.txt" localfile = "/tmp/eupstest-config.txt" - self.assertTrue(not Transporter.canHandle(loc)) + self.assertFalse(Transporter.canHandle(loc)) if os.path.exists(localfile): os.remove(localfile) trx = Transporter(loc) self.assertRaises(Exception, trx.listDir) self.assertRaises(Exception, trx.cacheToFile, localfile) - self.assertTrue(not os.path.exists(localfile)) + self.assertFalse(os.path.exists(localfile)) self.assertRaises(Exception, trx.listDir) def testLocalTransporter(self): @@ -39,7 +39,7 @@ def testLocalTransporter(self): trx = LocalTransporter(loc) # self.assertRaises(RemoteFileNotFound, trx.cacheToFile, localfile) - self.assertTrue(not os.path.exists(localfile)) + self.assertFalse(os.path.exists(localfile)) loc = os.path.join(base,"s2","config.txt") trx = LocalTransporter(loc) @@ -159,11 +159,11 @@ def testIsWritable(self): def testGetManifest(self): man = self.repos.getManifest("doxygen", "1.5.8", "generic") - self.assertTrue(man is not None) + self.assertIsNotNone(man) def testListPackages(self): pkgs = self.repos.listPackages() - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 1) self.assertEqual(pkgs[0][0], "doxygen") @@ -171,7 +171,7 @@ def testListPackages(self): self.assertEqual(pkgs[0][2], "generic") pkgs = self.repos.listPackages("doxygen") - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 1) self.assertEqual(pkgs[0][0], "doxygen") @@ -179,7 +179,7 @@ def testListPackages(self): self.assertEqual(pkgs[0][2], "generic") pkgs = self.repos.listPackages("doxygen", "1.5.10") - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 0) @@ -190,32 +190,32 @@ def testGetSupportedTags(self): def testFindPackage(self): pkg = self.repos.findPackage("doxygen") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") pkg = self.repos.findPackage("doxygen", "1.5.8") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") pkg = self.repos.findPackage("doxygen", "1.5.0") - self.assertTrue(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.8", "Linux") self.assertTrue(pkg[2] == 'generic') pkg = self.repos.findPackage("doxygen", "1.5.8", "generic") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") tag = Tag("latest") pkg = self.repos.findPackage("doxygen", tag) - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") @@ -238,7 +238,7 @@ def testInit(self): def testListPackages(self): pkgs = self.repos.listPackages() - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) # the # of repositories self.assertEqual(len(pkgs[0]), 2) # (pkgroot, pkg-list) @@ -253,7 +253,7 @@ def testListPackages(self): self.assertEqual(pkgs[1][1][0][2], "generic") pkgs = self.repos.listPackages("doxygen") - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) self.assertEqual(pkgs[0][1][0][0], "doxygen") @@ -261,7 +261,7 @@ def testListPackages(self): self.assertEqual(pkgs[0][1][0][2], "generic") pkgs = self.repos.listPackages("doxygen", "1.5.10") - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) # the # of repositories self.assertEqual(len(pkgs[0][1]), 0) # # of products per repos. @@ -269,7 +269,7 @@ def testListPackages(self): tag = Tag("latest") pkgs = self.repos.listPackages("doxygen", tag) - self.assertTrue(pkgs is not None) + self.assertIsNotNone(pkgs) self.assertTrue(isinstance(pkgs, list)) self.assertEqual(len(pkgs), 2) self.assertEqual(pkgs[0][1][0][0], "doxygen") @@ -281,26 +281,26 @@ def testListPackages(self): def testFindPackage(self): pkg = self.repos.findPackage("doxygen") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") pkg = self.repos.findPackage("doxygen", "1.5.8") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") self.assertEqual(pkg[3], self.pkgroot) pkg = self.repos.findPackage("doxygen", "1.5.0") - self.assertTrue(pkg is None) + self.assertIsNone(pkg) pkg = self.repos.findPackage("doxygen", "1.5.8", "Linux") self.assertTrue(pkg[2] == 'generic') pkg = self.repos.findPackage("doxygen", "1.5.8", "generic") - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") @@ -308,7 +308,7 @@ def testFindPackage(self): tag = Tag("latest") pkg = self.repos.findPackage("doxygen", tag) - self.assertTrue(pkg is not None) + self.assertIsNotNone(pkg) self.assertEqual(pkg[0], "doxygen") self.assertEqual(pkg[1], "1.5.8") self.assertEqual(pkg[2], "generic") diff --git a/tests/testServerSsh.py b/tests/testServerSsh.py index e95c61a5..85a46dbc 100644 --- a/tests/testServerSsh.py +++ b/tests/testServerSsh.py @@ -23,13 +23,13 @@ def setUp(self): def testGenericTransporter(self): loc = self.base+"s1/config.txt" localfile = "/tmp/eupstest-config.txt" - self.assert_(not Transporter.canHandle(loc)) + self.assertFalse(Transporter.canHandle(loc)) if os.path.exists(localfile): os.remove(localfile) trx = Transporter(loc) self.assertRaises(Exception, trx.listDir) self.assertRaises(Exception, trx.cacheToFile, localfile) - self.assert_(not os.path.exists(localfile)) + self.assertFalse(os.path.exists(localfile)) self.assertRaises(Exception, trx.listDir) def testSshTransporter(self): @@ -37,16 +37,16 @@ def testSshTransporter(self): localfile = "/tmp/eupstest-config.txt" if os.path.exists(localfile): os.remove(localfile) - self.assert_(SshTransporter.canHandle(loc)) + self.assertTrue(SshTransporter.canHandle(loc)) trx = SshTransporter(loc) # self.assertRaises(RemoteFileNotFound, trx.cacheToFile, localfile) - self.assert_(not os.path.exists(localfile)) + self.assertFalse(os.path.exists(localfile)) loc = self.base+"s2/config.txt" trx = SshTransporter(loc) trx.cacheToFile(localfile) - self.assert_(os.path.exists(localfile)) + self.assertTrue(os.path.exists(localfile)) loc = self.base+"s2" trx = SshTransporter(loc) @@ -72,7 +72,7 @@ def tearDown(self): def testGetConfigFile(self): ds = DistribServer(self.base) configFile = ds.getConfigFile(self.configFile) - self.assert_(os.path.exists(configFile)) + self.assertTrue(os.path.exists(configFile)) diff --git a/tests/testServerWeb.py b/tests/testServerWeb.py index b31576da..bc5ebd82 100644 --- a/tests/testServerWeb.py +++ b/tests/testServerWeb.py @@ -26,16 +26,16 @@ def testWebTransporter(self): localfile = "/tmp/eupstest-config.txt" if os.path.exists(localfile): os.remove(localfile) - self.assert_(WebTransporter.canHandle(loc)) + self.assertTrue(WebTransporter.canHandle(loc)) trx = WebTransporter(loc) self.assertRaises(RemoteFileNotFound, trx.cacheToFile, localfile) - self.assert_(not os.path.exists(localfile)) + self.assertFalse(os.path.exists(localfile)) loc = self.base+"s2/config.txt" trx = WebTransporter(loc) trx.cacheToFile(localfile) - self.assert_(os.path.exists(localfile)) + self.assertTrue(os.path.exists(localfile)) loc = self.base+"s2" trx = WebTransporter(loc) @@ -59,7 +59,7 @@ def tearDown(self): def testGetConfigFile(self): ds = DistribServer(self.base) configFile = ds.getConfigFile(self.configFile) - self.assert_(os.path.exists(configFile)) + self.assertTrue(os.path.exists(configFile)) diff --git a/tests/testStack.py b/tests/testStack.py index 17dac881..b09baada 100644 --- a/tests/testStack.py +++ b/tests/testStack.py @@ -23,15 +23,15 @@ def testNotFound(self): def testAddVersion(self): self.fam.addVersion("3.1", "/opt/LInux/magnum/3.1") self.assertEqual(len(self.fam.getVersions()), 1) - self.assert_(not self.fam.hasVersion("1.0")) - self.assert_(self.fam.hasVersion("3.1")) + self.assertFalse(self.fam.hasVersion("1.0")) + self.assertTrue(self.fam.hasVersion("3.1")) self.fam.addVersion("3.2", "/opt/LInux/magnum/3.2") self.assertEqual(len(self.fam.getVersions()), 2) - self.assert_(self.fam.hasVersion("3.1")) - self.assert_(not self.fam.removeVersion("1.0")) - self.assert_(self.fam.removeVersion("3.1")) - self.assert_(not self.fam.hasVersion("3.1")) - self.assert_(self.fam.removeVersion("3.2")) + self.assertTrue(self.fam.hasVersion("3.1")) + self.assertFalse(self.fam.removeVersion("1.0")) + self.assertTrue(self.fam.removeVersion("3.1")) + self.assertFalse(self.fam.hasVersion("3.1")) + self.assertTrue(self.fam.removeVersion("3.2")) def testGetProduct(self): self.fam.addVersion("3.1", "/opt/LInux/magnum/3.1") @@ -45,15 +45,15 @@ def testAssignTag(self): self.fam.addVersion("3.2", "/opt/LInux/magnum/3.2") self.assertEqual(len(self.fam.getTags()), 0) tag = "stable" - self.assert_(not self.fam.isTagAssigned(tag)) + self.assertFalse(self.fam.isTagAssigned(tag)) self.fam.assignTag(tag, "3.1") self.assertEqual(len(self.fam.getTags()), 1) - self.assert_(self.fam.isTagAssigned(tag)) + self.assertTrue(self.fam.isTagAssigned(tag)) self.fam.assignTag("beta", "3.2") self.fam.assignTag("current", "3.1") self.assertEqual(len(self.fam.getTags()), 3) - self.assert_(self.fam.isTagAssigned("beta")) - self.assert_(self.fam.isTagAssigned("current")) + self.assertTrue(self.fam.isTagAssigned("beta")) + self.assertTrue(self.fam.isTagAssigned("current")) p = self.fam.getProduct("3.1") self.assertEqual(len(p.tags), 2) self.assertIn(tag, p.tags) @@ -68,10 +68,10 @@ def testAssignTag(self): self.assertIn(tag, p.tags) self.assertIn("current", p.tags) - self.assert_(not self.fam.unassignTag("gurn")) - self.assert_(self.fam.unassignTag("beta")) - self.assert_(not self.fam.isTagAssigned("beta")) - self.assert_(self.fam.isTagAssigned("current")) + self.assertFalse(self.fam.unassignTag("gurn")) + self.assertTrue(self.fam.unassignTag("beta")) + self.assertFalse(self.fam.isTagAssigned("beta")) + self.assertTrue(self.fam.isTagAssigned("current")) def testExport(self): self.fam.addVersion("3.1", "/opt/LInux/magnum/3.1") @@ -85,7 +85,7 @@ def testExport(self): p = prods["3.1"] self.assertEqual(p.name, "magnum") self.assertEqual(p.flavor, "Linux") - self.assert_(p.db is None) + self.assertIsNone(p.db) self.assertEqual(len(p.tags), 2) self.assertIn("current", p.tags) p.name = "helpful" @@ -93,31 +93,31 @@ def testExport(self): fam = ProductFamily("helpful") fam.import_(prods) self.assertEqual(len(fam.getVersions()), 1) - self.assert_(fam.hasVersion("3.1")) + self.assertTrue(fam.hasVersion("3.1")) def testLoadTable(self): tablefile = os.path.join(testEupsStack,"mwi.table") self.fam.addVersion("3.1", "/opt/LInux/magnum/3.1", tablefile) prod = self.fam.getProduct("3.1") - self.assert_(prod.tablefile is not None) - self.assert_(os.path.exists(prod.tablefile)) - self.assert_(prod._table is None) + self.assertIsNotNone(prod.tablefile) + self.assertTrue(os.path.exists(prod.tablefile)) + self.assertIsNone(prod._table) self.fam.loadTableFor("3.1") prod = self.fam.getProduct("3.1") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) def testLoadTables(self): tablefile = os.path.join(testEupsStack,"mwi.table") self.fam.addVersion("3.1", "/opt/LInux/magnum/3.1", tablefile) prod = self.fam.getProduct("3.1") - self.assert_(prod.tablefile is not None) - self.assert_(os.path.exists(prod.tablefile)) - self.assert_(prod._table is None) + self.assertIsNotNone(prod.tablefile) + self.assertTrue(os.path.exists(prod.tablefile)) + self.assertIsNone(prod._table) self.fam.loadTableFor("3.1") self.fam.loadTables() prod = self.fam.getProduct("3.1") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) @@ -193,7 +193,7 @@ def testGetVersions(self): self.assertIn(ver, vers) def testAutoSave(self): - self.assert_(self.stack.saveNeeded()) + self.assertTrue(self.stack.saveNeeded()) cache = os.path.join(os.environ["PWD"], ProductStack.persistFilename("Darwin")) @@ -201,24 +201,24 @@ def testAutoSave(self): stack = ProductStack(os.path.join(testEupsStack, "ups_db"), os.environ["PWD"], autosave=True) - self.assert_(not stack.saveNeeded()) + self.assertFalse(stack.saveNeeded()) stack.addProduct(Product("fw", "1.2", "Darwin", "/opt/sw/Darwin/fw/1.2", "none")) - self.assert_(not stack.saveNeeded()) - self.assert_(os.path.exists(cache)) + self.assertFalse(stack.saveNeeded()) + self.assertTrue(os.path.exists(cache)) if os.path.exists(cache): os.remove(cache) def testHasProduct(self): - self.assert_(self.stack.hasProduct("fw")) - self.assert_(not self.stack.hasProduct("afw")) - self.assert_(self.stack.hasProduct("fw", "Darwin")) - self.assert_(not self.stack.hasProduct("fw", "Linux")) - self.assert_(self.stack.hasProduct("fw", "Darwin", "1.2")) - self.assert_(not self.stack.hasProduct("fw", "Darwin", "1.3")) - self.assert_(not self.stack.hasProduct("afw", "Darwin", "1.2")) - self.assert_(not self.stack.hasProduct("fw", "Linux", "1.2")) - self.assert_(self.stack.hasProduct("fw", version="1.2")) - self.assert_(not self.stack.hasProduct("fw", version="1.3")) + self.assertTrue(self.stack.hasProduct("fw")) + self.assertFalse(self.stack.hasProduct("afw")) + self.assertTrue(self.stack.hasProduct("fw", "Darwin")) + self.assertFalse(self.stack.hasProduct("fw", "Linux")) + self.assertTrue(self.stack.hasProduct("fw", "Darwin", "1.2")) + self.assertFalse(self.stack.hasProduct("fw", "Darwin", "1.3")) + self.assertFalse(self.stack.hasProduct("afw", "Darwin", "1.2")) + self.assertFalse(self.stack.hasProduct("fw", "Linux", "1.2")) + self.assertTrue(self.stack.hasProduct("fw", version="1.2")) + self.assertFalse(self.stack.hasProduct("fw", version="1.3")) def testAddProduct(self): self.assertRaises(TypeError, @@ -229,7 +229,7 @@ def testAddProduct(self): prod = Product("afw", "1.2", "Darwin", "/opt/sw/Darwin/afw/1.2", "none") self.stack.addProduct(prod) - self.assert_(self.stack.hasProduct("afw")) + self.assertTrue(self.stack.hasProduct("afw")) p = self.stack.getProduct("afw", "1.2", "Darwin") self.assertEqual(p.name, prod.name) self.assertEqual(p.version, prod.version) @@ -245,8 +245,8 @@ def testAddProduct(self): self.stack.getProduct, "afw", "1.3", "Darwin") self.stack.removeProduct("afw", "Darwin", "1.2") - self.assert_(not self.stack.hasProduct("afw")) - self.assert_(not self.stack.removeProduct("afw", "Darwin", "1.2")) + self.assertFalse(self.stack.hasProduct("afw")) + self.assertFalse(self.stack.removeProduct("afw", "Darwin", "1.2")) def testGetFlavors(self): flavors = self.stack.getFlavors() @@ -269,7 +269,7 @@ def testAddFlavor(self): flavors = self.stack.getFlavors() self.assertEqual(len(flavors), 1) self.assertEqual(flavors[0], "Darwin") - self.assert_(self.stack.lookup["Darwin"]) + self.assertTrue(self.stack.lookup["Darwin"]) self.stack.addFlavor("Linux") flavors = self.stack.getFlavors() @@ -278,7 +278,7 @@ def testAddFlavor(self): for flav in expected: self.assertIn(flav, flavors) self.assertEqual(len(self.stack.getProductNames("Linux")), 0) - self.assert_(not self.stack.lookup["Linux"]) + self.assertFalse(self.stack.lookup["Linux"]) def testTags(self): self.assertEqual(len(self.stack.getTags()), 0) @@ -295,7 +295,7 @@ def testTags(self): self.assertEqual(tags[0], "beta") self.assertEqual(tags[1], "current") prod = self.stack.getTaggedProduct("afw", "Linux", "stable") - self.assert_(prod is None) + self.assertIsNone(prod) prod = self.stack.getTaggedProduct("afw", "Linux", "beta") self.assertEqual(prod.version, "1.2") self.assertEqual(prod.flavor, "Linux") @@ -313,8 +313,8 @@ def testTags(self): self.assertEqual(prod.flavor, "Linux") self.assertEqual(prod.db, self.dbpath) - self.assert_(not self.stack.unassignTag("gurn", "afw", "Linux")) - self.assert_(self.stack.unassignTag("beta", "afw")) + self.assertFalse(self.stack.unassignTag("gurn", "afw", "Linux")) + self.assertTrue(self.stack.unassignTag("beta", "afw")) tags = self.stack.getTags() self.assertEqual(len(tags), 1) self.assertEqual(tags[0], "current") @@ -323,11 +323,11 @@ def testSaveEmptyFlavor(self): self.stack.clearCache("Linux") cache = os.path.join(self.dbpath, ProductStack.persistFilename("Linux")) - self.assert_(not os.path.exists(cache)) + self.assertFalse(os.path.exists(cache)) try: self.stack.save("Linux") - self.assert_(os.path.exists(cache)) + self.assertTrue(os.path.exists(cache)) self.stack.reload("Linux") flavors = self.stack.getFlavors() self.assertEqual(len(flavors), 2) @@ -341,18 +341,18 @@ def testSaveEmptyFlavor(self): os.remove(cache) def testSave(self): - self.assert_(self.stack.saveNeeded()) + self.assertTrue(self.stack.saveNeeded()) self.stack.clearCache("Linux Linux64 Darwin DarwinX86 generic".split()) self.assertEqual(len(ProductStack.findCachedFlavors(self.dbpath)),0) cache = os.path.join(self.dbpath, ProductStack.persistFilename("Darwin")) - self.assert_(not os.path.exists(cache)) + self.assertFalse(os.path.exists(cache)) self.stack.save() - self.assert_(not self.stack.saveNeeded()) - self.assert_(os.path.exists(cache)) + self.assertFalse(self.stack.saveNeeded()) + self.assertTrue(os.path.exists(cache)) saved = ProductStack.findCachedFlavors(self.dbpath) self.assertEqual(len(saved), 1) @@ -371,7 +371,7 @@ def testSave(self): self.stack.clearCache() self.assertEqual(len(ProductStack.findCachedFlavors(self.dbpath)),0) - self.assert_(not os.path.exists(cache)) + self.assertFalse(os.path.exists(cache)) def testLoadTable(self): tablefile = os.path.join(testEupsStack,"mwi.table") @@ -381,7 +381,7 @@ def testLoadTable(self): self.stack.loadTableFor(prod.name, prod.version, prod.flavor) prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) def testLoadTables(self): tablefile = os.path.join(testEupsStack,"mwi.table") @@ -391,7 +391,7 @@ def testLoadTables(self): self.stack.loadTables() prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) def testLoadTablesForFlavor(self): tablefile = os.path.join(testEupsStack,"mwi.table") @@ -401,11 +401,11 @@ def testLoadTablesForFlavor(self): self.stack.loadTables(flavors="Linux") prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is None) + self.assertIsNone(prod._table) self.stack.loadTables(flavors="Darwin") prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) def testLoadTablesForProd(self): tablefile = os.path.join(testEupsStack,"mwi.table") @@ -415,11 +415,11 @@ def testLoadTablesForProd(self): self.stack.loadTables("newprod") prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is None) + self.assertIsNone(prod._table) self.stack.loadTables("afw") prod = self.stack.getProduct("afw", "1.2", "Darwin") - self.assert_(prod._table is not None) + self.assertIsNotNone(prod._table) @@ -441,15 +441,15 @@ def tearDown(self): def testRegen(self): ps = ProductStack.fromCache(self.dbpath, "Linux", autosave=True, updateCache=True, verbose=False) - self.assert_(not ps.hasProduct("afw")) + self.assertFalse(ps.hasProduct("afw")) prod = Product("afw", "1.2", "Darwin", "/opt/sw/Darwin/afw/1.2", "none") ps.addProduct(prod) ps.reload("Linux") - self.assert_(ps.hasProduct("afw")) + self.assertTrue(ps.hasProduct("afw")) del ps ps = ProductStack.fromCache(self.dbpath, "Linux", autosave=False, updateCache=True, verbose=False) - self.assert_(not ps.hasProduct("afw")) + self.assertFalse(ps.hasProduct("afw")) def testDetectOutOfSync(self): ps1 = ProductStack.fromCache(self.dbpath, "Linux", autosave=False, @@ -459,11 +459,11 @@ def testDetectOutOfSync(self): time.sleep(1) ps1.addProduct(Product("fw", "1.2", "Linux", "/opt/sw/Darwin/fw/1.2", "none")) - self.assert_(ps1.cacheIsInSync()) + self.assertTrue(ps1.cacheIsInSync()) ps1.save() - self.assert_(ps1.cacheIsInSync()) + self.assertTrue(ps1.cacheIsInSync()) - self.assert_(not ps2.cacheIsInSync()) + self.assertFalse(ps2.cacheIsInSync()) ps2.addProduct(Product("fw", "1.2", "Linux", "/opt/sw/Darwin/fw/1.2", "none")) self.assertRaises(CacheOutOfSync, ps2.save) diff --git a/tests/testTags.py b/tests/testTags.py index 4e8a12ef..3106df50 100644 --- a/tests/testTags.py +++ b/tests/testTags.py @@ -17,21 +17,21 @@ def setUp(self): self.tags.registerUserTag("rlp") def testRecognized(self): - self.assert_(self.tags.isRecognized("stable"), "stable not recognized") - self.assert_(self.tags.isRecognized("global:stable"), + self.assertTrue(self.tags.isRecognized("stable"), "stable not recognized") + self.assertTrue(self.tags.isRecognized("global:stable"), "global:stable not recognized") - self.assert_(not self.tags.isRecognized("user:stable"), + self.assertFalse(self.tags.isRecognized("user:stable"), "stable recognized as user tag") - self.assert_(self.tags.isRecognized("rlp"), "rlp not recognized") - self.assert_(self.tags.isRecognized("user:rlp"), + self.assertTrue(self.tags.isRecognized("rlp"), "rlp not recognized") + self.assertTrue(self.tags.isRecognized("user:rlp"), "user:rlp not recognized") - self.assert_(not self.tags.isRecognized("global:rlp"), + self.assertFalse(self.tags.isRecognized("global:rlp"), "rlp recognized as global tag") def testGroupFor(self): self.assertEqual(self.tags.groupFor("stable"), Tags.global_) self.assertEqual(self.tags.groupFor("rlp"), Tags.user) - self.assert_(self.tags.groupFor("goober") is None, + self.assertIsNone(self.tags.groupFor("goober"), "Found group for undefined tag") def testTagNames(self): @@ -42,22 +42,22 @@ def testTagNames(self): def testGetTag(self): tag = self.tags.getTag("stable") - self.assert_(isinstance(tag, Tag), "non-Tag returned by getTag()") + self.assertTrue(isinstance(tag, Tag), "non-Tag returned by getTag()") self.assertEqual(tag.name, "stable") self.assertEqual(tag.group, Tags.global_) tag = self.tags.getTag("global:stable") - self.assert_(isinstance(tag, Tag), "non-Tag returned by getTag()") + self.assertTrue(isinstance(tag, Tag), "non-Tag returned by getTag()") self.assertEqual(tag.name, "stable") self.assertEqual(tag.group, Tags.global_) tag = self.tags.getTag("rlp") - self.assert_(isinstance(tag, Tag), "non-Tag returned by getTag()") + self.assertTrue(isinstance(tag, Tag), "non-Tag returned by getTag()") self.assertEqual(tag.name, "rlp") self.assertEqual(tag.group, Tags.user) tag = self.tags.getTag("user:rlp") - self.assert_(isinstance(tag, Tag), "non-Tag returned by getTag()") + self.assertTrue(isinstance(tag, Tag), "non-Tag returned by getTag()") self.assertEqual(tag.name, "rlp") self.assertEqual(tag.group, Tags.user) @@ -85,19 +85,19 @@ def testCmp(self): stable2 = self.tags.getTag("stable") self.assertEqual(stable, stable2) rlp = self.tags.getTag("rlp") - self.assertNotEquals(stable, rlp) + self.assertNotEqual(stable, rlp) self.assertEqual("rlp", rlp) def testSaveLoad(self): file = os.path.join(testEupsStack, "ups_db", "test.tags") if os.path.exists(file): os.remove(file) - self.assert_(not os.path.exists(file)) + self.assertFalse(os.path.exists(file)) try: self.tags.registerTag("current") self.tags.registerTag("beta") self.tags.save(self.tags.global_, file) - self.assert_(os.path.exists(file)) + self.assertTrue(os.path.exists(file)) tags = Tags() tags.load(tags.global_, file) @@ -117,11 +117,11 @@ def testSaveLoadUserTags(self): self.assertEqual(len(self.tags.getTagNames()), 2) self.tags.loadUserTags(dir) self.assertEqual(len(self.tags.getTagNames()), 2) - self.assert_(not os.path.exists(file)) + self.assertFalse(os.path.exists(file)) try: self.tags.saveUserTags(dir) - self.assert_(os.path.exists(file), "cache file not found: " + file) + self.assertTrue(os.path.exists(file), "cache file not found: " + file) tags = Tags() tags.loadUserTags(dir) @@ -140,7 +140,7 @@ def testSaveLoadGlobalTags(self): self.tags.registerTag("current") self.tags.registerTag("beta") self.tags.saveGlobalTags(dir) - self.assert_(os.path.exists(file), "cache file not found: " + file) + self.assertTrue(os.path.exists(file), "cache file not found: " + file) tags = Tags() tags.loadFromEupsPath(dir, 1) diff --git a/tests/test_eups.py b/tests/test_eups.py index f97fb7e3..764ac456 100755 --- a/tests/test_eups.py +++ b/tests/test_eups.py @@ -3,7 +3,6 @@ Tests for eups """ -from __future__ import print_function import sys import unittest import eups