#338 Black the code
Merged 5 years ago by ngompa. Opened 5 years ago by churchyard.
churchyard/FedoraReview black  into  master

file modified
+3
@@ -5,3 +5,6 @@ 

  	pylint-3 --rcfile=pylint.conf \

  	--msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" \

  	src/FedoraReview plugins

+ 

+ black:

+ 	black koji-download-scratch try-fedora-review update-version  src/fedora-create-review src/fedora-review .

file modified
+3 -3
@@ -26,13 +26,14 @@ 

  

  # Load from site lib

  from distutils.sysconfig import get_python_lib

- sitedir = os.path.join(get_python_lib(), 'FedoraReview')

+ 

+ sitedir = os.path.join(get_python_lib(), "FedoraReview")

  if os.path.exists(sitedir):

      sys.path.insert(0, sitedir)

  

  # Load from development lib

  here = os.path.dirname(os.path.realpath(__file__))

- srcdir = os.path.join(here, 'src', 'FedoraReview')

+ srcdir = os.path.join(here, "src", "FedoraReview")

  if os.path.exists(srcdir):

      sys.path.insert(0, srcdir)

  
@@ -43,4 +44,3 @@ 

      download_scratch.main()

  except Exception as err:

      print(err)

- 

file modified
+75 -69
@@ -15,9 +15,9 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Register all check in this file in group 'R' '''

+     """ Register all check in this file in group 'R' """

  

-     group = 'R'

+     group = "R"

  

      def is_applicable(self):

          """ Check is the tests are applicable, here it checks whether
@@ -30,17 +30,17 @@ 

  

  class RCheckBase(CheckBase):

      """ Base class for all R specific checks. """

-     DIR = ['%{packname}']

-     DOCS = ['doc', 'DESCRIPTION', 'NEWS', 'CITATION']

+ 

+     DIR = ["%{packname}"]

+     DOCS = ["doc", "DESCRIPTION", "NEWS", "CITATION"]

      URLS = [

-         'https://www.bioconductor.org/packages/release/data/'

-         'experiment/src/contrib/PACKAGES',

-         'https://www.bioconductor.org/packages/release/data/'

-         'annotation/src/contrib/PACKAGES',

-         'https://www.bioconductor.org/packages/release/bioc/'

-         'src/contrib/PACKAGES',

-         'https://cran.r-project.org/src/contrib/PACKAGES',

-         'https://r-forge.r-project.org/src/contrib/PACKAGES',

+         "https://www.bioconductor.org/packages/release/data/"

+         "experiment/src/contrib/PACKAGES",

+         "https://www.bioconductor.org/packages/release/data/"

+         "annotation/src/contrib/PACKAGES",

+         "https://www.bioconductor.org/packages/release/bioc/" "src/contrib/PACKAGES",

+         "https://cran.r-project.org/src/contrib/PACKAGES",

+         "https://r-forge.r-project.org/src/contrib/PACKAGES",

      ]

  

      def __init__(self, base):
@@ -60,21 +60,20 @@ 

                  content = stream.read()

                  stream.close()

              except IOError as err:

-                 self.log.warning('Could not retrieve info from %s', url)

-                 self.log.debug('Error: %s', err, exc_info=True)

+                 self.log.warning("Could not retrieve info from %s", url)

+                 self.log.debug("Error: %s", err, exc_info=True)

                  continue

-             res = re.search(('Package: %s\nVersion:.*' % name).encode(),

-                             content)

+             res = re.search(("Package: %s\nVersion:.*" % name).encode(), content)

              if res is not None:

                  self.log.debug("Found in: %s", url)

                  versionok.append(url)

                  if version is None:

-                     ver = res.group().split(b'\n')[1]

-                     version = ver.replace(b'Version:', b'').strip()

+                     ver = res.group().split(b"\n")[1]

+                     version = ver.replace(b"Version:", b"").strip()

                  else:

                      self.log.warning(

-                         " * Found two version of the package in %s",

-                         " ".join(versionok))

+                         " * Found two version of the package in %s", " ".join(versionok)

+                     )

          return version

  

  
@@ -84,20 +83,22 @@ 

      def __init__(self, base):

          """ Instanciate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/R/'

-         self.text = 'Package contains the mandatory BuildRequires.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/R/"

+         self.text = "Package contains the mandatory BuildRequires."

          self.automatic = True

  

      def run_on_applicable(self):

          """ Run the check """

          brs = self.spec.build_requires

-         tocheck = ['R-devel', 'tex(latex)']

+         tocheck = ["R-devel", "tex(latex)"]

          if set(tocheck).intersection(set(brs)):

              self.set_passed(self.PASS)

          else:

-             self.set_passed(self.FAIL,

-                             'Missing BuildRequires on %s'

-                             % ', '.join(set(tocheck).difference(set(brs))))

+             self.set_passed(

+                 self.FAIL,

+                 "Missing BuildRequires on %s"

+                 % ", ".join(set(tocheck).difference(set(brs))),

+             )

  

  

  class RCheckRequires(RCheckBase):
@@ -106,18 +107,17 @@ 

      def __init__(self, base):

          """ Instanciate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/R/'

-         self.text = 'Package requires R-core.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/R/"

+         self.text = "Package requires R-core."

          self.automatic = True

  

      def run_on_applicable(self):

          """ Run the check """

          brs = self.spec.get_requires()

-         if 'R' in brs and 'R-core' not in brs:

-             self.set_passed(self.FAIL,

-                             "Package should requires R-core rather than R")

+         if "R" in brs and "R-core" not in brs:

+             self.set_passed(self.FAIL, "Package should requires R-core rather than R")

          else:

-             self.set_passed('R-core' in brs)

+             self.set_passed("R-core" in brs)

  

  

  class RCheckDoc(RCheckBase):
@@ -126,9 +126,9 @@ 

      def __init__(self, base):

          """ Instanciate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/R/'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/R/"

          self.automatic = True

-         self.text = 'Package have the default element marked as %%doc :'

+         self.text = "Package have the default element marked as %%doc :"

  

      def run_on_applicable(self):

          """ Run the check """
@@ -148,31 +148,33 @@ 

  class RCheckLatestVersionIsPackaged(RCheckBase):

      """ Check if the last version of the R package is the one proposed """

  

-     deprecates = ['CheckLatestVersionIsPackaged']

+     deprecates = ["CheckLatestVersionIsPackaged"]

  

      def __init__(self, base):

          """ Instanciate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'ihttps://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Latest version is packaged.'

+         self.url = "ihttps://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Latest version is packaged."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          """ Run the check """

-         cur_version = self.spec.expand_tag('Version').decode('utf-8')

+         cur_version = self.spec.expand_tag("Version").decode("utf-8")

          up_version = self.get_upstream_r_package_version()

          if up_version is None:

              self.set_passed(

                  self.PENDING,

-                 'The package does not come from one of the standard sources')

+                 "The package does not come from one of the standard sources",

+             )

              return

-         up_version = up_version.replace(b'-', b'.').decode('utf-8')

+         up_version = up_version.replace(b"-", b".").decode("utf-8")

  

          self.set_passed(

              up_version == cur_version,

              "Latest upstream version is %s, packaged version is %s"

-             % (up_version, cur_version))

+             % (up_version, cur_version),

+         )

  

  

  class RCheckCheckMacro(RCheckBase):
@@ -181,14 +183,14 @@ 

      def __init__(self, base):

          """ Instantiate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'The %check macro is present'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "The %check macro is present"

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          """ Run the check """

-         sec_check = self.spec.get_section('%check')

+         sec_check = self.spec.get_section("%check")

          self.set_passed(bool(sec_check))

  

  
@@ -198,10 +200,10 @@ 

      def __init__(self, base):

          """ Instanciate check variable """

          RCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/R/'

-         self.text = 'The package has the standard %install section.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/R/"

+         self.text = "The package has the standard %install section."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          """ Run the check """
@@ -209,41 +211,45 @@ 

          b_test = False

          b_rm = False

          b_install = False

-         section = self.spec.get_section('%install')

+         section = self.spec.get_section("%install")

          if not section:

              self.set_passed(self.FAIL)

              return

  

          for line in section:

-             if 'mkdir -p' in line and \

-                 ('/R/library' in line or 'rlibdir' in line):

+             if "mkdir -p" in line and ("/R/library" in line or "rlibdir" in line):

                  b_dir = True

-             if rpm.expandMacro("test -d %{packname}/src && "

-                                "(cd %{packname}/src; rm -f *.o *.so)") in line:

+             if (

+                 rpm.expandMacro(

+                     "test -d %{packname}/src && " "(cd %{packname}/src; rm -f *.o *.so)"

+                 )

+                 in line

+             ):

                  b_test = True

-             if 'rm' in line and 'R.css' in line:

+             if "rm" in line and "R.css" in line:

                  b_rm = True

-             if 'R CMD INSTALL' in line \

-                 and '-l ' in line \

-                 and rpm.expandMacro('%{packname}') in line \

-                 and ('/R/library' in line or 'rlibdir' in line):

-                     b_install = True

+             if (

+                 "R CMD INSTALL" in line

+                 and "-l " in line

+                 and rpm.expandMacro("%{packname}") in line

+                 and ("/R/library" in line or "rlibdir" in line)

+             ):

+                 b_install = True

          if b_dir and b_test and b_rm and b_install:

              self.set_passed(self.PASS)

          else:

-             cmt = ''

+             cmt = ""

              if not b_dir:

-                 cmt += "Package doesn't have the standard " \

-                     "directory creation.\n"

+                 cmt += "Package doesn't have the standard " "directory creation.\n"

              if not b_test:

-                 cmt += "Package doesn't have the standard " \

-                     "removal of *.o and *.so.\n"

+                 cmt += "Package doesn't have the standard " "removal of *.o and *.so.\n"

              if not b_rm:

-                 cmt += "Package doesn't have the standard " \

-                     "removal of the R.css file\n"

+                 cmt += (

+                     "Package doesn't have the standard " "removal of the R.css file\n"

+                 )

              if not b_install:

-                 cmt += "Package doesn't have the standard " \

-                     "R CMD INSTALL function\n"

+                 cmt += "Package doesn't have the standard " "R CMD INSTALL function\n"

              self.set_passed(self.FAIL, cmt)

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+1 -1
@@ -1,3 +1,3 @@ 

  # -*- coding: utf-8 -*-

  # vim: set expandtab ts=4 sw=4:

- ''' Needed for development and to make pylint happy. '''

+ """ Needed for development and to make pylint happy. """

file modified
+159 -120
@@ -9,170 +9,193 @@ 

  class Registry(RegistryBase):

      """ Register all checks in this file. """

  

-     group = 'C/C++'

+     group = "C/C++"

  

      def is_applicable(self):

          """Need more comprehensive check and return True in valid cases"""

          if self.is_user_enabled():

              return self.user_enabled_value()

-         archs = self.checks.spec.expand_tag('BuildArchs')

-         if len(archs) == 1 and archs[0].lower() == b'noarch':

+         archs = self.checks.spec.expand_tag("BuildArchs")

+         if len(archs) == 1 and archs[0].lower() == b"noarch":

              return False

          if self.checks.buildsrc.is_available:

              src = self.checks.buildsrc

          else:

              src = self.checks.sources

          rpms = self.checks.rpms

-         if rpms.find_re(r'/usr/(lib|lib64)/[\w\-]*\.so\.[0-9]') or \

-             rpms.find('*.h') or rpms.find('*.a') or \

-                 src.find('*.c') or src.find('*.C') or src.find('*.cpp'):

-                     return True

+         if (

+             rpms.find_re(r"/usr/(lib|lib64)/[\w\-]*\.so\.[0-9]")

+             or rpms.find("*.h")

+             or rpms.find("*.a")

+             or src.find("*.c")

+             or src.find("*.C")

+             or src.find("*.cpp")

+         ):

+             return True

          return False

  

  

  class CCppCheckBase(CheckBase):

-     ''' Common base class for module tests (a. k. a. checks). '''

+     """ Common base class for module tests (a. k. a. checks). """

  

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  

  

  class CheckLDConfig(CCppCheckBase):

-     '''

+     """

      MUST: Every binary RPM package (or subpackage) which stores shared

      library files (not just symlinks) in any of the dynamic linker's

      default paths, must call ldconfig in %post and %postun.

-     '''

+     """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_shared_libraries'

-         self.text = 'ldconfig called in %post and %postun if required.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_shared_libraries"

+         )

+         self.text = "ldconfig called in %post and %postun if required."

          self.automatic = True

-         self.type = 'MUST'

-         self.sofiles_regex = r'/usr/(lib|lib64)/[\w\-]*\.so\.[0-9]'

+         self.type = "MUST"

+         self.sofiles_regex = r"/usr/(lib|lib64)/[\w\-]*\.so\.[0-9]"

  

      def is_applicable(self):

-         ''' check if this test is applicable '''

+         """ check if this test is applicable """

          return bool(self.rpms.find_re(self.sofiles_regex))

  

      def run_on_applicable(self):

-         ''' Run the test, called if is_applicable() is True. '''

+         """ Run the test, called if is_applicable() is True. """

          bad_pkgs = []

          for pkg in self.spec.packages:

              nvr = self.spec.get_package_nvr(pkg)

              rpm = RpmFile(pkg, nvr.version, nvr.release)

              if not self.rpms.find_re(self.sofiles_regex, pkg):

                  continue

-             if self.flags['EPEL6'] \

-                 or self.flags['EPEL7']:

-                 if not rpm.post or '/sbin/ldconfig' not in rpm.post or \

-                     not rpm.postun or '/sbin/ldconfig' not in rpm.postun:

-                         bad_pkgs.append(pkg)

+             if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                 if (

+                     not rpm.post

+                     or "/sbin/ldconfig" not in rpm.post

+                     or not rpm.postun

+                     or "/sbin/ldconfig" not in rpm.postun

+                 ):

+                     bad_pkgs.append(pkg)

              else:

-                 if (rpm.post and '/sbin/ldconfig' in rpm.post) \

-                     or (rpm.postun and '/sbin/ldconfig' in rpm.postun):

-                         bad_pkgs.append(pkg)

+                 if (rpm.post and "/sbin/ldconfig" in rpm.post) or (

+                     rpm.postun and "/sbin/ldconfig" in rpm.postun

+                 ):

+                     bad_pkgs.append(pkg)

  

-         if self.flags['EPEL6'] \

-             or self.flags['EPEL7']:

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              if bad_pkgs:

-                 self.set_passed(self.FAIL,

-                                 '/sbin/ldconfig not called in ' +

-                                 ', '.join(bad_pkgs))

+                 self.set_passed(

+                     self.FAIL, "/sbin/ldconfig not called in " + ", ".join(bad_pkgs)

+                 )

              else:

                  self.set_passed(self.PASS)

          else:

-             self.url = 'https://fedoraproject.org/wiki/Changes/' \

-                 'Removing_ldconfig_scriptlets'

-             self.text = 'ldconfig not called in %post and %postun ' \

-                 'for Fedora 28 and later.'

+             self.url = (

+                 "https://fedoraproject.org/wiki/Changes/" "Removing_ldconfig_scriptlets"

+             )

+             self.text = (

+                 "ldconfig not called in %post and %postun " "for Fedora 28 and later."

+             )

              if bad_pkgs:

-                 self.set_passed(self.FAIL,

-                                 '/sbin/ldconfig called in ' +

-                                 ', '.join(bad_pkgs))

+                 self.set_passed(

+                     self.FAIL, "/sbin/ldconfig called in " + ", ".join(bad_pkgs)

+                 )

              else:

                  self.set_passed(self.PASS)

  

  

  class CheckHeaderFiles(CCppCheckBase):

-     '''

+     """

      MUST: Header files must be in a -devel package

-     '''

+     """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_devel_packages'

-         self.text = 'Header files in -devel subpackage, if present.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_devel_packages"

+         )

+         self.text = "Header files in -devel subpackage, if present."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

-         ''' check if this test is applicable '''

-         return self.rpms.find('*.h')

+         """ check if this test is applicable """

+         return self.rpms.find("*.h")

  

      def run_on_applicable(self):

-         ''' Run the test, called if is_applicable() is True. '''

+         """ Run the test, called if is_applicable() is True. """

          passed = True

          extra = ""

          for pkg in self.spec.packages:

-             for path in self.rpms.find_all('*.h', pkg):

+             for path in self.rpms.find_all("*.h", pkg):

                  # header files (.h) under /usr/src/debug/* will be in

                  #  the -debuginfo package.

-                 if path.startswith('/usr/src/debug/') and \

-                    ('-debuginfo' in pkg or '-debugsource' in pkg):

+                 if path.startswith("/usr/src/debug/") and (

+                     "-debuginfo" in pkg or "-debugsource" in pkg

+                 ):

                      continue

                  # All other .h files should be in a -devel package.

-                 if '-devel' not in pkg:

+                 if "-devel" not in pkg:

                      passed = False

                      extra += "{} : {}\n".format(pkg, path)

          self.set_passed(passed, extra)

  

  

  class CheckNoStaticExecutables(CCppCheckBase):

-     ''' We do not packaga static executables, do we? '''

+     """ We do not packaga static executables, do we? """

  

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_statically_linking_executables'

-         self.text = 'Package contains no static executables.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_statically_linking_executables"

+         )

+         self.text = "Package contains no static executables."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckSoFiles(CCppCheckBase):

-     '''

+     """

      MUST: If a package contains library files with a suffix (e.g.

      libfoo.so.1.1), then library files that end in .so (without suffix)

      must go in a -devel package.

-     '''

+     """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_devel_packages'

-         self.text = 'Development (unversioned) .so files ' \

-                     'in -devel subpackage, if present.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_devel_packages"

+         )

+         self.text = (

+             "Development (unversioned) .so files " "in -devel subpackage, if present."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

          # we ignore .so files in private directories

-         self.bad_re = re.compile(r'/usr/(lib|lib64)/[\w\-]*\.so$')

+         self.bad_re = re.compile(r"/usr/(lib|lib64)/[\w\-]*\.so$")

  

      def run(self):

-         ''' Run the test, always called '''

-         if not self.rpms.find('*.so'):

+         """ Run the test, always called """

+         if not self.rpms.find("*.so"):

              self.set_passed(self.NA)

              return

-         passed = 'pass'

+         passed = "pass"

          in_libdir = False

          in_private = False

          bad_list = []

          attachments = []

          extra = None

          for pkg in self.spec.packages:

-             if pkg.endswith('-devel'):

+             if pkg.endswith("-devel"):

                  continue

-             for path in self.rpms.find_all('*.so', pkg):

+             for path in self.rpms.find_all("*.so", pkg):

                  bad_list.append("{}: {}".format(pkg, path))

                  if self.bad_re.search(path):

                      in_libdir = True
@@ -180,133 +203,149 @@ 

                      in_private = True

  

          if in_private and not in_libdir:

-             extra = "Unversioned so-files in private" \

-                     " %_libdir subdirectory (see attachment)." \

-                     " Verify they are not in ld path. "

-             passed = 'pending'

+             extra = (

+                 "Unversioned so-files in private"

+                 " %_libdir subdirectory (see attachment)."

+                 " Verify they are not in ld path. "

+             )

+             passed = "pending"

  

          if in_libdir:

              extra = "Unversioned so-files directly in %_libdir."

-             passed = 'fail'

+             passed = "fail"

  

          if bad_list:

-             attachments = [self.Attachment('Unversioned so-files',

-                                            "\n".join(bad_list))]

+             attachments = [self.Attachment("Unversioned so-files", "\n".join(bad_list))]

  

          self.set_passed(passed, extra, attachments)

  

  

  class CheckLibToolArchives(CCppCheckBase):

-     '''

+     """

      MUST: Packages must NOT contain any .la libtool archives,

      these must be removed in the spec if they are built.

-     '''

+     """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#packaging-static-libraries'

-         self.text = 'Package does not contain any libtool archives (.la)'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#packaging-static-libraries"

+         )

+         self.text = "Package does not contain any libtool archives (.la)"

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         ''' Run the test, called if is_applicable() is True. '''

-         if not self.rpms.find('*.la'):

+         """ Run the test, called if is_applicable() is True. """

+         if not self.rpms.find("*.la"):

              self.set_passed(self.PASS)

          else:

              extra = ""

              for pkg in self.spec.packages:

-                 for path in self.rpms.find_all('*.la', pkg):

+                 for path in self.rpms.find_all("*.la", pkg):

                      extra += "{} : {}\n".format(pkg, path)

              self.set_passed(self.FAIL, extra)

  

  

  class CheckRPATH(CCppCheckBase):

-     ''' Thou shall not use bad RPATH. '''

+     """ Thou shall not use bad RPATH. """

  

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_beware_of_rpath'

-         self.text = 'Rpath absent or only used for internal libs.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_beware_of_rpath"

+         )

+         self.text = "Rpath absent or only used for internal libs."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs.append('CheckRpmlint')

+         self.type = "MUST"

+         self.needs.append("CheckRpmlint")

  

      def run_on_applicable(self):

-         ''' Run the test, called if is_applicable() is True. '''

-         if self.checks.checkdict['CheckRpmlint'].is_disabled:

-             self.set_passed(self.PENDING, 'Rpmlint run disabled')

+         """ Run the test, called if is_applicable() is True. """

+         if self.checks.checkdict["CheckRpmlint"].is_disabled:

+             self.set_passed(self.PENDING, "Rpmlint run disabled")

              return

          for line in Mock.rpmlint_output:

-             if 'binary-or-shlib-defines-rpath' in line:

-                 self.set_passed(self.PENDING, 'See rpmlint output')

+             if "binary-or-shlib-defines-rpath" in line:

+                 self.set_passed(self.PENDING, "See rpmlint output")

                  return

          self.set_passed(self.PASS)

  

  

  class CheckBundledGnulib(CCppCheckBase):

-     ''' Make sure there is a Provides: matching bundled gnulib. '''

+     """ Make sure there is a Provides: matching bundled gnulib. """

  

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki' \

-                    '/Bundled_Libraries#Requirement_if_you_bundle'

-         self.text = 'Provides: bundled(gnulib) in place as required.'

+         self.url = (

+             "https://fedoraproject.org/wiki"

+             "/Bundled_Libraries#Requirement_if_you_bundle"

+         )

+         self.text = "Provides: bundled(gnulib) in place as required."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          try:

-             if not self.buildsrc.find('*00gnulib.m4'):

+             if not self.buildsrc.find("*00gnulib.m4"):

                  self.set_passed(self.NA)

                  return

          except LookupError:

              self.set_passed(self.PENDING, "Sources not installed")

              return

          for pkg in self.spec.packages:

-             if 'bundled(gnulib)' in self.rpms.get(pkg).provides:

+             if "bundled(gnulib)" in self.rpms.get(pkg).provides:

                  self.set_passed(self.PASS)

                  break

          else:

-             self.set_passed(self.FAIL,

-                             'Bundled gnulib but no '

-                             'Provides: bundled(gnulib)')

+             self.set_passed(

+                 self.FAIL, "Bundled gnulib but no " "Provides: bundled(gnulib)"

+             )

  

  

  class CheckNoKernelModules(CCppCheckBase):

-     '''

+     """

      At one point (pre Fedora 8), packages containing "addon" kernel modules

      were permitted.  This is no longer the case. Fedora strongly encourages

      kernel module packagers to submit their code into the upstream kernel tree.

-     '''

+     """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/what-can-be-packaged' \

-                    '/#_no_external_kernel_modules'

-         self.text = 'Package does not contain kernel modules.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/what-can-be-packaged"

+             "/#_no_external_kernel_modules"

+         )

+         self.text = "Package does not contain kernel modules."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckGccBuildRequires(CCppCheckBase):

      """ Check that gcc/gcc-c++/clang is present """

+ 

      def __init__(self, base):

          CCppCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines' \

-                    '/C_and_C++/'

-         self.text = 'If your application is a C or C++ application you must ' \

-                     'list a BuildRequires against gcc, gcc-c++ or clang.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines" "/C_and_C++/"

+         )

+         self.text = (

+             "If your application is a C or C++ application you must "

+             "list a BuildRequires against gcc, gcc-c++ or clang."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          """ Run the check """

          br = self.spec.build_requires

-         if not 'gcc' in br and not 'gcc-c++' in br and not 'clang' in br:

-             self.set_passed(self.FAIL, 'No gcc, gcc-c++ or clang found in ' \

-                                        'BuildRequires')

+         if not "gcc" in br and not "gcc-c++" in br and not "clang" in br:

+             self.set_passed(

+                 self.FAIL, "No gcc, gcc-c++ or clang found in " "BuildRequires"

+             )

              return

          self.set_passed(self.PASS)

  

file modified
+7 -4
@@ -1,14 +1,14 @@ 

  # -*- coding: utf-8 -*-

  

- ''' fonts specifics checks '''

+ """ fonts specifics checks """

  

  from FedoraReview import CheckBase, RegistryBase

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'fonts'. '''

+     """ Register all checks in this file in group 'fonts'. """

  

-     group = 'fonts'

+     group = "fonts"

  

      def is_applicable(self):

          """ Check if these tests are applicable i. e., if this is a fonts
@@ -21,6 +21,9 @@ 

  

  class FontsCheckBase(CheckBase):

      """ Base class for all fonts specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/FontsPolicy/'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines/FontsPolicy/"

+         )

file modified
+928 -732
@@ -17,7 +17,7 @@ 

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

  

- ''' Generic MUST checks, default Generic group. '''

+ """ Generic MUST checks, default Generic group. """

  

  import os

  import os.path
@@ -29,18 +29,18 @@ 

  import rpm

  from FedoraReview.el_compat import check_output

  from FedoraReview import CheckBase, Mock, ReviewDirs

- from FedoraReview import ReviewError             # pylint: disable=W0611

+ from FedoraReview import ReviewError  # pylint: disable=W0611

  from FedoraReview import RegistryBase, Settings

  

  import FedoraReview.deps as deps

  

- _DIR_SORT_KEY = '30'

- _LICENSE_SORT_KEY = '20'

- _GL_SORT_KEY = '90'

+ _DIR_SORT_KEY = "30"

+ _LICENSE_SORT_KEY = "20"

+ _GL_SORT_KEY = "90"

  

  

  def in_list(what, list_):

-     ''' test if 'what' is in each item in list_. '''

+     """ test if 'what' is in each item in list_. """

      for item in list_:

          if not item:

              return False
@@ -50,18 +50,17 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Module registration, register all checks. '''

-     group = 'Generic'

+     """ Module registration, register all checks. """

+ 

+     group = "Generic"

  

      def register_flags(self):

-         epel6 = self.Flag('EPEL6', 'Review package for EPEL6', __file__)

-         epel7 = self.Flag('EPEL7', 'Review package for EPEL7', __file__)

-         disttag = self.Flag('DISTTAG',

-                             'Default disttag e. g., "fc21".',

-                             __file__)

-         batch = self.Flag('BATCH',

-                           'Disable all build, install, rpmlint etc. tasks',

-                           __file__)

+         epel6 = self.Flag("EPEL6", "Review package for EPEL6", __file__)

+         epel7 = self.Flag("EPEL7", "Review package for EPEL7", __file__)

+         disttag = self.Flag("DISTTAG", 'Default disttag e. g., "fc21".', __file__)

+         batch = self.Flag(

+             "BATCH", "Disable all build, install, rpmlint etc. tasks", __file__

+         )

          self.checks.flags.add(epel6)

          self.checks.flags.add(epel7)

          self.checks.flags.add(disttag)
@@ -72,48 +71,55 @@ 

  

  

  class GenericCheckBase(CheckBase):

-     ''' Base class for all generic tests. '''

+     """ Base class for all generic tests. """

  

      def __init__(self, checks):

          CheckBase.__init__(self, checks, __file__)

  

  

  class CheckApprovedLicense(GenericCheckBase):

-     '''

+     """

      MUST: The package must be licensed with a Fedora approved license and

      meet the Licensing Guidelines .

-     '''

+     """

  

      sort_key = _LICENSE_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines/'

-         self.text = 'Package is licensed with an open-source'       \

-                     ' compatible license and meets other legal'     \

-                     ' requirements as defined in the legal section' \

-                     ' of Packaging Guidelines.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines/"

+         )

+         self.text = (

+             "Package is licensed with an open-source"

+             " compatible license and meets other legal"

+             " requirements as defined in the legal section"

+             " of Packaging Guidelines."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckBundledLibs(GenericCheckBase):

-     '''

+     """

      MUST: Packages must NOT bundle copies of system libraries.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#bundling'

-         self.text = 'Package contains no bundled libraries without' \

-                     ' FPC exception.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#bundling"

+         )

+         self.text = "Package contains no bundled libraries without" " FPC exception."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         pattern = '(.*?/)(3rdparty|thirdparty|libraries|libs|ext|external' \

-             '|include|3rd_party|third_party)/.*'

+         pattern = (

+             "(.*?/)(3rdparty|thirdparty|libraries|libs|ext|external"

+             "|include|3rd_party|third_party)/.*"

+         )

          regex = re.compile(pattern, re.IGNORECASE)

          check_dirs = set()

          for i in self.sources.get_filelist():
@@ -123,70 +129,75 @@ 

          if check_dirs:

              self.set_passed(

                  self.PENDING,

-                 'Especially check following dirs for bundled code: ' +

-                 ', '.join(check_dirs))

+                 "Especially check following dirs for bundled code: "

+                 + ", ".join(check_dirs),

+             )

          else:

              self.set_passed(self.PENDING)

  

  

  class CheckBuildCompilerFlags(GenericCheckBase):

-     '''Thou shall use %{optflags}. '''

+     """Thou shall use %{optflags}. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_compiler_flags'

-         self.text = '%build honors applicable compiler flags or ' \

-                     'justifies otherwise.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_compiler_flags"

+         )

+         self.text = "%build honors applicable compiler flags or " "justifies otherwise."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs.append('generic-large-data')      # Ensure unpacked rpms

+         self.type = "MUST"

+         self.needs.append("generic-large-data")  # Ensure unpacked rpms

  

      def run(self):

-         archs = self.checks.spec.expand_tag('BuildArchs')

-         if len(archs) == 1 and archs[0].lower() == b'noarch':

+         archs = self.checks.spec.expand_tag("BuildArchs")

+         if len(archs) == 1 and archs[0].lower() == b"noarch":

              self.set_passed(self.NA)

              return

          self.set_passed(self.PENDING)

  

  

  class CheckChangelogFormat(GenericCheckBase):

-     ''' Changelog in correct format. '''

+     """ Changelog in correct format. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#changelogs'

-         self.text = 'Changelog in prescribed format.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#changelogs"

+         )

+         self.text = "Changelog in prescribed format."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckCodeAndContent(GenericCheckBase):

-     ''' MUST: The package must contain code, or permissable content. '''

+     """ MUST: The package must contain code, or permissable content. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/what-can-be-packaged' \

-                    '/#_impermissible_content'

-         self.text = 'Sources contain only permissible' \

-                     ' code or content.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/what-can-be-packaged"

+             "/#_impermissible_content"

+         )

+         self.text = "Sources contain only permissible" " code or content."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckConfigNoReplace(GenericCheckBase):

-     ''' '%config files are marked noreplace or reason justified. '''

+     """ '%config files are marked noreplace or reason justified. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_configuration_files'

-         self.text = '%config files are marked noreplace or the reason' \

-                     ' is justified.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_configuration_files"

+         )

+         self.text = "%config files are marked noreplace or the reason" " is justified."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          rc = self.NA
@@ -194,283 +205,311 @@ 

          extra = None

          for pkg in self.spec.packages:

              for line in self.spec.get_files(pkg):

-                 if line.startswith('%config'):

-                     if not line.startswith('%config(noreplace)'):

+                 if line.startswith("%config"):

+                     if not line.startswith("%config(noreplace)"):

                          bad_lines.append(line)

                      else:

                          rc = self.PASS

          if bad_lines:

-             extra = "No (noreplace) in " + ' '.join(bad_lines)

+             extra = "No (noreplace) in " + " ".join(bad_lines)

              rc = self.PENDING

          self.set_passed(rc, extra)

  

  

  class CheckCleanBuildroot(GenericCheckBase):

-     ''' Check that buildroot is cleaned as appropriate. '''

+     """ Check that buildroot is cleaned as appropriate. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.text = 'Package does not run rm -rf %{buildroot}' \

-                     ' (or $RPM_BUILD_ROOT) at the beginning of %install.'

+         self.text = (

+             "Package does not run rm -rf %{buildroot}"

+             " (or $RPM_BUILD_ROOT) at the beginning of %install."

+         )

          self.automatic = True

  

      def run(self):

          has_clean = False

-         regex = r'rm\s+\-[rf][rf]\s+(@buildroot@|$RPM_BUILD_ROOT)[^/]'

-         buildroot = rpm.expandMacro('%{buildroot}')

+         regex = r"rm\s+\-[rf][rf]\s+(@buildroot@|$RPM_BUILD_ROOT)[^/]"

+         buildroot = rpm.expandMacro("%{buildroot}")

          # BZ 908830: handle '+' in package name.

-         buildroot = buildroot.replace('+', r'\+')

-         regex = regex.replace('@buildroot@', buildroot)

-         install_sec = self.spec.get_section('%install', raw=True)

+         buildroot = buildroot.replace("+", r"\+")

+         regex = regex.replace("@buildroot@", buildroot)

+         install_sec = self.spec.get_section("%install", raw=True)

          if not install_sec:

              self.set_passed(self.NA)

              return

-         self.log.debug('regex: %s', regex)

-         self.log.debug('install_sec: %s', install_sec)

+         self.log.debug("regex: %s", regex)

+         self.log.debug("install_sec: %s", install_sec)

          has_clean = install_sec and re.search(regex, install_sec)

          if has_clean:

-             self.set_passed(self.PENDING,

-                             'rm -rf %{buildroot} present but not required')

+             self.set_passed(

+                 self.PENDING, "rm -rf %{buildroot} present but not required"

+             )

          else:

              self.set_passed(self.PASS)

  

  

  class CheckDaemonCompileFlags(GenericCheckBase):

-     '''

+     """

      MUST: Sensitive code should use hardened build flags.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_compiler_flags'

-         self.text = 'Package uses hardened build flags if required to.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_compiler_flags"

+         )

+         self.text = "Package uses hardened build flags if required to."

          self.automatic = True

-         self.needs.append('generic-large-data')      # Ensure unpacked rpms

+         self.needs.append("generic-large-data")  # Ensure unpacked rpms

  

      def run(self):

-         extra = ''

-         rpms_dir = os.path.join(ReviewDirs.root, 'rpms-unpacked')

+         extra = ""

+         rpms_dir = os.path.join(ReviewDirs.root, "rpms-unpacked")

          try:

-             cmd = 'find %s -perm -4000' % rpms_dir

-             with open('/dev/null', 'w') as f:

-                 suids = check_output(cmd.split(), stderr=f, universal_newlines=True).strip().split()

+             cmd = "find %s -perm -4000" % rpms_dir

+             with open("/dev/null", "w") as f:

+                 suids = (

+                     check_output(cmd.split(), stderr=f, universal_newlines=True)

+                     .strip()

+                     .split()

+                 )

          except CalledProcessError:

-             self.log.info('Cannot run find command: %s', cmd)

+             self.log.info("Cannot run find command: %s", cmd)

              suids = []

          else:

              suids = [os.path.basename(s) for s in suids]

              if suids:

-                 extra += 'suid files: ' + ', '.join(suids)

+                 extra += "suid files: " + ", ".join(suids)

  

-         systemd_files = self.rpms.find_all('/lib/systemd/system/*')

+         systemd_files = self.rpms.find_all("/lib/systemd/system/*")

          if systemd_files:

              files = [os.path.basename(f) for f in systemd_files]

-             extra += 'Systemd files (daemon?): ' + ', '.join(files)

+             extra += "Systemd files (daemon?): " + ", ".join(files)

  

          if not extra:

              self.set_passed(self.NA)

-         elif self.spec.find_re(r'[^# ]*%global\s+_hardened_build\s+1'):

+         elif self.spec.find_re(r"[^# ]*%global\s+_hardened_build\s+1"):

              self.set_passed(self.PASS, extra)

          else:

-             extra += ' and not %global _hardened_build'

+             extra += " and not %global _hardened_build"

              self.set_passed(self.FAIL, extra)

  

  

  class CheckDefattr(GenericCheckBase):

-     '''

+     """

      MUST: Permissions on files must be set properly.  Executables

      should be set with executable permissions, for example.  Every

      %files section must include a %defattr(...) line.

      Update: 29-04-2011 This is only for pre rpm 4.4 that this is needed

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_permissions'

-         self.text = 'Each %files section contains %defattr if rpm < 4.4'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_permissions"

+         )

+         self.text = "Each %files section contains %defattr if rpm < 4.4"

          self.automatic = True

  

      def run(self):

          has_defattr = False

          for pkg in self.spec.packages:

-             if pkg.endswith(('-debuginfo', '-debugsource')):

+             if pkg.endswith(("-debuginfo", "-debugsource")):

                  # auto-generated %defattr, ignore

                  continue

              for line in self.spec.get_files(pkg):

-                 if line.startswith('%defattr('):

+                 if line.startswith("%defattr("):

                      has_defattr = True

                      break

          if has_defattr:

-             self.set_passed(self.PENDING, '%defattr present but not needed')

+             self.set_passed(self.PENDING, "%defattr present but not needed")

          else:

              self.set_passed(self.NA)

  

  

  class CheckDescMacros(GenericCheckBase):

-     ''' Macros in description etc. should be expandable. '''

+     """ Macros in description etc. should be expandable. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_source_rpm_buildtime_macros'

-         self.text = 'Macros in Summary, %description expandable at' \

-                     ' SRPM build time.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_source_rpm_buildtime_macros"

+         )

+         self.text = "Macros in Summary, %description expandable at" " SRPM build time."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          bad_tags = []

          for pkg_name in self.spec.packages:

-             if '%' in self.spec.expand_tag('Summary', pkg_name).decode('utf-8'):

-                 bad_tags.append(pkg_name + ' (summary)')

-             if '%' in self.spec.expand_tag('Description', pkg_name).decode('utf-8'):

-                 bad_tags.append(pkg_name + ' (description)')

+             if "%" in self.spec.expand_tag("Summary", pkg_name).decode("utf-8"):

+                 bad_tags.append(pkg_name + " (summary)")

+             if "%" in self.spec.expand_tag("Description", pkg_name).decode("utf-8"):

+                 bad_tags.append(pkg_name + " (description)")

          if bad_tags:

-             self.set_passed(self.PENDING,

-                             'Macros in: ' + ', '.join(bad_tags))

+             self.set_passed(self.PENDING, "Macros in: " + ", ".join(bad_tags))

          else:

              self.set_passed(self.PASS)

  

  

  class CheckDesktopFile(GenericCheckBase):

-     '''

+     """

      MUST: Packages containing GUI applications must include a

      %{name}.desktop file. If you feel that your packaged GUI

      application does not need a .desktop file, you must put a

      comment in the spec file with your explanation.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_desktop_files'

-         self.text = 'Package contains desktop file if it is a GUI' \

-                     ' application.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_desktop_files"

+         )

+         self.text = "Package contains desktop file if it is a GUI" " application."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         have_desktop = self.rpms.find('*.desktop')

+         have_desktop = self.rpms.find("*.desktop")

          self.set_passed(True if have_desktop else self.PENDING)

  

  

  class CheckDesktopFileInstall(GenericCheckBase):

-     '''

+     """

      MUST: Packages containing GUI applications must include a

      %{name}.desktop file, and that file must be properly installed

      with desktop-file-install in the %install section.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_desktop_files'

-         self.text = 'Package installs a  %{name}.desktop using' \

-                     ' desktop-file-install or desktop-file-validate' \

-                     ' if there is such a file.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_desktop_files"

+         )

+         self.text = (

+             "Package installs a  %{name}.desktop using"

+             " desktop-file-install or desktop-file-validate"

+             " if there is such a file."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         if not self.rpms.find('*.desktop'):

+         if not self.rpms.find("*.desktop"):

              self.set_passed(self.NA)

              return

-         pattern = r'(desktop-file-install|desktop-file-validate)' \

-                     r'.*(desktop|SOURCE|\$\w+)'

+         pattern = (

+             r"(desktop-file-install|desktop-file-validate)" r".*(desktop|SOURCE|\$\w+)"

+         )

          found = self.spec.find_re(re.compile(pattern))

          self.set_passed(self.PASS if found else self.FAIL)

  

  

  class CheckDevelFilesInDevel(GenericCheckBase):

-     ''' MUST: Development files must be in a -devel package '''

+     """ MUST: Development files must be in a -devel package """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_devel_packages'

-         self.text = 'Development files must be in a -devel package'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_devel_packages"

+         )

+         self.text = "Development files must be in a -devel package"

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckDistTag(GenericCheckBase):

-     ''' Disttag %{?dist} is present in Release: '''

+     """ Disttag %{?dist} is present in Release: """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/DistTag/'

-         self.text = 'Dist tag is present.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/DistTag/"

+         )

+         self.text = "Dist tag is present."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         rel_tags = self.spec.find_all_re(r'^Release\s*:')

-         found = in_list('%{?dist}', rel_tags)

+         rel_tags = self.spec.find_all_re(r"^Release\s*:")

+         found = in_list("%{?dist}", rel_tags)

          if len(rel_tags) > 1:

-             self.set_passed(found, 'Multiple Release: tags found')

+             self.set_passed(found, "Multiple Release: tags found")

          elif not rel_tags:

-             self.set_passed(found, 'No Release: tags found')

+             self.set_passed(found, "No Release: tags found")

          else:

              self.set_passed(found)

  

  

  class CheckDirectoryRequire(GenericCheckBase):

-     ''' Package should require directories it uses. '''

+     """ Package should require directories it uses. """

  

      sort_key = _DIR_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_and_directory_ownership'

-         self.text = 'Package requires other packages for directories it uses.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_and_directory_ownership"

+         )

+         self.text = "Package requires other packages for directories it uses."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         '''

+         """

          Build raw list of directory paths in pkg, package owning the

          leaf.

          Split list into /part1 /part1/part2 /part1/part2/part3...

          Remove all paths part of filesystem.

          Remove all paths part of package.

          Remaining dirs must have a owner, test one by one (painful).

-         '''

+         """

          dirs = []

          for path in self.rpms.get_filelist():

-             path = path.rsplit('/', 1)[0]  # We own the leaf.

+             path = path.rsplit("/", 1)[0]  # We own the leaf.

              while path:

                  dirs.append(path)

-                 path = path.rsplit('/', 1)[0]

+                 path = path.rsplit("/", 1)[0]

          dirs = set(dirs)

-         filesys_dirs = set(deps.list_paths('filesystem'))

+         filesys_dirs = set(deps.list_paths("filesystem"))

          dirs -= filesys_dirs

          rpm_paths = set(self.rpms.get_filelist())

          dirs -= rpm_paths

          bad_dirs = [d for d in dirs if not deps.list_owners(d)]

          if bad_dirs:

-             self.set_passed(self.PENDING,

-                             "No known owner of " + ", ".join(bad_dirs))

+             self.set_passed(self.PENDING, "No known owner of " + ", ".join(bad_dirs))

          else:

              self.set_passed(self.PASS)

  

  

  class CheckDocRuntime(GenericCheckBase):

-     '''

+     """

      MUST: If a package includes something as %doc, it must not affect

      the runtime of the application.  To summarize: If it is in %doc,

      the program must run properly if it is not present.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_documentation'

-         self.text = 'Package uses nothing in %doc for runtime.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_documentation"

+         )

+         self.text = "Package uses nothing in %doc for runtime."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckExcludeArch(GenericCheckBase):

-     '''

+     """

      MUST: If the package does not successfully compile, build or work

      on an architecture, then those architectures should be listed in

      the spec in ExcludeArch.  Each architecture listed in ExcludeArch
@@ -478,32 +517,38 @@ 

      package does not compile/build/work on that architecture.  The bug

      number MUST be placed in a comment, next to the corresponding

      ExcludeArch line.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_architecture_build_failures'

-         self.text = 'Package is not known to require ExcludeArch.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_architecture_build_failures"

+         )

+         self.text = "Package is not known to require ExcludeArch."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckFileDuplicates(GenericCheckBase):

-     '''

+     """

      MUST: A Fedora package must not list a file more than once in the

      spec file's %files listings.  (Notable exception: license texts in

      specific situations)

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_duplicate_files'

-         self.text = 'Package does not contain duplicates in %files.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_duplicate_files"

+         )

+         self.text = "Package does not contain duplicates in %files."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         filename = os.path.join(Mock.resultdir, 'build.log')

+         filename = os.path.join(Mock.resultdir, "build.log")

          try:

              stream = open(filename)

          except IOError:
@@ -511,131 +556,142 @@ 

              return

          content = stream.read()

          stream.close()

-         for line in content.split('\n'):

-             if 'File listed twice' in line:

+         for line in content.split("\n"):

+             if "File listed twice" in line:

                  self.set_passed(self.FAIL, line)

                  return

          self.set_passed(self.PASS)

  

  

  class CheckFilePermissions(GenericCheckBase):

-     '''

+     """

      MUST: Permissions on files must be set properly.  Executables

      should be set with executable permissions, for example. Every

      %files section must include a %defattr(...) line

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_permissions'

-         self.text = 'Permissions on files are set properly.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_permissions"

+         )

+         self.text = "Permissions on files are set properly."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs.append('CheckRpmlint')

+         self.type = "MUST"

+         self.needs.append("CheckRpmlint")

  

      def run(self):

-         if self.checks.checkdict['CheckRpmlint'].is_disabled:

-             self.set_passed(self.PENDING, 'Rpmlint run disabled')

+         if self.checks.checkdict["CheckRpmlint"].is_disabled:

+             self.set_passed(self.PENDING, "Rpmlint run disabled")

              return

          for line in Mock.rpmlint_output:

-             if 'non-standard-executable-perm' in line:

-                 self.set_passed(self.FAIL, 'See rpmlint output')

+             if "non-standard-executable-perm" in line:

+                 self.set_passed(self.FAIL, "See rpmlint output")

                  return

          self.set_passed(self.PASS)

  

  

  class CheckGuidelines(GenericCheckBase):

-     ''' MUST: The package complies to the Packaging Guidelines.  '''

+     """ MUST: The package complies to the Packaging Guidelines.  """

  

      sort_key = _GL_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Package complies to the Packaging Guidelines'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Package complies to the Packaging Guidelines"

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckLargeDocs(GenericCheckBase):

-     '''

+     """

      MUST: Large documentation files must go in a -doc subpackage.

      (The definition of large is left up to the packager's best

      judgement, but is not restricted to size. Large can refer to

      either size or quantity).

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_documentation'

-         self.text = 'Large documentation files are in a -doc' \

-                     ' subpackage, if required.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_documentation"

+         )

+         self.text = (

+             "Large documentation files are in a -doc" " subpackage, if required."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckLicenseField(GenericCheckBase):

-     '''

+     """

      MUST: The License field in the package spec file must match the

      actual license.

-     '''

+     """

  

      sort_key = _LICENSE_SORT_KEY

-     unknown_license = 'Unknown or generated'

+     unknown_license = "Unknown or generated"

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines/' \

-                    '#_valid_license_short_names'

-         self.text = 'License field in the package spec file' \

-                     ' matches the actual license.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines/"

+             "#_valid_license_short_names"

+         )

+         self.text = (

+             "License field in the package spec file" " matches the actual license."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      @staticmethod

      def _write_license(files_by_license, filename):

-         ''' Dump files_by_license to filename. '''

-         with open(filename, 'w') as f:

+         """ Dump files_by_license to filename. """

+         with open(filename, "w") as f:

              for license_ in sorted(files_by_license.keys()):

-                 f.write('\n' + license_ + '\n')

-                 f.write('-' * len(license_) + '\n')

+                 f.write("\n" + license_ + "\n")

+                 f.write("-" * len(license_) + "\n")

                  for path in sorted(files_by_license[license_]):

-                     relpath = re.sub('.*BUILD/', '', path)

-                     f.write(relpath + '\n')

+                     relpath = re.sub(".*BUILD/", "", path)

+                     f.write(relpath + "\n")

  

      @staticmethod

      def _get_source_dir():

-         ''' Decide which directory to run licensecheck on. This can be

+         """ Decide which directory to run licensecheck on. This can be

          either patched sources, or we use vanilla unpacked upstream

-         tarballs if first option fails '''

-         s = Mock.get_builddir('BUILD') + '/*'

+         tarballs if first option fails """

+         s = Mock.get_builddir("BUILD") + "/*"

          globs = glob(s)

          if globs:

-             msg = 'Checking patched sources after %prep for licenses.'

+             msg = "Checking patched sources after %prep for licenses."

              source_dir = globs[0]

          else:

-             msg = 'There is no build directory. Running licensecheck ' \

-                   'on vanilla upstream sources.'

+             msg = (

+                 "There is no build directory. Running licensecheck "

+                 "on vanilla upstream sources."

+             )

              source_dir = ReviewDirs.upstream_unpacked

          return (source_dir, msg)

  

      def _parse_licenses(self, raw_text):

-         ''' Convert licensecheck output to files_by_license dict. '''

+         """ Convert licensecheck output to files_by_license dict. """

  

          def license_is_valid(_license):

-             ''' Test that license from licencecheck is parsed OK. '''

-             return 'UNKNOWN' not in _license and \

-                 'GENERATED' not in _license

+             """ Test that license from licencecheck is parsed OK. """

+             return "UNKNOWN" not in _license and "GENERATED" not in _license

  

          files_by_license = {}

-         raw_file = BytesIO(raw_text.encode('utf-8'))

+         raw_file = BytesIO(raw_text.encode("utf-8"))

          while True:

-             line = raw_file.readline().decode('utf-8')

+             line = raw_file.readline().decode("utf-8")

              if not line:

                  break

              try:

-                 file_, license_ = line.split(':')

+                 file_, license_ = line.split(":")

              except ValueError:

                  continue

              file_ = file_.strip()
@@ -652,61 +708,65 @@ 

              source_dir, msg = self._get_source_dir()

              self.log.debug("Scanning sources in %s", source_dir)

              if os.path.exists(source_dir):

-                 cmd = 'licensecheck -r ' + source_dir

+                 cmd = "licensecheck -r " + source_dir

                  try:

                      out = check_output(cmd, shell=True, universal_newlines=True)

                  except (OSError, CalledProcessError) as err:

-                     self.set_passed(self.PENDING,

-                                     "Cannot run licensecheck: " + str(err))

+                     self.set_passed(

+                         self.PENDING, "Cannot run licensecheck: " + str(err)

+                     )

                      return

                  self.log.debug("Got license reply, length: %d", len(out))

                  files_by_license = self._parse_licenses(out)

-                 filename = os.path.join(ReviewDirs.root,

-                                         'licensecheck.txt')

+                 filename = os.path.join(ReviewDirs.root, "licensecheck.txt")

                  self._write_license(files_by_license, filename)

              else:

-                 self.log.error('Source directory %s does not exist!',

-                                source_dir)

+                 self.log.error("Source directory %s does not exist!", source_dir)

              if not files_by_license:

-                 msg += ' No licenses found.'

-                 msg += ' Please check the source files for licenses manually.'

+                 msg += " No licenses found."

+                 msg += " Please check the source files for licenses manually."

              else:

-                 msg += ' Licenses found: "' \

-                        + '", "'.join(files_by_license.keys()) + '".'

+                 msg += (

+                     ' Licenses found: "' + '", "'.join(files_by_license.keys()) + '".'

+                 )

                  if self.unknown_license in files_by_license:

-                     msg += ' %d files have unknown license.' % \

-                                 len(files_by_license[self.unknown_license])

-                 msg += ' Detailed output of licensecheck in ' + filename

+                     msg += " %d files have unknown license." % len(

+                         files_by_license[self.unknown_license]

+                     )

+                 msg += " Detailed output of licensecheck in " + filename

              self.set_passed(self.PENDING, msg)

          except OSError as e:

-             self.log.error('OSError: %s', str(e))

-             msg = ' Programmer error: ' + e.strerror

+             self.log.error("OSError: %s", str(e))

+             msg = " Programmer error: " + e.strerror

              self.set_passed(self.PENDING, msg)

  

  

  class CheckLicensInDoc(GenericCheckBase):

-     ''' Package includes license text files. '''

+     """ Package includes license text files. """

  

      sort_key = _LICENSE_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines/#_license_text'

-         if not self.flags['EPEL6']:

-             self._license_flag = 'L'

-             self._license_macro = '%license'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines/#_license_text"

+         )

+         if not self.flags["EPEL6"]:

+             self._license_flag = "L"

+             self._license_macro = "%license"

          else:

-             self._license_flag = 'd'

-             self._license_macro = '%doc'

- 

-         self.text = 'If (and only if) the source package includes' \

-                     ' the text of the license(s) in its own file,' \

-                     ' then that file, containing the text of the'  \

-                     ' license(s) for the package is included in %s.' % \

-                     self._license_macro

+             self._license_flag = "d"

+             self._license_macro = "%doc"

+ 

+         self.text = (

+             "If (and only if) the source package includes"

+             " the text of the license(s) in its own file,"

+             " then that file, containing the text of the"

+             " license(s) for the package is included in %s." % self._license_macro

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          """ Check if there is a license file and if it is present in the
@@ -715,13 +775,17 @@ 

          # pylint: disable=invalid-name

  

          licenses = []

-         for potentialfile in ['COPYING', 'copying',

-                               'LICEN', 'licen',

-                               'COPYRIGHT', 'copyright']:

-             pattern = '*' + potentialfile + '*'

+         for potentialfile in [

+             "COPYING",

+             "copying",

+             "LICEN",

+             "licen",

+             "COPYRIGHT",

+             "copyright",

+         ]:

+             pattern = "*" + potentialfile + "*"

              licenses.extend(self.rpms.find_all(pattern))

-         licenses = [l.split('/')[-1] for l in licenses

-                     if not self.rpms.find(l + '/*')]

+         licenses = [l.split("/")[-1] for l in licenses if not self.rpms.find(l + "/*")]

          if licenses == []:

              self.set_passed(self.PENDING)

              return
@@ -731,221 +795,242 @@ 

          for pkg in self.spec.packages:

              nvr = self.spec.get_package_nvr(pkg)

              rpm_path = Mock.get_package_rpm_path(nvr)

-             cmd = 'rpm -qp{} {}'.format(self._license_flag, rpm_path)

+             cmd = "rpm -qp{} {}".format(self._license_flag, rpm_path)

              doclist = check_output(cmd.split(), universal_newlines=True)

-             flagged_files.extend(doclist.split('\n'))

-         flagged_files = [f.split('/')[-1] for f in flagged_files]

+             flagged_files.extend(doclist.split("\n"))

+         flagged_files = [f.split("/")[-1] for f in flagged_files]

  

-         if self._license_flag == 'L':

+         if self._license_flag == "L":

              for pkg in self.spec.packages:

                  nvr = self.spec.get_package_nvr(pkg)

                  rpm_path = Mock.get_package_rpm_path(nvr)

-                 cmd = 'rpm -qpL %s' % rpm_path

+                 cmd = "rpm -qpL %s" % rpm_path

                  qpL_list = check_output(cmd.split(), universal_newlines=True)

-                 qpL_files.extend(qpL_list.split('\n'))

-             qpL_files = [f.split('/')[-1] for f in qpL_files]

+                 qpL_files.extend(qpL_list.split("\n"))

+             qpL_files = [f.split("/")[-1] for f in qpL_files]

  

          for _license in licenses:

-             if self._license_flag == 'L' and _license not in qpL_files:

+             if self._license_flag == "L" and _license not in qpL_files:

                  self.log.debug("Found %s not marked as %%license", _license)

                  self.set_passed(

-                     self.FAIL,

-                     "License file %s is not marked as %%license" % _license)

+                     self.FAIL, "License file %s is not marked as %%license" % _license

+                 )

                  return

              if _license not in flagged_files:

                  self.log.debug("Cannot find %s in doclist", _license)

-                 self.set_passed(self.FAIL,

-                                 "Cannot find %s in rpm(s)", _license)

+                 self.set_passed(self.FAIL, "Cannot find %s in rpm(s)", _license)

                  return

          self.set_passed(self.PASS)

  

  

  class CheckLicenseInSubpackages(GenericCheckBase):

-     ''' License should always be installed when subpackages.'''

+     """ License should always be installed when subpackages."""

  

      sort_key = _LICENSE_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines' \

-                    '/#subpackage-licensing'

-         self.text = 'License file installed when any subpackage' \

-                     ' combination is installed.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines"

+             "/#subpackage-licensing"

+         )

+         self.text = (

+             "License file installed when any subpackage" " combination is installed."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

-         '''Check if subpackages exists'''

+         """Check if subpackages exists"""

          return len(self.spec.packages) > 1

  

  

  class CheckLocale(GenericCheckBase):

-     '''

+     """

      MUST: The spec file MUST handle locales properly.  This is done by

      using the %find_lang macro. Using %{_datadir}/locale/* is strictly

      forbidden.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_handling_locale_files'

-         self.text = 'The spec file handles locales properly.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_handling_locale_files"

+         )

+         self.text = "The spec file handles locales properly."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

-         return self.rpms.find('/usr/share/locale/*/LC_MESSAGES/*.mo')

+         return self.rpms.find("/usr/share/locale/*/LC_MESSAGES/*.mo")

  

  

  class CheckMacros(GenericCheckBase):

-     ''' Each package must consistently use macros.  '''

+     """ Each package must consistently use macros.  """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_macros'

-         self.text = 'Package consistently uses macros' \

-                     ' (instead of hard-coded directory names).'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_macros"

+         )

+         self.text = (

+             "Package consistently uses macros"

+             " (instead of hard-coded directory names)."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckBuildrootMacros(GenericCheckBase):

-     '''Package must use either %{buildroot} or $RPM_BUILD_ROOT.  '''

+     """Package must use either %{buildroot} or $RPM_BUILD_ROOT.  """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_macros'

-         self.text = 'Package uses either  %{buildroot} or $RPM_BUILD_ROOT'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_macros"

+         )

+         self.text = "Package uses either  %{buildroot} or $RPM_BUILD_ROOT"

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         br_tag1 = self.spec.find_all_re('.*%{buildroot}.*', True)

-         br_tag2 = self.spec.find_all_re(r'.*\$RPM_BUILD_ROOT.*', True)

+         br_tag1 = self.spec.find_all_re(".*%{buildroot}.*", True)

+         br_tag2 = self.spec.find_all_re(r".*\$RPM_BUILD_ROOT.*", True)

          if br_tag1 and br_tag2:

-             self.set_passed(self.FAIL,

-                             'Using both %{buildroot} and $RPM_BUILD_ROOT')

+             self.set_passed(self.FAIL, "Using both %{buildroot} and $RPM_BUILD_ROOT")

          else:

              self.set_passed(self.PASS)

  

  

  class CheckMakeinstall(GenericCheckBase):

-     ''' Thou shall not use %makeinstall. '''

+     """ Thou shall not use %makeinstall. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/' \

-                    '#_why_the_makeinstall_macro_should_not_be_used'

-         self.text = "Package use %makeinstall only when make install" \

-                     " DESTDIR=... doesn't work."

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/"

+             "#_why_the_makeinstall_macro_should_not_be_used"

+         )

+         self.text = (

+             "Package use %makeinstall only when make install"

+             " DESTDIR=... doesn't work."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         install = self.spec.get_section('%install', raw=True)

-         if install and '%makeinstall' in install:

-             self.set_passed(self.PENDING,

-                             '%makeinstall used in %install section')

+         install = self.spec.get_section("%install", raw=True)

+         if install and "%makeinstall" in install:

+             self.set_passed(self.PENDING, "%makeinstall used in %install section")

          else:

              self.set_passed(self.PASS)

  

  

  class CheckMultipleLicenses(GenericCheckBase):

-     ''' If multiple licenses, we should provide a break-down. '''

+     """ If multiple licenses, we should provide a break-down. """

  

      sort_key = _LICENSE_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines' \

-                    '/#_multiple_licensing_scenarios'

-         self.text = 'If the package is under multiple licenses, the licensing'\

-                     ' breakdown must be documented in the spec.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines"

+             "/#_multiple_licensing_scenarios"

+         )

+         self.text = (

+             "If the package is under multiple licenses, the licensing"

+             " breakdown must be documented in the spec."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

-         license_ = self.spec.expand_tag('License').decode('utf-8').lower().split()

-         return 'and' in license_ or 'or' in license_

+         license_ = self.spec.expand_tag("License").decode("utf-8").lower().split()

+         return "and" in license_ or "or" in license_

  

  

  class CheckNameCharset(GenericCheckBase):

-     '''

+     """

      MUST:all Fedora packages must be named using only the following

           ASCII characters...

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Naming/'

-         self.text = 'Package is named using only allowed ASCII characters.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/Naming/"

+         )

+         self.text = "Package is named using only allowed ASCII characters."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         allowed_chars = 'abcdefghijklmnopqrstuvwxyz' \

-             'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._+'

-         output = ''

+         allowed_chars = (

+             "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._+"

+         )

+         output = ""

          passed = True

          for char in self.spec.name:

              if char not in allowed_chars:

-                 output += '^'

+                 output += "^"

                  passed = False

              else:

-                 output += ' '

+                 output += " "

          if passed:

              self.set_passed(passed)

          else:

-             self.set_passed(passed, '{}\n{}'.format(self.spec.name, output))

+             self.set_passed(passed, "{}\n{}".format(self.spec.name, output))

  

  

  class CheckNaming(GenericCheckBase):

-     '''

+     """

      MUST: The package must be named according to the Package Naming

      Guidelines.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Naming/'

-         self.text = 'Package is named according to the Package Naming' \

-                     ' Guidelines.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/Naming/"

+         )

+         self.text = "Package is named according to the Package Naming" " Guidelines."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckNoConfigInUsr(GenericCheckBase):

-     ''' No config file under /usr. '''

+     """ No config file under /usr. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_configuration_files'

-         self.text = 'No %config files under /usr.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_configuration_files"

+         )

+         self.text = "No %config files under /usr."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

          for pkg in self.spec.packages:

              for line in self.spec.get_files(pkg):

-                 if line.startswith('%config'):

+                 if line.startswith("%config"):

                      return True

          return False

  

      def run_on_applicable(self):

          passed = True

-         extra = ''

+         extra = ""

          for pkg in self.spec.packages:

              for line in self.spec.get_files(pkg):

-                 if line.startswith('%config'):

+                 if line.startswith("%config"):

                      l = line.replace("%config", "")

                      l = l.replace("(noreplace)", "").strip()

-                     if l.startswith('/usr'):

+                     if l.startswith("/usr"):

                          passed = False

                          extra += line

  
@@ -953,87 +1038,96 @@ 

  

  

  class CheckNoConflicts(GenericCheckBase):

-     '''

+     """

      Whenever possible, Fedora packages should avoid conflicting

      with each other

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_conflicts'

-         self.text = 'Package does not generate any conflict.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_conflicts"

+         )

+         self.text = "Package does not generate any conflict."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          text = None

-         if self.spec.expand_tag('Conflicts'):

-             text = 'Package contains Conflicts: tag(s)' \

-                         ' needing fix or justification.'

+         if self.spec.expand_tag("Conflicts"):

+             text = "Package contains Conflicts: tag(s)" " needing fix or justification."

          self.set_passed(self.PENDING, text)

  

  

  class CheckObeysFHS(GenericCheckBase):

-     ''' Package obeys FHS (besides /usr/libexec and /usr/target). '''

+     """ Package obeys FHS (besides /usr/libexec and /usr/target). """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_filesystem_layout'

-         self.text = 'Package obeys FHS, except libexecdir and /usr/target.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_filesystem_layout"

+         )

+         self.text = "Package obeys FHS, except libexecdir and /usr/target."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckObsoletesForRename(GenericCheckBase):

-     ''' If package is a rename, we should provide Obsoletes: etc. '''

+     """ If package is a rename, we should provide Obsoletes: etc. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines' \

-                    '/#renaming-or-replacing-existing-packages'

-         self.text = 'If the package is a rename of another package, proper' \

-                     ' Obsoletes and Provides are present.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines"

+             "/#renaming-or-replacing-existing-packages"

+         )

+         self.text = (

+             "If the package is a rename of another package, proper"

+             " Obsoletes and Provides are present."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckOwnDirs(GenericCheckBase):

-     '''

+     """

      MUST: A package must own all directories that it creates.  If it

      does not create a directory that it uses, then it should require a

      package which does create that directory.

-     '''

+     """

  

      sort_key = _DIR_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_and_directory_ownership'

-         self.text = 'Package must own all directories that it creates.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_and_directory_ownership"

+         )

+         self.text = "Package must own all directories that it creates."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         ''' Test if all directories created by us are owned by us or

+         """ Test if all directories created by us are owned by us or

          of a dependency. Dependency resolution recurses one level, but

          no more. This is partly to limit the result set, partly a

          a best practise not to trust deep dependency chains for

          package directory ownership.

-         '''

+         """

  

          # pylint: disable=R0912

          def resolve(requires_arg):

-             '''

+             """

              Resolve list of symbols to packages in srpm or by repoquery,

              skipping any version requirements.

-             '''

+             """

              pkgs = []

              requires_to_process = list(requires_arg)

              for r in requires_arg:

-                 if r.startswith('rpmlib'):

+                 if r.startswith("rpmlib"):

                      requires_to_process.remove(r)

                      continue

                  for pkg in self.spec.packages:
@@ -1047,7 +1141,7 @@ 

              return list(set(pkgs))

  

          def get_deps_paths(pkg_deps):

-             ''' Return aggregated  list of files in all pkg_deps. '''

+             """ Return aggregated  list of files in all pkg_deps. """

              if not pkg_deps:

                  return []

              paths = deps.list_paths(pkg_deps)
@@ -1059,29 +1153,29 @@ 

          bad_dirs = []

          for pkg in self.spec.packages:

              pkg_deps = resolve(self.rpms.get(pkg).requires)

-             pkg_deps.append('filesystem')

+             pkg_deps.append("filesystem")

              pkg_deps_paths = get_deps_paths(pkg_deps)

              rpm_paths = self.rpms.get_filelist(pkg)

              for p in rpm_paths:

-                 path = p.rsplit('/', 1)[0]  # We own leaf, for sure.

+                 path = p.rsplit("/", 1)[0]  # We own leaf, for sure.

                  while path:

                      if path not in rpm_paths:

                          if path in pkg_deps_paths:

                              break

                          else:

                              bad_dirs.append(path)

-                     path = path.rsplit('/', 1)[0]

+                     path = path.rsplit("/", 1)[0]

          if bad_dirs:

              bad_dirs = list(set(bad_dirs))

-             self.set_passed(self.PENDING,

-                             "Directories without known owners: " +

-                             ', '.join(bad_dirs))

+             self.set_passed(

+                 self.PENDING, "Directories without known owners: " + ", ".join(bad_dirs)

+             )

          else:

              self.set_passed(self.PASS)

  

  

  class CheckOwnOther(GenericCheckBase):

-     '''

+     """

      MUST: Packages must not own files or directories already owned by

      other packages.  The rule of thumb here is that the first package

      to be installed should own the files or directories that other
@@ -1091,46 +1185,47 @@ 

      that you have a good reason to own a file or directory that

      another package owns, then please present that at package review

      time.

-     '''

+     """

  

      sort_key = _DIR_SORT_KEY

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_and_directory_ownership'

-         self.text = 'Package does not own files or directories' \

-                     ' owned by other packages.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_and_directory_ownership"

+         )

+         self.text = (

+             "Package does not own files or directories" " owned by other packages."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

- 

          def format_msg(owners_by_dir):

-             ''' Message string for PENDING message. '''

+             """ Message string for PENDING message. """

              items = []

              for d in owners_by_dir:

-                 owners = ', '.join(owners_by_dir[d])

+                 owners = ", ".join(owners_by_dir[d])

                  items.append("{}({})".format(d, owners))

-             return "Dirs in package are owned also by: " + \

-                 ', '.join(items)

+             return "Dirs in package are owned also by: " + ", ".join(items)

  

          def skip_rpm(path):

-             ' Return True if this rpm  should not be checked. '

-             if path.endswith('.src.rpm'):

+             " Return True if this rpm  should not be checked. "

+             if path.endswith(".src.rpm"):

                  return True

-             pkg = path.rsplit('-', 2)[0]

-             return pkg.endswith(('-debuginfo', '-debugsource'))

+             pkg = path.rsplit("-", 2)[0]

+             return pkg.endswith(("-debuginfo", "-debugsource"))

  

          bad_owners_by_dir = {}

-         rpm_files = glob(os.path.join(Mock.resultdir, '*.rpm'))

+         rpm_files = glob(os.path.join(Mock.resultdir, "*.rpm"))

          rpm_files = [r for r in rpm_files if not skip_rpm(r)]

          for rpm_file in rpm_files:

              rpm_dirs = sorted(deps.list_dirs(rpm_file))

              my_dirs = []

              allowed = set(self.spec.packages)

              for rpm_dir in rpm_dirs:

-                 if '/usr/lib/.build-id' in rpm_dir:

+                 if "/usr/lib/.build-id" in rpm_dir:

                      continue

                  if rpm_dir.startswith(tuple(my_dirs)):

                      continue
@@ -1146,54 +1241,64 @@ 

  

  

  class CheckRelocatable(GenericCheckBase):

-     '''

+     """

      MUST: If the package is designed to be relocatable,

      the packager must state this fact in the request for review,

      along with the rationalization for relocation of that specific package.

      Without this, use of Prefix: /usr is considered a blocker.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_relocatable_packages'

-         self.text = 'Package is not relocatable.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_relocatable_packages"

+         )

+         self.text = "Package is not relocatable."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

-         if self.spec.find_re('^Prefix:'):

+         if self.spec.find_re("^Prefix:"):

              self.set_passed(self.FAIL, 'Package has a "Prefix:" tag')

          else:

              self.set_passed(self.PASS)

  

  

  class CheckRequires(GenericCheckBase):

-     '''

+     """

      https://docs.fedoraproject.org/en-US/packaging-guidelines/#_explicit_requires

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_explicit_requires'

-         self.text = 'Requires correct, justified where necessary.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_explicit_requires"

+         )

+         self.text = "Requires correct, justified where necessary."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckSourceMD5(GenericCheckBase):

-     '''

+     """

      MUST: The sources used to build the package must match the

      upstream source, as provided in the spec URL. Reviewers should use

      md5sum for this task.  If no upstream URL can be specified for

      this package, please see the Source URL Guidelines for how to deal

      with this.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/SourceURL/'

-         self.text = 'Sources used to build the package match the' \

-                     ' upstream source, as provided in the spec URL.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/SourceURL/"

+         )

+         self.text = (

+             "Sources used to build the package match the"

+             " upstream source, as provided in the spec URL."

+         )

          self.automatic = True

  

      def make_diff(self, sources):
@@ -1207,13 +1312,14 @@ 

              upstream = s.extract_dir

              local = self.srpm.extract(s.filename)

              if not local:

-                 self.log.warn(

-                     "Cannot extract local source: %s", s.filename)

-                 return(False, None)

-             cmd = '/usr/bin/diff -U2 -r {} {}'.format(upstream, local)

-             self.log.debug(' Diff cmd: %s', cmd)

+                 self.log.warn("Cannot extract local source: %s", s.filename)

+                 return (False, None)

+             cmd = "/usr/bin/diff -U2 -r {} {}".format(upstream, local)

+             self.log.debug(" Diff cmd: %s", cmd)

              try:

-                 p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE, universal_newlines=True)

+                 p = Popen(

+                     cmd.split(), stdout=PIPE, stderr=PIPE, universal_newlines=True

+                 )

                  output = p.communicate()[0]

              except OSError:

                  self.log.error("Cannot run diff", exc_info=True)
@@ -1223,24 +1329,24 @@ 

          return (True, None)

  

      def check_checksums(self, sources):

-         ''' For all sources, compare checksum with upstream. '''

-         text = ''

+         """ For all sources, compare checksum with upstream. """

+         text = ""

          all_sources_passed = True

          for source in sources:

              if source.local:

-                 self.log.debug('Skipping md5-test for %s',

-                                source.filename)

+                 self.log.debug("Skipping md5-test for %s", source.filename)

                  continue

              if source.local_src:

-                 text += "Using local file " + source.local_src + \

-                         " as upstream\n"

+                 text += "Using local file " + source.local_src + " as upstream\n"

              local = self.srpm.check_source_checksum(source.filename)

              upstream = source.check_source_checksum()

-             text += source.url + ' :\n'

-             text += '  CHECKSUM({}) this package     : {}\n'.\

-                     format(Settings.checksum.upper(), local)

-             text += '  CHECKSUM({}) upstream package : {}\n'.\

-                     format(Settings.checksum.upper(), upstream)

+             text += source.url + " :\n"

+             text += "  CHECKSUM({}) this package     : {}\n".format(

+                 Settings.checksum.upper(), local

+             )

+             text += "  CHECKSUM({}) upstream package : {}\n".format(

+                 Settings.checksum.upper(), upstream

+             )

              if local != upstream:

                  all_sources_passed = False

          return (all_sources_passed, text)
@@ -1248,196 +1354,218 @@ 

      def run(self):

          sources = self.sources.get_all()

          if sources == []:

-             self.log.debug('No testable sources')

-             self.set_passed(self.PENDING, 'Package has no sources or they'

-                             ' are generated by developer')

+             self.log.debug("No testable sources")

+             self.set_passed(

+                 self.PENDING,

+                 "Package has no sources or they" " are generated by developer",

+             )

              return

-         msg = 'Check did not complete'

+         msg = "Check did not complete"

          passed = True

-         text = ''

+         text = ""

          try:

              sources = [self.sources.get(s) for s in self.sources.get_all()]

              passed, text = self.check_checksums(sources)

              if not passed:

                  passed, diff = self.make_diff(sources)

                  if passed:

-                     text += 'However, diff -r shows no differences\n'

-                     msg = 'checksum differs but diff -r is OK'

+                     text += "However, diff -r shows no differences\n"

+                     msg = "checksum differs but diff -r is OK"

                  elif not diff:

-                     msg += 'checksum differs and there are problems '\

-                            'running diff. Please verify manually.\n'

+                     msg += (

+                         "checksum differs and there are problems "

+                         "running diff. Please verify manually.\n"

+                     )

                  else:

-                     p = os.path.join(ReviewDirs.root, 'diff.txt')

-                     with open(p, 'w') as f:

+                     p = os.path.join(ReviewDirs.root, "diff.txt")

+                     with open(p, "w") as f:

                          f.write(diff)

-                     text += 'diff -r also reports differences\n'

-                     msg = 'Upstream MD5sum check error, diff is in ' + p

+                     text += "diff -r also reports differences\n"

+                     msg = "Upstream MD5sum check error, diff is in " + p

          except AttributeError as e:

-             self.log.debug("CheckSourceMD5(): Attribute error %s", str(e),

-                            exc_info=True)

-             msg = 'Internal Error!'

+             self.log.debug(

+                 "CheckSourceMD5(): Attribute error %s", str(e), exc_info=True

+             )

+             msg = "Internal Error!"

              passed = False

          finally:

              if passed:

                  msg = None

              if text:

-                 attachments = [self.Attachment('Source checksums', text)]

+                 attachments = [self.Attachment("Source checksums", text)]

              else:

                  attachments = []

              self.set_passed(passed, msg, attachments)

  

  

  class CheckSpecLegibility(GenericCheckBase):

-     ''' Spec file legible and written in American English. '''

+     """ Spec file legible and written in American English. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_spec_legibility'

-         self.text = 'Spec file is legible and written in American English.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_spec_legibility"

+         )

+         self.text = "Spec file is legible and written in American English."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

  

  class CheckSpecName(GenericCheckBase):

-     '''

+     """

      MUST: The spec file name must match the base package %{name},

      in the format %{name}.spec unless your package has an exemption.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_spec_file_naming'

-         self.text = 'Spec file name must match the spec package' \

-                     ' %{name}, in the format %{name}.spec.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_spec_file_naming"

+         )

+         self.text = (

+             "Spec file name must match the spec package"

+             " %{name}, in the format %{name}.spec."

+         )

          self.automatic = True

  

      def run(self):

-         spec_name = '%s.spec' % self.spec.name

+         spec_name = "%s.spec" % self.spec.name

          if os.path.basename(self.spec.filename) == spec_name:

              self.set_passed(self.PASS)

          else:

-             self.set_passed(self.FAIL, '%s should be %s ' %

-                             (os.path.basename(self.spec.filename), spec_name))

+             self.set_passed(

+                 self.FAIL,

+                 "%s should be %s " % (os.path.basename(self.spec.filename), spec_name),

+             )

  

  

  class CheckStaticLibs(GenericCheckBase):

-     ''' MUST: Static libraries must be in a -static or -devel package.  '''

+     """ MUST: Static libraries must be in a -static or -devel package.  """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#packaging-static-libraries'

-         self.text = 'Static libraries in -static or -devel subpackage, ' \

-                      'providing  -devel if present.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#packaging-static-libraries"

+         )

+         self.text = (

+             "Static libraries in -static or -devel subpackage, "

+             "providing  -devel if present."

+         )

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

-         ''' check if this test is applicable '''

-         return self.rpms.find('*.a')

+         """ check if this test is applicable """

+         return self.rpms.find("*.a")

  

      def run_on_applicable(self):

-         ''' Run the test, called if is_applicable() is True. '''

-         extra = ''

+         """ Run the test, called if is_applicable() is True. """

+         extra = ""

          names = []

          bad_names = []

          no_provides = []

          for pkg in self.spec.packages:

-             if self.rpms.find('*.a', pkg):

+             if self.rpms.find("*.a", pkg):

                  names.append(pkg)

-                 if not pkg.endswith(('-static', '-devel')):

+                 if not pkg.endswith(("-static", "-devel")):

                      bad_names.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 ok = [r for r in rpm_pkg.provides if r.endswith('-static')]

+                 ok = [r for r in rpm_pkg.provides if r.endswith("-static")]

                  if not ok:

                      no_provides.append(pkg)

          if names:

-             extra = 'Package has .a files: ' + ', '.join(names) + '. '

+             extra = "Package has .a files: " + ", ".join(names) + ". "

          if bad_names:

-             extra += 'Illegal package name: ' + ', '.join(bad_names)  + '. '

+             extra += "Illegal package name: " + ", ".join(bad_names) + ". "

          if no_provides:

-             extra += \

-                 'Does not provide -static: ' + ', '.join(no_provides)  + '.'

+             extra += "Does not provide -static: " + ", ".join(no_provides) + "."

          failed = bool(bad_names) or bool(no_provides)

          self.set_passed(self.FAIL if failed else self.PASS, extra)

  

  

  class CheckSystemdScripts(GenericCheckBase):

-     ''' systemd files if applicable. '''

+     """ systemd files if applicable. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Package contains  systemd file(s) if in need.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Package contains  systemd file(s) if in need."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs.append('CheckDaemonCompileFlags')

+         self.type = "MUST"

+         self.needs.append("CheckDaemonCompileFlags")

  

      def run_on_applicable(self):

-         if self.checks.checkdict['CheckDaemonCompileFlags'].is_na:

+         if self.checks.checkdict["CheckDaemonCompileFlags"].is_na:

              self.set_passed(self.PENDING)

          else:

              self.set_passed(self.PASS)

  

  

  class CheckUTF8Filenames(GenericCheckBase):

-     ''' All filenames in rpm packages must be valid UTF-8.  '''

+     """ All filenames in rpm packages must be valid UTF-8.  """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_non_ascii_filenames'

-         self.text = 'File names are valid UTF-8.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_non_ascii_filenames"

+         )

+         self.text = "File names are valid UTF-8."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs.append('CheckRpmlint')

+         self.type = "MUST"

+         self.needs.append("CheckRpmlint")

  

      def run(self):

-         if self.checks.checkdict['CheckRpmlint'].is_disabled:

-             self.set_passed(self.PENDING, 'Rpmlint run disabled')

+         if self.checks.checkdict["CheckRpmlint"].is_disabled:

+             self.set_passed(self.PENDING, "Rpmlint run disabled")

              return

          for line in Mock.rpmlint_output:

-             if 'wrong-file-end-of-line-encoding' in line or \

-                     'file-not-utf8' in line:

+             if "wrong-file-end-of-line-encoding" in line or "file-not-utf8" in line:

                  self.set_passed(self.FAIL)

          self.set_passed(self.PASS)

  

  

  class CheckUsefulDebuginfo(GenericCheckBase):

-     '''

+     """

      Packages should produce useful -debuginfo packages, or explicitly

      disable them when it is not possible to generate a useful one but

      rpmbuild would do it anyway.  Whenever a -debuginfo package is

      explicitly disabled, an explanation why it was done is required in

      the specfile.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_debuginfo_packages'

-         self.text = 'Useful -debuginfo package or justification' \

-                     ' otherwise.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_debuginfo_packages"

+         )

+         self.text = "Useful -debuginfo package or justification" " otherwise."

          self.automatic = False

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def is_applicable(self):

          for path in Mock.get_package_rpm_paths(self.spec):

-             if not path.endswith('noarch.rpm'):

+             if not path.endswith("noarch.rpm"):

                  return True

          return False

  

  

  class CheckNoNameConflict(GenericCheckBase):

-     ''' Check that there isn't already a package with this name.  '''

+     """ Check that there isn't already a package with this name.  """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = "https://docs.fedoraproject.org/en-US" \

-                    "/packaging-guidelines/Naming/#_conflicting_package_names"

-         self.text = 'Package does not use a name that already exists.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Naming/#_conflicting_package_names"

+         )

+         self.text = "Package does not use a name that already exists."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          import json
@@ -1447,15 +1575,14 @@ 

          name = self.spec.name

  

          def already_exist(name):

-             ''' Check if a package name is already in Fedora '''

+             """ Check if a package name is already in Fedora """

              buf = BytesIO()

-             params = {'pattern': name, 'short': '1', 'fork': '0'}

-             url = 'https://src.fedoraproject.org/api/0/projects'

-             headers = ['Content-Type: application/json',

-                        'Accept: application/json']

+             params = {"pattern": name, "short": "1", "fork": "0"}

+             url = "https://src.fedoraproject.org/api/0/projects"

+             headers = ["Content-Type: application/json", "Accept: application/json"]

  

              curl = pycurl.Curl()

-             curl.setopt(pycurl.URL, url + '?' + urlencode(params))

+             curl.setopt(pycurl.URL, url + "?" + urlencode(params))

              curl.setopt(pycurl.HTTPHEADER, headers)

              curl.setopt(pycurl.WRITEFUNCTION, buf.write)

              try:
@@ -1465,10 +1592,10 @@ 

  

              try:

                  j = json.loads(buf.getvalue())

-                 if j['total_projects'] <= 0:

+                 if j["total_projects"] <= 0:

                      return None

  

-                 return [str(x['fullname']) for x in j['projects']]

+                 return [str(x["fullname"]) for x in j["projects"]]

              except (ValueError, KeyError):

                  return None

  
@@ -1477,104 +1604,113 @@ 

              if fullnames is None:

                  fullnames = already_exist(name)

              if fullnames is not None:

-                 urls = ['https://src.fedoraproject.org/' + x

-                         for x in fullnames]

+                 urls = ["https://src.fedoraproject.org/" + x for x in fullnames]

                  self.set_passed(

                      self.FAIL,

-                     'A package with this name already exists.  Please check ' +

-                     ', '.join(urls))

+                     "A package with this name already exists.  Please check "

+                     + ", ".join(urls),

+                 )

              else:

                  self.set_passed(self.PASS)

          except pycurl.error:

-             self.set_passed(self.PENDING,

-                             "Couldn't connect to Pagure, check manually")

+             self.set_passed(self.PENDING, "Couldn't connect to Pagure, check manually")

  

  

  class CheckSourcedirMacroUse(GenericCheckBase):

-     ''' Check for usage of %_sourcedir macro. '''

+     """ Check for usage of %_sourcedir macro. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_improper_use_of_sourcedir'

-         self.text = 'Only use %_sourcedir in very specific situations.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_improper_use_of_sourcedir"

+         )

+         self.text = "Only use %_sourcedir in very specific situations."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

-         text = ''.join(self.spec.lines)

-         if '%_sourcedir' in text or '$RPM_SOURCE_DIR' in text or \

-                                     '%{_sourcedir}' in text:

-             self.set_passed(self.PENDING,

-                             '%_sourcedir/$RPM_SOURCE_DIR is used.')

+         text = "".join(self.spec.lines)

+         if (

+             "%_sourcedir" in text

+             or "$RPM_SOURCE_DIR" in text

+             or "%{_sourcedir}" in text

+         ):

+             self.set_passed(self.PENDING, "%_sourcedir/$RPM_SOURCE_DIR is used.")

          else:

              self.set_passed(self.NA)

  

  

  class CheckUpdateIconCache(GenericCheckBase):

-     ''' Check that gtk-update-icon-cache is run if required. '''

+     """ Check that gtk-update-icon-cache is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#Icon_Cache'

-         self.text = 'gtk-update-icon-cache is invoked in %postun' \

-                     ' and %posttrans if package contains icons.'

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#Icon_Cache"

+         self.text = (

+             "gtk-update-icon-cache is invoked in %postun"

+             " and %posttrans if package contains icons."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

          for pkg in self.spec.packages:

-             if self.rpms.find('/usr/share/icons/*', pkg):

+             if self.rpms.find("/usr/share/icons/*", pkg):

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('gtk-update-icon-cache',

-                                    [rpm_pkg.postun, rpm_pkg.posttrans]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "gtk-update-icon-cache", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

                  else:

-                     if in_list('gtk-update-icon-cache',

-                                [rpm_pkg.postun, rpm_pkg.posttrans]):

+                     if in_list(

+                         "gtk-update-icon-cache", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

          if not using:

              self.set_passed(self.NA)

              return

-         text = "icons in " + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "icons in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = ''

-             self.text = 'gtk-update-icon-cache must not be invoked' \

-                         ' in %post and %posttrans for Fedora 26 and later.'

+             self.url = ""

+             self.text = (

+                 "gtk-update-icon-cache must not be invoked"

+                 " in %post and %posttrans for Fedora 26 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckUpdateDesktopDatabase(GenericCheckBase):

-     ''' Check that update-desktop-database is run if required. '''

+     """ Check that update-desktop-database is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#desktop-database'

-         self.text = 'update-desktop-database is invoked in %post and' \

-                     ' %postun if package contains desktop file(s)' \

-                     ' with a MimeType: entry.'

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#desktop-database"

+         self.text = (

+             "update-desktop-database is invoked in %post and"

+             " %postun if package contains desktop file(s)"

+             " with a MimeType: entry."

+         )

  

          self.automatic = True

-         self.needs.append('generic-large-docs')   # Needed to unpack rpms

-         self.type = 'MUST'

+         self.needs.append("generic-large-docs")  # Needed to unpack rpms

+         self.type = "MUST"

  

      def run(self):

- 

          def has_mimetype(pkg, fname):

-             ''' Return True if the file fname contains a MimeType entry. '''

+             """ Return True if the file fname contains a MimeType entry. """

              nvr = self.spec.get_package_nvr(pkg)

-             rpm_dirs = glob(os.path.join(ReviewDirs.root,

-                                          'rpms-unpacked',

-                                          pkg + '-' + nvr.version + '*'))

+             rpm_dirs = glob(

+                 os.path.join(

+                     ReviewDirs.root, "rpms-unpacked", pkg + "-" + nvr.version + "*"

+                 )

+             )

              path = os.path.join(rpm_dirs[0], fname[1:])

              if os.path.isdir(path):

                  return False
@@ -1583,367 +1719,426 @@ 

                  return False

              with open(path) as f:

                  for line in f.readlines():

-                     if line.strip().lower().startswith('mimetype'):

+                     if line.strip().lower().startswith("mimetype"):

                          return True

              return False

  

          using = []

          failed = False

          for pkg in self.spec.packages:

-             dt_files = self.rpms.find_all('*.desktop', pkg)

+             dt_files = self.rpms.find_all("*.desktop", pkg)

              dt_files = [f for f in dt_files if has_mimetype(pkg, f)]

              if dt_files:

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('update-desktop-database',

-                                    [rpm_pkg.post, rpm_pkg.postun]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "update-desktop-database", [rpm_pkg.post, rpm_pkg.postun]

+                     ):

                          failed = True

                  else:

-                     if in_list('update-desktop-database',

-                                [rpm_pkg.post, rpm_pkg.postun]):

+                     if in_list(

+                         "update-desktop-database", [rpm_pkg.post, rpm_pkg.postun]

+                     ):

                          failed = True

          if not using:

              self.set_passed(self.NA)

              return

-         text = "desktop file(s) with MimeType entry in " + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "desktop file(s) with MimeType entry in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#desktop-database'

-             self.text = 'update-desktop-database must not be invoked' \

-                         ' in %post and %postun for Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#desktop-database"

+             )

+             self.text = (

+                 "update-desktop-database must not be invoked"

+                 " in %post and %postun for Fedora 24 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckGioQueryModules(GenericCheckBase):

-     ''' Check that gio-querymodules is run if required. '''

+     """ Check that gio-querymodules is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL:Packaging#GIO_modules'

-         self.text = 'gio-querymodules is invoked in %postun and %post' \

-                     ' if package has /lib/gio/modules/* files'

+         self.url = "https://fedoraproject.org/wiki/EPEL:Packaging#GIO_modules"

+         self.text = (

+             "gio-querymodules is invoked in %postun and %post"

+             " if package has /lib/gio/modules/* files"

+         )

  

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

-         libdir = Mock.get_macro('%_libdir', self.spec, self.flags)

-         gio_pattern = os.path.join(libdir, 'gio/modules/', '*')

+         libdir = Mock.get_macro("%_libdir", self.spec, self.flags)

+         gio_pattern = os.path.join(libdir, "gio/modules/", "*")

          for pkg in self.spec.packages:

              if self.rpms.find(gio_pattern, pkg):

                  using.append(pkg)

                  rpmpkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('gio-querymodules',

-                                    [rpmpkg.post, rpmpkg.postun]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list("gio-querymodules", [rpmpkg.post, rpmpkg.postun]):

                          failed = True

                  else:

-                     if in_list('gio-querymodules',

-                                [rpmpkg.post, rpmpkg.postun]):

+                     if in_list("gio-querymodules", [rpmpkg.post, rpmpkg.postun]):

                          failed = True

          if not using:

              self.set_passed(self.NA)

              return

-         text = "gio module file(s) in " + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "gio module file(s) in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#GIO_modules'

-             self.text = 'gio-querymodules must not be invoked in %postun' \

-                         ' and %post ifor Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#GIO_modules"

+             )

+             self.text = (

+                 "gio-querymodules must not be invoked in %postun"

+                 " and %post ifor Fedora 24 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckGtkQueryModules(GenericCheckBase):

-     ''' Check that gtk-query-immodules is run if required. '''

+     """ Check that gtk-query-immodules is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#GTK.2B_modules'

-         self.text = 'gtk-query-immodules is invoked when required'

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#GTK.2B_modules"

+         self.text = "gtk-query-immodules is invoked when required"

  

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

-         libdir = Mock.get_macro('%_libdir', self.spec, self.flags)

-         pattern = os.path.join(libdir, 'gtk-3.0/', '*')

+         libdir = Mock.get_macro("%_libdir", self.spec, self.flags)

+         pattern = os.path.join(libdir, "gtk-3.0/", "*")

          for pkg in self.spec.packages:

              if self.rpms.find(pattern, pkg):

                  using.append(pkg)

                  rpmpkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('gtk-query-immodules',

-                                    [rpmpkg.postun, rpmpkg.posttrans]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "gtk-query-immodules", [rpmpkg.postun, rpmpkg.posttrans]

+                     ):

                          failed = True

                  else:

-                     if in_list('gtk-query-immodules',

-                                [rpmpkg.postun, rpmpkg.posttrans]):

+                     if in_list(

+                         "gtk-query-immodules", [rpmpkg.postun, rpmpkg.posttrans]

+                     ):

                          failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = "Gtk module file(s) in " + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "Gtk module file(s) in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#GTK.2B_modules'

-             self.text = 'gtk-query-immodules must not be invoked for' \

-                         ' Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#GTK.2B_modules"

+             )

+             self.text = (

+                 "gtk-query-immodules must not be invoked for" " Fedora 24 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckGlibCompileSchemas(GenericCheckBase):

-     ''' Check that glib-compile-schemas is run if required. '''

+     """ Check that glib-compile-schemas is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#GSettings_Schema'

-         self.text = 'glib-compile-schemas is run in %postun and' \

-                     ' %posttrans if package has *.gschema.xml files. '

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#GSettings_Schema"

+         self.text = (

+             "glib-compile-schemas is run in %postun and"

+             " %posttrans if package has *.gschema.xml files. "

+         )

  

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

          for pkg in self.spec.packages:

-             if self.rpms.find('*.gschema.xml', pkg):

+             if self.rpms.find("*.gschema.xml", pkg):

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('glib-compile-schemas',

-                                    [rpm_pkg.postun, rpm_pkg.posttrans]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "glib-compile-schemas", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

                  else:

-                     if in_list('glib-compile-schemas',

-                                [rpm_pkg.postun, rpm_pkg.posttrans]):

+                     if in_list(

+                         "glib-compile-schemas", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = 'gschema file(s) in ' + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "gschema file(s) in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#GSettings_Schema'

-             self.text = 'glib-compile-schemas must not be run in %postun and' \

-                         ' %posttrans for Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#GSettings_Schema"

+             )

+             self.text = (

+                 "glib-compile-schemas must not be run in %postun and"

+                 " %posttrans for Fedora 24 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckGconfSchemaInstall(GenericCheckBase):

-     ''' Check that gconf schemas are properly installed. '''

+     """ Check that gconf schemas are properly installed. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Scriptlets/#_gconf'

-         self.text = 'GConf schemas are properly installed'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Scriptlets/#_gconf"

+         )

+         self.text = "GConf schemas are properly installed"

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

          for pkg in self.spec.packages:

-             if self.rpms.find('/etc/gconf/schemas/*.schemas', pkg):

+             if self.rpms.find("/etc/gconf/schemas/*.schemas", pkg):

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if not in_list('%gconf_schema',

-                                [rpm_pkg.post, rpm_pkg.pre]):

+                 if not in_list("%gconf_schema", [rpm_pkg.post, rpm_pkg.pre]):

                      failed = True

          if not using:

              self.set_passed(self.NA)

              return

-         text = 'gconf file(s) in ' + ', '.join(using)

+         text = "gconf file(s) in " + ", ".join(using)

          self.set_passed(self.FAIL if failed else self.PENDING, text)

  

  

  class CheckInfoInstall(GenericCheckBase):

-     ''' Check that info files are properly installed. '''

+     """ Check that info files are properly installed. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Scriptlets/#_texinfo'

-         self.text = 'Texinfo files are installed using install-info' \

-                     ' in %post and %preun if package has .info files.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Scriptlets/#_texinfo"

+         )

+         self.text = (

+             "Texinfo files are installed using install-info"

+             " in %post and %preun if package has .info files."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

          for pkg in self.spec.packages:

-             if self.rpms.find('/usr/share/info/*', pkg):

+             if self.rpms.find("/usr/share/info/*", pkg):

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if not in_list('install-info',

-                                [rpm_pkg.post, rpm_pkg.preun]):

+                 if not in_list("install-info", [rpm_pkg.post, rpm_pkg.preun]):

                      failed = True

          if not using:

              self.set_passed(self.NA)

              return

-         text = 'Texinfo .info file(s) in ' + ', '.join(using)

+         text = "Texinfo .info file(s) in " + ", ".join(using)

          self.set_passed(self.FAIL if failed else self.PENDING, text)

  

  

  class CheckGdkPixbufLoaders(GenericCheckBase):

-     ''' Check that gdk-pixbuf-query-loaders is run if required. '''

+     """ Check that gdk-pixbuf-query-loaders is run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#gdk-pixbuf_loaders'

-         self.text = 'gdk-pixbuf-query-loaders is invoked in %post and' \

-                     ' %postun to update gdk-pixbuf'

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#gdk-pixbuf_loaders"

+         self.text = (

+             "gdk-pixbuf-query-loaders is invoked in %post and"

+             " %postun to update gdk-pixbuf"

+         )

  

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

-         libdir = Mock.get_macro('%_libdir', self.spec, self.flags)

-         pattern = os.path.join(libdir, 'gdk-pixbuf-2.0/2.10.0/loaders/', '*')

+         libdir = Mock.get_macro("%_libdir", self.spec, self.flags)

+         pattern = os.path.join(libdir, "gdk-pixbuf-2.0/2.10.0/loaders/", "*")

          for pkg in self.spec.packages:

              if self.rpms.find(pattern, pkg):

                  using.append(pkg)

                  rpmpkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('gdk-pixbuf-query-loaders',

-                                    [rpmpkg.postun, rpmpkg.post]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "gdk-pixbuf-query-loaders", [rpmpkg.postun, rpmpkg.post]

+                     ):

                          failed = True

                  else:

-                     if in_list('gdk-pixbuf-query-loaders',

-                                [rpmpkg.postun, rpmpkg.post]):

+                     if in_list(

+                         "gdk-pixbuf-query-loaders", [rpmpkg.postun, rpmpkg.post]

+                     ):

                          failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = "gdk-pixbux module file(s) in " + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "gdk-pixbux module file(s) in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#gdk-pixbuf_loaders'

-             self.text = 'gdk-pixbuf-query-loaders must not be invoked for' \

-                         ' Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#gdk-pixbuf_loaders"

+             )

+             self.text = (

+                 "gdk-pixbuf-query-loaders must not be invoked for"

+                 " Fedora 24 and later."

+             )

              self.set_passed(self.FAIL if failed else self.NA, text)

  

  

  class CheckSystemdUnitdirScriplets(GenericCheckBase):

-     ''' Check that Systemd unitdir scriplets are run if required. '''

+     """ Check that Systemd unitdir scriplets are run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Scriptlets/#_scriptlets'

-         self.text = 'systemd_post is invoked in %post, systemd_preun in' \

-                     ' %preun, and systemd_postun in %postun for Systemd' \

-                     ' service files.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Scriptlets/#_scriptlets"

+         )

+         self.text = (

+             "systemd_post is invoked in %post, systemd_preun in"

+             " %preun, and systemd_postun in %postun for Systemd"

+             " service files."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

-         systemd_post_re = re.compile(re.escape(rpm.expandMacro('%systemd_post .*.service')).replace(r'\.\*', '.*')[2:-4], re.M)

-         systemd_preun_re = re.compile(re.escape(rpm.expandMacro('%systemd_preun .*.service')).replace(r'\.\*', '.*')[2:-4], re.M)

+         systemd_post_re = re.compile(

+             re.escape(rpm.expandMacro("%systemd_post .*.service")).replace(

+                 r"\.\*", ".*"

+             )[2:-4],

+             re.M,

+         )

+         systemd_preun_re = re.compile(

+             re.escape(rpm.expandMacro("%systemd_preun .*.service")).replace(

+                 r"\.\*", ".*"

+             )[2:-4],

+             re.M,

+         )

          for pkg in self.spec.packages:

-             if self.rpms.find('/usr/lib/systemd/system/*', pkg):

+             if self.rpms.find("/usr/lib/systemd/system/*", pkg):

                  using.append(pkg)

                  rpmpkg = self.rpms.get(pkg)

-                 if not systemd_post_re.search(str(rpmpkg.post)) \

-                     or not systemd_preun_re.search(str(rpmpkg.preun)):

+                 if not systemd_post_re.search(

+                     str(rpmpkg.post)

+                 ) or not systemd_preun_re.search(str(rpmpkg.preun)):

                      failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = "Systemd service file(s) in " + ', '.join(using)

+         text = "Systemd service file(s) in " + ", ".join(using)

          self.set_passed(self.FAIL if failed else self.PASS, text)

  

  

  class CheckSystemdUserunitdirScriplets(GenericCheckBase):

-     ''' Check that Systemd userunitdir scriplets are run if required. '''

+     """ Check that Systemd userunitdir scriplets are run if required. """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Scriptlets/#_user_units'

-         self.text = 'systemd_user_post is invoked in %post and' \

-                     ' systemd_user_preun in %preun for Systemd' \

-                     ' user units service files.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Scriptlets/#_user_units"

+         )

+         self.text = (

+             "systemd_user_post is invoked in %post and"

+             " systemd_user_preun in %preun for Systemd"

+             " user units service files."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run(self):

          using = []

          failed = False

-         systemd_user_post_re = re.compile(re.escape(rpm.expandMacro('%systemd_user_post .*.service')).replace(r'\.\*', '.*')[2:], re.M)

-         systemd_user_preun_re = re.compile(re.escape(rpm.expandMacro('%systemd_user_preun .*.service')).replace(r'\.\*', '.*')[2:], re.M)

+         systemd_user_post_re = re.compile(

+             re.escape(rpm.expandMacro("%systemd_user_post .*.service")).replace(

+                 r"\.\*", ".*"

+             )[2:],

+             re.M,

+         )

+         systemd_user_preun_re = re.compile(

+             re.escape(rpm.expandMacro("%systemd_user_preun .*.service")).replace(

+                 r"\.\*", ".*"

+             )[2:],

+             re.M,

+         )

          for pkg in self.spec.packages:

-             if self.rpms.find('/usr/lib/systemd/user/*', pkg):

+             if self.rpms.find("/usr/lib/systemd/user/*", pkg):

                  using.append(pkg)

                  rpmpkg = self.rpms.get(pkg)

-                 if not systemd_user_post_re.search(str(rpmpkg.post)) \

-                     or not systemd_user_preun_re.search(str(rpmpkg.preun)):

+                 if not systemd_user_post_re.search(

+                     str(rpmpkg.post)

+                 ) or not systemd_user_preun_re.search(str(rpmpkg.preun)):

                      failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = "Systemd user unit service file(s) in " + ', '.join(using)

+         text = "Systemd user unit service file(s) in " + ", ".join(using)

          self.set_passed(self.FAIL if failed else self.PASS, text)

  

  

  class CheckIfDepsDeprecated(GenericCheckBase):

-     '''

+     """

      MUST: Check if package does not depend on deprecated() packages

-     '''

+     """

  

      def __init__(self, base):

          GenericCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/deprecating-packages/'

-         self.text = 'Package must not depend on deprecated() packages.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/deprecating-packages/"

+         )

+         self.text = "Package must not depend on deprecated() packages."

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

  

          # pylint: disable=R0912

          def resolve(requires_arg):

-             '''

+             """

              Resolve list of symbols to packages in srpm or by repoquery

-             '''

+             """

              pkgs = []

              requires_to_process = list(requires_arg)

              for r in requires_arg:

-                 if r.startswith('rpmlib'):

+                 if r.startswith("rpmlib"):

                      requires_to_process.remove(r)

                      continue

                  if "python(abi)" in r:
@@ -1967,9 +2162,10 @@ 

  

          for pkg in pkg_deps:

              provides = deps.list_provides(pkg)

-             if any('deprecated()' in p for p in provides):

-                 self.set_passed(self.FAIL, pkg + ' is deprecated, you must '

-                                 'not depend on it.')

+             if any("deprecated()" in p for p in provides):

+                 self.set_passed(

+                     self.FAIL, pkg + " is deprecated, you must " "not depend on it."

+                 )

                  return

  

          self.set_passed(self.PASS)

file modified
+48 -58
@@ -16,7 +16,7 @@ 

  #

  # (C) 2013 - Pavel Raiskup <praiskup@redhat.com>

  

- ''' Autotools SHOULD checks, default Generic group. '''

+ """ Autotools SHOULD checks, default Generic group. """

  

  import textwrap

  from subprocess import Popen, PIPE
@@ -31,38 +31,30 @@ 

  # would be appreciated.               #

  #######################################

  

- _OBS_M4S_AUTOMAKE = [

-     'AM_CONFIG_HEADER',

-     'AM_PROG_CC_STDC',

- ]

+ _OBS_M4S_AUTOMAKE = ["AM_CONFIG_HEADER", "AM_PROG_CC_STDC"]

  

- _OBS_M4S_LIBTOOL = [

-     'AC_PROG_LIBTOOL',

-     'AM_PROG_LIBTOOL',

- ]

+ _OBS_M4S_LIBTOOL = ["AC_PROG_LIBTOOL", "AM_PROG_LIBTOOL"]

  

- _OBSOLETE_CHECKS = {

-     'automake': _OBS_M4S_AUTOMAKE,

-     'libtool': _OBS_M4S_LIBTOOL,

- }

+ _OBSOLETE_CHECKS = {"automake": _OBS_M4S_AUTOMAKE, "libtool": _OBS_M4S_LIBTOOL}

  

  

  def _prepend_indent(text):

-     ''' add the paragraph indentation '''

+     """ add the paragraph indentation """

      lines = text.splitlines()

-     return '\n'.join(["  " + x if x != "" else "" for x in lines])

+     return "\n".join(["  " + x if x != "" else "" for x in lines])

  

  

  class Registry(RegistryBase):

-     ''' Module registration, register all checks. '''

-     group = 'Generic.autotools'

+     """ Module registration, register all checks. """

+ 

+     group = "Generic.autotools"

  

      def is_applicable(self):

          return True

  

  

  class AutotoolsCheckBase(CheckBase):

-     ''' Base class for all Autotool-related tests. '''

+     """ Base class for all Autotool-related tests. """

  

      used_tools = None

  
@@ -70,21 +62,23 @@ 

          CheckBase.__init__(self, checks, __file__)

  

          # construct text wrapper

-         self.wrapper = textwrap.TextWrapper(break_long_words=False,

-                                             drop_whitespace=True,

-                                             replace_whitespace=True,

-                                             fix_sentence_endings=True)

+         self.wrapper = textwrap.TextWrapper(

+             break_long_words=False,

+             drop_whitespace=True,

+             replace_whitespace=True,

+             fix_sentence_endings=True,

+         )

  

      def text_wrap(self, text, width=76):

-         ''' wrap the text on the specified character '''

+         """ wrap the text on the specified character """

          self.wrapper.width = width

          return self.wrapper.fill(text)

  

      def find_used_tools(self):

-         ''' get the list of autotools relevant for this package '''

+         """ get the list of autotools relevant for this package """

  

          def check_for(tool, packages):

-             ''' helper - try all known package names for the tool '''

+             """ helper - try all known package names for the tool """

              for name in packages:

                  if name in brequires:

                      self.used_tools.append(tool)
@@ -97,20 +91,20 @@ 

  

          self.used_tools = []

  

-         am_pkgs = ['automake', 'automake14', 'automake15', 'automake16',

-                    'automake17']

-         check_for('automake', am_pkgs)

+         am_pkgs = ["automake", "automake14", "automake15", "automake16", "automake17"]

+         check_for("automake", am_pkgs)

          # Re-enable once some autoconf-related checkers are added

          # check_for('autoconf', ['autoconf', 'autoconf213'])

-         check_for('libtool', ['libtool'])

+         check_for("libtool", ["libtool"])

  

-         self.log.debug("autotools used: %s", ' '.join(self.used_tools))

+         self.log.debug("autotools used: %s", " ".join(self.used_tools))

  

  

  # CHECKERS #

  

+ 

  class CheckAutotoolsObsoletedMacros(AutotoolsCheckBase):

-     ''' obsolete macros (shorthly m4s) checker '''

+     """ obsolete macros (shorthly m4s) checker """

  

      warn_items = {}

  
@@ -118,13 +112,13 @@ 

          AutotoolsCheckBase.__init__(self, base)

  

          # basic settings

-         self.text = 'Package should not use obsolete m4 macros'

+         self.text = "Package should not use obsolete m4 macros"

          self.automatic = True

-         self.type = 'EXTRA'

-         self.url = 'https://fedorahosted.org/FedoraReview/wiki/AutoTools'

+         self.type = "EXTRA"

+         self.url = "https://fedorahosted.org/FedoraReview/wiki/AutoTools"

  

      def get_trace_command(self):

-         ''' construct the basic grep command '''

+         """ construct the basic grep command """

          trace_cmd = ["grep", "-E", "-n", "-o"]

  

          for tool in self.used_tools:
@@ -142,14 +136,14 @@ 

          return trace_cmd

  

      def trace(self):

-         ''' trace for obsoleted macros '''

+         """ trace for obsoleted macros """

  

          def shorter_configure(configure):

-             ''' remove the workdir prefix from configure file '''

+             """ remove the workdir prefix from configure file """

              prefix = ReviewDirs.root + "/BUILD"

              simple = configure

              if configure.startswith(prefix):

-                 simple = configure[len(prefix) + 1:]

+                 simple = configure[len(prefix) + 1 :]

              return simple

  

          # find traced files
@@ -157,8 +151,7 @@ 

              src = self.checks.buildsrc

          else:

              src = self.checks.sources

-         trace_files = src.find_all('*configure.ac') \

-                     + src.find_all('*configure.in')

+         trace_files = src.find_all("*configure.ac") + src.find_all("*configure.in")

  

          # get the base tracing command (grep)

          trace_cmd = self.get_trace_command()
@@ -170,39 +163,35 @@ 

              cmd = trace_cmd + [configure_ac]

  

              try:

-                 self.log.debug("running: %s", ' '.join(cmd))

-                 p = Popen(cmd, stdout=PIPE, stderr=PIPE,

-                           universal_newlines=True)

+                 self.log.debug("running: %s", " ".join(cmd))

+                 p = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)

                  stdout, stderr = p.communicate()

              except IOError:

-                 self.set_passed(self.PENDING,

-                                 "error while tracing autoconf.ac")

+                 self.set_passed(self.PENDING, "error while tracing autoconf.ac")

                  return

  

              if p.returncode not in [0, 1]:

-                 msg = "grep returns bad exit value %d: " % p.returncode \

-                     + stderr

+                 msg = "grep returns bad exit value %d: " % p.returncode + stderr

                  self.set_passed(self.PENDING, msg)

                  return

  

              m4_lines = stdout.splitlines(False)

-             m4_lines = [x.strip('(') for x in m4_lines]

+             m4_lines = [x.strip("(") for x in m4_lines]

              for m4_line in m4_lines:

-                 line, m4 = m4_line.split(':')

+                 line, m4 = m4_line.split(":")

  

                  if m4 not in self.warn_items:

                      self.warn_items[m4] = []

  

-                 self.warn_items[m4].append({

-                     'file': shorter_configure(configure_ac),

-                     'line': int(line),

-                 })

+                 self.warn_items[m4].append(

+                     {"file": shorter_configure(configure_ac), "line": int(line)}

+                 )

  

      def generate_pretty_output(self):

-         '''

+         """

          take the results from self.warn_items and generate at pretty looking

          message

-         '''

+         """

  

          output = ""

  
@@ -216,8 +205,8 @@ 

                  if first:

                      first = False

                  else:

-                     hit = hit + ', '

-                 hit = hit + pos['file'] + ':' + str(pos['line'])

+                     hit = hit + ", "

+                 hit = hit + pos["file"] + ":" + str(pos["line"])

  

              output = output + _prepend_indent(self.text_wrap(hit))

              output = output + "\n"
@@ -225,7 +214,7 @@ 

          return output

  

      def run(self):

-         ''' standard entry point for each check '''

+         """ standard entry point for each check """

          self.set_passed(self.NA)

  

          self.find_used_tools()
@@ -245,4 +234,5 @@ 

          self.set_passed(self.FAIL, msg, [attachment])

          return

  

+ 

  # vim: set expandtab ts=4 sw=4 tw=79:

file modified
+159 -141
@@ -17,14 +17,14 @@ 

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

  

- '''

+ """

  Test setup: build, install, run rpmlint and install sources.

  

  This is a a sequence of tests which builds, install runs

  rpmlint and finally re-install the sources using rpmbuild -bp.

  It offers the standard dependency CheckBuildCompleted, which other

  tests by default depends on.

- '''

+ """

  

  import glob

  import os
@@ -42,18 +42,18 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Module registration, register all checks in group Setup. '''

+     """ Module registration, register all checks in group Setup. """

  

-     group = 'Generic.build'

+     group = "Generic.build"

  

      def is_applicable(self):

-         return self.checks.groups['Generic'].is_applicable()

+         return self.checks.groups["Generic"].is_applicable()

  

  

  class BuildCheckBase(CheckBase):

-     ''' Base class for all generic tests. '''

+     """ Base class for all generic tests. """

  

-     sort_key = '10'

+     sort_key = "10"

  

      def __init__(self, checks):

          CheckBase.__init__(self, checks, __file__)
@@ -68,19 +68,19 @@ 

          rpmlint_cfg.write(b'addFilter("unknown-key")')

          rpmlint_cfg.close()

  

-         cmd = 'rpmlint -f ' + rpmlint_cfg.name + ' ' + ' '.join(filenames)

-         out = 'Checking: '

-         sep = '\n' + ' ' * len(out)

+         cmd = "rpmlint -f " + rpmlint_cfg.name + " " + " ".join(filenames)

+         out = "Checking: "

+         sep = "\n" + " " * len(out)

          out += sep.join([os.path.basename(f) for f in filenames])

-         out += '\n'

+         out += "\n"

          out += self._run_cmd(cmd)

-         out += '\n'

+         out += "\n"

  

          os.unlink(rpmlint_cfg.name)

  

-         with open('rpmlint.txt', 'w') as f:

+         with open("rpmlint.txt", "w") as f:

              f.write(out)

-         for line in out.split('\n'):

+         for line in out.split("\n"):

              if line:

                  self.rpmlint_output.append(line)

          no_errors, msg = self.check_rpmlint_errors(out, self.log)
@@ -98,35 +98,37 @@ 

          if rpms is None:

              rpms = Mock.get_package_rpm_paths(self.spec, with_srpm=True)

          no_errors, result = self.run_rpmlint(rpms)

-         return no_errors, result + '\n'

+         return no_errors, result + "\n"

  

  

  def _mock_root_setup(while_what, force=False):

-     ''' Wrap mock --init. '''

+     """ Wrap mock --init. """

  

      class DependencyInstallError(ReviewError):

-         ''' Raised when a package in local repo can't be installed. '''

+         """ Raised when a package in local repo can't be installed. """

+ 

          pass

  

      Mock.init(force)

      if Settings.repo:

          repodir = Settings.repo

-         if not repodir.startswith('/'):

+         if not repodir.startswith("/"):

              repodir = os.path.join(ReviewDirs.startdir, repodir)

-         rpms = glob.glob(os.path.join(repodir, '*.rpm'))

+         rpms = glob.glob(os.path.join(repodir, "*.rpm"))

          error = Mock.install(rpms)

          if error:

-             raise DependencyInstallError(while_what + ': ' + error)

+             raise DependencyInstallError(while_what + ": " + error)

  

  

  class CheckResultdir(BuildCheckBase):

-     '''

+     """

      EXTRA: The resultdir must be empty, since we later on will assume

      anything there is generated by mock.

-     '''

+     """

  

      class NotEmptyError(ReviewError):

-         ''' The resultdir is not empty. '''

+         """ The resultdir is not empty. """

+ 

          def __init__(self):

              ReviewError.__init__(self, "The result dir is not empty")

              self.show_logs = False
@@ -135,66 +137,68 @@ 

          BuildCheckBase.__init__(self, base)

          self.automatic = True

          self.needs = []

-         self.text = 'Resultdir need to be empty before review'

+         self.text = "Resultdir need to be empty before review"

  

      def run(self):

          if Settings.nobuild or Settings.prebuilt:

              self.set_passed(self.NA)

              return

-         for f in glob.glob(os.path.join(Mock.resultdir, '*.*')):

-             if not f.endswith('.log'):

-                 raise self.NotEmptyError()       # pylint: disable=W0311

+         for f in glob.glob(os.path.join(Mock.resultdir, "*.*")):

+             if not f.endswith(".log"):

+                 raise self.NotEmptyError()  # pylint: disable=W0311

              os.unlink(f)

          self.set_passed(self.NA)

  

  

  class CheckBuild(BuildCheckBase):

-     '''

+     """

      MUST: The package MUST successfully compile and build into binary

      rpms on at least one primary architecture.

-     '''

+     """

  

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_architecture_support'

-         self.text = 'Package successfully compiles and builds into' \

-                     ' binary rpms on at least one supported primary' \

-                     ' architecture.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_architecture_support"

+         )

+         self.text = (

+             "Package successfully compiles and builds into"

+             " binary rpms on at least one supported primary"

+             " architecture."

+         )

          self.automatic = True

-         self.needs = ['CheckResultdir']

+         self.needs = ["CheckResultdir"]

  

      def run(self):

          # pylint: disable=W0632

  

          def listfiles():

-             ''' Generate listing of dirs and files in each package. '''

-             with open('files.dir', 'w') as f:

+             """ Generate listing of dirs and files in each package. """

+             with open("files.dir", "w") as f:

                  for pkg in self.spec.packages:

                      nvr = self.spec.get_package_nvr(pkg)

                      path = Mock.get_package_rpm_path(nvr)

                      dirs, files = deps.listpaths(path)

-                     f.write(pkg + '\n')

-                     f.write('=' * len(pkg) + '\n')

+                     f.write(pkg + "\n")

+                     f.write("=" * len(pkg) + "\n")

                      for line in sorted(dirs):

-                         f.write(line + '\n')

-                     f.write('\n')

+                         f.write(line + "\n")

+                     f.write("\n")

                      for line in sorted(files):

-                         f.write(line + '\n')

-                     f.write('\n')

+                         f.write(line + "\n")

+                     f.write("\n")

  

          if Settings.prebuilt:

-             self.set_passed(self.PENDING, 'Using prebuilt packages')

+             self.set_passed(self.PENDING, "Using prebuilt packages")

              listfiles()

              return

          if Settings.nobuild:

              if Mock.have_cache_for(self.spec):

-                 self.set_passed(self.PENDING,

-                                 'Re-using old build in mock')

+                 self.set_passed(self.PENDING, "Re-using old build in mock")

                  return

              else:

-                 self.log.info(

-                     'No valid cache, building despite --no-build.')

+                 self.log.info("No valid cache, building despite --no-build.")

          _mock_root_setup("While building")

          Mock.build(self.srpm.filename)

          listfiles()
@@ -202,42 +206,48 @@ 

  

  

  class CheckRpmlint(BuildCheckBase):

-     '''

+     """

      MUST: rpmlint must be run on the source rpm and all binary rpms

      the build produces.  The output should be posted in the review.

-     '''

+     """

+ 

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/#_use_rpmlint'

-         self.text = 'Rpmlint is run on all rpms the build produces.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines/#_use_rpmlint"

+         )

+         self.text = "Rpmlint is run on all rpms the build produces."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs = ['CheckBuild']

+         self.type = "MUST"

+         self.needs = ["CheckBuild"]

  

      def run(self):

-         if not self.checks.checkdict['CheckBuild'].is_failed:

+         if not self.checks.checkdict["CheckBuild"].is_failed:

              no_errors, retval = self.rpmlint_rpms()

-             text = 'No rpmlint messages.' if no_errors else \

-                         'There are rpmlint messages (see attachment).'

-             attachments = [self.Attachment('Rpmlint', retval, 5)]

+             text = (

+                 "No rpmlint messages."

+                 if no_errors

+                 else "There are rpmlint messages (see attachment)."

+             )

+             attachments = [self.Attachment("Rpmlint", retval, 5)]

              self.set_passed(self.PASS, text, attachments)

          else:

-             self.set_passed(self.FAIL, 'Mock build failed')

+             self.set_passed(self.FAIL, "Mock build failed")

  

  

  class CheckPackageInstalls(BuildCheckBase):

-     ''' Install package in mock. '''

+     """ Install package in mock. """

  

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Package installs properly.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Package installs properly."

          self.automatic = True

-         self.type = 'MUST'

-         self.needs = ['CheckRpmlint']

+         self.type = "MUST"

+         self.needs = ["CheckRpmlint"]

  

      def check_build_installed(self):

-         ''' Return list of used rpms which are not installed'''

+         """ Return list of used rpms which are not installed"""

          bad_ones = []

          for pkg in self.spec.packages:

              try:
@@ -249,8 +259,9 @@ 

  

      def run(self):

          if not Mock.is_available():

-             self.set_passed(self.PENDING,

-                             "No installation test done (mock unavailable)")

+             self.set_passed(

+                 self.PENDING, "No installation test done (mock unavailable)"

+             )

              return

          if Settings.nobuild:

              bad_ones = self.check_build_installed()
@@ -258,76 +269,81 @@ 

                  self.set_passed(self.PASS)

              else:

                  bad_ones = list(set(bad_ones))

-                 self.set_passed(self.FAIL,

-                                 '--no-build: package(s) not installed')

-                 self.log.info('Packages required by --no-build are'

-                               ' not installed: %s', ', '.join(bad_ones))

+                 self.set_passed(self.FAIL, "--no-build: package(s) not installed")

+                 self.log.info(

+                     "Packages required by --no-build are" " not installed: %s",

+                     ", ".join(bad_ones),

+                 )

              return

-         _mock_root_setup('While installing built packages', force=True)

+         _mock_root_setup("While installing built packages", force=True)

          rpms = Mock.get_package_rpm_paths(self.spec)

-         rpms.extend(

-             Mock.get_package_debuginfo_paths(self.spec.get_package_nvr()))

-         self.log.info('Installing built package(s)')

+         rpms.extend(Mock.get_package_debuginfo_paths(self.spec.get_package_nvr()))

+         self.log.info("Installing built package(s)")

          output = Mock.install(rpms)

          if not output:

              self.set_passed(self.PASS)

          else:

-             attachments = [

-                 self.Attachment('Installation errors', output, 3)]

-             self.set_passed(self.FAIL,

-                             "Installation errors (see attachment)",

-                             attachments)

+             attachments = [self.Attachment("Installation errors", output, 3)]

+             self.set_passed(

+                 self.FAIL, "Installation errors (see attachment)", attachments

+             )

  

  

  class CheckRpmlintInstalled(BuildCheckBase):

-     '''

+     """

      EXTRA: Not in guidelines, but running rpmlint on the installed

      package occasionally reveals things otherwise not found.

-     '''

+     """

+ 

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_use_rpmlint'

-         self.text = 'Rpmlint is run on all installed packages.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_use_rpmlint"

+         )

+         self.text = "Rpmlint is run on all installed packages."

          self.automatic = True

-         self.type = 'EXTRA'

-         self.needs = ['CheckPackageInstalls']

+         self.type = "EXTRA"

+         self.needs = ["CheckPackageInstalls"]

  

      def run(self):

          if not Mock.is_available():

              self.set_passed(self.NA)

              return

-         if self.checks.checkdict['CheckPackageInstalls'].is_passed:

+         if self.checks.checkdict["CheckPackageInstalls"].is_passed:

              rpms = Mock.get_package_rpm_paths(self.spec)

-             rpms.extend(

-                 Mock.get_package_debuginfo_paths(self.spec.get_package_nvr()))

+             rpms.extend(Mock.get_package_debuginfo_paths(self.spec.get_package_nvr()))

              no_errors, retcode = Mock.rpmlint_rpms(rpms)

-             text = 'No rpmlint messages.' if no_errors else \

-                              'There are rpmlint messages (see attachment).'

-             attachments = \

-                 [self.Attachment('Rpmlint (installed packages)',

-                                  retcode + '\n', 7)]

+             text = (

+                 "No rpmlint messages."

+                 if no_errors

+                 else "There are rpmlint messages (see attachment)."

+             )

+             attachments = [

+                 self.Attachment("Rpmlint (installed packages)", retcode + "\n", 7)

+             ]

              self.set_passed(self.PASS, text, attachments)

          else:

-             self.set_passed(self.FAIL, 'Mock build failed')

+             self.set_passed(self.FAIL, "Mock build failed")

  

  

  class CheckRpmlintDebuginfo(BuildCheckBase):

-     '''

+     """

      EXTRA: Not in guidelines, but running rpmlint on the debuginfo

      package occasionally reveals things otherwise not found.

-     '''

+     """

+ 

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_use_rpmlint'

-         self.text = 'Rpmlint is run on debuginfo package(s).'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_use_rpmlint"

+         )

+         self.text = "Rpmlint is run on debuginfo package(s)."

          self.automatic = True

-         self.type = 'EXTRA'

-         self.needs = ['CheckRpmlintInstalled']

+         self.type = "EXTRA"

+         self.needs = ["CheckRpmlintInstalled"]

  

      def run(self):

-         if not self.checks.checkdict['CheckPackageInstalls'].is_passed:

+         if not self.checks.checkdict["CheckPackageInstalls"].is_passed:

              self.set_passed(self.NA)

              return self.NA

          rpms = Mock.get_package_debuginfo_paths(self.spec.get_package_nvr())
@@ -335,81 +351,83 @@ 

              self.set_passed(self.NA)

              return self.NA

          no_errors, retcode = self.rpmlint_rpms(rpms)

-         text = 'No rpmlint messages.' if no_errors else \

-                          'There are rpmlint messages (see attachment).'

-         attachments = \

-             [self.Attachment('Rpmlint (debuginfo)', retcode + '\n', 6)]

+         text = (

+             "No rpmlint messages."

+             if no_errors

+             else "There are rpmlint messages (see attachment)."

+         )

+         attachments = [self.Attachment("Rpmlint (debuginfo)", retcode + "\n", 6)]

          self.set_passed(self.PASS, text, attachments)

  

  

  class CheckInitDeps(BuildCheckBase):

-     ''' EXTRA: Setup the repoquery wrapper.  No output in report '''

+     """ EXTRA: Setup the repoquery wrapper.  No output in report """

  

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

          self.automatic = True

-         self.type = 'EXTRA'

-         self.needs = ['CheckRpmlintDebuginfo']

+         self.type = "EXTRA"

+         self.needs = ["CheckRpmlintDebuginfo"]

  

      def run(self):

          # Dirty work-around for

          # https://bugzilla.redhat.com/show_bug.cgi?id=1028332

-         subprocess.call(['dnf', '-q', 'clean', 'all'])

+         subprocess.call(["dnf", "-q", "clean", "all"])

          deps.init()

          self.set_passed(self.NA)

  

  

  class CheckBuildCompleted(BuildCheckBase):

-     '''

+     """

      EXTRA: This test is the default dependency. Requiring this test means

      requiring the build, rpmlint and restored source using rpmbuild -bp

      under BUILD. The test runs rpmbuild -bp, but leaves no trace in report.

-     '''

+     """

+ 

      def __init__(self, base):

          BuildCheckBase.__init__(self, base)

-         self.url = ''

-         self.text = 'This text is never shown'

+         self.url = ""

+         self.text = "This text is never shown"

          self.automatic = True

-         self.type = 'EXTRA'

-         self.needs = ['CheckInitDeps']

+         self.type = "EXTRA"

+         self.needs = ["CheckInitDeps"]

  

      def setup_attachment(self):

-         ''' Return a setup info attachment. '''

-         text = 'Generated by fedora-review %s (%s) last change: %s\n' % \

-             (__version__, BUILD_ID, BUILD_DATE)

-         text += 'Command line :' + ' '.join(sys.argv) + '\n'

-         text += 'Buildroot used: %s\n' % Mock.buildroot

+         """ Return a setup info attachment. """

+         text = "Generated by fedora-review %s (%s) last change: %s\n" % (

+             __version__,

+             BUILD_ID,

+             BUILD_DATE,

+         )

+         text += "Command line :" + " ".join(sys.argv) + "\n"

+         text += "Buildroot used: %s\n" % Mock.buildroot

          plugins = self.checks.get_plugins(True)

-         text += 'Active plugins: ' + ', '.join(plugins) + '\n'

+         text += "Active plugins: " + ", ".join(plugins) + "\n"

          plugins = self.checks.get_plugins(False)

-         text += 'Disabled plugins: ' + ', '.join(plugins) + '\n'

-         flags = [f for f in self.checks.flags.keys()

-                  if not self.checks.flags[f]]

-         flags = ', '.join(flags) if flags else 'None'

-         text += 'Disabled flags: ' + flags + '\n'

-         return self.Attachment('', text, 10)

+         text += "Disabled plugins: " + ", ".join(plugins) + "\n"

+         flags = [f for f in self.checks.flags.keys() if not self.checks.flags[f]]

+         flags = ", ".join(flags) if flags else "None"

+         text += "Disabled flags: " + flags + "\n"

+         return self.Attachment("", text, 10)

  

      def run(self):

          if not Mock.is_available():

-             self.log.info(

-                 "Mock unavailable, build and installation not checked.")

+             self.log.info("Mock unavailable, build and installation not checked.")

              self.set_passed(self.NA)

              return

          Mock.clear_builddir()

          errmsg = Mock.rpmbuild_bp(self.srpm)

          if errmsg:

-             self.log.debug(

-                 "Cannot do rpmbuild -bp, trying with builddeps")

+             self.log.debug("Cannot do rpmbuild -bp, trying with builddeps")

              Mock.install(self.spec.build_requires)

              Mock.rpmbuild_bp(self.srpm)

-         if os.path.lexists('BUILD'):

-             if os.path.islink('BUILD'):

-                 os.unlink('BUILD')

+         if os.path.lexists("BUILD"):

+             if os.path.islink("BUILD"):

+                 os.unlink("BUILD")

              else:

-                 shutil.rmtree('BUILD')

-         os.symlink(Mock.get_builddir('BUILD'), 'BUILD')

-         self.log.info('Active plugins: %s',

-                       ', '.join(self.checks.get_plugins(True)))

+                 shutil.rmtree("BUILD")

+         os.symlink(Mock.get_builddir("BUILD"), "BUILD")

+         self.log.info("Active plugins: %s", ", ".join(self.checks.get_plugins(True)))

          self.set_passed(self.NA, None, [self.setup_attachment()])

  

  

file modified
+346 -287
@@ -16,7 +16,7 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''  Generic SHOULD  and EXTRA checks. '''

+ """  Generic SHOULD  and EXTRA checks. """

  

  import os.path

  import os
@@ -28,276 +28,287 @@ 

  import rpm

  

  from FedoraReview import CheckBase, Mock, ReviewDirs

- from FedoraReview import ReviewError             # pylint: disable=W0611

+ from FedoraReview import ReviewError  # pylint: disable=W0611

  from FedoraReview import RegistryBase, Settings

  

  from .generic import in_list

  

  

  class Registry(RegistryBase):

-     '''

+     """

      Module registration, register all checks, supplements MUST module.

-     '''

+     """

  

-     group = 'Generic.should'

+     group = "Generic.should"

  

      def is_applicable(self):

-         return self.checks.groups['Generic'].is_applicable()

+         return self.checks.groups["Generic"].is_applicable()

  

  

  class GenericShouldCheckBase(CheckBase):

-     ''' Base class for all generic SHOULD + EXTRA tests. '''

+     """ Base class for all generic SHOULD + EXTRA tests. """

  

      def __init__(self, checks):

          CheckBase.__init__(self, checks, __file__)

  

  

  class CheckBuildInMock(GenericShouldCheckBase):

-     '''

+     """

      SHOULD: The reviewer should test that the package builds in mock.

      https://fedoraproject.org/wiki/PackageMaintainers/MockTricks

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/' \

-                    'PackageMaintainers/MockTricks'

-         self.text = 'Reviewer should test that the package builds in mock.'

+         self.url = "https://fedoraproject.org/wiki/" "PackageMaintainers/MockTricks"

+         self.text = "Reviewer should test that the package builds in mock."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         self.set_passed(self.checks.checkdict['CheckBuild'].is_passed)

+         self.set_passed(self.checks.checkdict["CheckBuild"].is_passed)

  

  

  class CheckBuildroot(GenericShouldCheckBase):

-     ''' Is buildroot defined as appropriate? '''

+     """ Is buildroot defined as appropriate? """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Buildroot is not present'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Buildroot is not present"

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         br_tags = self.spec.find_all_re('^BuildRoot')

+         br_tags = self.spec.find_all_re("^BuildRoot")

          if not br_tags:

              self.set_passed(self.PASS)

              return

          elif len(br_tags) > 1:

-             self.set_passed(self.FAIL,

-                             'Multiple BuildRoot definitions found')

+             self.set_passed(self.FAIL, "Multiple BuildRoot definitions found")

              return

  

          try:

-             br = br_tags[0].split(':')[1].strip()

+             br = br_tags[0].split(":")[1].strip()

          except IndexError:

-             br = 'Illegal buildroot line:' + br_tags[0]

+             br = "Illegal buildroot line:" + br_tags[0]

          legal_buildroots = [

-             '%(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)',

-             '%{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)',

-             '%{_tmppath}/%{name}-%{version}-%{release}-root']

+             "%(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)",

+             "%{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)",

+             "%{_tmppath}/%{name}-%{version}-%{release}-root",

+         ]

          if br in legal_buildroots:

-             self.set_passed(self.PENDING,

-                             'Buildroot: present but not needed')

+             self.set_passed(self.PENDING, "Buildroot: present but not needed")

          else:

-             self.set_passed(self.FAIL,

-                             'Invalid buildroot found: %s' % br)

+             self.set_passed(self.FAIL, "Invalid buildroot found: %s" % br)

  

  

  class CheckClean(GenericShouldCheckBase):

-     ''' Package has not %clean. '''

+     """ Package has not %clean. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_tags_and_sections'

-         self.text = 'Package has no %clean section with rm -rf' \

-                     ' %{buildroot} (or $RPM_BUILD_ROOT)'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_tags_and_sections"

+         )

+         self.text = (

+             "Package has no %clean section with rm -rf"

+             " %{buildroot} (or $RPM_BUILD_ROOT)"

+         )

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          has_clean = False

-         sec_clean = self.spec.find_re('^[ ]*%clean')

+         sec_clean = self.spec.find_re("^[ ]*%clean")

          if sec_clean:

-             sec_clean = self.spec.get_section('%clean', raw=True)

-             buildroot = rpm.expandMacro('%{buildroot}')

-             buildroot = buildroot.replace('+', r'\+')

-             regex = r'rm\s+\-[rf][rf]\s+(%{buildroot}|\$RPM_BUILD_ROOT)'

-             regex = regex.replace('%{buildroot}', buildroot)

+             sec_clean = self.spec.get_section("%clean", raw=True)

+             buildroot = rpm.expandMacro("%{buildroot}")

+             buildroot = buildroot.replace("+", r"\+")

+             regex = r"rm\s+\-[rf][rf]\s+(%{buildroot}|\$RPM_BUILD_ROOT)"

+             regex = regex.replace("%{buildroot}", buildroot)

              has_clean = re.search(regex, sec_clean)

          if has_clean:

-             self.set_passed(self.PENDING,

-                             '%clean present but not required')

+             self.set_passed(self.PENDING, "%clean present but not required")

          else:

              self.set_passed(self.PASS)

  

  

  class CheckContainsLicenseText(GenericShouldCheckBase):

-     ''' Handle missing license info.  '''

+     """ Handle missing license info.  """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines/#_license_text'

-         self.text = 'If the source package does not include license' \

-                     ' text(s) as a separate file from upstream, the' \

-                     ' packager SHOULD query upstream to include it.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines/#_license_text"

+         )

+         self.text = (

+             "If the source package does not include license"

+             " text(s) as a separate file from upstream, the"

+             " packager SHOULD query upstream to include it."

+         )

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckFileRequires(GenericShouldCheckBase):

-     '''

+     """

      If the package has file dependencies outside of /etc,

      /bin, /sbin, /usr/bin, or /usr/sbin consider requiring the package

      which provides the file instead of the file itself.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_file_and_directory_dependencies'

-         self.text = 'No file requires outside of' \

-                     ' /etc, /bin, /sbin, /usr/bin, /usr/sbin.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_file_and_directory_dependencies"

+         )

+         self.text = (

+             "No file requires outside of" " /etc, /bin, /sbin, /usr/bin, /usr/sbin."

+         )

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

- 

          def is_acceptable(req):

-             ''' Is a requiremetn acceptable? '''

-             for acceptable in ['/usr/bin/', '/etc/', '/bin/', '/sbin/',

-                                '/usr/sbin/']:

+             """ Is a requiremetn acceptable? """

+             for acceptable in ["/usr/bin/", "/etc/", "/bin/", "/sbin/", "/usr/sbin/"]:

                  if req.startswith(acceptable):

                      return True

-             return not req.startswith('/')

+             return not req.startswith("/")

  

          def get_requires(rpm_name, requires):

-             ''' Return printable requirements for a rpm. '''

-             requires = [s for s in requires

-                         if 'rpmlib' not in s and 'GLIBC' not in s]

+             """ Return printable requirements for a rpm. """

+             requires = [s for s in requires if "rpmlib" not in s and "GLIBC" not in s]

              requires = sorted(list(set(requires)))

-             hdr = rpm_name + ' (rpmlib, GLIBC filtered):'

+             hdr = rpm_name + " (rpmlib, GLIBC filtered):"

              requires.insert(0, hdr)

-             return '\n    '.join(requires) + '\n'

+             return "\n    ".join(requires) + "\n"

  

          def get_provides(rpm_name, provides):

-             ''' Return printable Provides:  for a rpm. '''

+             """ Return printable Provides:  for a rpm. """

              provides = sorted(list(set(provides)))

-             provides.insert(0, rpm_name + ':')

-             return '\n    '.join(provides) + '\n'

+             provides.insert(0, rpm_name + ":")

+             return "\n    ".join(provides) + "\n"

  

          wrong_req = []

-         req_txt = ''

-         prov_txt = ''

+         req_txt = ""

+         prov_txt = ""

          for pkg in self.rpms.get_keys():

              rpm_pkg = self.rpms.get(pkg)

              requires = rpm_pkg.requires

              for req in requires:

                  if not is_acceptable(req):

                      wrong_req.append(req)

-             req_txt += get_requires(pkg, requires) + '\n'

-             prov_txt += get_provides(pkg, rpm_pkg.provides) + '\n'

-         attachments = [self.Attachment('Requires', req_txt),

-                        self.Attachment('Provides', prov_txt)]

+             req_txt += get_requires(pkg, requires) + "\n"

+             prov_txt += get_provides(pkg, rpm_pkg.provides) + "\n"

+         attachments = [

+             self.Attachment("Requires", req_txt),

+             self.Attachment("Provides", prov_txt),

+         ]

          if not wrong_req:

              self.set_passed(self.PASS, None, attachments)

          else:

-             text = "Incorrect Requires : %s " % (', '.join(wrong_req))

+             text = "Incorrect Requires : %s " % (", ".join(wrong_req))

              self.set_passed(self.FAIL, text, attachments)

  

  

  class CheckFinalRequiresProvides(GenericShouldCheckBase):

-     ''' Final Requires: and Provides: should be sane. '''

+     """ Final Requires: and Provides: should be sane. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Final provides and requires are sane' \

-                     ' (see attachments).'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Final provides and requires are sane" " (see attachments)."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckFunctionAsDescribed(GenericShouldCheckBase):

-     '''

+     """

      The reviewer should test that the package functions as described.

      A package should not segfault instead of running, for example.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Package functions as described.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Package functions as described."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckFullVerReqSub(GenericShouldCheckBase):

-     ''' Sub-packages requires base package using fully-versioned dep. '''

+     """ Sub-packages requires base package using fully-versioned dep. """

  

-     HDR = 'No Requires: %{name}%{?_isa} = %{version}-%{release} in '

-     REGEX = r'%{name}%{?_isa} = %{version}-%{release}'

+     HDR = "No Requires: %{name}%{?_isa} = %{version}-%{release} in "

+     REGEX = r"%{name}%{?_isa} = %{version}-%{release}"

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_requiring_base_package'

-         self.text = 'Fully versioned dependency in subpackages' \

-                     ' if applicable.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_requiring_base_package"

+         )

+         self.text = "Fully versioned dependency in subpackages" " if applicable."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          bad_pkgs = []

-         archs = self.checks.spec.expand_tag('BuildArchs')

+         archs = self.checks.spec.expand_tag("BuildArchs")

          if len(self.spec.packages) == 1:

              self.set_passed(self.NA)

              return

-         if len(archs) == 1 and archs[0].lower() == b'noarch':

-             isa = ''

+         if len(archs) == 1 and archs[0].lower() == b"noarch":

+             isa = ""

          else:

-             isa = Mock.get_macro('%_isa', self.spec, self.flags)

-         regex = self.REGEX.replace('%{?_isa}', isa)

+             isa = Mock.get_macro("%_isa", self.spec, self.flags)

+         regex = self.REGEX.replace("%{?_isa}", isa)

          regex = rpm.expandMacro(regex)

-         regex = re.sub('[.](fc|el)[0-9]+', '', regex)

+         regex = re.sub("[.](fc|el)[0-9]+", "", regex)

          for pkg in self.spec.packages:

              if pkg == self.spec.base_package:

                  continue

-             if pkg.endswith(('debuginfo', 'debugsource', '-javadoc', '-doc')):

+             if pkg.endswith(("debuginfo", "debugsource", "-javadoc", "-doc")):

                  continue

-             reqs = ''.join(self.rpms.get(pkg).format_requires)

+             reqs = "".join(self.rpms.get(pkg).format_requires)

              if regex not in reqs:

                  bad_pkgs.append(pkg)

          if bad_pkgs:

-             self.set_passed(self.PENDING,

-                             self.HDR + ' , '.join(bad_pkgs))

+             self.set_passed(self.PENDING, self.HDR + " , ".join(bad_pkgs))

          else:

              self.set_passed(self.PASS)

  

  

  class CheckIllegalSpecTags(GenericShouldCheckBase):

-     ''' Thou shall not use illegal spec tags. '''

+     """ Thou shall not use illegal spec tags. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_tags_and_sections'

-         self.text = 'Packager, Vendor, PreReq, Copyright tags should not be ' \

-                     'in spec file'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_tags_and_sections"

+         )

+         self.text = (

+             "Packager, Vendor, PreReq, Copyright tags should not be " "in spec file"

+         )

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          passed = True

-         output = ''

-         for tag in ('Packager', 'Vendor', 'PreReq', 'Copyright'):

-             if not self.spec.find_re(r'^\s*' + tag + r'\s*:'):

+         output = ""

+         for tag in ("Packager", "Vendor", "PreReq", "Copyright"):

+             if not self.spec.find_re(r"^\s*" + tag + r"\s*:"):

                  continue

-             value = self.spec.expand_tag(tag).decode('utf-8')

+             value = self.spec.expand_tag(tag).decode("utf-8")

              if value:

                  passed = False

-                 output += 'Found : {}: {}\n'.format(tag, value)

+                 output += "Found : {}: {}\n".format(tag, value)

          if not passed:

              self.set_passed(passed, output)

          else:
@@ -305,171 +316,192 @@ 

  

  

  class CheckLatestVersionIsPackaged(GenericShouldCheckBase):

-     ''' We package latest version, don't we? '''

+     """ We package latest version, don't we? """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/'

-         self.text = 'Latest version is packaged.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/"

+         self.text = "Latest version is packaged."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckLicenseUpstream(GenericShouldCheckBase):

-     '''

+     """

      If the source package does not include license text(s)

      as a separate file from upstream, the packager SHOULD query upstream

      to include it.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/LicensingGuidelines/#_license_text'

-         self.text = 'Package does not include license text files' \

-                     ' separate from upstream.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/LicensingGuidelines/#_license_text"

+         )

+         self.text = (

+             "Package does not include license text files" " separate from upstream."

+         )

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckManPages(GenericShouldCheckBase):

-     '''

+     """

      your package should contain man pages for binaries or

      scripts.  If it doesn't, work with upstream to add them where they

      make sense.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_manpages'

-         self.text = 'Man pages included for all executables.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_manpages"

+         )

+         self.text = "Man pages included for all executables."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def is_applicable(self):

-         return self.rpms.find('[/usr]/[s]bin/*')

+         return self.rpms.find("[/usr]/[s]bin/*")

  

  

  class CheckParallelMake(GenericShouldCheckBase):

-     ''' Thou shall use parallell make. '''

+     """ Thou shall use parallell make. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_parallel_make'

-         self.text = 'Uses parallel make %{?_smp_mflags} macro.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_parallel_make"

+         )

+         self.text = "Uses parallel make %{?_smp_mflags} macro."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          rc = self.NA

-         build_sec = self.spec.get_section('build')

+         build_sec = self.spec.get_section("build")

          if build_sec:

-             smp_mflags = rpm.expandMacro('%{?_smp_mflags}')

+             smp_mflags = rpm.expandMacro("%{?_smp_mflags}")

              for line in build_sec:

-                 if line.startswith('make'):

+                 if line.startswith("make"):

                      ok = smp_mflags in line

                      rc = self.PASS if ok else self.FAIL

          self.set_passed(rc)

  

  

  class CheckPatchComments(GenericShouldCheckBase):

-     ''' Patches should have comments. '''

+     """ Patches should have comments. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_patch_guidelines'

-         self.text = 'Patches link to upstream bugs/comments/lists' \

-                     ' or are otherwise justified.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_patch_guidelines"

+         )

+         self.text = (

+             "Patches link to upstream bugs/comments/lists"

+             " or are otherwise justified."

+         )

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def is_applicable(self):

          return len(self.spec.patches_by_tag) > 0

  

  

  class CheckPkgConfigFiles(GenericShouldCheckBase):

-     '''

+     """

      The placement of pkgconfig(.pc) files depends on their

      usecase, and this is usually for development purposes, so should

      be placed in a -devel pkg.  A reasonable exception is that the

      main pkg itself is a devel tool not installed in a user runtime,

      e.g. gcc or gdb.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_pkgconfig_files_foo_pc'

-         self.text = 'The placement of pkgconfig(.pc) files are correct.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_pkgconfig_files_foo_pc"

+         )

+         self.text = "The placement of pkgconfig(.pc) files are correct."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          files_by_pkg = {}

          for pkg in self.spec.packages:

-             file_list = self.rpms.find_all('*.pc', pkg)

+             file_list = self.rpms.find_all("*.pc", pkg)

              if file_list:

                  files_by_pkg[pkg] = file_list

          if files_by_pkg == {}:

              self.set_passed(self.NA)

              return

-         passed = 'pass'

-         extra = ''

+         passed = "pass"

+         extra = ""

          for pkg in files_by_pkg.keys():

              for fn in files_by_pkg[pkg]:

-                 if '-devel' not in pkg:

-                     passed = 'pending'

-                     extra += '{} : {}\n'.format(pkg, fn)

+                 if "-devel" not in pkg:

+                     passed = "pending"

+                     extra += "{} : {}\n".format(pkg, fn)

          self.set_passed(passed, extra)

  

  

  class CheckRubyPlugin(GenericShouldCheckBase):

-     '''

+     """

      EXTRA: If this is ruby code, the ruby plugin should be installed

      This test is overridden (i. e., disabled) by the plugin if installed.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://pagure.io/FedoraReview'

-         self.text = 'When checking ruby code, install the ruby plugin.'

+         self.url = "https://pagure.io/FedoraReview"

+         self.text = "When checking ruby code, install the ruby plugin."

          self.automatic = True

-         self.type = 'EXTRA'

+         self.type = "EXTRA"

  

      def run(self):

          self.set_passed(self.NA)

-         if self.spec.name.startswith('ruby-'):

+         if self.spec.name.startswith("ruby-"):

              self.set_passed(self.FAIL)

-         if self.spec.name.startswith('rubygem-'):

+         if self.spec.name.startswith("rubygem-"):

              self.set_passed(self.FAIL)

  

  

  class CheckScriptletSanity(GenericShouldCheckBase):

-     '''

+     """

      SHOULD: If scriptlets are used, those scriptlets must be sane.

      This is vague, and left up to the reviewers judgement to determine

      sanity.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_scriptlets'

-         self.text = 'Scriptlets must be sane, if used.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_scriptlets"

+         )

+         self.text = "Scriptlets must be sane, if used."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def is_applicable(self):

-         regex = re.compile(r'%(post|postun|posttrans|preun|pretrans|pre)\s+')

+         regex = re.compile(r"%(post|postun|posttrans|preun|pretrans|pre)\s+")

          return self.spec.find_re(regex)

  

  

  class CheckSourceComment(GenericShouldCheckBase):

-     ''' Source tarballs shoud have comment on how to generate it. '''

+     """ Source tarballs shoud have comment on how to generate it. """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/SourceURL/'

-         self.text = 'SourceX tarball generation or download is documented.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines/SourceURL/"

+         )

+         self.text = "SourceX tarball generation or download is documented."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          passed = True
@@ -482,29 +514,31 @@ 

              self.set_passed(self.NA)

          else:

              self.set_passed(

-                 self.PENDING,

-                 'Package contains tarball without URL, check comments')

+                 self.PENDING, "Package contains tarball without URL, check comments"

+             )

  

  

  class CheckSourceUrl(GenericShouldCheckBase):

-     ''' SourceX is a working URL. '''

+     """ SourceX is a working URL. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/SourceURL/'

-         self.text = 'SourceX is a working URL.'

-         self.type = 'SHOULD'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines/SourceURL/"

+         )

+         self.text = "SourceX is a working URL."

+         self.type = "SHOULD"

          self.automatic = True

  

      def run(self):

-         output = ''

+         output = ""

          passed = True

          for source_tag in self.sources.get_all():

              source = self.sources.get(source_tag)

-             if not source.url.startswith('file:'):

+             if not source.url.startswith("file:"):

                  if not source.downloaded:

                      passed = False

-                     output += '%s\n' % source.url

+                     output += "%s\n" % source.url

  

          if passed:

              self.set_passed(self.PASS)
@@ -513,36 +547,34 @@ 

  

  

  class CheckSpecAsInSRPM(GenericShouldCheckBase):

-     '''

+     """

      Not in guidelines, buth the spec in the spec URL should

      be the same as the one in the srpm.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.text = 'Spec file according to URL is the same as in SRPM.'

+         self.text = "Spec file according to URL is the same as in SRPM."

          self.automatic = True

-         self.type = 'EXTRA'

+         self.type = "EXTRA"

  

      def run(self):

          self.srpm.unpack()

-         pattern = os.path.join(ReviewDirs.srpm_unpacked, '*.spec')

+         pattern = os.path.join(ReviewDirs.srpm_unpacked, "*.spec")

          spec_files = glob(pattern)

          if len(spec_files) != 1:

-             self.set_passed(self.FAIL,

-                             '0 or more than one spec file in srpm(!)')

+             self.set_passed(self.FAIL, "0 or more than one spec file in srpm(!)")

              return

          srpm_spec_file = spec_files[0]

-         pkg_name = \

-              os.path.basename(self.srpm.filename).rsplit('-', 2)[0]

-         if os.path.basename(srpm_spec_file) != pkg_name + '.spec':

-             self.set_passed(self.FAIL,

-                             "Bad spec filename: " + srpm_spec_file)

+         pkg_name = os.path.basename(self.srpm.filename).rsplit("-", 2)[0]

+         if os.path.basename(srpm_spec_file) != pkg_name + ".spec":

+             self.set_passed(self.FAIL, "Bad spec filename: " + srpm_spec_file)

              return

          if Settings.rpm_spec:

              self.set_passed(self.NA)

              return

          url_spec_file = self.spec.filename

-         cmd = ["diff", '-U2', url_spec_file, srpm_spec_file]

+         cmd = ["diff", "-U2", url_spec_file, srpm_spec_file]

          try:

              p = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)

              output = p.communicate()[0]
@@ -551,10 +583,11 @@ 

              self.set_passed(self.FAIL, "OS error runnning diff")

              return

          if output:

-             a = self.Attachment("Diff spec file in url and in SRPM",

-                                 output)

-             text = ('Spec file as given by url is not the same as in '

-                     'SRPM (see attached diff).')

+             a = self.Attachment("Diff spec file in url and in SRPM", output)

+             text = (

+                 "Spec file as given by url is not the same as in "

+                 "SRPM (see attached diff)."

+             )

              self.set_passed(self.FAIL, text, [a])

          else:

              self.set_passed(self.PASS)
@@ -562,42 +595,52 @@ 

  

  

  class CheckSpecDescTranslation(GenericShouldCheckBase):

-     '''

+     """

      The description and summary sections in the package spec file

      should contain translations for supported Non-English languages,

      if available.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_summary_and_description'

-         self.text = 'Description and summary sections in the' \

-                     ' package spec file contains translations' \

-                     ' for supported Non-English languages, if available.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_summary_and_description"

+         )

+         self.text = (

+             "Description and summary sections in the"

+             " package spec file contains translations"

+             " for supported Non-English languages, if available."

+         )

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckSupportAllArchs(GenericShouldCheckBase):

-     '''

+     """

      The package should compile and build into binary rpms on

      all supported architectures.

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_architecture_support'

-         self.text = 'Package should compile and build into binary' \

-                     ' rpms on all supported architectures.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_architecture_support"

+         )

+         self.text = (

+             "Package should compile and build into binary"

+             " rpms on all supported architectures."

+         )

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         build_ok = self.checks.checkdict['CheckBuild'].is_passed

+         build_ok = self.checks.checkdict["CheckBuild"].is_passed

  

-         arch = self.spec.expand_tag('BuildArch')

-         noarch = arch and arch[0].lower() == b'noarch'

-         one_arch = self.spec.expand_tag('ExclusiveArch')

+         arch = self.spec.expand_tag("BuildArch")

+         noarch = arch and arch[0].lower() == b"noarch"

+         one_arch = self.spec.expand_tag("ExclusiveArch")

          if build_ok and (one_arch or noarch):

              self.set_passed(self.PASS)

          else:
@@ -605,68 +648,76 @@ 

  

  

  class CheckTestSuites(GenericShouldCheckBase):

-     '''

+     """

      https://docs.fedoraproject.org/en-US/packaging-guidelines/#_test_suites

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_test_suites'

-         self.text = '%check is present and all tests pass.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_test_suites"

+         )

+         self.text = "%check is present and all tests pass."

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckTimeStamps(GenericShouldCheckBase):

-     ''' Preserve timestamps if possible. '''

+     """ Preserve timestamps if possible. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_timestamps'

-         self.text = 'Packages should try to preserve timestamps of' \

-                     ' original installed files.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/#_timestamps"

+         )

+         self.text = (

+             "Packages should try to preserve timestamps of" " original installed files."

+         )

          self.automatic = False

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

  

  class CheckUseGlobal(GenericShouldCheckBase):

-     ''' Thou shall not use %define. '''

+     """ Thou shall not use %define. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_global_preferred_over_define'

-         self.text = 'Spec use %global instead of %define unless' \

-                     ' justified.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_global_preferred_over_define"

+         )

+         self.text = "Spec use %global instead of %define unless" " justified."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         regex = re.compile(r'(\%define.*)')

+         regex = re.compile(r"(\%define.*)")

          result = self.spec.find_all_re(regex, skip_changelog=True)

          if result:

-             extra = '%define requiring justification: ' +  \

-                     ', '.join(result)

+             extra = "%define requiring justification: " + ", ".join(result)

              self.set_passed(self.PENDING, extra)

          else:

              self.set_passed(self.PASS)

  

  

  class CheckTmpfiles(GenericShouldCheckBase):

-     '''

+     """

      Check for files in /run, /var/run etc, candidates for tmpfiles.d

-     '''

+     """

+ 

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/Tmpfiles.d/'

-         self.text = 'Files in /run, var/run and /var/lock uses tmpfiles.d' \

-                     ' when appropriate'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US/packaging-guidelines/Tmpfiles.d/"

+         )

+         self.text = (

+             "Files in /run, var/run and /var/lock uses tmpfiles.d" " when appropriate"

+         )

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         for p in ['/run/*', '/var/run/*', '/var/lock/*', '/run/lock/*']:

+         for p in ["/run/*", "/var/run/*", "/var/lock/*", "/run/lock/*"]:

              if self.rpms.find(p):

                  self.set_passed(self.PENDING)

                  break
@@ -675,39 +726,41 @@ 

  

  

  class CheckBundledFonts(GenericShouldCheckBase):

-     ''' Check for bundled font files '''

+     """ Check for bundled font files """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_avoid_bundling_of_fonts_in_other_packages'

-         self.text = 'Avoid bundling fonts in non-fonts packages. '

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_avoid_bundling_of_fonts_in_other_packages"

+         )

+         self.text = "Avoid bundling fonts in non-fonts packages. "

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

-         if self.spec.name.endswith('-fonts'):

+         if self.spec.name.endswith("-fonts"):

              self.set_passed(self.NA)

              return

-         for p in ['*.pfb', '*.pfa', '*.afm', '*.ttf', '*.otf']:

+         for p in ["*.pfb", "*.pfa", "*.afm", "*.ttf", "*.otf"]:

              if self.rpms.find(p):

-                 self.set_passed(self.PENDING,

-                                 'Package contains font files')

+                 self.set_passed(self.PENDING, "Package contains font files")

                  break

          else:

              self.set_passed(self.NA)

  

  

  class CheckSourceDownloads(GenericShouldCheckBase):

-     ''' Check that sources could be downloaded from their URI. '''

+     """ Check that sources could be downloaded from their URI. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/SourceURL/'

-         self.text = 'Sources can be downloaded from URI in Source: tag'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US" "/packaging-guidelines/SourceURL/"

+         )

+         self.text = "Sources can be downloaded from URI in Source: tag"

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          sources = [self.sources.get(s) for s in self.sources.get_all()]
@@ -719,52 +772,58 @@ 

          if not failed_src:

              self.set_passed(self.PASS)

              return

-         failed = ', '.join([s.tag  + ': ' + s.specurl for s in failed_src])

+         failed = ", ".join([s.tag + ": " + s.specurl for s in failed_src])

          self.set_passed(self.FAIL, "Could not download " + failed)

  

  

  class CheckUpdateMimeDatabase(GenericShouldCheckBase):

-     ''' Check that update-mime-database is run if required. '''

+     """ Check that update-mime-database is run if required. """

  

      def __init__(self, base):

          GenericShouldCheckBase.__init__(self, base)

-         self.url = 'https://fedoraproject.org/wiki/EPEL' \

-                    ':Packaging#mimeinfo'

-         self.text = 'update-mime-database is invoked in %posttrans and' \

-                     ' %postun if package stores mime configuration' \

-                     ' in /usr/share/mime/packages.'

+         self.url = "https://fedoraproject.org/wiki/EPEL" ":Packaging#mimeinfo"

+         self.text = (

+             "update-mime-database is invoked in %posttrans and"

+             " %postun if package stores mime configuration"

+             " in /usr/share/mime/packages."

+         )

  

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run(self):

          using = []

          failed = False

          for pkg in self.spec.packages:

-             if self.rpms.find('/usr/share/mime/packages/*', pkg):

+             if self.rpms.find("/usr/share/mime/packages/*", pkg):

                  using.append(pkg)

                  rpm_pkg = self.rpms.get(pkg)

-                 if self.flags['EPEL6'] \

-                     or self.flags['EPEL7']:

-                     if not in_list('update-mime-database',

-                                    [rpm_pkg.postun, rpm_pkg.posttrans]):

+                 if self.flags["EPEL6"] or self.flags["EPEL7"]:

+                     if not in_list(

+                         "update-mime-database", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

                  else:

-                     if in_list('update-mime-database',

-                                [rpm_pkg.postun, rpm_pkg.posttrans]):

+                     if in_list(

+                         "update-mime-database", [rpm_pkg.postun, rpm_pkg.posttrans]

+                     ):

                          failed = True

  

          if not using:

              self.set_passed(self.NA)

              return

-         text = 'mimeinfo file(s) in ' + ', '.join(using)

-         if self.flags['EPEL6'] or self.flags['EPEL7']:

+         text = "mimeinfo file(s) in " + ", ".join(using)

+         if self.flags["EPEL6"] or self.flags["EPEL7"]:

              self.set_passed(self.FAIL if failed else self.PENDING, text)

          else:

-             self.url = 'https://fedoraproject.org/w/index.php?title=' \

-                        'Packaging:Scriptlets&oldid=494555#mimeinfo'

-             self.text = 'update-mime-database must not be run in %postun and' \

-                         ' %posttrans for Fedora 24 and later.'

+             self.url = (

+                 "https://fedoraproject.org/w/index.php?title="

+                 "Packaging:Scriptlets&oldid=494555#mimeinfo"

+             )

+             self.text = (

+                 "update-mime-database must not be run in %postun and"

+                 " %posttrans for Fedora 24 and later."

+             )

  

              self.set_passed(self.FAIL if failed else self.NA, text)

  

file modified
+12 -9
@@ -1,16 +1,16 @@ 

  # -*- coding: utf-8 -*-

  

- '''

+ """

  Haskell specifics checks, https://docs.fedoraproject.org/en-US/packaging-guidelines/Haskell/

- '''

+ """

  

  from FedoraReview import CheckBase, RegistryBase

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'Haskell' '''

+     """ Register all checks in this file in group 'Haskell' """

  

-     group = 'Haskell'

+     group = "Haskell"

  

      def is_applicable(self):

          """ Check if the tests are applicable, here it checks whether
@@ -18,24 +18,27 @@ 

          """

          if self.is_user_enabled():

              return self.user_enabled_value()

-         return self.checks.spec.name.startswith("ghc-") or \

-             bool(self.checks.spec.find_re('%cabal'))

+         return self.checks.spec.name.startswith("ghc-") or bool(

+             self.checks.spec.find_re("%cabal")

+         )

  

  

  class HaskellCheckBase(CheckBase):

      """ Base class for all Haskell specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  

  

  class HaskellCheckStaticLibs(HaskellCheckBase):

-     ''' Disable static lib checking, haskell has an exception. '''

+     """ Disable static lib checking, haskell has an exception. """

+ 

      # TBD: checks that libraries provides themselves as -devel.

  

      def __init__(self, checks):

          HaskellCheckBase.__init__(self, checks)

-         self.text = 'This should never happen'

-         self.deprecates.append('CheckStaticLibs')

+         self.text = "This should never happen"

+         self.deprecates.append("CheckStaticLibs")

          self.automatic = True

  

      def run_on_applicable(self):

file modified
+19 -10
@@ -5,31 +5,39 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'Java'. '''

+     """ Register all checks in this file in group 'Java'. """

  

-     group = 'Java'

+     group = "Java"

  

      def is_applicable(self):

-         ''' Return True if this is a java package. '''

+         """ Return True if this is a java package. """

          if self.is_user_enabled():

              return self.user_enabled_value()

          rpms = self.checks.rpms

-         return (rpms.find("*.pom") or rpms.find("pom.xml") or

-                 rpms.find("*.class") or rpms.find("*.jar") or

-                 rpms.find("*.ear") or rpms.find("*.war"))

+         return (

+             rpms.find("*.pom")

+             or rpms.find("pom.xml")

+             or rpms.find("*.class")

+             or rpms.find("*.jar")

+             or rpms.find("*.ear")

+             or rpms.find("*.war")

+         )

  

  

  class CheckJavaPlugin(CheckBase):

      """

      Check to warn when external plugin for reviewing Java is not installed

      """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

-         self.url = 'https://fedoraproject.org/wiki/Packaging:Java'

-         self.text = "This seems like a Java package, please install " \

-                     "fedora-review-plugin-java to get additional checks"

+         self.url = "https://fedoraproject.org/wiki/Packaging:Java"

+         self.text = (

+             "This seems like a Java package, please install "

+             "fedora-review-plugin-java to get additional checks"

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          """ Use the is_applicable() defined in main group: """
@@ -38,4 +46,5 @@ 

          else:

              self.set_passed(self.FAIL)

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+8 -7
@@ -1,16 +1,16 @@ 

  # -*- coding: utf-8 -*-

  

- '''

+ """

  Ocaml specifics checks, https://docs.fedoraproject.org/en-US/packaging-guidelines/OCaml/

- '''

+ """

  

  from FedoraReview import CheckBase, RegistryBase

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'ocaml' '''

+     """ Register all checks in this file in group 'ocaml' """

  

-     group = 'Ocaml'

+     group = "Ocaml"

  

      def is_applicable(self):

          """ Check if the tests are applicable, here it checks whether
@@ -24,18 +24,19 @@ 

  

  class OcamlCheckBase(CheckBase):

      """ Base class for all Ocaml specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  

  

  class OcamlCheckStaticLibs(OcamlCheckBase):

-     ''' Disable static lib checking, ocaml has an exception. '''

+     """ Disable static lib checking, ocaml has an exception. """

  

      def __init__(self, checks):

          OcamlCheckBase.__init__(self, checks)

          self.automatic = True

-         self.text = 'This should never happen'

-         self.deprecates.append('CheckStaticLibs')

+         self.text = "This should never happen"

+         self.deprecates.append("CheckStaticLibs")

  

      def run_on_applicable(self):

          self.set_passed(self.PASS)

file modified
+18 -16
@@ -1,5 +1,5 @@ 

  # -*- coding: utf-8 -*-

- ''' Checks for perl packages. '''

+ """ Checks for perl packages. """

  

  import rpm

  
@@ -7,15 +7,18 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'Perl'. '''

+     """ Register all checks in this file in group 'Perl'. """

  

-     group = 'Perl'

+     group = "Perl"

  

      def is_applicable(self):

          if self.is_user_enabled():

              return self.user_enabled_value()

-         return self.checks.spec.name.startswith("perl-") or \

-             self.checks.rpms.find('*.pm') or self.checks.rpms.find('*.pl')

+         return (

+             self.checks.spec.name.startswith("perl-")

+             or self.checks.rpms.find("*.pm")

+             or self.checks.rpms.find("*.pl")

+         )

  

  

  class PerlCheckBase(CheckBase):
@@ -30,9 +33,8 @@ 

  

      def __init__(self, checks):

          PerlCheckBase.__init__(self, checks)

-         self.url = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/Perl/'

-         self.text = 'Package contains the mandatory BuildRequires' \

-                     ' and Requires:.'

+         self.url = "https://docs.fedoraproject.org/en-US/packaging-guidelines/Perl/"

+         self.text = "Package contains the mandatory BuildRequires" " and Requires:."

          self.automatic = True

  

      def run_on_applicable(self):
@@ -41,20 +43,20 @@ 

          Requires: perl_compat thin.

          """

  

-         perl_compat = 'perl(:MODULE_COMPAT_%(eval "`%{__perl}' \

-                       ' -V:version`"; echo $version))'

+         perl_compat = (

+             'perl(:MODULE_COMPAT_%(eval "`%{__perl}' ' -V:version`"; echo $version))'

+         )

          for br in self.spec.build_requires:

-             if br.startswith('perl-devel'):

-                 self.set_passed(self.FAIL,

-                                 'Explicit dependency on perl-devel'

-                                 ' is not allowed')

+             if br.startswith("perl-devel"):

+                 self.set_passed(

+                     self.FAIL, "Explicit dependency on perl-devel" " is not allowed"

+                 )

                  return

          compat = rpm.expandMacro(perl_compat)

          for r in self.spec.get_requires():

              if r == compat:

                  break

          else:

-             self.set_passed(self.PENDING,

-                             'Requires: ' + perl_compat + ' missing?')

+             self.set_passed(self.PENDING, "Requires: " + perl_compat + " missing?")

              return

          self.set_passed(self.PENDING)

file modified
+4 -3
@@ -1,14 +1,14 @@ 

  # -*- coding: utf-8 -*-

  

- ''' PHP specifics checks, https://docs.fedoraproject.org/en-US/packaging-guidelines/PHP/ '''

+ """ PHP specifics checks, https://docs.fedoraproject.org/en-US/packaging-guidelines/PHP/ """

  

  from FedoraReview import CheckBase, RegistryBase

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'PHP' '''

+     """ Register all checks in this file in group 'PHP' """

  

-     group = 'PHP'

+     group = "PHP"

  

      def is_applicable(self):

          """ Check is the tests are applicable, here it checks whether
@@ -21,5 +21,6 @@ 

  

  class PhpCheckBase(CheckBase):

      """ Base class for all PHP specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

file modified
+54 -36
@@ -1,5 +1,5 @@ 

  # -*- coding: utf-8 -*-

- ''' Python package tests '''

+ """ Python package tests """

  

  import re

  import rpm
@@ -8,16 +8,17 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'Python' '''

+     """ Register all checks in this file in group 'Python' """

  

-     group = 'Python'

+     group = "Python"

  

      def is_applicable(self):

-         ''' Return true if this is a python package. '''

+         """ Return true if this is a python package. """

          if self.is_user_enabled():

              return self.user_enabled_value()

-         return self.checks.spec.name.startswith("python") or \

-            self.checks.rpms.find('*.pyc')

+         return self.checks.spec.name.startswith("python") or self.checks.rpms.find(

+             "*.pyc"

+         )

  

  

  class PythonCheckBase(CheckBase):
@@ -32,46 +33,52 @@ 

  

      def __init__(self, checks):

          PythonCheckBase.__init__(self, checks)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Python/#_dependencies'

-         self.text = 'Package contains BR: python2-devel or python3-devel'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Python/#_dependencies"

+         )

+         self.text = "Package contains BR: python2-devel or python3-devel"

          self.automatic = True

  

      def run_on_applicable(self):

          br = self.spec.build_requires

-         passed = 'python2-devel' in br or 'python3-devel' in br

+         passed = "python2-devel" in br or "python3-devel" in br

          self.set_passed(self.PASS if passed else self.FAIL)

  

  

  class CheckPythonRequires(PythonCheckBase):

      """ Check that there is no unversioned Python dependencies """

+ 

      def __init__(self, base):

          PythonCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/Python/#_dependencies'

-         self.text = 'Packages MUST NOT have dependencies (either build-time ' \

-             'or runtime) on packages named with the unversioned python- ' \

-             'prefix unless no properly versioned package exists. ' \

-             'Dependencies on Python packages instead MUST use names ' \

-             'beginning with python2- or python3- as appropriate.'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/Python/#_dependencies"

+         )

+         self.text = (

+             "Packages MUST NOT have dependencies (either build-time "

+             "or runtime) on packages named with the unversioned python- "

+             "prefix unless no properly versioned package exists. "

+             "Dependencies on Python packages instead MUST use names "

+             "beginning with python2- or python3- as appropriate."

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          """ Run the check """

-         regex = re.compile('(^python-)|(-python$)|(-python-)', re.M)

+         regex = re.compile("(^python-)|(-python$)|(-python-)", re.M)

          br = self.spec.build_requires

          rr = self.spec.get_requires()

  

-         if regex.search('\n'.join(br)) or regex.search('\n'.join(rr)):

-             self.set_passed(self.FAIL, 'Unversionned Python dependency '

-                                        'found.')

+         if regex.search("\n".join(br)) or regex.search("\n".join(rr)):

+             self.set_passed(self.FAIL, "Unversionned Python dependency " "found.")

              return

          self.set_passed(self.PASS)

  

  

  class CheckPythonX_Site(PythonCheckBase):

-     '''

+     """

      MUST: One must not use any of the following in the %files section:

  

      %{python3_sitelib}/*
@@ -83,30 +90,41 @@ 

      

      https://pagure.io/packaging-committee/issue/782

  

-     '''

+     """

+ 

      def __init__(self, base):

          PythonCheckBase.__init__(self, base)

-         self.url = 'https://pagure.io/packaging-committee/issue/782'

-         self.text = 'Python packages must not contain %{pythonX_site(lib|arch)}/* in %files'

+         self.url = "https://pagure.io/packaging-committee/issue/782"

+         self.text = (

+             "Python packages must not contain %{pythonX_site(lib|arch)}/* in %files"

+         )

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          has_python_site = False

-         python_sitelib = re.compile(rpm.expandMacro(r'^%{python_sitelib}\/\*$') + '|' + \

-             rpm.expandMacro(r'^%{python_sitearch}\/\*$') + '|' + \

-             rpm.expandMacro(r'^%{python2_sitelib}\/\*$') + '|' + \

-             rpm.expandMacro(r'^%{python2_sitearch}\/\*$') + '|' + \

-             rpm.expandMacro(r'^%{python3_sitelib}\/\*$')  + '|' + \

-             rpm.expandMacro(r'^%{python3_sitearch}\/\*$'))

-         

+         python_sitelib = re.compile(

+             rpm.expandMacro(r"^%{python_sitelib}\/\*$")

+             + "|"

+             + rpm.expandMacro(r"^%{python_sitearch}\/\*$")

+             + "|"

+             + rpm.expandMacro(r"^%{python2_sitelib}\/\*$")

+             + "|"

+             + rpm.expandMacro(r"^%{python2_sitearch}\/\*$")

+             + "|"

+             + rpm.expandMacro(r"^%{python3_sitelib}\/\*$")

+             + "|"

+             + rpm.expandMacro(r"^%{python3_sitearch}\/\*$")

+         )

+ 

          for pkg in self.spec.packages:

              for line in self.spec.get_files(pkg):

                  if python_sitelib.match(line):

                      has_python_site = True

                      break

          if has_python_site:

-             self.set_passed(self.FAIL, 'Package contains %{pythonX_site(lib|arch)}/* in %files')

+             self.set_passed(

+                 self.FAIL, "Package contains %{pythonX_site(lib|arch)}/* in %files"

+             )

          else:

              self.set_passed(self.PASS)

- 

file modified
+157 -122
@@ -1,30 +1,30 @@ 

  # -*- coding: utf-8 -*-

- ''' Checks for ruby and rubygem packages.'''

+ """ Checks for ruby and rubygem packages."""

  

  import re

  import rpm

  

  from FedoraReview import CheckBase, Mock, RegistryBase

  

- _GUIDELINES_URI = 'https://docs.fedoraproject.org/en-US/packaging-guidelines/Ruby/'

- _GUIDELINES_SECTION_URI = '%(uri)s#%%(section)s' % {'uri': _GUIDELINES_URI}

+ _GUIDELINES_URI = "https://docs.fedoraproject.org/en-US/packaging-guidelines/Ruby/"

+ _GUIDELINES_SECTION_URI = "%(uri)s#%%(section)s" % {"uri": _GUIDELINES_URI}

  

  

  def _is_nongem(spec):

      """ Return true for pure ruby packages"""

-     return spec.name.startswith('ruby-')

+     return spec.name.startswith("ruby-")

  

  

  def _is_gem(spec):

      """ Return true for rubygem packages"""

-     return spec.name.startswith('rubygem-')

+     return spec.name.startswith("rubygem-")

  

  

  def _has_extension(check):

      """ Return True if the package contains native extension """

      # pylint: disable=W0511

      # TODO: will need altering for jruby .jar files

-     return check.rpms.find_re(r'.*\.c(?:pp)')

+     return check.rpms.find_re(r".*\.c(?:pp)")

  

  

  def _gl_uri():
@@ -38,9 +38,9 @@ 

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group 'Ruby' '''

+     """ Register all checks in this file in group 'Ruby' """

  

-     group = 'Ruby'

+     group = "Ruby"

  

      def is_applicable(self):

          """ Check if the tests are applicable, here it checks whether
@@ -53,12 +53,14 @@ 

  

  class RubyCheckBase(CheckBase):

      """ Base class for all general Ruby checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  

  

  class GemCheckBase(CheckBase):

      """ Base class for all Gem specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  
@@ -69,6 +71,7 @@ 

  

  class NonGemCheckBase(CheckBase):

      """ Base class for all non-Gem specific checks. """

+ 

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  
@@ -78,13 +81,14 @@ 

  

  

  class DisableCheckRubyPlugin(RubyCheckBase):

-     ''' Disabke the plugin check code in generic_should.  '''

+     """ Disabke the plugin check code in generic_should.  """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = 'https:not-used'

-         self.text = 'not-used'

+         self.url = "https:not-used"

+         self.text = "not-used"

          self.automatic = True

-         self.type = 'EXTRA'

+         self.type = "EXTRA"

          self.deprecates = ["CheckRubyPlugin"]

  

      def run(self):
@@ -93,68 +97,75 @@ 

  

  class RubyCheckNotRequiresRubyAbi(RubyCheckBase):

      """ Check if package doesn't require ruby(abi) """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Ruby_Compatibility'})

-         self.text = 'Package does not contain Requires: ruby(abi).'

+         self.url = _gl_fmt_uri({"section": "Ruby_Compatibility"})

+         self.text = "Package does not contain Requires: ruby(abi)."

          self.automatic = True

  

      def run_on_applicable(self):

          br = self.spec.get_requires()

-         self.set_passed('ruby(abi)' not in br)

+         self.set_passed("ruby(abi)" not in br)

  

  

  class RubyCheckRequiresRubyRelease(RubyCheckBase):

      """ Check if package requires ruby(release) """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Ruby_Compatibility'})

-         self.text = 'Package contains Requires: ruby(release).'

+         self.url = _gl_fmt_uri({"section": "Ruby_Compatibility"})

+         self.text = "Package contains Requires: ruby(release)."

          self.automatic = True

  

      def run_on_applicable(self):

          br = self.spec.get_requires()

-         self.set_passed('ruby(release)' in br)

+         self.set_passed("ruby(release)" in br)

  

  

  class RubyCheckBuildArchitecture(RubyCheckBase):

      """ Check if package is noarch """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = 'https://docs.fedoraproject.org/en-US' \

-                    '/packaging-guidelines/#_architecture_support'

-         self.text = 'Pure Ruby package must be built as noarch'

+         self.url = (

+             "https://docs.fedoraproject.org/en-US"

+             "/packaging-guidelines/#_architecture_support"

+         )

+         self.text = "Pure Ruby package must be built as noarch"

          self.automatic = True

  

      def run_on_applicable(self):

-         arch = self.spec.expand_tag('arch').decode('utf-8')

+         arch = self.spec.expand_tag("arch").decode("utf-8")

          if _has_extension(self):

-             self.set_passed('noarch' not in arch,

-                             "Package with binary extension can't be built"

-                             " as noarch.")

+             self.set_passed(

+                 "noarch" not in arch,

+                 "Package with binary extension can't be built" " as noarch.",

+             )

          else:

-             self.set_passed('noarch' in arch)

+             self.set_passed("noarch" in arch)

  

  

  class RubyCheckPlatformSpecificFilePlacement(RubyCheckBase):

      """ Check if architecture specific files are placed in correct directories

      """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section':

-                                 'Ruby_packages_with_binary_content.'

-                                 '2Fshared_libraries'})

-         self.text = 'Platform specific files must be located under ' \

-                     '/usr/lib[64]'

+         self.url = _gl_fmt_uri(

+             {"section": "Ruby_packages_with_binary_content." "2Fshared_libraries"}

+         )

+         self.text = "Platform specific files must be located under " "/usr/lib[64]"

          self.automatic = True

  

      def is_applicable(self):

-         return super(RubyCheckPlatformSpecificFilePlacement,

-                      self).is_applicable() and _has_extension(self)

+         return super(

+             RubyCheckPlatformSpecificFilePlacement, self

+         ).is_applicable() and _has_extension(self)

  

      def run_on_applicable(self):

-         usr_lib_re = re.compile(r'/usr/lib')

-         so_file_re = re.compile(r'\.so$')

+         usr_lib_re = re.compile(r"/usr/lib")

+         so_file_re = re.compile(r"\.so$")

          rc = self.PASS

          for f in self.checks.rpms.filelist:

              if so_file_re.match(f) and not usr_lib_re.match(f):
@@ -165,32 +176,34 @@ 

  

  class RubyCheckTestsRun(RubyCheckBase):

      """ Check if test suite is being run """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Running_test_suites'})

-         self.text = 'Test suite of the library should be run.'

+         self.url = _gl_fmt_uri({"section": "Running_test_suites"})

+         self.text = "Test suite of the library should be run."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

-         check_section = self.spec.get_section('%check')

+         check_section = self.spec.get_section("%check")

          self.set_passed(self.PASS if check_section else self.FAIL)

  

  

  class RubyCheckTestsNotRunByRake(RubyCheckBase):

      """ Check and fail if tests are being run by rake """

+ 

      def __init__(self, base):

          RubyCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Running_test_suites'})

-         self.text = 'Test suite should not be run by rake.'

+         self.url = _gl_fmt_uri({"section": "Running_test_suites"})

+         self.text = "Test suite should not be run by rake."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          rc = self.PASS

-         check_section = self.spec.get_section('%check', raw=True)

+         check_section = self.spec.get_section("%check", raw=True)

          if check_section:

-             if 'rake ' in check_section:

+             if "rake " in check_section:

                  rc = self.FAIL

          else:

              rc = self.NA
@@ -199,17 +212,18 @@ 

  

  class NonGemCheckUsesMacros(NonGemCheckBase):

      """ Check if spec files uses proper macros instead of hardcoding """

+ 

      def __init__(self, base):

          NonGemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Macros'})

-         self.text = 'Specfile should utilize macros from ruby-devel package.'

+         self.url = _gl_fmt_uri({"section": "Macros"})

+         self.text = "Specfile should utilize macros from ruby-devel package."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          ok = False

-         vendorarchdir = rpm.expandMacro('%{vendorarchdir}')

-         vendorlibdir = rpm.expandMacro('%{vendorlibdir}')

+         vendorarchdir = rpm.expandMacro("%{vendorarchdir}")

+         vendorlibdir = rpm.expandMacro("%{vendorlibdir}")

          for pkg in self.spec.packages:

              for line in self.spec.get_files(pkg):

                  if _has_extension(self) and vendorarchdir in line:
@@ -221,107 +235,119 @@ 

  

  class NonGemCheckFilePlacement(NonGemCheckBase):

      """ Check if files are placed in correct directories"""

+ 

      def __init__(self, base):

          NonGemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section':

-                                 'Build_Architecture_and_File_Placement'})

-         self.text = 'Platform dependent files must go under ' \

-             '%{ruby_vendorarchdir}, platform independent under ' \

-             '%{ruby_vendorlibdir}.'

+         self.url = _gl_fmt_uri({"section": "Build_Architecture_and_File_Placement"})

+         self.text = (

+             "Platform dependent files must go under "

+             "%{ruby_vendorarchdir}, platform independent under "

+             "%{ruby_vendorlibdir}."

+         )

          self.automatic = False

  

  

  class GemCheckFilePlacement(GemCheckBase):

      """ Check if gem files are placed in correct directories """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': '.25install'})

-         self.text = 'Platform dependent files must all go under ' \

-             '%{gem_extdir_mri}, platform independent under %{gem_dir}.'

+         self.url = _gl_fmt_uri({"section": ".25install"})

+         self.text = (

+             "Platform dependent files must all go under "

+             "%{gem_extdir_mri}, platform independent under %{gem_dir}."

+         )

          self.automatic = False

  

  

  class GemCheckGemExtdirMacro(GemCheckBase):

      """ Check for deprecated macro %{gem_extdir} """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': '.25install'})

-         self.text = 'Macro %{gem_extdir} is deprecated.'

+         self.url = _gl_fmt_uri({"section": ".25install"})

+         self.text = "Macro %{gem_extdir} is deprecated."

          self.automatic = True

  

      def run_on_applicable(self):

-         gem_extdir_macro = self.spec.find_re(r'\%\{gem_extdir\}')

+         gem_extdir_macro = self.spec.find_re(r"\%\{gem_extdir\}")

          self.set_passed(self.FAIL if gem_extdir_macro else self.PASS)

  

  

  class GemCheckRequiresProperDevel(GemCheckBase):

      """ Check that gem packages contain proper BuildRequires """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'RubyGems'})

-         self.text = 'Package contains BuildRequires: rubygems-devel.'

+         self.url = _gl_fmt_uri({"section": "RubyGems"})

+         self.text = "Package contains BuildRequires: rubygems-devel."

          self.automatic = True

  

      def run_on_applicable(self):

          """ Run the check """

          br = self.spec.build_requires

-         self.set_passed('rubygems-devel' in br)

+         self.set_passed("rubygems-devel" in br)

          if _has_extension(self):

-             self.set_passed('ruby-devel' in br,

-                             'The Gem package must have BuildRequires: '

-                             'ruby-devel if the Gem contains binary extension.')

+             self.set_passed(

+                 "ruby-devel" in br,

+                 "The Gem package must have BuildRequires: "

+                 "ruby-devel if the Gem contains binary extension.",

+             )

  

  

  class NonGemCheckRequiresProperDevel(NonGemCheckBase):

      """ Check that non-gem packages contain proper BuildRequires """

+ 

      def __init__(self, base):

          NonGemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Non-Gem_Packages'})

-         self.text = 'Package contains BuildRequires: ruby-devel.'

+         self.url = _gl_fmt_uri({"section": "Non-Gem_Packages"})

+         self.text = "Package contains BuildRequires: ruby-devel."

          self.automatic = True

  

      def run_on_applicable(self):

-         self.set_passed('ruby-devel' in self.spec.build_requires)

+         self.set_passed("ruby-devel" in self.spec.build_requires)

  

  

  class GemCheckSetsGemName(GemCheckBase):

      """ Check for proper gem_name macro """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'RubyGems'})

-         self.text = 'Gem package must define %{gem_name} macro.'

+         self.url = _gl_fmt_uri({"section": "RubyGems"})

+         self.text = "Gem package must define %{gem_name} macro."

          self.automatic = True

  

      def run_on_applicable(self):

-         expanded = rpm.expandMacro('%{gem_name}')

-         self.set_passed(self.FAIL if '%' in expanded else self.PASS)

+         expanded = rpm.expandMacro("%{gem_name}")

+         self.set_passed(self.FAIL if "%" in expanded else self.PASS)

  

  

  class GemCheckProperName(GemCheckBase):

      """ Check for proper naming of package """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Naming_Guidelines'})

-         self.text = 'Gem package is named rubygem-%{gem_name}'

+         self.url = _gl_fmt_uri({"section": "Naming_Guidelines"})

+         self.text = "Gem package is named rubygem-%{gem_name}"

          self.automatic = True

  

      def run_on_applicable(self):

-         name = self.spec.find_re(r'^Name\s*:')

-         self.set_passed('rubygem-%{gem_name}' in name)

+         name = self.spec.find_re(r"^Name\s*:")

+         self.set_passed("rubygem-%{gem_name}" in name)

  

  

  class GemCheckDoesntHaveNonGemSubpackage(GemCheckBase):

      """ Check and fail if gem package contains non-gem subpackage """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section':

-                                 'Packaging_for_Gem_and_non-Gem_use'})

-         self.text = 'Gem package must not define a non-gem subpackage'

+         self.url = _gl_fmt_uri({"section": "Packaging_for_Gem_and_non-Gem_use"})

+         self.text = "Gem package must not define a non-gem subpackage"

          self.automatic = True

  

      def run_on_applicable(self):

          for pkg in self.spec.packages:

-             if '-ruby-' in pkg or pkg.startswith('ruby-'):

+             if "-ruby-" in pkg or pkg.startswith("ruby-"):

                  self.set_passed(self.FAIL)

                  break

          else:
@@ -330,12 +356,13 @@ 

  

  class GemCheckObsoleteRequiresRubygems(GemCheckBase):

      """ gems should not have obsolete Requires: rubygem """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'RubyGems'})

-         self.text = 'gems should not require rubygems package'

+         self.url = _gl_fmt_uri({"section": "RubyGems"})

+         self.text = "gems should not require rubygems package"

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          try:
@@ -346,9 +373,9 @@ 

          if fedora_vers <= 20:

              self.set_passed(self.NA)

              return

-         failed = self.spec.find_re(r'Requires:\s*rubygem\s*$')

+         failed = self.spec.find_re(r"Requires:\s*rubygem\s*$")

          if failed:

-             text = 'Obsolete %s  found in spec' % failed

+             text = "Obsolete %s  found in spec" % failed

              self.set_passed(self.FAIL, text)

          else:

              self.set_passed(self.PASS)
@@ -356,12 +383,13 @@ 

  

  class GemCheckRequiresRubygems(GemCheckBase):

      """ gems should have Requires: rubygem """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'RubyGems'})

-         self.text = 'gems should require rubygems package'

+         self.url = _gl_fmt_uri({"section": "RubyGems"})

+         self.text = "gems should require rubygems package"

          self.automatic = True

-         self.type = 'MUST'

+         self.type = "MUST"

  

      def run_on_applicable(self):

          try:
@@ -374,15 +402,17 @@ 

              return

          failed = []

          for pkg_name in self.spec.packages:

-             for suffix in ['-doc', '-fonts', '-devel']:

+             for suffix in ["-doc", "-fonts", "-devel"]:

                  if pkg_name.endswith(suffix):

                      continue

              rpm_pkg = self.rpms.get(pkg_name)

-             if 'rubygems' not in rpm_pkg.requires and \

-                     'ruby(rubygems)' not in rpm_pkg.requires:

+             if (

+                 "rubygems" not in rpm_pkg.requires

+                 and "ruby(rubygems)" not in rpm_pkg.requires

+             ):

                  failed.append(pkg_name)

          if failed:

-             text = 'Requires: rubygems missing in ' + ', '.join(failed)

+             text = "Requires: rubygems missing in " + ", ".join(failed)

              self.set_passed(self.FAIL, text)

          else:

              self.set_passed(self.PASS)
@@ -390,57 +420,60 @@ 

  

  class GemCheckGemInstallMacro(GemCheckBase):

      """ gems should use %gem_install macro """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Building_gems'})

-         self.text = 'Gem should use %gem_install macro.'

+         self.url = _gl_fmt_uri({"section": "Building_gems"})

+         self.text = "Gem should use %gem_install macro."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

-         gem_install_re = re.compile(r'^.*gem\s+install', re.I)

-         self.set_passed(

-             self.FAIL if self.spec.find_re(gem_install_re) else self.PASS)

+         gem_install_re = re.compile(r"^.*gem\s+install", re.I)

+         self.set_passed(self.FAIL if self.spec.find_re(gem_install_re) else self.PASS)

  

  

  class GemCheckExcludesGemCache(GemCheckBase):

      """ Check if cached gem is excluded """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

          self.url = _gl_uri

-         self.text = 'Gem package should exclude cached Gem.'

+         self.text = "Gem package should exclude cached Gem."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

          # it seems easier to check whether .gem is not present in rpms

          # than to examine %files

-         self.set_passed(

-             self.FAIL if self.rpms.find('*.gem') else self.PASS)

+         self.set_passed(self.FAIL if self.rpms.find("*.gem") else self.PASS)

  

  

  class GemCheckUsesMacros(GemCheckBase):

      """ Check if spec files uses proper macros instead of hardcoding """

+ 

      def __init__(self, base):

          GemCheckBase.__init__(self, base)

-         self.url = _gl_fmt_uri({'section': 'Macros'})

-         self.text = 'Specfile should use macros from rubygem-devel package.'

+         self.url = _gl_fmt_uri({"section": "Macros"})

+         self.text = "Specfile should use macros from rubygem-devel package."

          self.automatic = True

-         self.type = 'SHOULD'

+         self.type = "SHOULD"

  

      def run_on_applicable(self):

-         gem_libdir_re = re.compile(rpm.expandMacro('%{gem_libdir}'), re.I)

-         gem_extdir_re = re.compile(rpm.expandMacro('%{gem_extdir_mri}'), re.I)

-         doc_gem_docdir_re = \

-             re.compile(rpm.expandMacro(r'%doc\s+%{gem_docdir}'), re.I)

-         exclude_gem_cache_re = \

-             re.compile(rpm.expandMacro(r'%exclude\s+%{gem_cache}'), re.I)

-         gem_spec_re = re.compile(rpm.expandMacro('%{gem_spec}'), re.I)

- 

-         re_dict = {gem_libdir_re: False,

-                    doc_gem_docdir_re: False,

-                    exclude_gem_cache_re: False,

-                    gem_spec_re: False}

+         gem_libdir_re = re.compile(rpm.expandMacro("%{gem_libdir}"), re.I)

+         gem_extdir_re = re.compile(rpm.expandMacro("%{gem_extdir_mri}"), re.I)

+         doc_gem_docdir_re = re.compile(rpm.expandMacro(r"%doc\s+%{gem_docdir}"), re.I)

+         exclude_gem_cache_re = re.compile(

+             rpm.expandMacro(r"%exclude\s+%{gem_cache}"), re.I

+         )

+         gem_spec_re = re.compile(rpm.expandMacro("%{gem_spec}"), re.I)

+ 

+         re_dict = {

+             gem_libdir_re: False,

+             doc_gem_docdir_re: False,

+             exclude_gem_cache_re: False,

+             gem_spec_re: False,

+         }

          if _has_extension(self):

              re_dict[gem_extdir_re] = False

  
@@ -455,13 +488,15 @@ 

          # construct the error message for all non-present macros

          for key, value in re_dict.items():

              if value is False:

-                 err_message.append(key.pattern.replace('\\s+', ' '))

+                 err_message.append(key.pattern.replace("\\s+", " "))

  

          if not err_message:

              self.set_passed(self.PASS)

          else:

-             self.set_passed(self.PENDING,

-                             'The specfile doesn\'t use these macros: %s'

-                             % ', '.join(err_message))

+             self.set_passed(

+                 self.PENDING,

+                 "The specfile doesn't use these macros: %s" % ", ".join(err_message),

+             )

+ 

  

  # vim: set expandtab ts=4 sw=4:

file modified
+118 -120
@@ -15,12 +15,12 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''

+ """

  Plugin module acting as an interface between, simple, shell-based plugins

  and the regular python plugins.

- '''

+ """

  

- import logging                                   # pylint: disable=W0611

+ import logging  # pylint: disable=W0611

  import os

  import os.path

  import re
@@ -147,10 +147,10 @@ 

  

  """

  

- ENV_PATH = 'review-env.sh'

+ ENV_PATH = "review-env.sh"

  

- _TAGS = ['name', 'version', 'release', 'group', 'license', 'url']

- _SECTIONS = ['prep', 'build', 'install', 'check']

+ _TAGS = ["name", "version", "release", "group", "license", "url"]

+ _SECTIONS = ["prep", "build", "install", "check"]

  

  _PASS = 80

  _FAIL = 81
@@ -159,147 +159,143 @@ 

  

  

  def _find_value(line, key):

-     ''' Locate tag like @tag:, return value or None. '''

-     key = '@' + key + ':'

+     """ Locate tag like @tag:, return value or None. """

+     key = "@" + key + ":"

      if key in line:

-         return re.sub('.*' + key, '', line).strip()

+         return re.sub(".*" + key, "", line).strip()

      return None

  

  

  def _quote(s):

-     ''' Fix string to be included within '' '''

+     """ Fix string to be included within '' """

      return s.replace("'", "'\\''")

  

  

  def _settings_generator():

-     ''' Bash code defining FR_SETTINGS, reflecting Settings. '''

-     body = 'declare -A FR_SETTINGS \n'

+     """ Bash code defining FR_SETTINGS, reflecting Settings. """

+     body = "declare -A FR_SETTINGS \n"

      for key in Settings.__dict__.keys():

-         if key.startswith('_'):

+         if key.startswith("_"):

              continue

          value = Settings.__dict__[key]

          if not value:

-             value = ''

+             value = ""

          if isinstance(value, str):

-             value = value.replace('"', r'\"')

+             value = value.replace('"', r"\"")

          body += 'FR_SETTINGS[{}]="{}"\n'.format(key, value)

      return body

  

  

  def _source_generator(spec):

-     ''' Bash code defining the %sourceX items. '''

-     body = ''

+     """ Bash code defining the %sourceX items. """

+     body = ""

      for tag, path in spec.sources_by_tag.items():

-         body += 'export ' + tag + '="' + path + '"\n'

+         body += "export " + tag + '="' + path + '"\n'

      return body

  

  

  def _patch_generator(spec):

-     ''' Bash code defining the %patchX items. '''

-     body = ''

+     """ Bash code defining the %patchX items. """

+     body = ""

      for tag, path in spec.patches_by_tag.items():

-         body += 'export ' + tag + '="' + path + '"\n'

+         body += "export " + tag + '="' + path + '"\n'

      return body

  

  

  def _files_generator(spec):

-     ''' Bash code defining FR_FILES,reflecting %files. '''

-     body = 'declare -A FR_FILES\n'

+     """ Bash code defining FR_FILES,reflecting %files. """

+     body = "declare -A FR_FILES\n"

      for pkg in spec.packages:

-         item = _quote('\n'.join(spec.get_files(pkg)))

+         item = _quote("\n".join(spec.get_files(pkg)))

          body += """FR_FILES[{}]='{}'\n""".format(pkg, item)

      return body

  

  

  def _description_generator(spec):

-     '''

+     """

      Bash code defining FR_DESCRIPTION,reflecting %description.

-     '''

-     body = 'declare -A FR_DESCRIPTION\n'

+     """

+     body = "declare -A FR_DESCRIPTION\n"

      for pkg in spec.packages:

-         section = spec.get_section('%description', pkg)

+         section = spec.get_section("%description", pkg)

          if section:

-             item = _quote('\n'.join(section))

+             item = _quote("\n".join(section))

              body += """FR_DESCRIPTION[{}]='{}'\n""".format(pkg, item)

      return body

  

  

  def _flags_generator(flags):

-     ''' Bash code defining FR_FLAGS,reflecting checks.flags. '''

-     body = 'declare -A FR_FLAGS\n'

+     """ Bash code defining FR_FLAGS,reflecting checks.flags. """

+     body = "declare -A FR_FLAGS\n"

      for flag in flags.values():

          body += """FR_FLAGS[{}]='{}'\n""".format(flag.name, str(flag))

      return body

  

  

  def _write_section(spec, env, s):

-     ''' Substitute a spec section into env.'''

-     body = ''

-     section = '%' + s.strip()

+     """ Substitute a spec section into env."""

+     body = ""

+     section = "%" + s.strip()

      lines = spec.get_section(section)

      if lines:

-         body += _quote('\n'.join(lines))

+         body += _quote("\n".join(lines))

      body = "'" + body + "'"

      if len(body) < 5:

-         body = ''

-     env = env.replace('@' + s + '@', body)

+         body = ""

+     env = env.replace("@" + s + "@", body)

      return env

  

  

  def _write_tag(spec, env, tag):

-     ''' Substitute a spec tag into env. '''

-     value = spec.expand_tag(tag.upper()).decode('utf-8')

+     """ Substitute a spec tag into env. """

+     value = spec.expand_tag(tag.upper()).decode("utf-8")

      if value:

-         env = env.replace('@' + tag + '@', value)

+         env = env.replace("@" + tag + "@", value)

      else:

-         env = env.replace('@' + tag + '@', '""')

+         env = env.replace("@" + tag + "@", '""')

      return env

  

  

  def _create_env(checks):

-     ''' Create the review-env.sh file. '''

+     """ Create the review-env.sh file. """

  

      env = ENVIRON_TEMPLATE

-     env = env.replace('FR_SETTINGS_generator', _settings_generator())

-     env = env.replace('@review_dir@', ReviewDirs.root)

+     env = env.replace("FR_SETTINGS_generator", _settings_generator())

+     env = env.replace("@review_dir@", ReviewDirs.root)

      for tag in _TAGS:

          env = _write_tag(checks.spec, env, tag)

-     env = env.replace('FR_SOURCE_generator',

-                       _source_generator(checks.spec))

-     env = env.replace('FR_PATCH_generator',

-                       _patch_generator(checks.spec))

+     env = env.replace("FR_SOURCE_generator", _source_generator(checks.spec))

+     env = env.replace("FR_PATCH_generator", _patch_generator(checks.spec))

      for s in _SECTIONS:

          env = _write_section(checks.spec, env, s)

-     env = env.replace('FR_FILES_generator',

-                       _files_generator(checks.spec))

-     env = env.replace('FR_FLAGS_generator',

-                       _flags_generator(checks.flags))

-     env = env.replace('FR_DESCRIPTION_generator',

-                       _description_generator(checks.spec))

-     with open(ENV_PATH, 'w') as f:

+     env = env.replace("FR_FILES_generator", _files_generator(checks.spec))

+     env = env.replace("FR_FLAGS_generator", _flags_generator(checks.flags))

+     env = env.replace("FR_DESCRIPTION_generator", _description_generator(checks.spec))

+     with open(ENV_PATH, "w") as f:

          f.write(env)

-     attach_path = os.path.join(ReviewDirs.root, '.attachments')

+     attach_path = os.path.join(ReviewDirs.root, ".attachments")

      if os.path.exists(attach_path):

          shutil.rmtree(attach_path)

      os.makedirs(attach_path)

  

  

  class Registry(AbstractRegistry):

-     ''' Registers all script plugins. '''

+     """ Registers all script plugins. """

+ 

      # pylint: disable=R0201

  

-     group = 'Shell-api'

+     group = "Shell-api"

  

      class CreateEnvCheck(GenericCheck):

-         ''' Create the review-env.sh file in review dir. No output. '''

+         """ Create the review-env.sh file in review dir. No output. """

  

-         group = 'Generic'

+         group = "Generic"

  

          def __init__(self, checks, registry):

              GenericCheck.__init__(self, checks, __file__)

-             self.text = 'Create review-env.sh'

+             self.text = "Create review-env.sh"

              self.automatic = True

-             self.type = 'EXTRA'

+             self.type = "EXTRA"

              self.registry = registry

  

          def run(self):
@@ -307,7 +303,7 @@ 

              self.set_passed(self.NA)

  

          def is_applicable(self):

-             '''' Always True, we want this to happen. '''

+             """' Always True, we want this to happen. """

              return True

  

      def __init__(self, checks):
@@ -320,54 +316,54 @@ 

          return True

  

      def is_user_enabled(self):

-         ''' Not modifiable.... '''

+         """ Not modifiable.... """

          return False

  

      def user_enabled_value(self):

-         ''' The actual value set if is_user_enabled() is True '''

+         """ The actual value set if is_user_enabled() is True """

          self.log.warning("shell-api: illegal user_enabled_value() call")

          return True

  

      def register(self, plugin):

-         ''' Return all available scripts as ShellCheck instances. '''

+         """ Return all available scripts as ShellCheck instances. """

  

          def _get_plugin_dirs():

-             ''' Return list of dirs to scan for scripts. '''

+             """ Return list of dirs to scan for scripts. """

              dir_list = []

              plugindir = os.path.realpath(os.path.dirname(__file__))

-             plugindir = os.path.join(plugindir, '../scripts')

+             plugindir = os.path.join(plugindir, "../scripts")

              plugindir = os.path.normpath(plugindir)

              dir_list.append(plugindir)

-             dir_list.append(os.path.join(XdgDirs.app_datadir,

-                                          'scripts'))

+             dir_list.append(os.path.join(XdgDirs.app_datadir, "scripts"))

              return dir_list

  

          dirs = _get_plugin_dirs()

          my_checks = [self.CreateEnvCheck(self.checks, self)]

          for d in dirs:

-             for f in glob(os.path.join(d, '*.sh')):

+             for f in glob(os.path.join(d, "*.sh")):

                  my_checks.append(ShellCheck(self, f))

          return my_checks

  

  

  class ShellCheck(GenericCheck):

      """ A single test  defined by a shell plugin. """

-     DEFAULT_GROUP = 'Generic'

-     DEFAULT_TYPE = 'MUST'

-     implementation = 'script'

+ 

+     DEFAULT_GROUP = "Generic"

+     DEFAULT_TYPE = "MUST"

+     implementation = "script"

  

      def __init__(self, registry, path):

          GenericCheck.__init__(self, registry.checks, path)

          for tag in _TAGS:

              try:

-                 setattr(self, tag, tag + ': undefined')

+                 setattr(self, tag, tag + ": undefined")

              except AttributeError:

                  pass

          self.type = self.DEFAULT_TYPE

          self.group = self.DEFAULT_GROUP

-         self.needs = ['CreateEnvCheck']

+         self.needs = ["CreateEnvCheck"]

          self.deprecates = []

-         self.text = ''

+         self.text = ""

          self.registry = registry

          self._name = None

          self._parse(path)
@@ -375,33 +371,32 @@ 

      groups = property(lambda self: self.registry.checks.groups)

  

      def _parse_attributes(self, lines):

-         ''' Parse all tags and populate attributes. '''

+         """ Parse all tags and populate attributes. """

  

          for line in lines:

-             for attr in ['group', 'url', 'type']:

+             for attr in ["group", "url", "type"]:

                  value = _find_value(line, attr)

                  if value:

                      setattr(self, attr, value)

-             text = _find_value(line, 'register-flag')

+             text = _find_value(line, "register-flag")

              if text:

                  (name, doc) = text.split(None, 1)

-                 self.checks.flags.add(

-                     self.registry.Flag(name, doc, self.defined_in))

-             text = _find_value(line, 'set-flag')

+                 self.checks.flags.add(self.registry.Flag(name, doc, self.defined_in))

+             text = _find_value(line, "set-flag")

              if text:

                  (flag, value) = text.split(None, 2)

                  self.checks.flags[flag].value = value

-             text = _find_value(line, 'text')

+             text = _find_value(line, "text")

              if text:

                  if self.text:

-                     self.text += ' '

+                     self.text += " "

                  self.text += text

-             victims = _find_value(line, 'deprecates')

+             victims = _find_value(line, "deprecates")

              if victims:

-                 self.deprecates = victims.replace(',', ' ').split()

-             needed = _find_value(line, 'needs')

+                 self.deprecates = victims.replace(",", " ").split()

+             needed = _find_value(line, "needs")

              if needed:

-                 self.needs.extend(needed.replace(',', ' ').split())

+                 self.needs.extend(needed.replace(",", " ").split())

  

      def _parse(self, path):

          """
@@ -419,7 +414,7 @@ 

          with open(path) as f:

              lines = f.readlines()

          for line in lines:

-             name = _find_value(line, 'name')

+             name = _find_value(line, "name")

              if name:

                  break

          if not name:
@@ -428,10 +423,10 @@ 

          self._parse_attributes(lines)

  

      def _do_run(self, cmd):

-         '''

+         """

          Actually invoke the external script, returning

          (retcode, stdout, stderr)

-         '''

+         """

          p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True)

          try:

              stdout, stderr = p.communicate()
@@ -439,28 +434,30 @@ 

              self.log.warning("Cannot execute " + cmd)

              self.log.debug("Cannot execute " + cmd, exc_info=True)

              return -1, None, None

-         stdout = None if stdout == '' else stdout

-         stderr = None if stderr == '' else stderr

+         stdout = None if stdout == "" else stdout

+         stderr = None if stderr == "" else stderr

          return p.returncode, stdout, stderr

  

      @property

-     def name(self):                             # pylint: disable=E0202

-         ''' Check's name. '''

+     def name(self):  # pylint: disable=E0202

+         """ Check's name. """

          return self._name

  

      def _get_attachments(self):

-         ''' Pick up shell-script attachments from .attachments. '''

+         """ Pick up shell-script attachments from .attachments. """

          attachments = []

-         for path in glob(os.path.join(ReviewDirs.root,

-                                       '.attachments', '*;*;*')):

+         for path in glob(os.path.join(ReviewDirs.root, ".attachments", "*;*;*")):

              with open(path) as f:

                  body = f.read(8192)

-             sort_hint, header = os.path.basename(path).split(';')[:2]

+             sort_hint, header = os.path.basename(path).split(";")[:2]

              try:

                  sort_hint = int(sort_hint)

              except ValueError:

-                 self.log.warning('Cannot decode attachment sorting hint: '

-                                  + sort_hint + ', defaulting to 7')

+                 self.log.warning(

+                     "Cannot decode attachment sorting hint: "

+                     + sort_hint

+                     + ", defaulting to 7"

+                 )

                  sort_hint = 7

              a = self.Attachment(header, body, sort_hint)

              attachments.append(a)
@@ -468,46 +465,42 @@ 

          return attachments

  

      def _handle_log_messages(self):

-         ''' Handle log messages from plugin. '''

-         logfile = os.path.join(ReviewDirs.root, '.log')

+         """ Handle log messages from plugin. """

+         logfile = os.path.join(ReviewDirs.root, ".log")

          if not os.path.exists(logfile):

              return

          with open(logfile) as f:

              for line in f.readlines():

                  try:

-                     tag, msg = line.split(':')

+                     tag, msg = line.split(":")

                      # pylint: disable=eval-used

-                     level = eval('logging.' + tag.upper())

+                     level = eval("logging." + tag.upper())

                  except (ValueError, AttributeError):

                      self.log.error("Malformed plugin log: " + line)

                  self.log.log(level, msg)

          os.unlink(logfile)

  

      def is_applicable(self):

-         ''' Return is_applicable() for proper group. '''

+         """ Return is_applicable() for proper group. """

          return self.groups[self.group].is_applicable()

  

      def run(self):

-         ''' Run the check. '''

+         """ Run the check. """

          if self.is_run:

              return

          if self.group not in self.groups:

-             self.set_passed(self.PENDING,

-                             "Test run failed: illegal group")

-             self.log.warning('Illegal group %s in %s' %

-                              (self.group, self.defined_in))

+             self.set_passed(self.PENDING, "Test run failed: illegal group")

+             self.log.warning("Illegal group %s in %s" % (self.group, self.defined_in))

              return

          if not self.groups[self.group].is_applicable():

              self.set_passed(self.NA)

              return

-         cmd = 'env -i bash -c "source ./review-env.sh; source %s"' % \

-             self.defined_in

+         cmd = 'env -i bash -c "source ./review-env.sh; source %s"' % self.defined_in

          retval, stdout, stderr = self._do_run(cmd)

          self._handle_log_messages()

          attachments = self._get_attachments()

          if retval == -1:

-             self.set_passed(self.PENDING,

-                             "Cannot execute shell command" + cmd)

+             self.set_passed(self.PENDING, "Cannot execute shell command" + cmd)

          elif retval == _PASS and not stderr:

              self.set_passed(self.PASS, stdout, attachments)

          elif retval == _FAIL and not stderr:
@@ -518,9 +511,14 @@ 

              self.set_passed(self.NA, stdout)

          else:

              self.log.warning(

-                 'Illegal return from %s, code %d, output: %s' %

-                 (self.defined_in, retval,

-                  'stdout:' + str(stdout) + ' stderr:' + str(stderr)))

-             self.set_passed(self.PENDING, 'Test run failed')

+                 "Illegal return from %s, code %d, output: %s"

+                 % (

+                     self.defined_in,

+                     retval,

+                     "stdout:" + str(stdout) + " stderr:" + str(stderr),

+                 )

+             )

+             self.set_passed(self.PENDING, "Test run failed")

+ 

  

  # vim: set expandtab ts=4 sw=4:

file modified
+23 -22
@@ -15,69 +15,70 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  # (C) 2012 - Michael Scherer <misc@fedoraproject.org>

- ''' Sugar tests plugin module. '''

+ """ Sugar tests plugin module. """

  

  from FedoraReview import CheckBase, RegistryBase

  

- _SUGAR_URL = \

-     'https://docs.fedoraproject.org/en-US/packaging-guidelines/SugarActivityGuidelines/#'

+ _SUGAR_URL = "https://docs.fedoraproject.org/en-US/packaging-guidelines/SugarActivityGuidelines/#"

  

  

  class Registry(RegistryBase):

-     ''' Register all checks in this file in group SugarActivity. '''

+     """ Register all checks in this file in group SugarActivity. """

  

-     group = 'SugarActivity'

+     group = "SugarActivity"

  

      def is_applicable(self):

          if self.is_user_enabled():

              return self.user_enabled_value()

-         regex = '^/usr/(share|lib|lib64)/sugar/activities/'

+         regex = "^/usr/(share|lib|lib64)/sugar/activities/"

          return bool(self.checks.rpms.find(regex))

  

  

  class SugarActivityCheckBase(CheckBase):

-     ''' Common base class for sugar checks. '''

+     """ Common base class for sugar checks. """

  

      def __init__(self, base):

          CheckBase.__init__(self, base, __file__)

  

  

  class SugarActivityCheckNaming(SugarActivityCheckBase):

-     ''' All activities MUST be named sugar-<activity name>  '''

+     """ All activities MUST be named sugar-<activity name>  """

+ 

      def __init__(self, base):

          SugarActivityCheckBase.__init__(self, base)

-         self.url = _SUGAR_URL + '_naming'

-         self.text = 'Sugar activities must be named sugar-<activity name>'

-         self.type = 'MUST'

+         self.url = _SUGAR_URL + "_naming"

+         self.text = "Sugar activities must be named sugar-<activity name>"

+         self.type = "MUST"

          self.automatic = True

  

      def run_on_applicable(self):

-         if not self.spec.name.startswith('sugar-'):

+         if not self.spec.name.startswith("sugar-"):

              self.set_passed(self.FAIL)

              return

          self.set_passed(self.PENDING)

  

  

  class SugarActivityCheckBuildRequires(SugarActivityCheckBase):

-     ''' All activities requires sugar-toolkit to build '''

+     """ All activities requires sugar-toolkit to build """

+ 

      def __init__(self, base):

          SugarActivityCheckBase.__init__(self, base)

-         self.url = _SUGAR_URL + '_necessary_buildrequires'

-         self.text = 'Sugar activities depend on sugar-toolkit'

-         self.type = 'MUST'

+         self.url = _SUGAR_URL + "_necessary_buildrequires"

+         self.text = "Sugar activities depend on sugar-toolkit"

+         self.type = "MUST"

          self.automatic = True

  

      def run_on_applicable(self):

          br = self.spec.build_requires()

-         self.set_passed('sugar-toolkit' in br)

+         self.set_passed("sugar-toolkit" in br)

  

  

  class SugarActivityCheckRuntimeDeps(SugarActivityCheckBase):

-     ''' All runtime dependency information MUST be manually added. '''

+     """ All runtime dependency information MUST be manually added. """

+ 

      def __init__(self, base):

          SugarActivityCheckBase.__init__(self, base)

-         self.url = _SUGAR_URL + '_runtime_dependencies'

-         self.text = 'All runtime dependency information need to be' \

-                     ' manually added.'

-         self.type = 'MUST'

+         self.url = _SUGAR_URL + "_runtime_dependencies"

+         self.text = "All runtime dependency information need to be" " manually added."

+         self.type = "MUST"

          self.automatic = False

file modified
+20 -22
@@ -4,8 +4,9 @@ 

  """

  import os

  import sys

+ 

  MAIN_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))

- PKG_DIR = os.path.join(MAIN_DIR, 'src')

+ PKG_DIR = os.path.join(MAIN_DIR, "src")

  sys.path.insert(0, PKG_DIR)

  

  from distutils.core import setup
@@ -13,7 +14,7 @@ 

  

  

  def list_files_in_dir(dir_, extension):

-     ''' Return recursive listing of all regular files under dir. '''

+     """ Return recursive listing of all regular files under dir. """

      file_list = []

      for filename in os.listdir(os.path.join(MAIN_DIR, dir_)):

          if filename.endswith(extension):
@@ -22,24 +23,21 @@ 

  

  

  setup(

-     name = 'fedora-review',

-     description = 'Tools to help review packages for inclusion in Fedora',

-     data_files = [('/usr/share/man/man1/',

-                       ['fedora-review.1', 'fedora-create-review.1']),

-                   ('/usr/share/fedora-review/scripts',

-                       list_files_in_dir('scripts', '.sh')),

-                   ('/usr/share/fedora-review/plugins',

-                       list_files_in_dir('plugins', '.py')),

-         ],

-     version = __version__,

-     license = 'GPLv2+',

-     download_url = 'https://fedorahosted.org/releases/F/e/FedoraReview/',

-     url = 'https://fedorahosted.org/FedoraReview/',

-     package_dir = {'FedoraReview': 'src/FedoraReview'},

-     packages = ['FedoraReview'],

-     package_data = {'': ['*.tmpl', 'version']},

-     scripts = ["src/fedora-review", "src/fedora-create-review",

-         "koji-download-scratch"],

-     maintainer  = 'fedora-review maintainers',

-     maintainer_email = 'fedorareview@lists.fedorahosted.org'

+     name="fedora-review",

+     description="Tools to help review packages for inclusion in Fedora",

+     data_files=[

+         ("/usr/share/man/man1/", ["fedora-review.1", "fedora-create-review.1"]),

+         ("/usr/share/fedora-review/scripts", list_files_in_dir("scripts", ".sh")),

+         ("/usr/share/fedora-review/plugins", list_files_in_dir("plugins", ".py")),

+     ],

+     version=__version__,

+     license="GPLv2+",

+     download_url="https://fedorahosted.org/releases/F/e/FedoraReview/",

+     url="https://fedorahosted.org/FedoraReview/",

+     package_dir={"FedoraReview": "src/FedoraReview"},

+     packages=["FedoraReview"],

+     package_data={"": ["*.tmpl", "version"]},

+     scripts=["src/fedora-review", "src/fedora-create-review", "koji-download-scratch"],

+     maintainer="fedora-review maintainers",

+     maintainer_email="fedorareview@lists.fedorahosted.org",

  )

file modified
+10 -10
@@ -16,18 +16,18 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

- from .check_base   import AbstractCheck, GenericCheck, CheckBase

- from .mock         import Mock

+ from .check_base import AbstractCheck, GenericCheck, CheckBase

+ from .mock import Mock

  from .review_error import ReviewError

- from .review_dirs  import ReviewDirs

- from .registry     import AbstractRegistry, RegistryBase

- from .rpm_file     import RpmFile

- from .settings     import Settings

- from .version      import __version__, BUILD_ID, BUILD_DATE, BUILD_FULL

- from .xdg_dirs     import XdgDirs

+ from .review_dirs import ReviewDirs

+ from .registry import AbstractRegistry, RegistryBase

+ from .rpm_file import RpmFile

+ from .settings import Settings

+ from .version import __version__, BUILD_ID, BUILD_DATE, BUILD_FULL

+ from .xdg_dirs import XdgDirs

  

  # vim: set expandtab ts=4 sw=4:

@@ -14,10 +14,10 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@@fedoraproject.org>

  

- '''

+ """

  Common bug base class. A Bug is a filter that provides usable URL:s to

  srpm and spec file given some kind of key when created.

- '''

+ """

  

  import os.path

  import tempfile
@@ -45,12 +45,13 @@ 

      Concrete implementations basically understands how to

      set the urls, this base class handles the rest.

      """

+ 

      # pylint:disable=R0201

  

      __metaclass__ = ABCMeta

  

      class BugError(ReviewError):

-         ''' Generic error thrown in bugs, not showing logs. '''

+         """ Generic error thrown in bugs, not showing logs. """

  

          def __init__(self, what):

              ReviewError.__init__(self, what, 2)
@@ -99,9 +100,12 @@ 

          """

  

          def has_srpm():

-             ''' Return true iff self.srpmfile is a valid path. '''

-             return hasattr(self, 'srpm_file') and self.srpm_file and \

-                 os.path.exists(self.srpm_file)

+             """ Return true iff self.srpmfile is a valid path. """

+             return (

+                 hasattr(self, "srpm_file")

+                 and self.srpm_file

+                 and os.path.exists(self.srpm_file)

+             )

  

          if not self.dir:

              self.dir = ReviewDirs.srpm
@@ -118,7 +122,7 @@ 

          Download the spec file and srpm extracted from the page.

          Raises IOError.

          """

-         self.log.info('Downloading .spec and .srpm files')

+         self.log.info("Downloading .spec and .srpm files")

          if not self.srpm_file:

              self.do_download_srpm()

          if not self.spec_file:
@@ -126,26 +130,28 @@ 

          return True

  

      def is_downloaded(self):

-         ''' Return true iff self.{specfile, srpmfile} are valid. '''

-         ok = (self.spec_file and os.path.exists(self.spec_file) and

-               self.srpm_file and os.path.exists(self.srpm_file))

+         """ Return true iff self.{specfile, srpmfile} are valid. """

+         ok = (

+             self.spec_file

+             and os.path.exists(self.spec_file)

+             and self.srpm_file

+             and os.path.exists(self.srpm_file)

+         )

          return ok

  

      def _check_cache(self):

-         ''' return True iff srpm and spec are in srpm dir . '''

+         """ return True iff srpm and spec are in srpm dir . """

          name = self.get_name()

-         assert name != '?'

-         specs = glob(os.path.join(ReviewDirs.srpm,

-                                   name + '*.spec'))

+         assert name != "?"

+         specs = glob(os.path.join(ReviewDirs.srpm, name + "*.spec"))

          found = len(specs)

-         srpms = glob(os.path.join(ReviewDirs.srpm,

-                                   name + '*.src.rpm'))

+         srpms = glob(os.path.join(ReviewDirs.srpm, name + "*.src.rpm"))

          found += len(srpms)

          if found == 2:

              self.spec_file = specs[0]

              self.srpm_file = srpms[0]

-             self.spec_url = 'file://' + specs[0]

-             self.srpm_url = 'file://' + srpms[0]

+             self.spec_url = "file://" + specs[0]

+             self.srpm_url = "file://" + srpms[0]

              return True

  

          return False
@@ -160,32 +166,30 @@ 

          try:

              self.do_download_files()

          except IOError as ex:

-             self.log.debug('bug download error', exc_info=True)

-             self.log.error('Cannot download file(s): %s', str(ex))

+             self.log.debug("bug download error", exc_info=True)

+             self.log.error("Cannot download file(s): %s", str(ex))

              return False

          return True

  

      def _get_spec_from_srpm(self):

-         ''' Extract spec from srpm and update self.spec_url. '''

+         """ Extract spec from srpm and update self.spec_url. """

          path = urlparse(self.srpm_url).path

-         name = os.path.basename(path).rsplit('-', 2)[0]

+         name = os.path.basename(path).rsplit("-", 2)[0]

          ReviewDirs.workdir_setup(name, Settings.cache)

          self.do_download_srpm()

  

          SRPMFile(self.srpm_file).unpack()

          try:

-             path = glob(os.path.join(ReviewDirs.srpm_unpacked,

-                                      name + '*.spec'))[0]

+             path = glob(os.path.join(ReviewDirs.srpm_unpacked, name + "*.spec"))[0]

          except IndexError:

              raise ReviewError("Cannot find spec file in srpm")

          self.spec_file = path

-         self.spec_url = 'file://' + path

+         self.spec_url = "file://" + path

  

      def find_urls(self):

          """ Retrieve the page and parse for srpm and spec url. """

          # pylint: disable=bare-except

-         self.log.info('Getting .spec and .srpm Urls from : %s',

-                       self.get_location())

+         self.log.info("Getting .spec and .srpm Urls from : %s", self.get_location())

          try:

              self.find_srpm_url()

              self.log.info("  --> SRPM url: %s", self.srpm_url)
@@ -197,50 +201,49 @@ 

          except ReviewError as fre:

              raise fre

          except:

-             self.log.debug('url_bug link parse error', exc_info=True)

-             self.log.error('Cannot find usable urls here')

+             self.log.debug("url_bug link parse error", exc_info=True)

+             self.log.error("Cannot find usable urls here")

              return False

          return True

  

      def get_name(self):

-         ''' Return name of bug. '''

+         """ Return name of bug. """

          if self.spec_file:

-             return os.path.basename(self.spec_file).rsplit('.', 1)[0]

+             return os.path.basename(self.spec_file).rsplit(".", 1)[0]

          elif self.spec_url:

              basename = os.path.basename(urlparse(self.spec_url).path)

-             return basename.rsplit('.', 1)[0]

+             return basename.rsplit(".", 1)[0]

          elif self.srpm_file:

-             return os.path.basename(self.srpm_file).rsplit('-', 2)[0]

+             return os.path.basename(self.srpm_file).rsplit("-", 2)[0]

          elif self.srpm_url:

              basename = os.path.basename(urlparse(self.srpm_url).path)

-             return basename.rsplit('-', 2)[0]

+             return basename.rsplit("-", 2)[0]

  

-         return '?'

+         return "?"

  

-     def get_dirname(self, prefix='review-'):

-         ''' Return dirname to be used for this bug. '''

-         if self.get_name() != '?':

+     def get_dirname(self, prefix="review-"):

+         """ Return dirname to be used for this bug. """

+         if self.get_name() != "?":

              return prefix + self.get_name()

  

-         return prefix + tempfile.mkdtemp(prefix=prefix,

-                                          dir=os.getcwd())

+         return prefix + tempfile.mkdtemp(prefix=prefix, dir=os.getcwd())

  

      @staticmethod

      def do_check_options(mode, bad_opts):

-         '''

+         """

          Verify that Settings don't have bad options, raise

          SettingsError if so.

-         '''

+         """

  

          class SettingsError(ReviewError):

-             ''' Thrown for invalid settings combinations. '''

+             """ Thrown for invalid settings combinations. """

+ 

              def __init__(self, what):

                  ReviewError.__init__(self, "Incompatible settings: " + what)

  

          for opt in bad_opts:

              if hasattr(Settings, opt) and getattr(Settings, opt):

-                 raise SettingsError(

-                     '--' + opt + ' can not be used with ' + mode)

+                 raise SettingsError("--" + opt + " can not be used with " + mode)

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+19 -18
@@ -15,65 +15,66 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- ''' ANSI colored terminal output support '''

+ """ ANSI colored terminal output support """

  import sys

  import curses

+ 

  # pylint: disable=W1401

  # pylint: disable=bad-whitespace

  

- BLACK   = "\033[1;30m"

- RED     = "\033[1;31m"

- GREEN   = "\033[1;32m"

- YELLOW  = "\033[1;33m"

- BLUE    = "\033[1;34m"

+ BLACK = "\033[1;30m"

+ RED = "\033[1;31m"

+ GREEN = "\033[1;32m"

+ YELLOW = "\033[1;33m"

+ BLUE = "\033[1;34m"

  MAGENTA = "\033[1;35m"

- CYAN    = "\033[1;36m"

- WHITE   = "\033[1;37m"

- RESET   = "\033[0m"

+ CYAN = "\033[1;36m"

+ WHITE = "\033[1;37m"

+ RESET = "\033[0m"

  

  

  def black(s):

-     ''' Return s with optional ansi chars to print in black. '''

+     """ Return s with optional ansi chars to print in black. """

      return BLACK + s + RESET

  

  

  def green(s):

-     ''' Return s with optional ansi chars to print in green. '''

+     """ Return s with optional ansi chars to print in green. """

      return GREEN + s + RESET

  

  

  def yellow(s):

-     ''' Return s with optional ansi chars to print in yellow. '''

+     """ Return s with optional ansi chars to print in yellow. """

      return YELLOW + s + RESET

  

  

  def blue(s):

-     ''' Return s with optional ansi chars to print in blue. '''

+     """ Return s with optional ansi chars to print in blue. """

      return BLUE + s + RESET

  

  

  def magenta(s):

-     ''' Return s with optional ansi chars to print in magenta. '''

+     """ Return s with optional ansi chars to print in magenta. """

      return MAGENTA + s + RESET

  

  

  def red(s):

-     ''' Return s with optional ansi chars to print in red. '''

+     """ Return s with optional ansi chars to print in red. """

      return RED + s + RESET

  

  

  def cyan(s):

-     ''' Return s with optional ansi chars to print in cyan. '''

+     """ Return s with optional ansi chars to print in cyan. """

      return CYAN + s + RESET

  

  

  def white(s):

-     ''' Return s with optional ansi chars to print in white. '''

+     """ Return s with optional ansi chars to print in white. """

      return WHITE + s + RESET

  

  

  def color_supported():

-     ''' Return true if we are running on color supporting terminal '''

+     """ Return true if we are running on color supporting terminal """

      try:

          if sys.stdout.isatty() and sys.stderr.isatty():

              curses.setupterm()

@@ -13,9 +13,9 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  import os.path

  

  from .url_bug import UrlBug
@@ -24,7 +24,7 @@ 

  

  

  class BugzillaBug(UrlBug):

-     ''' Bugzilla handling, a special case of the url_bug case. '''

+     """ Bugzilla handling, a special case of the url_bug case. """

  

      def __init__(self, bug):

          """ Constructor.
@@ -32,23 +32,22 @@ 

          """

          self.check_options()

          self.bug_num = bug

-         url = os.path.join(Settings.current_bz_url,

-                            'show_bug.cgi?id=' + str(bug))

+         url = os.path.join(Settings.current_bz_url, "show_bug.cgi?id=" + str(bug))

          UrlBug.__init__(self, url)

  

      def get_location(self):

          return Settings.bug

  

-     def get_dirname(self, prefix=''):

-         ''' Return dirname to be used for this bug. '''

-         if self.get_name() != '?':

-             return self.bug_num + '-' + self.get_name()

+     def get_dirname(self, prefix=""):

+         """ Return dirname to be used for this bug. """

+         if self.get_name() != "?":

+             return self.bug_num + "-" + self.get_name()

  

          return self.bug_num

  

-     def check_options(self):                    # pylint: disable=R0201

-         ''' Raise SettingsError if Settings combinations is invalid. '''

-         AbstractBug.do_check_options('--bug', ['prebuilt'])

+     def check_options(self):  # pylint: disable=R0201

+         """ Raise SettingsError if Settings combinations is invalid. """

+         AbstractBug.do_check_options("--bug", ["prebuilt"])

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+69 -64
@@ -18,7 +18,7 @@ 

  

  # pylint: disable=bad-whitespace

  

- ''' Basic definitions: AbstractCheck + descendants, TestResult.  '''

+ """ Basic definitions: AbstractCheck + descendants, TestResult.  """

  

  import re

  from six.moves import StringIO
@@ -48,8 +48,8 @@ 

      def __str__(self):

          if not self.header:

              return self.text

-         s = self.header + '\n'

-         s += '-' * len(self.header) + '\n'

+         s = self.header + "\n"

+         s += "-" * len(self.header) + "\n"

          s += self.text

          return s

  
@@ -72,7 +72,7 @@ 

          return self.__cmp__(other) >= 0

  

      def __cmp__(self, other):

-         if not hasattr(other, 'order_hint'):

+         if not hasattr(other, "order_hint"):

              return NotImplemented

          if self.order_hint < other.order_hint:

              return -1
@@ -111,18 +111,19 @@ 

      Equality:

        - Tests are considered equal if they have the same name.

      """

+ 

      # pylint: disable=R0201,C0103,W0223

  

      __metaclass__ = ABCMeta

  

-     PASS    = 'pass'

-     FAIL    = 'fail'

-     NA      = 'na'

-     PENDING = 'pending'

+     PASS = "pass"

+     FAIL = "fail"

+     NA = "na"

+     PENDING = "pending"

  

-     version        = '0.1'

-     implementation = 'python'

-     sort_key       = 50

+     version = "0.1"

+     implementation = "python"

+     sort_key = 50

  

      def __init__(self, defined_in):

          self.defined_in = defined_in
@@ -130,7 +131,7 @@ 

          self.needs = []

          self.is_disabled = False

          try:

-             self.name = 'Undefined'

+             self.name = "Undefined"

          except AttributeError:

              pass

  
@@ -148,22 +149,22 @@ 

  

      @abstractmethod

      def run(self):

-         ''' Perform the check, update result. '''

+         """ Perform the check, update result. """

          pass

  

      @property

      def state(self):

-         ''' None for (not is_run or is_na), else result.result '''

+         """ None for (not is_run or is_na), else result.result """

          assert self

-         if hasattr(self, 'result'):

+         if hasattr(self, "result"):

              return self.result.result if self.result else None

          return None

  

-     is_run     = property(lambda self: hasattr(self, 'result'))

-     is_failed  = property(lambda self: self.state == self.FAIL)

-     is_passed  = property(lambda self: self.state == self.PASS)

+     is_run = property(lambda self: hasattr(self, "result"))

+     is_failed = property(lambda self: self.state == self.FAIL)

+     is_passed = property(lambda self: self.state == self.PASS)

      is_pending = property(lambda self: self.state == self.PENDING)

-     is_na      = property(lambda self: self.is_run and not self.state)

+     is_na = property(lambda self: self.is_run and not self.state)

  

  

  class GenericCheck(AbstractCheck):
@@ -183,61 +184,63 @@ 

  

      class Attachment(_Attachment):

          """ Text written after the test lines. """

+ 

          pass

  

      def __init__(self, checks, defined_in):

          AbstractCheck.__init__(self, defined_in)

          self.checks = checks

-         self.url = '(this test has no URL)'

+         self.url = "(this test has no URL)"

          self.text = self.__class__.__name__

-         self.description = 'This test has no description'

-         self.type = 'MUST'

-         self.needs = ['CheckBuildCompleted']

-         self.attachments = []      # Keep attachments here to support NA

- 

-     spec       = property(lambda self: self.checks.spec)

-     flags      = property(lambda self: self.checks.flags)

-     srpm       = property(lambda self: self.checks.srpm)

-     sources    = property(lambda self: self.checks.sources)

-     buildsrc   = property(lambda self: self.checks.buildsrc)

-     log        = property(lambda self: self.checks.log)

-     rpms       = property(lambda self: self.checks.rpms)

+         self.description = "This test has no description"

+         self.type = "MUST"

+         self.needs = ["CheckBuildCompleted"]

+         self.attachments = []  # Keep attachments here to support NA

+ 

+     spec = property(lambda self: self.checks.spec)

+     flags = property(lambda self: self.checks.flags)

+     srpm = property(lambda self: self.checks.srpm)

+     sources = property(lambda self: self.checks.sources)

+     buildsrc = property(lambda self: self.checks.buildsrc)

+     log = property(lambda self: self.checks.log)

+     rpms = property(lambda self: self.checks.rpms)

  

      def run(self):

-         ''' GenericCheck is usually used indirectly through CheckBase '''

+         """ GenericCheck is usually used indirectly through CheckBase """

          raise NotImplementedError("Use CheckBase as parent for your Check")

  

      @property

-     def name(self):                              # pylint: disable=E0202

-         ''' The check's name. '''

+     def name(self):  # pylint: disable=E0202

+         """ The check's name. """

          return self.__class__.__name__

  

      def set_passed(self, result, output_extra=None, attachments=None):

-         '''

+         """

          Set if the test is passed, failed or N/A and set optional

          extra output and/or attachments to be shown in repost.

-         '''

+         """

          # pylint: disable=attribute-defined-outside-init

  

          self.attachments = attachments if attachments else []

-         if result in ['not_applicable', self.NA, None]:

+         if result in ["not_applicable", self.NA, None]:

              self.result = None

              return

          elif result is True or result == self.PASS:

              state = self.PASS

          elif result is False or result == self.FAIL:

              state = self.FAIL

-         elif result == 'inconclusive' or result == self.PENDING:

+         elif result == "inconclusive" or result == self.PENDING:

              state = self.PENDING

          else:

              state = self.FAIL

-             self.log.warning('Illegal return code: ' + str(result))

+             self.log.warning("Illegal return code: " + str(result))

          r = TestResult(self, state, output_extra, attachments)

-         self.result = r                          # pylint: disable=W0201

+         self.result = r  # pylint: disable=W0201

  

  

  class CheckBase(GenericCheck, HelpersMixin):

      """ Base class for "regular" python checks. """

+ 

      # pylint: disable=R0201

  

      def __init__(self, checks, defined_in):
@@ -252,13 +255,13 @@ 

          return self.registry.is_applicable()

  

      def run_on_applicable(self):

-         ''' Called by run() if is_applicable is true(). '''

+         """ Called by run() if is_applicable is true(). """

          self.set_passed(self.PENDING)

  

      def run(self):

-         '''

+         """

          Default implementation, returns run_on_applicable() or self.NA.

-         '''

+         """

          if self.is_applicable():

              self.run_on_applicable()

          else:
@@ -268,16 +271,15 @@ 

  

  

  class TestResult(object):

-     ''' The printable outcome of a test, stored in check.result. '''

+     """ The printable outcome of a test, stored in check.result. """

  

-     TEST_STATES = {

-         'pending': '[ ]', 'pass': '[x]', 'fail': '[!]', 'na': '[-]'}

+     TEST_STATES = {"pending": "[ ]", "pass": "[x]", "fail": "[!]", "na": "[-]"}

  

      def __init__(self, check, result, output_extra, attachments=None):

          self.check = check

-         self.text = re.sub(r"\s+", " ", check.text) if check.text else ''

+         self.text = re.sub(r"\s+", " ", check.text) if check.text else ""

          self.result = result

-         self._leader = self.TEST_STATES[result] + ': '

+         self._leader = self.TEST_STATES[result] + ": "

          self.output_extra = output_extra

          self.attachments = attachments if attachments else []

          if self.output_extra:
@@ -294,29 +296,31 @@ 

      state = property(lambda self: self.result)

  

      def set_indent(self, indent):

-         ''' Set indentation level for get_text (int, defaults to 5). '''

+         """ Set indentation level for get_text (int, defaults to 5). """

          # pylint: disable=W0201

-         self.wrapper = TextWrapper(width=75,

-                                    subsequent_indent=" " * indent,

-                                    break_long_words=False, )

+         self.wrapper = TextWrapper(

+             width=75, subsequent_indent=" " * indent, break_long_words=False

+         )

  

      def set_leader(self, leader):

-         ''' Set the leading string, defaults to [!], [ ], [-], etc. '''

+         """ Set the leading string, defaults to [!], [ ], [-], etc. """

          self._leader = leader

  

      def get_text(self):

-         ''' Return printable representation of test. '''

+         """ Return printable representation of test. """

          strbuf = StringIO()

          main_lines = self.wrapper.wrap(self._leader + self.text)

-         strbuf.write('\n'.join(main_lines))

+         strbuf.write("\n".join(main_lines))

          if self.output_extra and self.output_extra != "":

              strbuf.write("\n")

              extra_lines = self.wrapper.wrap(

-                 self.wrapper.subsequent_indent + "Note: " + self.output_extra)

-             strbuf.write('\n'.join(extra_lines))

+                 self.wrapper.subsequent_indent + "Note: " + self.output_extra

+             )

+             strbuf.write("\n".join(extra_lines))

              if self.is_failed:

                  see = self.wrapper.wrap(

-                     self.wrapper.subsequent_indent + "See: " + self.url)

+                     self.wrapper.subsequent_indent + "See: " + self.url

+                 )

                  strbuf.write("\n" + "\n".join(see))

  

          return strbuf.getvalue()
@@ -326,15 +330,16 @@ 

  

  

  class SimpleTestResult(TestResult):

-     ''' Simple, failed result not based on a check. '''

+     """ Simple, failed result not based on a check. """

+ 

      # pylint: disable=W0212,W0231

  

      def __set_name(self, n):

-         ''' property setter. '''

+         """ property setter. """

          self._name = n

  

      def __set_type(self, t):

-         ''' property setter. '''

+         """ property setter. """

          self._type = t

  

      name = property(lambda self: self._name, __set_name)
@@ -343,9 +348,9 @@ 

      is_failed = property(lambda self: True)

  

      def __init__(self, name, text, extra):

-         ''' Create a  printable, failed result. '''

+         """ Create a  printable, failed result. """

          self._name = name

-         self._type = 'ERROR'

+         self._type = "ERROR"

          self.text = text

          self._output_extra = extra

  

file modified
+82 -82
@@ -16,16 +16,16 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  This module contains misc helper funtions and classes

- '''

+ """

  

  import os

  import sys

  import time

  

  from operator import attrgetter

- from straight.plugin import load                  # pylint: disable=F0401

+ from straight.plugin import load  # pylint: disable=F0401

  

  from .datasrc import RpmDataSource, BuildFilesSource, SourcesDataSource

  from .settings import Settings
@@ -36,8 +36,10 @@ 

  from .reports import write_xml_report, write_template

  

  

- _BATCH_EXCLUDED = 'CheckBuild,CheckPackageInstalls,CheckRpmlintInstalled,' \

-     'CheckNoNameConflict,CheckInitDeps,CheckRpmlint'

+ _BATCH_EXCLUDED = (

+     "CheckBuild,CheckPackageInstalls,CheckRpmlintInstalled,"

+     "CheckNoNameConflict,CheckInitDeps,CheckRpmlint"

+ )

  

  

  class _CheckDict(dict):
@@ -50,6 +52,7 @@ 

          - On insertion, items listed in the 'deprecates'property

            are removed.

      """

+ 

      # pylint: disable=R0904

  

      def __init__(self, *args, **kwargs):
@@ -59,12 +62,15 @@ 

          self.deprecations = {}

  

      def __setitem__(self, key, value):

- 

          def log_duplicate(first, second):

-             ''' Log warning for duplicate test. '''

-             self.log.warning("Duplicate checks %s in %s, %s in %s",

-                              first.name, first.defined_in, second.name,

-                              second.defined_in)

+             """ Log warning for duplicate test. """

+             self.log.warning(

+                 "Duplicate checks %s in %s, %s in %s",

+                 first.name,

+                 first.defined_in,

+                 second.name,

+                 second.defined_in,

+             )

  

          if key in self.keys():

              log_duplicate(value, self[key])
@@ -73,26 +79,25 @@ 

  

      def update(self, *args, **kwargs):

          if len(args) > 1:

-             raise TypeError("update: at most 1 arguments, got %d" %

-                             len(args))

+             raise TypeError("update: at most 1 arguments, got %d" % len(args))

          other = dict(*args, **kwargs)

          for key in other.keys():

              self[key] = other[key]

  

      def add(self, check):

-         ''' As list.add(). '''

+         """ As list.add(). """

          self[check.name] = check

  

      def extend(self, checks):

-         ''' As list.extend() '''

+         """ As list.extend() """

          for c in checks:

              self.add(c)

  

      def set_single_check(self, check_name):

-         ''' Remove all checks besides check_name and it's deps. '''

+         """ Remove all checks besides check_name and it's deps. """

  

          def reap_needed(node):

-             ''' Collect all deps into needed. '''

+             """ Collect all deps into needed. """

              needed.append(node)

              node.result = None

              for n in node.needs:
@@ -102,16 +107,20 @@ 

          reap_needed(self[check_name])

          self.clear()

          self.extend(needed)

-         delattr(self[check_name], 'result')

+         delattr(self[check_name], "result")

  

      def fix_deprecations(self, key):

-         ''' Remove deprecated tests, needs Registry.is_applicable(). '''

+         """ Remove deprecated tests, needs Registry.is_applicable(). """

  

          def log_kill(victim, killer):

-             ''' Log test skipped due to deprecation. '''

-             self.log.debug("Skipping %s in %s, deprecated by %s in %s",

-                            victim.name, victim.defined_in, killer.name,

-                            killer.defined_in)

+             """ Log test skipped due to deprecation. """

+             self.log.debug(

+                 "Skipping %s in %s, deprecated by %s in %s",

+                 victim.name,

+                 victim.defined_in,

+                 killer.name,

+                 killer.defined_in,

+             )

  

          value = self[key]

          for victim in value.deprecates:
@@ -125,22 +134,22 @@ 

  

  

  class _Flags(dict):

-     ''' A dict storing Flag  entries with some added behaviour. '''

+     """ A dict storing Flag  entries with some added behaviour. """

  

      def __init__(self):

          dict.__init__(self)

  

      def add(self, flag):

-         ''' As list.add(). '''

+         """ As list.add(). """

          self[flag.name] = flag

  

      def update(self, optarg):

-         '''

+         """

          Try to update a flag with command line setting.

          Raises KeyError if flag not registered.

-         '''

-         if '=' in optarg:

-             key, value = optarg.split('=')

+         """

+         if "=" in optarg:

+             key, value = optarg.split("=")

              self[key].value = value

          else:

              self[optarg].set_active()
@@ -154,11 +163,12 @@ 

      """

  

      class Data(object):

-         ''' Simple DataSource stuff container. '''

+         """ Simple DataSource stuff container. """

+ 

          pass

  

      def __init__(self):

-         ''' Create a Checks, load checkdict. '''

+         """ Create a Checks, load checkdict. """

          self.log = Settings.get_logger()

          self.checkdict = None

          self.flags = _Flags()
@@ -169,21 +179,21 @@ 

          elif Settings.exclude:

              self.exclude_checks(Settings.exclude)

          self._update_flags()

-         if self.flags['BATCH']:

+         if self.flags["BATCH"]:

              self.exclude_checks(_BATCH_EXCLUDED)

  

      def _update_flags(self):

-         ''' Update registered flags with user -D settings. '''

+         """ Update registered flags with user -D settings. """

          for flag_opt in Settings.flags:

              try:

-                 if '=' not in flag_opt:

+                 if "=" not in flag_opt:

                      key = flag_opt

                      self.flags[flag_opt].activate()

                  else:

-                     key, value = flag_opt.split('=')

+                     key, value = flag_opt.split("=")

                      self.flags[key].value = value

              except KeyError:

-                 raise ReviewError(key + ': No such flag')

+                 raise ReviewError(key + ": No such flag")

  

      def _load_checks(self):

          """
@@ -194,13 +204,12 @@ 

          self.checkdict = _CheckDict()

          self.groups = {}

  

-         appdir = os.path.realpath(

-             os.path.join(os.path.dirname(__file__)))

+         appdir = os.path.realpath(os.path.join(os.path.dirname(__file__)))

          sys.path.insert(0, appdir)

          sys.path.insert(0, XdgDirs.app_datadir)

-         plugins = load('plugins')

+         plugins = load("plugins")

          for plugin in sorted(plugins, key=lambda p: len(p.__name__)):

-             if plugin.__name__ == 'plugins.plugins':

+             if plugin.__name__ == "plugins.plugins":

                  continue

              registry = plugin.Registry(self)

              tests = registry.register(plugin)
@@ -213,8 +222,8 @@ 

          sys.path.remove(appdir)

  

      def exclude_checks(self, exclude_arg):

-         ''' Mark all checks in exclude_arg (string) as already done. '''

-         for c in [l.strip() for l in exclude_arg.split(',')]:

+         """ Mark all checks in exclude_arg (string) as already done. """

+         for c in [l.strip() for l in exclude_arg.split(",")]:

              if c in self.checkdict:

                  # Mark check as run, don't delete it. We want

                  # checks depending on this to run.
@@ -224,31 +233,31 @@ 

                  self.log.warn("I can't remove check: %s", c)

  

      def set_single_check(self, check):

-         ''' Remove all checks but arg and it's deps. '''

+         """ Remove all checks but arg and it's deps. """

          self.checkdict.set_single_check(check)

          self.checkdict[check].needs = []

  

      def get_checks(self):

-         ''' Return the Checkdict instance holding all checks. '''

+         """ Return the Checkdict instance holding all checks. """

          return self.checkdict

  

-     def get_plugins(self, state='true_or_false'):

-         ''' Return list of groups (i. e., plugins) being active/passive. '''

+     def get_plugins(self, state="true_or_false"):

+         """ Return list of groups (i. e., plugins) being active/passive. """

          plugins = []

          for p in self.groups.keys():

-             if state != 'true_or_false':

+             if state != "true_or_false":

                  r = self.groups[p]

                  if r.is_user_enabled():

                      if r.user_enabled_value() != state:

                          continue

                  elif not bool(r.is_applicable()) == state:

                      continue

-             plugins.append(p.split('.')[0] if '.' in p else p)

+             plugins.append(p.split(".")[0] if "." in p else p)

          return list(set(plugins))

  

  

  class ChecksLister(_ChecksLoader):

-     ''' A class only exporting get_checks() and checkdict. '''

+     """ A class only exporting get_checks() and checkdict. """

  

      def __init__(self):

          self.spec = None
@@ -261,12 +270,12 @@ 

  

  

  class Checks(_ChecksLoader):

-     ''' Interface class to run checks.  '''

+     """ Interface class to run checks.  """

  

      def __init__(self, spec_file, srpm_file):

-         ''' Create a Checks set. srpm_file and spec_file are required,

+         """ Create a Checks set. srpm_file and spec_file are required,

          unless invoked from ChecksLister.

-         '''

+         """

          _ChecksLoader.__init__(self)

          self.spec = SpecFile(spec_file, self.flags)

          self.srpm = SRPMFile(srpm_file)
@@ -283,11 +292,10 @@ 

  

      @staticmethod

      def _write_testdata(results):

-         ''' Write hidden file usable when writing tests. '''

-         with open('.testlog.txt', 'w') as f:

+         """ Write hidden file usable when writing tests. """

+         with open(".testlog.txt", "w") as f:

              for r in results:

-                 f.write('\n' + 24 * ' ' +

-                         "('{}', '{}'),".format(r.state, r.name))

+                 f.write("\n" + 24 * " " + "('{}', '{}'),".format(r.state, r.name))

  

      def _ready_to_run(self, name):

          """
@@ -300,15 +308,12 @@ 

              return False

          if check.is_run:

              return False

-         if check.registry.is_user_enabled() and not \

-             check.registry.user_enabled_value():

-                 return False

+         if check.registry.is_user_enabled() and not check.registry.user_enabled_value():

+             return False

          for dep in check.needs:

              if dep not in self.checkdict:

-                 self.log.warning('%s depends on deprecated %s',

-                                  name, dep)

-                 self.log.warning('Removing %s, cannot resolve deps',

-                                  name)

+                 self.log.warning("%s depends on deprecated %s", name, dep)

+                 self.log.warning("Removing %s, cannot resolve deps", name)

                  del self.checkdict[name]

                  return True

              elif not self.checkdict[dep].is_run:
@@ -316,7 +321,7 @@ 

          return True

  

      def deprecate(self):

-         ''' Mark all deprecated tests as run. '''

+         """ Mark all deprecated tests as run. """

          allkeys = list(self.checkdict.keys())

          for c in allkeys:

              if c not in self.checkdict:
@@ -325,41 +330,40 @@ 

                  self.checkdict.fix_deprecations(c)

  

      def _get_ready_to_run(self):

-         ''' Return checks ready to run, deprecating checks first. '''

+         """ Return checks ready to run, deprecating checks first. """

          names = self.checkdict.keys()

          tests_to_run = (n for n in names if self._ready_to_run(n))

-         return sorted(tests_to_run,

-                       key=lambda t: len(self.checkdict[t].deprecates),

-                       reverse=True)

+         return sorted(

+             tests_to_run, key=lambda t: len(self.checkdict[t].deprecates), reverse=True

+         )

  

      def is_external_plugin_installed(self, group_name):

-         ''' Return True if external plugin install for given group. '''

+         """ Return True if external plugin install for given group. """

          for reg_group, registry in self.groups.items():

-             basename = reg_group.split('.')[0]

+             basename = reg_group.split(".")[0]

              if basename == group_name and registry.external_plugin:

                  return True

          return False

  

      def run_checks(self, output=sys.stdout, writedown=True):

-         ''' Run all checks. '''

+         """ Run all checks. """

  

          def run_check(name):

              """ Run check. Update results, attachments and issues. """

              check = self.checkdict[name]

              if check.is_run:

                  return

-             self.log.debug('Running check: %s', name)

+             self.log.debug("Running check: %s", name)

              check.run()

              now = time.time()

-             self.log.debug('    %s completed: %.3f seconds', name,

-                            now - self._clock)

+             self.log.debug("    %s completed: %.3f seconds", name, now - self._clock)

              self._clock = now

              attachments.extend(check.attachments)

              result = check.result

              if not result:

                  return

              results.append(result)

-             if result.type == 'MUST' and result.result == "fail":

+             if result.type == "MUST" and result.result == "fail":

                  issues.append(result)

  

          issues = []
@@ -379,17 +383,13 @@ 

              tests_to_run = self._get_ready_to_run()

  

          if writedown:

-             key_getter = attrgetter('group', 'type', 'name')

-             write_template(output,

-                            sorted(results, key=key_getter),

-                            issues,

-                            attachments)

+             key_getter = attrgetter("group", "type", "name")

+             write_template(output, sorted(results, key=key_getter), issues, attachments)

              write_xml_report(self.spec, results)

          else:

-             with open('.testlog.txt', 'w') as f:

+             with open(".testlog.txt", "w") as f:

                  for r in results:

-                     f.write('\n' + 24 * ' ' +

-                             "('{}', '{}'),".format(r.state, r.name))

+                     f.write("\n" + 24 * " " + "('{}', '{}'),".format(r.state, r.name))

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+27 -26
@@ -32,13 +32,12 @@ 

  from .review_dirs import ReviewDirs

  from .settings import Settings

  

- COPR_API_URL_TEMPLATE = 'https://copr.fedoraproject.org/api/coprs/build/{}/'

+ COPR_API_URL_TEMPLATE = "https://copr.fedoraproject.org/api/coprs/build/{}/"

  

  

  def get_build_data(build_id):

      """ Fetch build data from COPR and return them as json """

-     build_data_file = urlopen(

-         COPR_API_URL_TEMPLATE.format(build_id))

+     build_data_file = urlopen(COPR_API_URL_TEMPLATE.format(build_id))

      return json.load(build_data_file)

  

  
@@ -52,23 +51,24 @@ 

          """

          self.log = Settings.get_logger()

  

-         if build_descriptor.startswith(('http://', 'https://')):

+         if build_descriptor.startswith(("http://", "https://")):

              build_id = self.parse_build_id_from_uri(build_descriptor)

          else:

-             build_id = build_descriptor.lstrip('0')

+             build_id = build_descriptor.lstrip("0")

  

          uri = self.get_location(build_id)

          UrlBug.__init__(self, uri)

          self.rpm_urls = None

  

-         builddir_name = 'copr-build-' + build_id

+         builddir_name = "copr-build-" + build_id

          self.copr_build_dir = os.path.join(os.getcwd(), builddir_name)

          try:

              os.makedirs(self.copr_build_dir)

          except os.error:

              self.log.error(

                  "Build directory ./%s cannot be created or exists already.",

-                 builddir_name)

+                 builddir_name,

+             )

              sys.exit(1)

  

          self.dir = self.copr_build_dir
@@ -78,36 +78,36 @@ 

      def find_urls(self):

          """ Retrieve the page and parse srpm, rpm and spec url. """

          # pylint: disable=bare-except

-         self.log.info('Getting .spec, .srpm, .rpm')

+         self.log.info("Getting .spec, .srpm, .rpm")

          try:

              self.find_srpm_url()

              self.log.info("  --> SRPM url: %s", self.srpm_url)

              self.find_spec_url()

              self.log.info("  --> Spec url: %s", self.spec_url)

              self.find_rpm_urls()

-             self.log.info("  --> RPM urls: %s", ' '.join(self.rpm_urls))

+             self.log.info("  --> RPM urls: %s", " ".join(self.rpm_urls))

          except ReviewError as fre:

              raise fre

          except:

-             self.log.debug('build link parse error', exc_info=True)

-             self.log.error('Cannot find usable urls here.')

+             self.log.debug("build link parse error", exc_info=True)

+             self.log.error("Cannot find usable urls here.")

              return False

          return True

  

      def find_rpm_urls(self):

          """ Get rpm urls for the build"""

-         urls = self._find_urls_by_ending('.rpm')

+         urls = self._find_urls_by_ending(".rpm")

          filtered_urls = []

          for url in urls:

-             if not re.match(r'.*.src.rpm$', url):

+             if not re.match(r".*.src.rpm$", url):

                  filtered_urls.append(url)

          if not filtered_urls:

-             raise self.BugError('Cannot find rpm URL')

+             raise self.BugError("Cannot find rpm URL")

          self.rpm_urls = filtered_urls

  

      def do_download_files(self):

          """ Download all the necessary files """

-         self.log.info('Downloading .spec, .srpm, .rpm')

+         self.log.info("Downloading .spec, .srpm, .rpm")

          if not self.srpm_file:

              self.do_download_srpm()

          if not self.spec_file:
@@ -127,27 +127,27 @@ 

  

      def parse_build_id_from_uri(self, uri):

          """ Get the COPR build-id from a given uri """

-         uri_last_part = os.path.basename(uri.strip('/'))

-         match = re.match(r'(\d+).*', uri_last_part)

+         uri_last_part = os.path.basename(uri.strip("/"))

+         match = re.match(r"(\d+).*", uri_last_part)

          if not match:

              self.log.error("Invalid build uri: %s.", uri)

              sys.exit(1)

-         return match.group(1).lstrip('0')

+         return match.group(1).lstrip("0")

  

      def get_location(self, build_id):

          """ Get COPR build URI """

          build_data = get_build_data(build_id)

  

-         if build_data['status'] != 'succeeded':

-             self.log.error("Build did not succeeded in all its chroots."

-                            "Exiting.")

+         if build_data["status"] != "succeeded":

+             self.log.error("Build did not succeeded in all its chroots." "Exiting.")

              sys.exit(1)

  

-         required_chroot = 'fedora-rawhide-' + platform.machine()

+         required_chroot = "fedora-rawhide-" + platform.machine()

  

          fedora_chroots = filter(

-             lambda pair: pair[0].startswith('fedora'),

-             build_data['results_by_chroot'].items())

+             lambda pair: pair[0].startswith("fedora"),

+             build_data["results_by_chroot"].items(),

+         )

  

          for chroot, uri in fedora_chroots:

              if chroot == required_chroot:
@@ -157,7 +157,8 @@ 

          sys.exit(1)

  

      def check_options(self):  # pylint: disable=R0201

-         ''' Raise error if Settings combination is invalid. '''

-         UrlBug.do_check_options('--copr-build', ['other_bz', 'url'])

+         """ Raise error if Settings combination is invalid. """

+         UrlBug.do_check_options("--copr-build", ["other_bz", "url"])

+ 

  

  # vim: set expandtab ts=4 sw=4:

file modified
+129 -109
@@ -47,9 +47,7 @@ 

  

  from bugzilla.rhbugzilla import RHBugzilla

  

- SETTINGS_FILE = os.path.join(os.environ['HOME'],

-                              '.config',

-                              'fedora-create-review')

+ SETTINGS_FILE = os.path.join(os.environ["HOME"], ".config", "fedora-create-review")

  

  BUG_COMMENT = """

  Spec URL: %s
@@ -62,24 +60,24 @@ 

  # Initial simple logging stuff

  logging.basicConfig()

  LOG = logging.getLogger("fedora-create-review")

- if '--debug' in sys.argv:

+ if "--debug" in sys.argv:

      LOG.setLevel(logging.DEBUG)

  

  

  def read_fas_user():

      """ Try to read FAS username """

-     if os.path.exists(os.path.expanduser('~/.fedora.upn')):

-         with open(os.path.expanduser('~/.fedora.upn'), 'r') as f:

-             return f.read().replace('\n', '')

+     if os.path.exists(os.path.expanduser("~/.fedora.upn")):

+         with open(os.path.expanduser("~/.fedora.upn"), "r") as f:

+             return f.read().replace("\n", "")

  

-     klist_line = 'Default principal: '

-     koutput = check_output('klist', universal_newlines=True).split('\n')

+     klist_line = "Default principal: "

+     koutput = check_output("klist", universal_newlines=True).split("\n")

      line = [l for l in koutput if l.startswith(klist_line)][0]

-     line = line[len(klist_line):]

-     if line.endswith('@FEDORAPROJECT.ORG'):

-         return line[:line.index('@')]

+     line = line[len(klist_line) :]

+     if line.endswith("@FEDORAPROJECT.ORG"):

+         return line[: line.index("@")]

  

-     raise Exception('Could not determine FAS username')

+     raise Exception("Could not determine FAS username")

  

  

  def create_conf(configfile):
@@ -104,7 +102,7 @@ 

      :arg parser, ConfigParser object containing the configuration to

      write down.

      """

-     with open(configfile, 'w') as conf:

+     with open(configfile, "w") as conf:

          parser.write(conf)

  

  
@@ -113,11 +111,11 @@ 

      koji command and add a comment with this link on the review

      request.

      """

-     print('Adding comment about the koji build')

+     print("Adding comment about the koji build")

      url = None

-     for line in output_build.split('\n'):

-         if 'Task info' in line:

-             url = line.split('Task info:')[1]

+     for line in output_build.split("\n"):

+         if "Task info" in line:

+             url = line.split("Task info:")[1]

      comment = "This package built on koji: %s" % url

      bug.addcomment(comment)

  
@@ -125,21 +123,23 @@ 

  class FedoraCreateReviewError(Exception):

      """ Generic Exception class used for the exception thrown in this

      project. """

+ 

      pass

  

  

  class Settings(object):

      """ gitsync Settings """

+ 

      # upload target

-     upload_target = 'fedorapeople.org:public_html/'

+     upload_target = "fedorapeople.org:public_html/"

  

      def __init__(self):

          """Constructor of the Settings object.

          This instanciate the Settings object and load into the _dict

          attributes the default configuration which each available option.

          """

-         self._dict = {'upload_target': self.upload_target, }

-         self.load_config(SETTINGS_FILE, 'fedora-create-review')

+         self._dict = {"upload_target": self.upload_target}

+         self.load_config(SETTINGS_FILE, "fedora-create-review")

  

      def load_config(self, configfile, sec):

          """Load the configuration in memory.
@@ -148,7 +148,7 @@ 

          :arg sec, section of the configuration retrieved.

          """

          parser = six.moves.configparser.ConfigParser()

-         configfile = os.path.join(os.environ['HOME'], configfile)

+         configfile = os.path.join(os.environ["HOME"], configfile)

          is_new = create_conf(configfile)

          parser.read(configfile)

          if not parser.has_section(sec):
@@ -194,37 +194,39 @@ 

          self.settings = Settings()

          self.info = {}

          self.log = LOG

-         self.specfile = ''

-         self.spec = ''

-         self.srpmfile = ''

+         self.specfile = ""

+         self.spec = ""

+         self.srpmfile = ""

          self.username = None

          self.bzclient = None

  

      def create_review_request(self, rename_request):

          """ Create the review request on the bugzilla. """

-         print('Creating review')

-         review_type = 'Review Request'

+         print("Creating review")

+         review_type = "Review Request"

          if rename_request:

-             review_type = 'Rename Request'

+             review_type = "Rename Request"

          data = {

-             'product': 'Fedora',

-             'component': 'Package Review',

-             'version': 'rawhide',

-             'short_desc': '{}: {} - {}'.format(review_type,

-                                            self.info['name'],

-                                            self.info['summary']),

-             'comment': BUG_COMMENT % (self.info['specurl'],

-                                       self.info['srpmurl'],

-                                       self.info['description']),

-             'rep_platform': 'Unspecified',

-             'bug_severity': 'unspecified',

-             'op_sys': 'Unspecified',

-             'bug_file_loc': '',

-             'priority': 'unspecified', }

+             "product": "Fedora",

+             "component": "Package Review",

+             "version": "rawhide",

+             "short_desc": "{}: {} - {}".format(

+                 review_type, self.info["name"], self.info["summary"]

+             ),

+             "comment": BUG_COMMENT

+             % (self.info["specurl"], self.info["srpmurl"], self.info["description"]),

+             "rep_platform": "Unspecified",

+             "bug_severity": "unspecified",

+             "op_sys": "Unspecified",

+             "bug_file_loc": "",

+             "priority": "unspecified",

+         }

          if rename_request:

-             data['comment'] = data['comment'] + \

-             '\n\n This is a Rename request for the former package \'%s\'' \

-             % rename_request

+             data["comment"] = (

+                 data["comment"]

+                 + "\n\n This is a Rename request for the former package '%s'"

+                 % rename_request

+             )

          self.log.debug("bz.createbug(%s)", data)

          try:

              bug = self.bzclient.createbug(**data)
@@ -235,13 +237,18 @@ 

              return self.create_review_request(rename_request)

          return bug

  

-     def do_scratch_build(self, target='rawhide'):

+     def do_scratch_build(self, target="rawhide"):

          """ Starts a scratch build on koji. """

-         print('Starting scratch build')

-         cmd = ['koji', 'build', '--scratch', target, self.srpmfile]

+         print("Starting scratch build")

+         cmd = ["koji", "build", "--scratch", target, self.srpmfile]

          self.log.debug(cmd)

          try:

-             proc = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

+             proc = Popen(

+                 cmd,

+                 stdout=subprocess.PIPE,

+                 stderr=subprocess.PIPE,

+                 universal_newlines=True,

+             )

              output = proc.communicate()[0]

          except OSError as err:

              print("OSError : %s" % str(err))
@@ -251,11 +258,10 @@ 

          """ Fill the spec and src.rpm urls into the info table using the

          info in the settings.

          """

-         complement_url = self.settings.upload_target.split('public_html/')[1]

-         url = 'https://{}.fedorapeople.org/{}/'.format(

-             self.username, complement_url)

-         self.info['specurl'] = url + os.path.basename(self.specfile)

-         self.info['srpmurl'] = url + os.path.basename(self.srpmfile)

+         complement_url = self.settings.upload_target.split("public_html/")[1]

+         url = "https://{}.fedorapeople.org/{}/".format(self.username, complement_url)

+         self.info["specurl"] = url + os.path.basename(self.specfile)

+         self.info["srpmurl"] = url + os.path.basename(self.srpmfile)

  

      def find_existing_reviews(self):

          """ Return information about the review request(s) sumitted
@@ -270,36 +276,38 @@ 

          """

          bugbz = self.bzclient.query(

              #  'bug_status': ['CLOSED'],

-             {'short_desc': "Request: {} -".format(self.info['name']),

-              'short_desc_type': 'allwordssubstr',

-              'query_format': 'advanced',

-              'component': 'Package Review'})

+             {

+                 "short_desc": "Request: {} -".format(self.info["name"]),

+                 "short_desc_type": "allwordssubstr",

+                 "query_format": "advanced",

+                 "component": "Package Review",

+             }

+         )

  

          if bugbz:

-             print('Reviews for a package of the same name have been found:')

+             print("Reviews for a package of the same name have been found:")

          for bug in bugbz:

-             print(' ', bug, '-', bug.resolution)

+             print(" ", bug, "-", bug.resolution)

              print("\t", bug.url)

  

          if bugbz:

-             usr_inp = input('Do you want to proceed anyway? [Y/N]')

-             if usr_inp.lower() == ''  or usr_inp.lower().startswith('n'):

+             usr_inp = input("Do you want to proceed anyway? [Y/N]")

+             if usr_inp.lower() == "" or usr_inp.lower().startswith("n"):

                  raise FedoraCreateReviewError()

  

      def login_bz(self):

          """ Login into the bugzilla. """

-         username = input('Bugzilla username: ')

-         self.bzclient.login(user=username,

-                             password=getpass.getpass())

+         username = input("Bugzilla username: ")

+         self.bzclient.login(user=username, password=getpass.getpass())

  

      def main(self):

          """ The main function."""

          parser = setup_parser()

          args = parser.parse_args()

          if not args.test:

-             bzurl = 'https://bugzilla.redhat.com'

+             bzurl = "https://bugzilla.redhat.com"

          else:

-             bzurl = 'https://partner-bugzilla.redhat.com'

+             bzurl = "https://partner-bugzilla.redhat.com"

              print("Using test bugzilla at: " + bzurl)

  

          self.username = args.username
@@ -308,67 +316,72 @@ 

              try:

                  self.username = read_fas_user()

              except:

-                 self.log.debug('Could not determine FAS username')

-                 self.username = input('FAS username: ')

+                 self.log.debug("Could not determine FAS username")

+                 self.username = input("FAS username: ")

  

          self.bzclient = RHBugzilla(url="%s/xmlrpc.cgi" % bzurl)

          self.srpmfile = os.path.expanduser(args.srpmfile)

          self.specfile = os.path.expanduser(args.specfile)

          self.spec = rpm.spec(self.specfile)

          if not args.no_build:

-             (output_build, returncode) = self.do_scratch_build(

-                 target=args.koji_target)

+             (output_build, returncode) = self.do_scratch_build(target=args.koji_target)

              if returncode != 0:

-                 raise FedoraCreateReviewError(

-                     'Koji build error: \n ' + output_build)

-         self.info['summary'] = self.retrieve_summary()

-         self.info['description'] = self.retrieve_description()

-         self.info['name'] = self.retrieve_name()

+                 raise FedoraCreateReviewError("Koji build error: \n " + output_build)

+         self.info["summary"] = self.retrieve_summary()

+         self.info["description"] = self.retrieve_description()

+         self.info["name"] = self.retrieve_name()

          self.find_existing_reviews()

          (output_upload, returncode) = self.upload_files()

          if returncode != 0:

-             raise FedoraCreateReviewError(

-                 'Uploading error(s):\n ' + output_upload)

+             raise FedoraCreateReviewError("Uploading error(s):\n " + output_upload)

          self.fill_urls()

          bug = self.create_review_request(args.rename_request)

          if not args.no_build:

              add_comment_build(output_build, bug)

-         print('Review created at: {}/show_bug.cgi?id={}'.format(bzurl,

-                                                             bug.id))

+         print("Review created at: {}/show_bug.cgi?id={}".format(bzurl, bug.id))

          print(bug)

  

      def retrieve_description(self):

          """ Retrieve the description tag from a spec file. """

-         description = self.spec.packages[0].header[1005].decode('utf-8')

-         self.log.debug('Description: %s', description)

+         description = self.spec.packages[0].header[1005].decode("utf-8")

+         self.log.debug("Description: %s", description)

          return description

  

      def retrieve_name(self):

          """ Retrieve the name tag from a spec file. """

-         name = self.spec.packages[0].header[1000].decode('utf-8')

-         self.log.debug('Name: %s', name)

+         name = self.spec.packages[0].header[1000].decode("utf-8")

+         self.log.debug("Name: %s", name)

          return name

  

      def retrieve_summary(self):

          """ Retrieve the summary tag from a spec file. """

-         summary = self.spec.packages[0].header[1004].decode('utf-8')

-         self.log.debug('Summary: %s', summary)

+         summary = self.spec.packages[0].header[1004].decode("utf-8")

+         self.log.debug("Summary: %s", summary)

          return summary

  

      def upload_files(self):

          """ Upload the spec file and the src.rpm files into

          fedorapeople.org, ensuring readable mode."""

-         print('Uploading files into fedorapeople')

-         self.log.debug('Target: %s', self.settings.upload_target)

+         print("Uploading files into fedorapeople")

+         self.log.debug("Target: %s", self.settings.upload_target)

          for path in [self.specfile, self.srpmfile]:

              mode = os.stat(path)[0]

              mode |= stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH

              os.chmod(path, mode)

-         cmd = ['scp', self.specfile, self.srpmfile,

-                self.username + "@" + self.settings.upload_target]

+         cmd = [

+             "scp",

+             self.specfile,

+             self.srpmfile,

+             self.username + "@" + self.settings.upload_target,

+         ]

          self.log.debug(cmd)

          try:

-             proc = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

+             proc = Popen(

+                 cmd,

+                 stdout=subprocess.PIPE,

+                 stderr=subprocess.PIPE,

+                 universal_newlines=True,

+             )

              output = proc.communicate()[0]

          except OSError as err:

              print("OSError : %s" % str(err))
@@ -379,34 +392,41 @@ 

      """

      Set the command line arguments.

      """

-     parser = argparse.ArgumentParser(

-         prog="fedora-create-review")

+     parser = argparse.ArgumentParser(prog="fedora-create-review")

      # General connection options

-     parser.add_argument('specfile', help='Path to the spec file')

-     parser.add_argument('srpmfile', help='Path to the src.rpm file')

-     parser.add_argument('--user', dest='username', help='FAS username')

-     parser.add_argument('--rename-request', default=False,

-                         help='Former name of the package.')

+     parser.add_argument("specfile", help="Path to the spec file")

+     parser.add_argument("srpmfile", help="Path to the src.rpm file")

+     parser.add_argument("--user", dest="username", help="FAS username")

+     parser.add_argument(

+         "--rename-request", default=False, help="Former name of the package."

+     )

      parser.add_argument(

-         '--koji-target', default='rawhide',

-         help='Target for the koji scratch build (default: rawhide)')

+         "--koji-target",

+         default="rawhide",

+         help="Target for the koji scratch build (default: rawhide)",

+     )

      parser.add_argument(

-         '--test', default=False, action='store_true',

-         help='Run on a test bugzilla instance')

+         "--test",

+         default=False,

+         action="store_true",

+         help="Run on a test bugzilla instance",

+     )

      parser.add_argument(

-         '--no-scratch-build', dest='no_build',

-         action='store_true',

-         help='Do not run the koji scratch build')

+         "--no-scratch-build",

+         dest="no_build",

+         action="store_true",

+         help="Do not run the koji scratch build",

+     )

      parser.add_argument(

-         '--debug', action='store_true',

-         help='Outputs bunches of debugging info')

+         "--debug", action="store_true", help="Outputs bunches of debugging info"

+     )

      return parser

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      try:

          ReviewRequest().main()

-     except Exception as err:                 # pylint: disable=broad-except

+     except Exception as err:  # pylint: disable=broad-except

          print(err)

  

  

file modified
+44 -46
@@ -13,11 +13,11 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  # (C) 2011 - Tim Lauridsen <timlau@@fedoraproject.org>

- '''

+ """

  Common data src base class. A DataSrc is a collection of containers

  (source tarballs, source rpm, binary rpms...) each of which holding

  a filelist.

- '''

+ """

  import os

  import os.path

  import re
@@ -33,7 +33,7 @@ 

  

  

  class AbstractDataSource(object):

-     '''

+     """

       A collection of file containers.

         - The contained files can be retrieved either for a

           single container or for all
@@ -41,7 +41,8 @@ 

           can be searched in different ways

         - Each container can be accessed using a key, normally

           a printable name.

-      '''

+      """

+ 

      # pylint:disable=R0201,W0613

  

      __metaclass__ = ABCMeta
@@ -52,40 +53,40 @@ 

  

      @abstractmethod

      def init(self):

-         ''' Lazy init. '''

+         """ Lazy init. """

  

      @abstractmethod

      def get_filelist(self, container=None):

-         '''

+         """

          Return list of all files in a container or consolidated list

          of files in all containers if container == None.

-         '''

+         """

          assert False

  

      @abstractmethod

      def get(self, key=None):

-         ''' Return the container object bound to key. '''

+         """ Return the container object bound to key. """

  

      @abstractmethod

      def get_keys(self):

-         ''' Return all keys usable with get(). '''

+         """ Return all keys usable with get(). """

  

      @property

      def is_available(self):

-         ''' Return True if source is available. '''

+         """ Return True if source is available. """

          return True

  

      def get_all(self):

-         ''' Return list of all containers. '''

+         """ Return list of all containers. """

          self.init()

          return self.containers

  

      def find(self, glob_pattern, container=None):

-         ''' Find first file matching glob_pattern, or None. '''

+         """ Find first file matching glob_pattern, or None. """

          self.init()

          if container and container not in self.containers:

-             raise ValueError('DataSource: bad source: ' + container)

-         if hasattr(glob_pattern, 'match'):

+             raise ValueError("DataSource: bad source: " + container)

+         if hasattr(glob_pattern, "match"):

              return self.find_re(glob_pattern, container)

          for s in [container] if container else self.containers:

              for f in self.get_filelist(s):
@@ -94,10 +95,10 @@ 

          return None

  

      def find_re(self, regex, container=None):

-         ''' Find first file matching regex, or None. '''

+         """ Find first file matching regex, or None. """

          self.init()

          if container and container not in self.containers:

-             raise ValueError('DataSource: bad source: ' + container)

+             raise ValueError("DataSource: bad source: " + container)

          if isinstance(regex, str):

              regex = re.compile(regex, re.IGNORECASE)

          for s in [container] if container else self.containers:
@@ -107,11 +108,11 @@ 

          return None

  

      def find_all(self, glob_pattern, container=None):

-         ''' List of all files matching glob_pattern. '''

+         """ List of all files matching glob_pattern. """

          self.init()

          if container and container not in self.containers:

-             raise ValueError('DataSource: bad source: ' + container)

-         if hasattr(glob_pattern, 'match'):

+             raise ValueError("DataSource: bad source: " + container)

+         if hasattr(glob_pattern, "match"):

              return self.find_all_re(glob_pattern, container)

          result = []

          for s in [container] if container else self.containers:
@@ -121,10 +122,10 @@ 

          return result

  

      def find_all_re(self, regex, container=None):

-         ''' List of all files matching regex. '''

+         """ List of all files matching regex. """

          self.init()

          if container and container not in self.containers:

-             raise ValueError('DataSource: bad source: ' + container)

+             raise ValueError("DataSource: bad source: " + container)

          if isinstance(regex, str):

              regex = re.compile(regex, re.IGNORECASE)

          result = []
@@ -136,8 +137,8 @@ 

  

  

  class BuildFilesSource(AbstractDataSource):

-     ''' Patched sources created using rpmbuild -bp. Accesses might

-     throw LookupError if buildsources are not installed correct. '''

+     """ Patched sources created using rpmbuild -bp. Accesses might

+     throw LookupError if buildsources are not installed correct. """

  

      def __init__(self):

          AbstractDataSource.__init__(self)
@@ -145,22 +146,22 @@ 

          self.files = None

  

      def _get_containers(self):

-         ''' Return the list of containers, i. e., builddir. '''

+         """ Return the list of containers, i. e., builddir. """

          self.init()

          return self._containers

  

      containers = property(_get_containers)

  

      def init(self):

-         ''' Lazy init, hopefully not called until BUILD is there. '''

+         """ Lazy init, hopefully not called until BUILD is there. """

          if self._containers:

              return

-         build_dir_pat = os.path.join(ReviewDirs.root, 'BUILD', '*')

+         build_dir_pat = os.path.join(ReviewDirs.root, "BUILD", "*")

          entries = glob(build_dir_pat)

          if not entries:

-             raise LookupError('No build directory found in BUILD')

+             raise LookupError("No build directory found in BUILD")

          if len(entries) > 1:

-             raise LookupError('More than one build directory in BUILD')

+             raise LookupError("More than one build directory in BUILD")

          self._containers = [entries[0]]

          self.files = None

  
@@ -177,7 +178,7 @@ 

      def get_filelist(self, container=None):

          self.init()

          if container and container not in self.containers:

-             raise ValueError('BuildFilesSource: illegal rootdir')

+             raise ValueError("BuildFilesSource: illegal rootdir")

          if self.files is None:

              self.files = []

              # pylint: disable=W0612
@@ -187,7 +188,7 @@ 

          return self.files

  

      def get(self, key=None):

-         ''' Return the root builddir under BUILD.'''

+         """ Return the root builddir under BUILD."""

          self.init()

          return self.containers[0]

  
@@ -196,7 +197,7 @@ 

  

  

  class RpmDataSource(AbstractDataSource):

-     ''' The binary rpms and their filelists. '''

+     """ The binary rpms and their filelists. """

  

      def __init__(self, spec):

          AbstractDataSource.__init__(self)
@@ -212,13 +213,12 @@ 

  

          for pkg in self.spec.packages:

              nvr = self.spec.get_package_nvr(pkg)

-             self.rpms_by_pkg[pkg] = RpmFile(

-                 pkg, nvr.version, nvr.release)

+             self.rpms_by_pkg[pkg] = RpmFile(pkg, nvr.version, nvr.release)

  

      def get_filelist(self, container=None):

          self.init()

          if container and container not in self.containers:

-             raise ValueError('RpmSource: bad package: ' + container)

+             raise ValueError("RpmSource: bad package: " + container)

          if container:

              return self.rpms_by_pkg[container].filelist

          all_ = []
@@ -227,7 +227,7 @@ 

          return all_

  

      def get(self, key=None):

-         ''' Return RpmFile object for a package name key. '''

+         """ Return RpmFile object for a package name key. """

          self.init()

          if key and key in self.rpms_by_pkg.keys():

              return self.rpms_by_pkg[key]
@@ -239,7 +239,7 @@ 

  

  

  class SourcesDataSource(AbstractDataSource):

-     ''' The tarballs listed as SourceX: in specfile. '''

+     """ The tarballs listed as SourceX: in specfile. """

  

      def __init__(self, spec):

          AbstractDataSource.__init__(self)
@@ -260,19 +260,17 @@ 

          source = self.sources_by_tag[tag]

          if not source.extract_dir:

              source.extract()

-         self.log.debug('Adding files in : %s', source.filename)

+         self.log.debug("Adding files in : %s", source.filename)

          self.files_by_tag[tag] = []

          # pylint: disable=W0612

          for root, dirs, files in os.walk(source.extract_dir):

              paths = [os.path.join(root, f) for f in files]

              self.files_by_tag[source.tag].extend(paths)

-         self.log.debug('Loaded %d files',

-                        len(self.files_by_tag[source.tag]))

+         self.log.debug("Loaded %d files", len(self.files_by_tag[source.tag]))

  

      def get_filelist(self, container=None):

          if container and container not in self.containers:

-             raise ValueError('SourcesDataSource: bad package: ' +

-                              container)

+             raise ValueError("SourcesDataSource: bad package: " + container)

          if container:

              self._load_files(container)

              return self.files_by_tag[container]
@@ -283,10 +281,10 @@ 

          return all_

  

      def get(self, key=None):

-         ''' Return Source object bound to a Source/patch tag '''

+         """ Return Source object bound to a Source/patch tag """

          if not key:

-             key = 'Source0'

-             self.log.warning('Retrieving default source as Source0')

+             key = "Source0"

+             self.log.warning("Retrieving default source as Source0")

          if key not in self.sources_by_tag.keys():

              return None

          return self.sources_by_tag[key]
@@ -295,8 +293,8 @@ 

          return self.sources_by_tag.keys()

  

      def get_files_sources(self):

-         ''' Compatibility, to be removed. '''

-         self.log.warning('SourcesDataSource: calling get_files_sources')

+         """ Compatibility, to be removed. """

+         self.log.warning("SourcesDataSource: calling get_files_sources")

          return self.get_filelist()

  

  

file modified
+105 -58
@@ -15,11 +15,12 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- ''' Interface to package dependencies. '''

+ """ Interface to package dependencies. """

  

  import subprocess

+ 

  try:

-     from subprocess import check_output          # pylint: disable=E0611

+     from subprocess import check_output  # pylint: disable=E0611

  except ImportError:

      from FedoraReview.el_compat import check_output

  
@@ -27,36 +28,48 @@ 

  

  

  def init():

-     ''' Setup module for subsequent calls. '''

+     """ Setup module for subsequent calls. """

      # pk.refresh_cache would be better, but requires privileges.

      # Might be solvable, see

      # https://bugs.launchpad.net/ubuntu/+source/packagekit/+bug/1008106

      try:

-         check_output(['mock', '-r', Settings.mock_config, '-qn', 'install',

-                       'dnf'])

+         check_output(["mock", "-r", Settings.mock_config, "-qn", "install", "dnf"])

      except subprocess.CalledProcessError:

-         Settings.get_logger().warning(

-             "Cannot install dnf, trouble ahead")

+         Settings.get_logger().warning("Cannot install dnf, trouble ahead")

      try:

-         check_output(['mock', '-r', Settings.mock_config, '-qn',

-                       '--enable-network', 'shell', 'dnf makecache'])

+         check_output(

+             [

+                 "mock",

+                 "-r",

+                 Settings.mock_config,

+                 "-qn",

+                 "--enable-network",

+                 "shell",

+                 "dnf makecache",

+             ]

+         )

      except subprocess.CalledProcessError:

-         Settings.get_logger().warning(

-             "Cannot run dnf makecache, trouble ahead")

+         Settings.get_logger().warning("Cannot run dnf makecache, trouble ahead")

  

  

  def list_deps(pkgs):

-     ''' Return list of all dependencies for named pkgs (scalar or list). '''

+     """ Return list of all dependencies for named pkgs (scalar or list). """

  

      if not isinstance(pkgs, list):

          pkgs = [pkgs]

      if not pkgs:

          return []

  

-     cmd = ['mock', '-r', Settings.mock_config, '-qn', '--enable-network',

-            'shell', 'dnf repoquery -q -C --requires --resolve ' +

-            ' '.join(list(set(pkgs)))]

-     Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+     cmd = [

+         "mock",

+         "-r",

+         Settings.mock_config,

+         "-qn",

+         "--enable-network",

+         "shell",

+         "dnf repoquery -q -C --requires --resolve " + " ".join(list(set(pkgs))),

+     ]

+     Settings.get_logger().debug("Running: %s", " ".join(cmd))

      try:

          dnf = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)

      except OSError:
@@ -68,22 +81,28 @@ 

              line = next(dnf.stdout).strip()

          except StopIteration:

              return list(set(deps))

-         name = line.rsplit('.', 2)[0]

-         deps.append(name.rsplit('-', 2)[0])

+         name = line.rsplit(".", 2)[0]

+         deps.append(name.rsplit("-", 2)[0])

  

  

  def list_provides(pkgs):

-     ''' Return list of all provides for named pkgs (scalar or list). '''

+     """ Return list of all provides for named pkgs (scalar or list). """

  

      if not isinstance(pkgs, list):

          pkgs = [pkgs]

      if not pkgs:

          return []

  

-     cmd = ['mock', '-r', Settings.mock_config, '-qn', '--enable-network',

-            'shell', 'dnf repoquery -q -C --provides '

-            + ' '.join(list(set(pkgs)))]

-     Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+     cmd = [

+         "mock",

+         "-r",

+         Settings.mock_config,

+         "-qn",

+         "--enable-network",

+         "shell",

+         "dnf repoquery -q -C --provides " + " ".join(list(set(pkgs))),

+     ]

+     Settings.get_logger().debug("Running: %s", " ".join(cmd))

      try:

          dnf = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)

      except OSError:
@@ -99,7 +118,7 @@ 

  

  

  def resolve(reqs):

-     ''' Return the packages providing the reqs symbols. '''

+     """ Return the packages providing the reqs symbols. """

  

      if not isinstance(reqs, list):

          reqs = [reqs]
@@ -115,10 +134,17 @@ 

  

  

  def resolve_one(req):

-     ''' Return the packages providing the req symbol. '''

-     cmd = ['mock', '-r', Settings.mock_config, '-qn', '--enable-network',

-            'shell', 'dnf repoquery -C --whatprovides "' + req + '"']

-     Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+     """ Return the packages providing the req symbol. """

+     cmd = [

+         "mock",

+         "-r",

+         Settings.mock_config,

+         "-qn",

+         "--enable-network",

+         "shell",

+         'dnf repoquery -C --whatprovides "' + req + '"',

+     ]

+     Settings.get_logger().debug("Running: %s", " ".join(cmd))

  

      try:

          dnf = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
@@ -134,17 +160,17 @@ 

              return list(set(pkgs))

  

          # Skip a line from dnf repoquery that should've gone to stderr

-         if ' metadata ' in line:

+         if " metadata " in line:

              continue

  

-         pkg = line.rsplit('.', 2)[0]

-         pkgs.append(pkg.rsplit('-', 2)[0])

+         pkg = line.rsplit(".", 2)[0]

+         pkgs.append(pkg.rsplit("-", 2)[0])

  

  

  def list_dirs(pkg_filename):

-     ''' Return list of directories in local pkg. '''

+     """ Return list of directories in local pkg. """

  

-     cmd = ['rpm', '-ql', '--dump', '-p', pkg_filename]

+     cmd = ["rpm", "-ql", "--dump", "-p", pkg_filename]

      try:

          rpm = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)

      except OSError:
@@ -167,7 +193,7 @@ 

  

  

  def list_owners(paths):

-     ''' Return list of packages owning paths (single path or list).'''

+     """ Return list of packages owning paths (single path or list)."""

      if not paths:

          return []

      if not isinstance(paths, list):
@@ -176,34 +202,48 @@ 

      owners = []

      paths_to_exam = list(paths)

      for path in paths:

-         p = subprocess.Popen(['mock', '-r', Settings.mock_config, '-qn',

-                               '--enable-network', 'shell',

-                               'rpm --qf %{NAME}\n -qf ' + path],

-                              stdout=subprocess.PIPE,

-                              stderr=subprocess.PIPE,

-                              universal_newlines=True)

+         p = subprocess.Popen(

+             [

+                 "mock",

+                 "-r",

+                 Settings.mock_config,

+                 "-qn",

+                 "--enable-network",

+                 "shell",

+                 "rpm --qf %{NAME}\n -qf " + path,

+             ],

+             stdout=subprocess.PIPE,

+             stderr=subprocess.PIPE,

+             universal_newlines=True,

+         )

          path_owners = p.communicate()[0].split()

          if p.returncode != 0:

              continue

          path_owners = [p.strip() for p in path_owners]

          if path_owners and path_owners[0]:

-             path_owners =  \

-                 [p for p in path_owners if not p.startswith('error:')]

+             path_owners = [p for p in path_owners if not p.startswith("error:")]

          if not path_owners or not path_owners[0]:

              continue

          paths_to_exam.remove(path)

          owners.extend(path_owners)

      for path in paths_to_exam:

-         cmd = ['mock', '-r', Settings.mock_config, '-qn', '--enable-network',

-                'shell', 'dnf repoquery -C --quiet --file ' + path]

-         Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+         cmd = [

+             "mock",

+             "-r",

+             Settings.mock_config,

+             "-qn",

+             "--enable-network",

+             "shell",

+             "dnf repoquery -C --quiet --file " + path,

+         ]

+         Settings.get_logger().debug("Running: %s", " ".join(cmd))

          try:

              lines = check_output(cmd, universal_newlines=True).split()

              lines = [l.strip() for l in lines]

              if not lines or not lines[0]:

                  continue

-             lines = [l.rsplit('.', 2)[0] for l in lines]

-             lines = [l.rsplit('-', 2)[0] for l in lines]

+             lines = [l.rsplit(".", 2)[0] for l in lines]

+             lines = [l.rsplit("-", 2)[0] for l in lines]

              owners.extend(list(set(lines)))

          except subprocess.CalledProcessError:

              Settings.get_logger().error("Cannot run %s", " ".join(cmd))
@@ -212,16 +252,23 @@ 

  

  

  def list_paths(pkgs):

-     ''' Return list of all files in pkgs (single name or list). '''

+     """ Return list of all files in pkgs (single name or list). """

      if not pkgs:

          return []

      if not isinstance(pkgs, list):

          pkgs = [pkgs]

  

-     cmd = ['mock', '-r', Settings.mock_config, '-qn', '--enable-network',

-            'shell', 'dnf repoquery -C -l ' + ' '.join(list(set(pkgs)))]

- 

-     Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+     cmd = [

+         "mock",

+         "-r",

+         Settings.mock_config,

+         "-qn",

+         "--enable-network",

+         "shell",

+         "dnf repoquery -C -l " + " ".join(list(set(pkgs))),

+     ]

+ 

+     Settings.get_logger().debug("Running: %s", " ".join(cmd))

      try:

          paths = check_output(cmd, universal_newlines=True)

      except OSError:
@@ -231,10 +278,10 @@ 

  

  

  def listpaths(pkg_filename):

-     ''' Return lists of files and dirs in local pkg. '''

+     """ Return lists of files and dirs in local pkg. """

  

-     cmd = ['rpm', '-ql', '--dump', '--nosignature', '-p', pkg_filename]

-     Settings.get_logger().debug("Running: %s", ' '.join(cmd))

+     cmd = ["rpm", "-ql", "--dump", "--nosignature", "-p", pkg_filename]

+     Settings.get_logger().debug("Running: %s", " ".join(cmd))

      try:

          rpm = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)

      except OSError:
@@ -260,14 +307,14 @@ 

  

  

  class Deps(object):

-     ''' Models the dependencies. '''

+     """ Models the dependencies. """

  

      def list_owners(self, path):

-         ''' Return possobly empty list of owners to path. '''

+         """ Return possobly empty list of owners to path. """

          pass

  

      def get_spec(self, pkg):

-         ''' Return a Spec object for a given dependency pkg.'''

+         """ Return a Spec object for a given dependency pkg."""

          pass

  

  

@@ -1,7 +1,7 @@ 

  # See: https://bugzilla.redhat.com/show_bug.cgi?id=675140#c1

  # From: https://people.redhat.com/mikeb/scripts/download-scratch.py

  

- ''' Download a scrath build from koji. '''

+ """ Download a scrath build from koji. """

  

  from __future__ import print_function

  import optparse
@@ -11,105 +11,122 @@ 

  import urlgrabber

  import urlgrabber.progress

  

- BASEURL = 'https://kojipkgs.fedoraproject.org/work/'

- HUBURL = 'https://koji.fedoraproject.org/kojihub'

+ BASEURL = "https://kojipkgs.fedoraproject.org/work/"

+ HUBURL = "https://koji.fedoraproject.org/kojihub"

  

  

  def _do_download(task, session, opts):

-     ''' Perform download of a single task. '''

+     """ Perform download of a single task. """

  

      if opts.arches:

-         print('Downloading %s rpms from task %i: %s'

-               % (', '.join(opts.arches), task['id'], koji.taskLabel(task)))

+         print(

+             "Downloading %s rpms from task %i: %s"

+             % (", ".join(opts.arches), task["id"], koji.taskLabel(task))

+         )

      else:

-         print('Downloading rpms from task %i: %s'

-               % (task['id'], koji.taskLabel(task)))

-     base_path = koji.pathinfo.taskrelpath(task['id'])

-     output = session.listTaskOutput(task['id'])

+         print("Downloading rpms from task %i: %s" % (task["id"], koji.taskLabel(task)))

+     base_path = koji.pathinfo.taskrelpath(task["id"])

+     output = session.listTaskOutput(task["id"])

      prog_meter = urlgrabber.progress.TextMeter()

      if output == []:

          print("This build is empty, no files to download")

          sys.exit(1)

      for filename in output:

-         if opts.nologs and filename.endswith('log'):

+         if opts.nologs and filename.endswith("log"):

              continue

-         elif filename.endswith('.rpm'):

+         elif filename.endswith(".rpm"):

              if opts.arches:

-                 arch = filename.rsplit('.', 3)[2]

+                 arch = filename.rsplit(".", 3)[2]

                  if arch not in opts.arches:

                      continue

-             if 'debuginfo' in filename and opts.nodebug:

+             if "debuginfo" in filename and opts.nodebug:

                  continue

-         what = opts.baseurl + base_path + '/' + filename

+         what = opts.baseurl + base_path + "/" + filename

          urlgrabber.grabber.urlgrab(what, progress_obj=prog_meter)

  

  

  def _download_scratch_rpms(parser, task_ids, opts):

-     ''' Given build id, tasks and CLI options download build results

-     to current dir. '''

+     """ Given build id, tasks and CLI options download build results

+     to current dir. """

  

      if not os.access(os.getcwd(), os.R_OK | os.W_OK | os.X_OK):

-         raise IOError("Insufficient permissons for current directory."

-                       " Aborting download")

+         raise IOError(

+             "Insufficient permissons for current directory." " Aborting download"

+         )

      session = koji.ClientSession(opts.huburl)

      for task_id in task_ids:

          task = session.getTaskInfo(task_id, request=True)

          if not task:

-             parser.error('Invalid task ID: %i' % task_id)

-         elif task['state'] in (koji.TASK_STATES['FREE'],

-                                koji.TASK_STATES['OPEN']):

-             parser.error('Task %i has not completed' % task['id'])

-         elif task['state'] != koji.TASK_STATES['CLOSED']:

-             parser.error('Task %i did not complete successfully' % task['id'])

- 

-         if task['method'] == 'build':

-             print('Getting rpms from children of task %i: %s'

-                   % (task['id'], koji.taskLabel(task)))

-             task_opts = {'parent': task_id,

-                          'method': 'buildArch',

-                          'state': [koji.TASK_STATES['CLOSED']],

-                          'decode': True}

+             parser.error("Invalid task ID: %i" % task_id)

+         elif task["state"] in (koji.TASK_STATES["FREE"], koji.TASK_STATES["OPEN"]):

+             parser.error("Task %i has not completed" % task["id"])

+         elif task["state"] != koji.TASK_STATES["CLOSED"]:

+             parser.error("Task %i did not complete successfully" % task["id"])

+ 

+         if task["method"] == "build":

+             print(

+                 "Getting rpms from children of task %i: %s"

+                 % (task["id"], koji.taskLabel(task))

+             )

+             task_opts = {

+                 "parent": task_id,

+                 "method": "buildArch",

+                 "state": [koji.TASK_STATES["CLOSED"]],

+                 "decode": True,

+             }

              tasks = session.listTasks(opts=task_opts)

-         elif task['method'] == 'buildArch':

+         elif task["method"] == "buildArch":

              tasks = [task]

          else:

-             parser.error('Task %i is not a build or buildArch task'

-                          % task['id'])

+             parser.error("Task %i is not a build or buildArch task" % task["id"])

          for task in tasks:

              _do_download(task, session, opts)

  

  

  def main():

-     ''' Main public entry. '''

+     """ Main public entry. """

  

-     usage = 'usage: %prog [options] task-ID [task-ID...]'

+     usage = "usage: %prog [options] task-ID [task-ID...]"

      parser = optparse.OptionParser(usage=usage)

      parser.add_option(

-         '--arch', action='append', dest='arches', metavar='ARCH', default=[],

-         help='Only download packages of the given arch '

-         '(may be specified multiple times)')

+         "--arch",

+         action="append",

+         dest="arches",

+         metavar="ARCH",

+         default=[],

+         help="Only download packages of the given arch "

+         "(may be specified multiple times)",

+     )

      parser.add_option(

-         '--huburl', '-u', default=HUBURL,

-         help='URL of Koji hub (default: %default)')

+         "--huburl", "-u", default=HUBURL, help="URL of Koji hub (default: %default)"

+     )

      parser.add_option(

-         '--baseurl', '-b', default=BASEURL,

-         help='Base URL for downloading RPMs  (default: %default)')

-     parser.add_option('--nologs', '-l', action='store_true',

-                       help='Do not download build logs')

-     parser.add_option('--nodebug', '-d', action='store_true',

-                       help='Do not download debuginfo packages')

+         "--baseurl",

+         "-b",

+         default=BASEURL,

+         help="Base URL for downloading RPMs  (default: %default)",

+     )

+     parser.add_option(

+         "--nologs", "-l", action="store_true", help="Do not download build logs"

+     )

+     parser.add_option(

+         "--nodebug",

+         "-d",

+         action="store_true",

+         help="Do not download debuginfo packages",

+     )

  

      opts, args = parser.parse_args()

      if not args:

-         parser.error('At least one task ID must be specified')

+         parser.error("At least one task ID must be specified")

      for task_id in args:

          if not task_id.isdigit():

-             parser.error('%s is not an integer task ID' % task_id)

+             parser.error("%s is not an integer task ID" % task_id)

  

      _download_scratch_rpms(parser, [int(tid) for tid in args], opts)

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      main()

  

  

@@ -15,20 +15,20 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''  EL6+ compatibility layer '''

+ """  EL6+ compatibility layer """

  

  import sys

  

- if sys.version < '2.7':

+ if sys.version < "2.7":

+ 

      def check_output(*popenargs, **kwargs):

          """Run command with arguments and return its output as a byte

          string.  Backported from Python 2.7.

          See https://gist.github.com/1027906

          """

          import subprocess

-         process = subprocess.Popen(stdout=subprocess.PIPE,

-                                    *popenargs,

-                                    **kwargs)

+ 

+         process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)

          output = process.communicate()[0]

          retcode = process.poll()

          if retcode:
@@ -39,7 +39,9 @@ 

              error.output = output

              raise error

          return output

+ 

+ 

  else:

-     from subprocess import check_output          # pylint: disable=E0611,W0611

+     from subprocess import check_output  # pylint: disable=E0611,W0611

  

  # vim: set expandtab ts=4 sw=4:

@@ -16,9 +16,9 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  import logging

  import os.path
@@ -32,14 +32,14 @@ 

  

  

  class DownloadError(ReviewError):

-     ''' Error in urlretrieve(). '''

+     """ Error in urlretrieve(). """

+ 

      def __init__(self, code, url):

-         ReviewError.__init__(

-             self, "Error {} downloading {}".format(code, url))

+         ReviewError.__init__(self, "Error {} downloading {}".format(code, url))

  

  

  class HelpersMixin(object):

-     ''' Miscellaneous library support mixin class. '''

+     """ Miscellaneous library support mixin class. """

  

      def __init__(self):

          try:
@@ -47,45 +47,46 @@ 

          except AttributeError:

              pass

  

-     def _run_cmd(self, cmd, header='Run command'):

-         ''' Run a command using using subprocess, return output. '''

-         self.log.debug(header + ': ' + cmd)

-         cmd = cmd.split(' ')

+     def _run_cmd(self, cmd, header="Run command"):

+         """ Run a command using using subprocess, return output. """

+         self.log.debug(header + ": " + cmd)

+         cmd = cmd.split(" ")

          proc = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)

-         output, error = '', 'undefined'

+         output, error = "", "undefined"

          try:

              output, error = proc.communicate()

          except OSError as e:

              self.log.debug("OS error, stderr: %s", error, exc_info=True)

-             self.log.error("OS error running %s %s", ' '.join(cmd), str(e))

+             self.log.error("OS error running %s %s", " ".join(cmd), str(e))

          return output

  

      @staticmethod

      def _checksum(path):

-         ''' get the checksum for a path using algorithm set by configuration

+         """ get the checksum for a path using algorithm set by configuration

          (default: md5)

  

          :arg path: the path to get the the checksum for

          :return: checksum

-         '''

+         """

          ck = hashlib.new(Settings.checksum)

-         with open(path, 'rb') as f:

-             for chunk in iter(lambda: f.read(8192), b''):

+         with open(path, "rb") as f:

+             for chunk in iter(lambda: f.read(8192), b""):

                  ck.update(chunk)

          return ck.hexdigest()

  

      @staticmethod

      def urlretrieve(url, path):

-         ''' Similar to urllib.urlretrieve, raises DownloadError. '''

+         """ Similar to urllib.urlretrieve, raises DownloadError. """

          try:

              # we need to timeout eventually if there are problems

              import socket

+ 

              socket.setdefaulttimeout(30)

  

              istream = FancyURLopener().open(url)

              if istream.getcode() and istream.getcode() != 200:

                  raise DownloadError(istream.getcode(), url)

-             with open(path, 'wb') as ostream:

+             with open(path, "wb") as ostream:

                  octets = istream.read(32767)

                  while octets:

                      ostream.write(octets)
@@ -94,13 +95,13 @@ 

              raise DownloadError(str(err), url)

  

      def _get_file(self, link, directory, logger=None):

-         ''' Download a file in link to directory. '''

-         fname = link.rsplit('/', 1)[1]

+         """ Download a file in link to directory. """

+         fname = link.rsplit("/", 1)[1]

          path = os.path.join(directory, fname)

          if os.path.exists(path) and Settings.cache:

              if logger:

                  logger(True)

-             logging.debug('Using cached source: %s', fname)

+             logging.debug("Using cached source: %s", fname)

              return path

          self.log.debug("  --> %s : %s", directory, link)

          if logger:
@@ -114,15 +115,19 @@ 

          Unpack archive in extract_dir. Returns true if

          from subprocess.call() returns 0

          """

-         cmd = 'rpmdev-extract -qC ' + extract_dir + ' ' + archive

-         cmd += ' &>/dev/null'

+         cmd = "rpmdev-extract -qC " + extract_dir + " " + archive

+         cmd += " &>/dev/null"

          p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True)

          stdout, stderr = p.communicate()

          if p.returncode != 0:

              log = Settings.get_logger()

              log.debug("Cannot unpack %s", archive)

-             log.debug("Status: %d, stdout: %s, stderr: %s.",

-                       p.returncode, str(stdout), str(stderr))

+             log.debug(

+                 "Status: %d, stdout: %s, stderr: %s.",

+                 p.returncode,

+                 str(stdout),

+                 str(stderr),

+             )

          return p.returncode == 0

  

      @staticmethod
@@ -133,23 +138,23 @@ 

          reflected in errmsg. If not ok and msg == None parsing

          is ok but there are warnings/errors"""

  

-         problems = re.compile(r'(\d+)\serrors\,\s(\d+)\swarnings')

-         lines = out.split('\n')[:-1]

-         err_lines = [l for l in lines if l.lower().find('error') != -1]

+         problems = re.compile(r"(\d+)\serrors\,\s(\d+)\swarnings")

+         lines = out.split("\n")[:-1]

+         err_lines = [l for l in lines if l.lower().find("error") != -1]

          if not err_lines:

-             Settings.get_logger().debug('Cannot parse rpmlint output: %s', out)

-             return False, 'Cannot parse rpmlint output:'

+             Settings.get_logger().debug("Cannot parse rpmlint output: %s", out)

+             return False, "Cannot parse rpmlint output:"

  

          res = problems.search(err_lines[-1])

          if res and len(res.groups()) == 2:

              errors, warnings = res.groups()

-             if errors == '0' and warnings == '0':

+             if errors == "0" and warnings == "0":

                  return True, None

  

              return False, None

  

-         log.debug('Cannot parse rpmlint output: ' + out)

-         return False, 'Cannot parse rpmlint output:'

+         log.debug("Cannot parse rpmlint output: " + out)

+         return False, "Cannot parse rpmlint output:"

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+196 -184
@@ -16,9 +16,9 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  import logging

  import os
@@ -30,7 +30,7 @@ 

  from subprocess import call, Popen, PIPE, STDOUT, CalledProcessError

  

  try:

-     from subprocess import check_output          # pylint: disable=E0611

+     from subprocess import check_output  # pylint: disable=E0611

  except ImportError:

      from FedoraReview.el_compat import check_output

  
@@ -40,78 +40,86 @@ 

  from .review_error import ReviewError

  

  

- _RPMLINT_SCRIPT = " mock  @config@ --chroot " \

+ _RPMLINT_SCRIPT = (

+     " mock  @config@ --chroot "

      """ "echo 'rpmlint:'; rpmlint @rpm_names@; echo 'rpmlint-done:'" """

+ )

  

  

  def _run_script(script):

      """ Run a script,  return (ok, output). """

      try:

-         p = Popen(script, stdout=PIPE, stderr=STDOUT, shell=True, universal_newlines=True)

+         p = Popen(

+             script, stdout=PIPE, stderr=STDOUT, shell=True, universal_newlines=True

+         )

          output, error = p.communicate()

      except OSError as e:

-         return False, e.strerror + ' stderr: ' + error

+         return False, e.strerror + " stderr: " + error

      return True, output

  

  

  def _get_tag(paths):

-     ''' Return common disttag from prebuilt files, possibly "" '''

+     """ Return common disttag from prebuilt files, possibly "" """

      if not paths:

-         return ''

-     releases = [p.rsplit('-', 2)[2] for p in paths]

-     releases = [r.rsplit('.', 2)[0] for r in releases]

+         return ""

+     releases = [p.rsplit("-", 2)[2] for p in paths]

+     releases = [r.rsplit(".", 2)[0] for r in releases]

      if not len(set(releases)) == 1:

          return ""

-     match = re.search('(fc|el)[0-9][0-9]', releases[0])

-     return match.group() if match else ''

+     match = re.search("(fc|el)[0-9][0-9]", releases[0])

+     return match.group() if match else ""

  

  

  def _get_tag_from_flags(self, flags):

-     ''' Retrieve disttag from user defined flag value. '''

-     if flags['DISTTAG']:

+     """ Retrieve disttag from user defined flag value. """

+     if flags["DISTTAG"]:

          self.log.info("Using disttag from DISTTAG flag.")

-         return flags['DISTTAG'].value

-     self.log.warning('No disttag found in prebuilt packages')

-     self.log.info('Use --define DISTTAG to set proper dist.'

-                   ' e. g. --define DISTTAG fc21.')

-     raise ReviewError('No disttag in package and no DISTTAG flag.'

-                       ' Use --define DISTTAG to set proper dist'

-                       ' e. g., --define DISTTAG=fc21.')

+         return flags["DISTTAG"].value

+     self.log.warning("No disttag found in prebuilt packages")

+     self.log.info(

+         "Use --define DISTTAG to set proper dist." " e. g. --define DISTTAG fc21."

+     )

+     raise ReviewError(

+         "No disttag in package and no DISTTAG flag."

+         " Use --define DISTTAG to set proper dist"

+         " e. g., --define DISTTAG=fc21."

+     )

  

  

  def _add_disttag_macros(macros, tag):

-     ''' Add macros derived from disttag. '''

-     if tag.startswith('el'):

-         macros['%epel'] = tag[2:]

-         macros['%fedora'] = '%fedora'

+     """ Add macros derived from disttag. """

+     if tag.startswith("el"):

+         macros["%epel"] = tag[2:]

+         macros["%fedora"] = "%fedora"

      else:

-         macros['%fedora'] = tag[2:]

-         macros['%epel'] = '%epel'

-     macros['%dist'] = '.' + tag

+         macros["%fedora"] = tag[2:]

+         macros["%epel"] = "%epel"

+     macros["%dist"] = "." + tag

      return macros

  

  

  def _add_buildarch_macros(macros, paths):

-     ''' Add macros derived from buildarch. '''

+     """ Add macros derived from buildarch. """

      if not paths:

-         return '', macros

-     arches = [p.rsplit('.', 2)[1] for p in paths]

-     if set(arches) == {'noarch'}:

-         buildarch = 'noarch'

+         return "", macros

+     arches = [p.rsplit(".", 2)[1] for p in paths]

+     if set(arches) == {"noarch"}:

+         buildarch = "noarch"

      else:

-         buildarch = [a for a in arches if a != 'noarch'][0]

-     macros['%buildarch'] = buildarch

-     if buildarch == 'x86_64':

-         macros['%_libdir'] = '/usr/lib64'

-         macros['%_isa'] = '(x86-64)'

+         buildarch = [a for a in arches if a != "noarch"][0]

+     macros["%buildarch"] = buildarch

+     if buildarch == "x86_64":

+         macros["%_libdir"] = "/usr/lib64"

+         macros["%_isa"] = "(x86-64)"

      else:

-         macros['%_libdir'] = '/usr/lib'

-         macros['%_isa'] = '(x86-32)'

+         macros["%_libdir"] = "/usr/lib"

+         macros["%_isa"] = "(x86-32)"

      return buildarch, macros

  

  

  class _Mock(HelpersMixin):

      """ Some basic operations on the mock chroot env, a singleton. """

+ 

      # pylint: disable=R0904

  

      def __init__(self):
@@ -124,8 +132,8 @@ 

          self._macros = None

  

      def _get_default_macros(self):

-         ''' Evaluate macros using rpm in mock. '''

-         tags = '%dist %fedora %epel %buildarch %_libdir %_isa %arch'

+         """ Evaluate macros using rpm in mock. """

+         tags = "%dist %fedora %epel %buildarch %_libdir %_isa %arch"

          macros = {}

          values = self._rpm_eval(tags).split()

          taglist = tags.split()
@@ -134,56 +142,64 @@ 

          return macros

  

      def _get_prebuilt_macros(self, spec, flags):

-         ''' Evaluate macros based on prebuilt packages (#208).'''

+         """ Evaluate macros based on prebuilt packages (#208)."""

  

          paths = self.get_package_rpm_paths(spec)

          tag = _get_tag(paths)

-         if not tag.startswith(('fc', 'el')):

+         if not tag.startswith(("fc", "el")):

              tag = _get_tag_from_flags(self, flags)

          macros = _add_disttag_macros({}, tag)

          buildarch, macros = _add_buildarch_macros(macros, paths)

          try:

-             _arch = check_output('rpm --eval %_arch'.split(), universal_newlines=True).strip()

+             _arch = check_output(

+                 "rpm --eval %_arch".split(), universal_newlines=True

+             ).strip()

          except CalledProcessError:

              raise ReviewError("Can't evaluate 'rpm --eval %_arch")

-         if buildarch == 'x86_64' and _arch != 'x86_64':

+         if buildarch == "x86_64" and _arch != "x86_64":

              raise ReviewError("Can't build x86_64 on i86 host")

          return macros

  

      def _get_root(self):

-         ''' Return mock's root according to Settings. '''

-         config = 'default'

+         """ Return mock's root according to Settings. """

+         config = "default"

          if Settings.mock_config:

              config = Settings.mock_config

-         mockdir = Settings.configdir if Settings.configdir \

-             else '/etc/mock'

-         path = os.path.join(mockdir, config + '.cfg') \

-             if not config.endswith('.cfg') \

+         mockdir = Settings.configdir if Settings.configdir else "/etc/mock"

+         path = (

+             os.path.join(mockdir, config + ".cfg")

+             if not config.endswith(".cfg")

              else os.path.join(mockdir, config)

+         )

  

          config_opts = {}

          with open(path) as f:

              content = f.read()

-             content = re.sub(r'include\((.*)\)',

-                              r'exec(open(\g<1>).read(), {}, locals())',

-                              content)

-             content = [line for line in content.splitlines() if

-                       line.find("config_opts['root']") >= 0]

-             config = compile(content[0], path, 'exec')

+             content = re.sub(

+                 r"include\((.*)\)", r"exec(open(\g<1>).read(), {}, locals())", content

+             )

+             content = [

+                 line

+                 for line in content.splitlines()

+                 if line.find("config_opts['root']") >= 0

+             ]

+             config = compile(content[0], path, "exec")

          exec(config)

-         self.mock_root = config_opts['root']

+         self.mock_root = config_opts["root"]

          if Settings.uniqueext:

              self.mock_root += Settings.uniqueext

  

-         if 'rawhide' not in self.mock_root:

-             self.log.info('WARNING: Probably non-rawhide buildroot used. ' +

-                           'Rawhide should be used for most package reviews')

+         if "rawhide" not in self.mock_root:

+             self.log.info(

+                 "WARNING: Probably non-rawhide buildroot used. "

+                 + "Rawhide should be used for most package reviews"

+             )

  

      def _get_dir(self, subdir=None):

-         ''' Return a directory under root, try to create if non-existing. '''

+         """ Return a directory under root, try to create if non-existing. """

          if not self.mock_root:

              self._get_root()

-         p = os.path.join('/var/lib/mock', self.mock_root)

+         p = os.path.join("/var/lib/mock", self.mock_root)

          p = os.path.join(p, subdir) if subdir else p

          if not os.path.exists(p):

              try:
@@ -193,29 +209,28 @@ 

          return p

  

      def _get_rpmlint_output(self):

-         ''' Return output from last rpmlint, list of lines. '''

+         """ Return output from last rpmlint, list of lines. """

          if not self._rpmlint_output:

-             if os.path.exists('rpmlint.txt'):

-                 with open('rpmlint.txt') as f:

+             if os.path.exists("rpmlint.txt"):

+                 with open("rpmlint.txt") as f:

                      self._rpmlint_output = f.readlines()

          return self._rpmlint_output

  

      def _mock_cmd(self):

-         ''' Return mock +  default options, a list of strings. '''

+         """ Return mock +  default options, a list of strings. """

          cmd = ["mock"]

          if Settings.mock_config:

-             cmd.extend(['-r', Settings.mock_config])

+             cmd.extend(["-r", Settings.mock_config])

          cmd.extend(shlex.split(self.get_mock_options()))

          return cmd

  

-     def _run_cmd(self, cmd, header='Mock'):

- 

+     def _run_cmd(self, cmd, header="Mock"):

          def log_text(out, err):

-             ''' Format stdout + stderr. '''

-             return header + " output: " + str(out) + ' ' + str(err)

+             """ Format stdout + stderr. """

+             return header + " output: " + str(out) + " " + str(err)

  

          header = header if header else ""

-         self.log.debug(header + ' command: ' + ', '.join(cmd))

+         self.log.debug(header + " command: " + ", ".join(cmd))

          try:

              p = Popen(cmd, stdout=PIPE, stderr=STDOUT, universal_newlines=True)

              output, error = p.communicate()
@@ -224,32 +239,32 @@ 

              logging.error("Command failed", exc_info=True)

              return "Command utterly failed. See logs for details"

          if p.returncode != 0 and header:

-             logging.info("%s command returned error code %i",

-                          header, p.returncode)

+             logging.info("%s command returned error code %i", header, p.returncode)

          return None if p.returncode == 0 else str(output)

  

      def _get_topdir(self):

-         ''' Update _topdir to reflect %_topdir in current mock config. '''

+         """ Update _topdir to reflect %_topdir in current mock config. """

          if self._topdir:

              return

          cmd = self._mock_cmd()

-         cmd.extend(['-q', '--chroot', '--', 'rpm --eval %_topdir'])

+         cmd.extend(["-q", "--chroot", "--", "rpm --eval %_topdir"])

          try:

              self._topdir = check_output(cmd, universal_newlines=True).strip()

              self.log.debug("_topdir: %s", str(self._topdir))

          except (CalledProcessError, OSError):

-             self.log.info("Cannot evaluate %topdir in mock, using"

-                           " hardcoded /builddir/build")

-             self._topdir = '/builddir/build'

+             self.log.info(

+                 "Cannot evaluate %topdir in mock, using" " hardcoded /builddir/build"

+             )

+             self._topdir = "/builddir/build"

  

      def _clear_rpm_db(self):

          """ Mock install uses host's dnf -> bad rpm database. """

          cmd = self._mock_cmd()

-         cmd.extend(['--shell', "'rm -f /var/lib/rpm/__db*'"])

+         cmd.extend(["--shell", "'rm -f /var/lib/rpm/__db*'"])

          self._run_cmd(cmd, None)

  

      def _get_rpm_paths(self, pattern):

-         ''' Return paths matching a rpm name pattern. '''

+         """ Return paths matching a rpm name pattern. """

          if Settings.prebuilt:

              paths = glob(os.path.join(ReviewDirs.startdir, pattern))

          else:
@@ -257,12 +272,12 @@ 

          return paths

  

      def _rpm_eval(self, arg):

-         ''' Run rpm --eval <arg> inside mock, return output. '''

+         """ Run rpm --eval <arg> inside mock, return output. """

          cmd = self._mock_cmd()

-         cmd.extend(['--quiet', '--chroot', '--', 'rpm --eval "' + arg + '"'])

+         cmd.extend(["--quiet", "--chroot", "--", 'rpm --eval "' + arg + '"'])

          return check_output(cmd, universal_newlines=True).strip()

  

- # Last (cached?) output from rpmlint, list of lines.

+     # Last (cached?) output from rpmlint, list of lines.

      rpmlint_output = property(_get_rpmlint_output)

  

      # The directory where mock leaves built rpms and logs
@@ -273,7 +288,7 @@ 

  

      @property

      def buildroot(self):

-         ''' Return path to current buildroot' '''

+         """ Return path to current buildroot' """

          if not self.mock_root:

              self._get_root()

          return self.mock_root
@@ -283,45 +298,44 @@ 

          if self.mock_root:

              self.mock_root = None

  

-     def get_resultdir(self):                     # pylint: disable=R0201

-         ''' Return resultdir used by mock. '''

+     def get_resultdir(self):  # pylint: disable=R0201

+         """ Return resultdir used by mock. """

          if Settings.resultdir:

              return Settings.resultdir

  

          return ReviewDirs.results

  

      def get_package_rpm_path(self, nvr):

-         '''

+         """

          Return path to generated pkg_name rpm, throws ReviewError

          on missing or multiple matches. Argument should have

          have name, version and release attributes.

-         '''

-         pattern = '{}-{}*'.format(nvr.name, nvr.version)

+         """

+         pattern = "{}-{}*".format(nvr.name, nvr.version)

          paths = self._get_rpm_paths(pattern)

-         paths = [p for p in paths if p.endswith('.rpm') and

-                  not p.endswith('.src.rpm')]

+         paths = [p for p in paths if p.endswith(".rpm") and not p.endswith(".src.rpm")]

          if not paths:

-             raise ReviewError('No built package found for ' + nvr.name)

+             raise ReviewError("No built package found for " + nvr.name)

          elif len(paths) > 1:

-             raise ReviewError('Multiple packages found for ' + nvr.name)

+             raise ReviewError("Multiple packages found for " + nvr.name)

          else:

              return paths[0]

  

      def get_package_rpm_paths(self, spec, with_srpm=False):

-         '''

+         """

          Return a list of paths to binary rpms corresponding to

          the packages generated by given spec.

-         '''

+         """

  

          def get_package_srpm_path(spec):

-             ''' Return path to srpm given a spec. '''

-             pattern = '*{}-{}*'.format(spec.name, spec.version)

+             """ Return path to srpm given a spec. """

+             pattern = "*{}-{}*".format(spec.name, spec.version)

              paths = self._get_rpm_paths(pattern)

-             paths = [p for p in paths if p.endswith('.src.rpm')]

+             paths = [p for p in paths if p.endswith(".src.rpm")]

              if not paths:

-                 raise ReviewError('No srpm found for ' + spec.name)

+                 raise ReviewError("No srpm found for " + spec.name)

              elif len(paths) > 1:

-                 raise ReviewError('Multiple srpms found for ' + spec.name)

+                 raise ReviewError("Multiple srpms found for " + spec.name)

              else:

                  return paths[0]

  
@@ -334,8 +348,8 @@ 

          return result

  

      def get_package_debuginfo_paths(self, nvr):

-         ''' Return paths to debuginfo rpms for given nvr.  '''

-         pattern = '{}-*debuginfo*-{}-*'.format(nvr.name, nvr.version)

+         """ Return paths to debuginfo rpms for given nvr.  """

+         pattern = "{}-*debuginfo*-{}-*".format(nvr.name, nvr.version)

          return self._get_rpm_paths(pattern)

  

      def get_builddir(self, subdir=None):
@@ -343,67 +357,66 @@ 

          mock. Optional subdir argument is added to returned path.

          """

          self._get_topdir()

-         p = self._get_dir(os.path.join('root', self._topdir[1:]))

+         p = self._get_dir(os.path.join("root", self._topdir[1:]))

          return os.path.join(p, subdir) if subdir else p

  

      def get_macro(self, macro, spec, flags):

-         ''' Return value of one of the system-defined rpm macros. '''

+         """ Return value of one of the system-defined rpm macros. """

          if not self._macros:

              if Settings.prebuilt:

                  self._macros = self._get_prebuilt_macros(spec, flags)

              else:

                  self._macros = self._get_default_macros()

-         key = macro if macro.startswith('%') else '%' + macro

+         key = macro if macro.startswith("%") else "%" + macro

          return self._macros[key] if key in self._macros else macro

  

      @staticmethod

      def get_mock_options():

          """ --mock-config option, with a guaranteed ---'resultdir' part

          """

-         if not hasattr(Settings, 'mock_options'):

-             return ''

+         if not hasattr(Settings, "mock_options"):

+             return ""

          opt = Settings.mock_options

          if not opt:

-             opt = ''

-         if 'resultdir' not in opt:

-             opt += ' --resultdir=' + ReviewDirs.results + ' '

+             opt = ""

+         if "resultdir" not in opt:

+             opt += " --resultdir=" + ReviewDirs.results + " "

          return opt

  

      def clear_builddir(self):

-         ''' Remove all sources installed in BUILD. '''

+         """ Remove all sources installed in BUILD. """

          cmd = self._mock_cmd()

-         cmd += ['--chroot', '--']

-         cmd.append('rm -rf $(rpm --eval %_builddir)/*')

+         cmd += ["--chroot", "--"]

+         cmd.append("rm -rf $(rpm --eval %_builddir)/*")

          errmsg = self._run_cmd(cmd)

          if errmsg:

-             self.log.debug('Cannot clear build area: %s (ignored)', errmsg)

+             self.log.debug("Cannot clear build area: %s (ignored)", errmsg)

          return None

  

      @staticmethod

      def is_available():

-         ''' Test if mock command is installed and usable. '''

+         """ Test if mock command is installed and usable. """

          try:

-             check_output(['mock', '--version'])

+             check_output(["mock", "--version"])

              return True

          except (CalledProcessError, OSError):

              return False

  

      def is_installed(self, package):

-         ''' Return true iff package is installed in mock chroot. '''

+         """ Return true iff package is installed in mock chroot. """

          cmd = self._mock_cmd()

-         cmd += ('--chroot', '--')

+         cmd += ("--chroot", "--")

          cmd.append('"rpm -q ' + package + '" &>/dev/null')

-         cmd = ' '.join(cmd)

+         cmd = " ".join(cmd)

          rc = call(cmd, shell=True)

-         self.log.debug('is_installed: Tested ' + package +

-                        ', result: ' + str(rc))

+         self.log.debug("is_installed: Tested " + package + ", result: " + str(rc))

          return rc == 0

  

      def rpmbuild_bp(self, srpm):

          """ Try to rebuild the sources from srpm. """

  

          cmd = self._mock_cmd()

-         cmd.append('--copyin')

+         cmd.append("--copyin")

          cmd.append(srpm.filename)

          cmd.append(os.path.basename(srpm.filename))

          errmsg = self._run_cmd(cmd)
@@ -411,16 +424,16 @@ 

              self.log.warning("Cannot run mock --copyin: %s", errmsg)

              return errmsg

          cmd = self._mock_cmd()

-         cmd += ['--chroot', '--']

-         script = 'rpm -i ' + os.path.basename(srpm.filename) + '; '

-         script += 'rpmbuild --nodeps -bp $(rpm --eval %_specdir)/' \

-                   + srpm.name + '.spec;'

-         script += 'chmod -R  go+r  $(rpm --eval %_builddir)/* || :'

+         cmd += ["--chroot", "--"]

+         script = "rpm -i " + os.path.basename(srpm.filename) + "; "

+         script += (

+             "rpmbuild --nodeps -bp $(rpm --eval %_specdir)/" + srpm.name + ".spec;"

+         )

+         script += "chmod -R  go+r  $(rpm --eval %_builddir)/* || :"

          cmd.append(script)

          errmsg = self._run_cmd(cmd)

          if errmsg:

-             self.log.warning("Cannot run mock --chroot rpmbuild -bp: %s",

-                              errmsg)

+             self.log.warning("Cannot run mock --chroot rpmbuild -bp: %s", errmsg)

              return errmsg

          return None

  
@@ -432,31 +445,30 @@ 

          """

          self.clear_builddir()

          mock_cmd = ['"' + s + '"' for s in self._mock_cmd()]

-         cmd = ' '.join(mock_cmd)

+         cmd = " ".join(mock_cmd)

          if Settings.log_level > logging.INFO:

-             cmd += ' -q'

-         cmd += ' --rebuild'

-         cmd += ' ' + filename + ' 2>&1 | tee build.log'

-         if not Settings.verbose and ' -q' not in cmd:

+             cmd += " -q"

+         cmd += " --rebuild"

+         cmd += " " + filename + " 2>&1 | tee build.log"

+         if not Settings.verbose and " -q" not in cmd:

              cmd += ' | egrep "Results and/or logs|ERROR" '

-         self.log.debug('Build command: %s', cmd)

+         self.log.debug("Build command: %s", cmd)

          rc = call(cmd, shell=True)

          self.builddir_cleanup()

          rc = str(rc)

          try:

-             with open('build.log') as f:

-                 log = '\n'.join(f.readlines())

-                 if 'ERROR' in log:

-                     rc = 'Build error(s)'

+             with open("build.log") as f:

+                 log = "\n".join(f.readlines())

+                 if "ERROR" in log:

+                     rc = "Build error(s)"

          except IOError:

              rc = "Can't open logfile"

-         if rc == '0':

-             self.log.info('Build completed')

+         if rc == "0":

+             self.log.info("Build completed")

              return None

          else:

-             self.log.debug('Build failed rc = %s', rc)

-             error = ReviewError('mock build failed, see %s/build.log' %

-                                 self.resultdir)

+             self.log.debug("Build failed rc = %s", rc)

+             error = ReviewError("mock build failed, see %s/build.log" % self.resultdir)

              error.show_logs = False

              raise error

  
@@ -466,23 +478,23 @@ 

          return None if OK, else the stdout+stderr

          """

  

-         def log_text(out, err):                  # pylint: disable=W0612

-             ''' Log message + default prefix. '''

-             return "Install output: " + str(out) + ' ' + str(err)

+         def log_text(out, err):  # pylint: disable=W0612

+             """ Log message + default prefix. """

+             return "Install output: " + str(out) + " " + str(err)

  

          def is_not_installed(package):

-             ''' Test if package (path or name) isn't installed. '''

+             """ Test if package (path or name) isn't installed. """

              p = package

              if os.path.exists(p):

-                 p = os.path.basename(p).rsplit('-', 2)[0]

+                 p = os.path.basename(p).rsplit("-", 2)[0]

              if self.is_installed(p):

-                 self.log.debug('Skipping already installed: %s', p)

+                 self.log.debug("Skipping already installed: %s", p)

                  return False

              return True

  

          cmd = self._mock_cmd()

-         cmd.append('--init')

-         self._run_cmd(cmd, '--init')

+         cmd.append("--init")

+         self._run_cmd(cmd, "--init")

          cmd = self._mock_cmd()

          rpms = [p for p in set(packages) if is_not_installed(p)]

          if not rpms:
@@ -492,28 +504,28 @@ 

          cmd = self._mock_cmd()

          cmd.append("install")

          cmd.extend(rpms)

-         return self._run_cmd(cmd, 'Install')

+         return self._run_cmd(cmd, "Install")

  

      def init(self, force=False):

          """ Run a mock --init command. """

          if not force:

              try:

-                 self._rpm_eval('%{_libdir}')

+                 self._rpm_eval("%{_libdir}")

                  self.log.debug("Avoiding init of working mock root")

                  return

              except (CalledProcessError, OSError):

                  pass

              self.log.info("Re-initializing mock build root")

          cmd = ["mock"]

-         if hasattr(Settings, 'mock_config') and Settings.mock_config:

-             cmd.extend(['-r', Settings.mock_config])

+         if hasattr(Settings, "mock_config") and Settings.mock_config:

+             cmd.extend(["-r", Settings.mock_config])

          for option in shlex.split(self.get_mock_options()):

-             if option.startswith('--uniqueext'):

+             if option.startswith("--uniqueext"):

                  cmd.append(option)

-             if option.startswith('--configdir'):

+             if option.startswith("--configdir"):

                  cmd.append(option)

-         cmd.append('--init')

-         self._run_cmd(cmd, 'Init')

+         cmd.append("--init")

+         self._run_cmd(cmd, "Init")

  

      def rpmlint_rpms(self, rpms):

          """ Install and run rpmlint on  packages,
@@ -521,55 +533,55 @@ 

          Return (True,  text) or (False, error_string)"""

  

          def filter_output(output):

-             ''' Return part of output to be displayed. '''

-             lines = output.split('\n')

-             l = ''

-             while not l.startswith('rpmlint:') and lines:

+             """ Return part of output to be displayed. """

+             lines = output.split("\n")

+             l = ""

+             while not l.startswith("rpmlint:") and lines:

                  l = lines.pop(0)

-             text = ''

+             text = ""

              for l in lines:

-                 if l.startswith('<mock-'):

-                     l = l[l.find('#'):]

-                 if l.startswith('rpmlint-done:'):

+                 if l.startswith("<mock-"):

+                     l = l[l.find("#") :]

+                 if l.startswith("rpmlint-done:"):

                      break

-                 text += l + '\n'

+                 text += l + "\n"

              return text

  

-         error = self.install(['rpmlint'])

+         error = self.install(["rpmlint"])

          if error:

              return False, error

  

          script = _RPMLINT_SCRIPT

          basenames = [os.path.basename(r) for r in rpms]

-         names = [r.rsplit('-', 2)[0] for r in basenames]

-         rpm_names = ' '.join(list(set(names)))

+         names = [r.rsplit("-", 2)[0] for r in basenames]

+         rpm_names = " ".join(list(set(names)))

  

-         config = ''

+         config = ""

          if Settings.mock_config:

-             config = '-r ' + Settings.mock_config

-         script = script.replace('@config@', config)

-         script = script.replace('@rpm_names@', rpm_names)

+             config = "-r " + Settings.mock_config

+         script = script.replace("@config@", config)

+         script = script.replace("@rpm_names@", rpm_names)

          ok, output = _run_script(script)

          self.log.debug("Script output: %s", output)

          if not ok:

-             return False, output + '\n'

+             return False, output + "\n"

          ok, err_msg = self.check_rpmlint_errors(output, self.log)

          if err_msg:

              return False, err_msg

          text = filter_output(output)

-         self._rpmlint_output = text.split('\n')

+         self._rpmlint_output = text.split("\n")

          return ok, text

  

      def have_cache_for(self, spec):

-         ''' True if all binary rpms for package are in resultdir. '''

+         """ True if all binary rpms for package are in resultdir. """

          for p in self.get_package_rpm_paths(spec):

              if not os.path.exists(p):

                  return False

          return True

  

      def builddir_cleanup(self):

-         ''' Remove broken symlinks left by mock command. '''

-         paths = glob(os.path.join(self.get_builddir('BUILD'), '*'))

+         """ Remove broken symlinks left by mock command. """

+         paths = glob(os.path.join(self.get_builddir("BUILD"), "*"))

          for p in paths:

              if not os.path.exists(p) and os.path.lexists(p):

                  os.unlink(p)

file modified
+14 -16
@@ -13,9 +13,9 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  # (C) 2011 - Tim Lauridsen <timlau@@fedoraproject.org>

- '''

+ """

  Handles -n, srpm and spec file already downloaded

- '''

+ """

  

  import os

  import os.path
@@ -31,6 +31,7 @@ 

  class NameBug(AbstractBug):

      """ Handles -n, spec and srpm already downloaded.

      """

+ 

      # pylint: disable=R0201

  

      def __init__(self, name):
@@ -42,43 +43,40 @@ 

          self.name = name

  

      def get_location(self):

-         return 'Local files in ' + ReviewDirs.startdir

+         return "Local files in " + ReviewDirs.startdir

  

      def find_srpm_url(self):

          """ Retrieve the page and parse for srpm url. """

          if Settings.rpm_spec:

              if os.path.isfile(self.name):

-                 self.srpm_url = 'file://' + os.path.abspath(self.name)

+                 self.srpm_url = "file://" + os.path.abspath(self.name)

                  return

-         pattern = os.path.join(ReviewDirs.startdir,

-                                self.name + '*.src.rpm')

+         pattern = os.path.join(ReviewDirs.startdir, self.name + "*.src.rpm")

          srpms = glob(pattern)

          if not srpms:

              raise self.BugError("Cannot find srpm: " + pattern)

          elif len(srpms) > 1:

-             raise self.BugError("More than one srpm found for: "

-                                 + pattern)

-         self.srpm_url = 'file://' + srpms[0]

+             raise self.BugError("More than one srpm found for: " + pattern)

+         self.srpm_url = "file://" + srpms[0]

  

      def find_spec_url(self):

          """ Retrieve the page and parse for spec url. """

-         pattern = os.path.join(ReviewDirs.startdir,

-                                self.name + '*.spec')

+         pattern = os.path.join(ReviewDirs.startdir, self.name + "*.spec")

          specs = glob(pattern)

          if not specs:

              raise self.BugError("Cannot find spec: " + pattern)

          elif len(specs) > 1:

-             raise self.BugError("More than one spec found for: "

-                                 + pattern)

-         self.spec_url = 'file://' + specs[0]

+             raise self.BugError("More than one spec found for: " + pattern)

+         self.spec_url = "file://" + specs[0]

  

      def check_options(self):

-         ''' Raise error if Settings options combination is invalid. '''

-         AbstractBug.do_check_options('--name', ['other_bz'])

+         """ Raise error if Settings options combination is invalid. """

+         AbstractBug.do_check_options("--name", ["other_bz"])

  

      def download_files(self):

          self.srpm_file = urlparse(self.srpm_url).path

          self.spec_file = urlparse(self.spec_url).path

          return True

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+24 -23
@@ -15,9 +15,9 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''

+ """

  Test module registration support

- '''

+ """

  import inspect

  

  
@@ -27,17 +27,17 @@ 

  

  

  class _Flag(object):

-     ''' A flag such as EPEL7, set byuser, handled by checks. '''

+     """ A flag such as EPEL7, set byuser, handled by checks. """

  

      def __init__(self, name, doc, defined_in):

-         '''

+         """

          Create a flag. Parameters:

            - name: Short name of flag

            - doc: flag's doc-string.

          As created, flag is 'off' i. e., False. If user sets flag using

          -D flag, flag is 'set'i. e., True. If set using -Dflag=value,

          value is available as str(flag).

-         '''

+         """

          self.name = name

          self.doc = doc

          self.defined_in = defined_in
@@ -49,11 +49,11 @@ 

      __nonzero__ = __bool__

  

      def __str__(self):

-         return self.value if self.value else ''

+         return self.value if self.value else ""

  

      def activate(self):

-         ''' Turn 'on' flag from default 'off' state. '''

-         self.value = '1'

+         """ Turn 'on' flag from default 'off' state. """

+         self.value = "1"

  

  

  class AbstractRegistry(object):
@@ -70,15 +70,17 @@ 

      is_applicable method returns if a given test is valid for current

      srpm.

      """

+ 

      # pylint: disable=R0201,W0613

  

-     group = 'Undefined'

+     group = "Undefined"

      external_plugin = False

      version = __version__

      build_id = BUILD_ID

  

      class Flag(_Flag):

-         ''' A value defined in a check, set by user e. g., EPEL7. '''

+         """ A value defined in a check, set by user e. g., EPEL7. """

+ 

          pass

  

      def register(self, plugin):
@@ -87,7 +89,7 @@ 

          Returns:   CheckDict instance.

  

          """

-         raise ReviewError('Abstract register() called')

+         raise ReviewError("Abstract register() called")

  

      def __init__(self, checks):

          """
@@ -101,8 +103,7 @@ 

          """

          Return True if these tests are applicable for current srpm.

          """

-         raise ReviewError(

-             'abstract Registry.is_applicable() called')

+         raise ReviewError("abstract Registry.is_applicable() called")

  

  

  class RegistryBase(AbstractRegistry):
@@ -110,14 +111,14 @@ 

      Register all classes containing 'Check' and not ending with 'Base'

      """

  

-     def __init__(self, checks, path=None):      # pylint: disable=W0613

+     def __init__(self, checks, path=None):  # pylint: disable=W0613

          AbstractRegistry.__init__(self, checks)

  

      def is_applicable(self):

          return self.registry.is_applicable()

  

      def register_flags(self):

-         ''' Register flags used by this module. '''

+         """ Register flags used by this module. """

          pass

  

      def register(self, plugin):
@@ -125,9 +126,9 @@ 

          tests = []

          id_and_classes = inspect.getmembers(plugin, inspect.isclass)

          for c in id_and_classes:

-             if 'Check' not in c[0]:

+             if "Check" not in c[0]:

                  continue

-             if c[0].endswith('Base'):

+             if c[0].endswith("Base"):

                  continue

              obj = (c[1])(self.checks)

              obj.registry = self
@@ -135,21 +136,21 @@ 

          return tests

  

      def find_re(self, regex):

-         ''' Files in rpms matching regex. '''

+         """ Files in rpms matching regex. """

          return self.checks.rpms.find_re(regex)

  

      def find(self, glob_pattern):

-         ''' Files in rpms matching glob_pattern. '''

+         """ Files in rpms matching glob_pattern. """

          return self.checks.rpms.find(glob_pattern)

  

      def is_user_enabled(self):

-         '''' True if this group is enabled/disabled using --plugins. '''

-         g = self.group.split('.')[0] if '.' in self.group else self.group

+         """' True if this group is enabled/disabled using --plugins. """

+         g = self.group.split(".")[0] if "." in self.group else self.group

          return g in Settings.plugins

  

      def user_enabled_value(self):

-         '''' The actual value set if is_user_enabled() is True '''

-         g = self.group.split('.')[0] if '.' in self.group else self.group

+         """' The actual value set if is_user_enabled() is True """

+         g = self.group.split(".")[0] if "." in self.group else self.group

          return Settings.plugins[g]

  

  

file modified
+56 -59
@@ -67,35 +67,35 @@ 

  

  

  def _get_specfile():

-     ' Return a (specfile, sha224sum) tuple. '

-     spec = glob('srpm-unpacked/*.spec')

+     " Return a (specfile, sha224sum) tuple. "

+     spec = glob("srpm-unpacked/*.spec")

      if len(spec) != 1:

-         return '?', '?'

+         return "?", "?"

      path = spec[0].strip()

-     cs = check_output(['sha224sum', path], universal_newlines=True).split()[0]

-     path = path.rsplit('/', 1)[1]

+     cs = check_output(["sha224sum", path], universal_newlines=True).split()[0]

+     path = path.rsplit("/", 1)[1]

      return path, cs

  

  

  def _write_section(results, output):

-     ''' Print a {SHOULD,MUST, EXTRA} section. '''

+     """ Print a {SHOULD,MUST, EXTRA} section. """

  

      def hdr(group):

-         ''' Return header this test is printed under. '''

-         if '.' in group:

-             return group.split('.')[0]

+         """ Return header this test is printed under. """

+         if "." in group:

+             return group.split(".")[0]

          return group

  

      def result_key(result):

-         ''' Return key used to sort results. '''

+         """ Return key used to sort results. """

          if result.check.is_failed:

-             return '0' + str(result.check.sort_key)

+             return "0" + str(result.check.sort_key)

          elif result.check.is_pending:

-             return '1' + str(result.check.sort_key)

+             return "1" + str(result.check.sort_key)

          elif result.check.is_passed:

-             return '2' + str(result.check.sort_key)

+             return "2" + str(result.check.sort_key)

  

-         return '3' + str(result.check.sort_key)

+         return "3" + str(result.check.sort_key)

  

      groups = list({hdr(test.group) for test in results})

      res = None
@@ -104,48 +104,48 @@ 

          if not res:

              continue

          res = sorted(res, key=result_key)

-         output.write('\n' + group + ':\n')

+         output.write("\n" + group + ":\n")

          for r in res:

-             output.write(r.get_text() + '\n')

+             output.write(r.get_text() + "\n")

  

  

  def write_template(output, results, issues, attachments):

-     ''' Print  review template results on output. '''

+     """ Print  review template results on output. """

  

      def dump_local_repo():

-         ''' print info on --local-repo rpms used. '''

+         """ print info on --local-repo rpms used. """

          repodir = Settings.repo

-         if not repodir.startswith('/'):

+         if not repodir.startswith("/"):

              repodir = os.path.join(ReviewDirs.startdir, repodir)

-         rpms = glob(os.path.join(repodir, '*.rpm'))

+         rpms = glob(os.path.join(repodir, "*.rpm"))

          output.write("\nBuilt with local dependencies:\n")

          for rpm in rpms:

-             output.write("    " + rpm + '\n')

+             output.write("    " + rpm + "\n")

  

      output.write(_HEADER)

  

      if issues:

          output.write("\nIssues:\n=======\n")

          for fail in issues:

-             fail.set_leader('- ')

+             fail.set_leader("- ")

              fail.set_indent(2)

              output.write(fail.get_text() + "\n")

          results = [r for r in results if r not in issues]

  

      output.write("\n\n===== MUST items =====\n")

-     musts = [r for r in results if r.type == 'MUST']

+     musts = [r for r in results if r.type == "MUST"]

      _write_section(musts, output)

  

      output.write("\n===== SHOULD items =====\n")

-     shoulds = [r for r in results if r.type == 'SHOULD']

+     shoulds = [r for r in results if r.type == "SHOULD"]

      _write_section(shoulds, output)

  

      output.write("\n===== EXTRA items =====\n")

-     extras = [r for r in results if r.type == 'EXTRA']

+     extras = [r for r in results if r.type == "EXTRA"]

      _write_section(extras, output)

  

      for a in sorted(attachments):

-         output.write('\n\n')

+         output.write("\n\n")

          output.write(a.__str__())

  

      if Settings.repo:
@@ -153,51 +153,48 @@ 

  

  

  def write_xml_report(spec, results):

-     ''' Create the firehose-compatible xml report, see

+     """ Create the firehose-compatible xml report, see

          https://github.com/fedora-static-analysis/firehose/

-     '''

+     """

  

      def create_xmltree(spec):

-         ''' Create the basic xml report complete with <metadata>. '''

-         root = ET.Element('analysis')

-         metadata = ET.SubElement(root, 'metadata')

-         ET.SubElement(metadata,

-                       'generator',

-                       {'name': 'fedora-review',

-                        'version': __version__,

-                        'build': BUILD_FULL})

+         """ Create the basic xml report complete with <metadata>. """

+         root = ET.Element("analysis")

+         metadata = ET.SubElement(root, "metadata")

+         ET.SubElement(

+             metadata,

+             "generator",

+             {"name": "fedora-review", "version": __version__, "build": BUILD_FULL},

+         )

          path, cs = _get_specfile()

-         file_ = ET.SubElement(metadata, 'file', {'given-path': path})

-         ET.SubElement(file_, 'hash', {'alg': 'sha224', 'hexdigest': cs})

-         sut = ET.SubElement(metadata, 'sut')

-         nvr = {'name': spec.name,

-                'version': spec.version,

-                'release': spec.release}

-         ET.SubElement(sut, 'source-rpm', nvr)

-         ET.SubElement(root, 'results')

+         file_ = ET.SubElement(metadata, "file", {"given-path": path})

+         ET.SubElement(file_, "hash", {"alg": "sha224", "hexdigest": cs})

+         sut = ET.SubElement(metadata, "sut")

+         nvr = {"name": spec.name, "version": spec.version, "release": spec.release}

+         ET.SubElement(sut, "source-rpm", nvr)

+         ET.SubElement(root, "results")

          return root

  

      def add_xml_result(root, result):

-         ''' Add a failed result to the xml report as a <result> tag. '''

+         """ Add a failed result to the xml report as a <result> tag. """

  

          def txt2utf(txt):

-             ''' Convert txt to utf-8. '''

+             """ Convert txt to utf-8. """

              if isinstance(txt, bytes):

-                 return txt.decode('utf-8', errors='replace')

+                 return txt.decode("utf-8", errors="replace")

  

              return txt

  

-         path = root.find('metadata/file').attrib['given-path']

-         results = root.find('results')

-         issue = ET.SubElement(results,

-                               'issue',

-                               {'test-id': result.name,

-                                'severity': result.type})

-         ET.SubElement(issue, 'message').text = txt2utf(result.text)

-         location = ET.SubElement(issue, 'location')

-         ET.SubElement(location, 'file', {'given-path': path})

+         path = root.find("metadata/file").attrib["given-path"]

+         results = root.find("results")

+         issue = ET.SubElement(

+             results, "issue", {"test-id": result.name, "severity": result.type}

+         )

+         ET.SubElement(issue, "message").text = txt2utf(result.text)

+         location = ET.SubElement(issue, "location")

+         ET.SubElement(location, "file", {"given-path": path})

          if result.output_extra:

-             ET.SubElement(issue, 'notes').text = txt2utf(result.output_extra)

+             ET.SubElement(issue, "notes").text = txt2utf(result.output_extra)

          return root

  

      root = create_xmltree(spec)
@@ -205,6 +202,6 @@ 

          if result.is_failed:

              root = add_xml_result(root, result)

      dom = xml.dom.minidom.parseString(ET.tostring(root))

-     prettyxml = dom.toprettyxml(indent='    ', encoding='utf-8')

-     with open('report.xml', 'wb') as f:

+     prettyxml = dom.toprettyxml(indent="    ", encoding="utf-8")

+     with open("report.xml", "wb") as f:

          f.write(prettyxml)

file modified
+53 -49
@@ -18,9 +18,9 @@ 

  

  # pylint: disable=bad-whitespace

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  import logging

  import os
@@ -29,65 +29,68 @@ 

  import tempfile

  

  from .review_error import ReviewError

- from .settings     import Settings

+ from .settings import Settings

  

- SRPM              = 'srpm'

- SRPM_UNPACKED     = 'srpm-unpacked'

- UPSTREAM          = 'upstream'

- UPSTREAM_UNPACKED = 'upstream-unpacked'

- RESULTS           = 'results'

- DEPENDENCIES      = 'dependencies'

+ SRPM = "srpm"

+ SRPM_UNPACKED = "srpm-unpacked"

+ UPSTREAM = "upstream"

+ UPSTREAM_UNPACKED = "upstream-unpacked"

+ RESULTS = "results"

+ DEPENDENCIES = "dependencies"

  

  

  class _ReviewDirs(object):

-     ''' Wraps the review directory and it's paths. '''

+     """ Wraps the review directory and it's paths. """

  

      class ResultDirNotEmptyError(ReviewError):

-         ''' Thrown when trying to reuse old review dir without --cache. '''

+         """ Thrown when trying to reuse old review dir without --cache. """

+ 

          def __init__(self):

              ReviewError.__init__(

-                 self,

-                 'The resultdir is not empty, I cannot handle this')

+                 self, "The resultdir is not empty, I cannot handle this"

+             )

  

      class ReviewDirExistsError(ReviewError):

-         ''' The review dir is already in place. '''

+         """ The review dir is already in place. """

+ 

          def __init__(self, path):

-             msg = 'The directory %s is in the way, please remove' % \

-                 os.path.abspath(path)

+             msg = "The directory %s is in the way, please remove" % os.path.abspath(

+                 path

+             )

              ReviewError.__init__(self, msg, 2)

              self.show_logs = False

  

      class ReviewDirChangeError(ReviewError):

-         ''' Attempt to change directory already set. '''

+         """ Attempt to change directory already set. """

+ 

          pass

  

-     WD_DIRS = [UPSTREAM, UPSTREAM_UNPACKED, SRPM, SRPM_UNPACKED,

-                RESULTS, DEPENDENCIES]

+     WD_DIRS = [UPSTREAM, UPSTREAM_UNPACKED, SRPM, SRPM_UNPACKED, RESULTS, DEPENDENCIES]

  

      def __init__(self):

          self.startdir = os.getcwd()

          self.wdir = None

  

      def reset(self, startdir=None):

-         ''' Clear persistent state (test tool). '''

+         """ Clear persistent state (test tool). """

          self.wdir = None

          if startdir:

              self.startdir = startdir

  

      @staticmethod

      def report_path():

-         ''' Return path for report. '''

-         return os.path.abspath('./review.txt')

+         """ Return path for report. """

+         return os.path.abspath("./review.txt")

  

      def _create_and_copy_wd(self, wd, reuse_old):

-         ''' Create wd, possibly filled with cached data. '''

+         """ Create wd, possibly filled with cached data. """

          if os.path.exists(wd) and not reuse_old:

              if Settings.cache:

-                 cache = tempfile.mkdtemp(dir='.')

+                 cache = tempfile.mkdtemp(dir=".")

                  for d in self.WD_DIRS:

                      shutil.move(os.path.join(wd, d), cache)

                  try:

-                     buildlink = os.readlink(os.path.join(wd, 'BUILD'))

+                     buildlink = os.readlink(os.path.join(wd, "BUILD"))

                  except OSError:

                      buildlink = None

              logging.info("Clearing old review directory: %s", wd)
@@ -99,23 +102,24 @@ 

                  if buildlink:

                      oldwd = os.getcwd()

                      os.chdir(wd)

-                     os.symlink(buildlink, 'BUILD')

+                     os.symlink(buildlink, "BUILD")

                      os.chdir(oldwd)

                  shutil.rmtree(cache)

          if not os.path.exists(wd):

              os.mkdir(wd)

  

      def workdir_setup(self, wd, reuse_old=False):

-         ''' Initiate a new review directory, or re-use an old one. '''

+         """ Initiate a new review directory, or re-use an old one. """

          reuse = reuse_old or Settings.cache

          if not reuse and os.path.exists(wd):

-             d = ''.join(wd.split(os.getcwd(), 1))

+             d = "".join(wd.split(os.getcwd(), 1))

              raise self.ReviewDirExistsError(d)

          wd = os.path.abspath(wd)

          if self.wdir:

              if self.wdir != wd and not reuse_old:

-                 raise self.ReviewDirChangeError('Old dir ' + self.wdir +

-                                                 ' new dir: ' + wd)

+                 raise self.ReviewDirChangeError(

+                     "Old dir " + self.wdir + " new dir: " + wd

+                 )

          self._create_and_copy_wd(wd, reuse_old)

          os.chdir(wd)

          logging.info("Using review directory: %s", wd)
@@ -128,61 +132,61 @@ 

      root = property(lambda self: self.wdir)

  

      srpm = property(lambda self: os.path.join(self.wdir, SRPM))

-     srpm_unpacked = property(lambda self: os.path.join(self.wdir,

-                                                        SRPM_UNPACKED))

+     srpm_unpacked = property(lambda self: os.path.join(self.wdir, SRPM_UNPACKED))

      upstream = property(lambda self: os.path.join(self.wdir, UPSTREAM))

-     upstream_unpacked = property(lambda self:

-                                  os.path.join(self.wdir, UPSTREAM_UNPACKED))

+     upstream_unpacked = property(

+         lambda self: os.path.join(self.wdir, UPSTREAM_UNPACKED)

+     )

      results = property(lambda self: os.path.join(self.wdir, RESULTS))

  

  

  class _ReviewDirsFixture(_ReviewDirs):

-     ''' Simple test mockup.Uses wdir unconditionally, don't

+     """ Simple test mockup.Uses wdir unconditionally, don't

      care about reuse and such things.

-     '''

+     """

+ 

      # pylint: disable=W0231

      def __init__(self):

-         ''' Setup.... '''

+         """ Setup.... """

          self.wdir = None

          self.startdir = None

  

      def init(self, workdir, startdir):

-         '''

+         """

          Create fixture. params:

            - startdir: where f-r is invoked, and looks fo r-p stuff.

            - wdir: the review_dir f-r works in, must exist.

-         '''

+         """

          self.startdir = os.path.abspath(startdir)

          self.wdir = os.path.abspath(workdir)

          os.chdir(self.wdir)

          for d in self.WD_DIRS:

              if not os.path.exists(d):

                  os.makedirs(d)

-         src_path = os.path.join(os.getcwd(), 'BUILD')

+         src_path = os.path.join(os.getcwd(), "BUILD")

          if not os.path.exists(src_path):

              try:

-                 os.makedirs(

-                     os.path.join(os.getcwd(), '..', 'dummy', 'pkg-1.0'))

+                 os.makedirs(os.path.join(os.getcwd(), "..", "dummy", "pkg-1.0"))

              except OSError:

                  pass

              try:

-                 os.symlink(os.path.join(os.getcwd(), '..', 'dummy'),

-                            src_path)

+                 os.symlink(os.path.join(os.getcwd(), "..", "dummy"), src_path)

              except OSError:

                  pass

  

-     def workdir_setup(self, wd, reuse='Ignored'):

-         ''' Lazy init while testing. wd: the review dir '''

-         if reuse == 'testing':

+     def workdir_setup(self, wd, reuse="Ignored"):

+         """ Lazy init while testing. wd: the review dir """

+         if reuse == "testing":

              self.init(wd, os.getcwd())

  

      def reset(self, startdir=None):

-         ''' Ignored while testing. '''

+         """ Ignored while testing. """

          pass

  

  

  try:

-     import test_env   # pylint: disable=W0611,F0401

+     import test_env  # pylint: disable=W0611,F0401

+ 

      ReviewDirs = _ReviewDirsFixture()

  except ImportError:

      ReviewDirs = _ReviewDirs()

@@ -16,9 +16,9 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  

  class ReviewError(Exception):
@@ -39,7 +39,8 @@ 

  

  

  class SpecParseReviewError(ReviewError):

-     ''' Thrown at an early stage, no spec available. '''

+     """ Thrown at an early stage, no spec available. """

+ 

      pass

  

  

@@ -18,9 +18,9 @@ 

  

  # pylint: disable=cell-var-from-loop

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  from __future__ import print_function

  import os.path
@@ -50,19 +50,20 @@ 

  

  

  class _Nvr(object):

-     ''' Simple name-version-release container. '''

+     """ Simple name-version-release container. """

  

-     def __init__(self, name, version='?', release='?'):

+     def __init__(self, name, version="?", release="?"):

          self.name = name

          self.version = version

          self.release = release

  

  

  class ReviewHelper(object):

-     ''' Make most of the actual work doing the review. '''

+     """ Make most of the actual work doing the review. """

  

      class HelperError(ReviewError):

-         ''' Error while processing bug. '''

+         """ Error while processing bug. """

+ 

          def __init__(self, msg):

              ReviewError.__init__(self, msg)

  
@@ -75,14 +76,13 @@ 

          self.prebuilt = False

  

      def _do_report(self, outfile=None):

-         ''' Create a review report'''

+         """ Create a review report"""

          clock = time.time()

  

          Settings.dump()

          if not self.bug.find_urls():

-             raise self.HelperError('Cannot find .spec or .srpm URL(s)')

-         self.log.debug("find_urls completed: %.3f",

-                        time.time() - clock)

+             raise self.HelperError("Cannot find .spec or .srpm URL(s)")

+         self.log.debug("find_urls completed: %.3f", time.time() - clock)

          clock = time.time()

  

          if not ReviewDirs.is_inited:
@@ -92,110 +92,108 @@ 

              Mock.init()

  

          if not self.bug.download_files():

-             raise self.HelperError('Cannot download .spec and .srpm')

+             raise self.HelperError("Cannot download .spec and .srpm")

          self.log.debug("Url download completed: %.3f", time.time() - clock)

  

          Settings.name = self.bug.get_name()

          self._run_checks(self.bug.spec_file, self.bug.srpm_file, outfile)

  

      def _run_checks(self, spec, srpm, outfile=None):

-         ''' Register and run all checks. '''

+         """ Register and run all checks. """

  

          def apply_color(s, formatter):

-             ''' Return s formatted by formatter or plain s. '''

+             """ Return s formatted by formatter or plain s. """

              return formatter(s) if Settings.use_colors else s

  

          self.checks = Checks(spec, srpm)

          if outfile:

              self.outfile = outfile

          elif Settings.no_report:

-             self.outfile = '/dev/null'

+             self.outfile = "/dev/null"

          else:

              self.outfile = ReviewDirs.report_path()

          with open(self.outfile, "w") as output:

-             self.log.info('Running checks and generating report')

-             self.checks.run_checks(output=output,

-                                    writedown=not Settings.no_report)

+             self.log.info("Running checks and generating report")

+             self.checks.run_checks(output=output, writedown=not Settings.no_report)

          if not Settings.no_report:

-             print(apply_color("Review template in: " + self.outfile,

-                               ansi.green))

+             print(apply_color("Review template in: " + self.outfile, ansi.green))

              print(apply_color(_EXIT_MESSAGE, ansi.red))

  

      @staticmethod

      def _list_flags():

-         ''' List all flags in simple, user-friendly format. '''

+         """ List all flags in simple, user-friendly format. """

          checks_lister = ChecksLister()

          for flag in checks_lister.flags.values():

-             print(flag.name + ': ' + flag.doc)

+             print(flag.name + ": " + flag.doc)

  

      @staticmethod

      def _list_plugins():

-         ''' --display-plugins implementation. '''

+         """ --display-plugins implementation. """

          checks_lister = ChecksLister()

          plugins = checks_lister.get_plugins()

-         print(', '.join(plugins))

+         print(", ".join(plugins))

  

      @staticmethod

      def _list_checks():

          """ List all the checks and flags available.  """

  

          def list_data_by_file(files, checks_list):

-             ''' print filename + flags and checks defined in it. '''

+             """ print filename + flags and checks defined in it. """

              for f in sorted(files):

-                 print('File:  ' + f)

-                 flags_by_src = [c for c in checks_lister.flags.values()

-                                 if c.defined_in == f]

+                 print("File:  " + f)

+                 flags_by_src = [

+                     c for c in checks_lister.flags.values() if c.defined_in == f

+                 ]

                  for flag in flags_by_src:

-                     print('Flag: ' + flag.name)

-                 files_per_src = [c for c in checks_list

-                                  if c.defined_in == f]

+                     print("Flag: " + flag.name)

+                 files_per_src = [c for c in checks_list if c.defined_in == f]

                  groups = list({c.group for c in files_per_src})

                  for group in sorted(groups):

  

                      def check_match(c):

-                         ''' check in correct group and file? '''

+                         """ check in correct group and file? """

                          return c.group == group and c.defined_in == f

  

                      checks = [c for c in checks_list if check_match(c)]

                      if checks == []:

                          continue

-                     print('Group: ' + group)

+                     print("Group: " + group)

                      for c in sorted(checks):

-                         print('    {}: {}'.format(c.name, c.text))

+                         print("    {}: {}".format(c.name, c.text))

                  print()

  

          checks_lister = ChecksLister()

          checks_list = list(checks_lister.get_checks().values())

          files = list({c.defined_in for c in checks_list})

          list_data_by_file(files, checks_list)

-         deps_list = [c for c in checks_list

-                      if c.needs != [] and c.needs != ['CheckBuildCompleted']]

+         deps_list = [

+             c

+             for c in checks_list

+             if c.needs != [] and c.needs != ["CheckBuildCompleted"]

+         ]

          for dep in deps_list:

-             print('Dependencies: ' + dep.name + ': ' +

-                   os.path.basename(dep.defined_in))

+             print("Dependencies: " + dep.name + ": " + os.path.basename(dep.defined_in))

              for needed in dep.needs:

-                 print('     ' + needed)

+                 print("     " + needed)

          deprecators = [c for c in checks_list if c.deprecates != []]

          for dep in deprecators:

-             print('Deprecations: ' + dep.name + ': ' +

-                   os.path.basename(dep.defined_in))

+             print("Deprecations: " + dep.name + ": " + os.path.basename(dep.defined_in))

              for victim in dep.deprecates:

-                 print('    ' + victim)

+                 print("    " + victim)

  

      @staticmethod

      def _print_version():

-         ''' Handle --version option. '''

+         """ Handle --version option. """

          # pylint: disable=superfluous-parens

-         print(('fedora-review version ' + __version__ + ' ' + BUILD_FULL))

-         print('external plugins:')

+         print(("fedora-review version " + __version__ + " " + BUILD_FULL))

+         print("external plugins:")

          checks_lister = ChecksLister()

          for registry in checks_lister.groups.values():

              if registry.external_plugin:

-                 print("{r.group} version {r.version} {r.build_id}".format(

-                     r=registry))

+                 print("{r.group} version {r.version} {r.build_id}".format(r=registry))

  

      def _do_run(self, outfile=None):

-         ''' Initiate, download url:s, run checks a write report. '''

+         """ Initiate, download url:s, run checks a write report. """

          Settings.init()

          make_report = True

          if Settings.list_checks:
@@ -214,8 +212,7 @@ 

              self.log.info("Processing bug on url: %s", Settings.url)

              self.bug = UrlBug(Settings.url)

          elif Settings.copr_build_descriptor:

-             self.log.info("Processing COPR build: %s",

-                           Settings.copr_build_descriptor)

+             self.log.info("Processing COPR build: %s", Settings.copr_build_descriptor)

              self.bug = CoprBug(Settings.copr_build_descriptor)

          elif Settings.bug:

              self.log.info("Processing bugzilla bug: %s", Settings.bug)
@@ -229,35 +226,35 @@ 

              self._do_report(outfile)

  

      def run(self, outfile=None):

-         ''' Load urls, run checks and make report, '''

+         """ Load urls, run checks and make report, """

          # pylint: disable=bare-except

          started_at = time.time()

-         self.log.debug('fedora-review %s %s started', __version__, BUILD_FULL)

-         self.log.debug("Command  line: %s", ' '.join(sys.argv))

+         self.log.debug("fedora-review %s %s started", __version__, BUILD_FULL)

+         self.log.debug("Command  line: %s", " ".join(sys.argv))

          try:

              rcode = 0

              self._do_run(outfile)

          except ReviewError as err:

              if isinstance(err, SpecParseReviewError):

                  nvr = _Nvr(self.bug.get_name())

-                 result = SimpleTestResult("SpecFileParseError",

-                                           "Can't parse the spec file: ",

-                                           str(err))

+                 result = SimpleTestResult(

+                     "SpecFileParseError", "Can't parse the spec file: ", str(err)

+                 )

                  write_xml_report(nvr, [result])

              self.log.debug("ReviewError: %s", str(err), exc_info=True)

              if not err.silent:

-                 msg = 'ERROR: ' + str(err)

+                 msg = "ERROR: " + str(err)

                  if err.show_logs:

-                     msg += ' (logs in ' + Settings.session_log + ')'

+                     msg += " (logs in " + Settings.session_log + ")"

                  self.log.error(msg)

              rcode = err.exitcode

          except:

              self.log.debug("Exception down the road...", exc_info=True)

-             self.log.error('Exception down the road...'

-                            '(logs in %s)', Settings.session_log)

+             self.log.error(

+                 "Exception down the road..." "(logs in %s)", Settings.session_log

+             )

              rcode = 1

-         self.log.debug("Report completed:  %.3f seconds",

-                        time.time() - started_at)

+         self.log.debug("Report completed:  %.3f seconds", time.time() - started_at)

          return rcode

  

  

file modified
+49 -50
@@ -15,9 +15,9 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''

+ """

  Binary rpm file management.

- '''

+ """

  

  import os

  import rpm
@@ -27,15 +27,16 @@ 

  

  

  class RpmFile(object):

-     '''

+     """

      Wrapper class for getting information from a binary RPM file

-     '''

+     """

+ 

      # pylint: disable=W0212

  

      def __init__(self, pkg_name, version, release):

-         '''

+         """

          Create a RPM wrapper given a package name.

-         '''

+         """

          self.log = Settings.get_logger()

          self._inited = False

          self.name = pkg_name
@@ -52,24 +53,24 @@ 

          eq = rpm.RPMSENSE_EQUAL

          for ix in range(0, len(names) - 1):

              if not versions[ix]:

-                 dp.append(names[ix].decode('utf-8'))

+                 dp.append(names[ix].decode("utf-8"))

                  continue

-             s = names[ix].decode('utf-8') + ' '

+             s = names[ix].decode("utf-8") + " "

              if sense[ix] and eq:

-                 s += '= '

+                 s += "= "

              elif sense[ix] and lt:

-                 s += '< '

+                 s += "< "

              elif sense[ix] and gt:

-                 s += '> '

+                 s += "> "

              else:

-                 s += 'What? : ' + bin(sense[ix])

+                 s += "What? : " + bin(sense[ix])

                  self.log.warning("Bad RPMSENSE: %s", bin(sense[ix]))

-             s += versions[ix].decode('utf-8')

+             s += versions[ix].decode("utf-8")

              dp.append(s)

          return dp

  

      def init(self):

-         ''' Lazy init, we have no rpms until they are built. '''

+         """ Lazy init, we have no rpms until they are built. """

          if self._inited:

              return

  
@@ -84,16 +85,16 @@ 

  

      # RPMTAG_POSTTRANSPROG are given as list on F18, but not before

      def header_to_str(self, tag):

-         ''' Convert header in a string, to cope with API changes in F18'''

+         """ Convert header in a string, to cope with API changes in F18"""

          if isinstance(self.header[tag], (dict, list)):

-             return b' '.join(self.header[tag]).decode('utf-8')

+             return b" ".join(self.header[tag]).decode("utf-8")

          elif self.header[tag]:

-             return self.header[tag].decode('utf-8')

+             return self.header[tag].decode("utf-8")

          else:

              return None

  

      def _scriptlet(self, prog_tag, script_tag):

-         ''' Return inline -p script, script or None. '''

+         """ Return inline -p script, script or None. """

          self.init()

          prog = self.header_to_str(prog_tag)

          script = self.header_to_str(script_tag)
@@ -105,71 +106,69 @@ 

  

      @property

      def posttrans(self):

-         ''' Return postTrans scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_POSTTRANSPROG,

-                                rpm.RPMTAG_POSTTRANS)

+         """ Return postTrans scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_POSTTRANSPROG, rpm.RPMTAG_POSTTRANS)

  

      @property

      def pretrans(self):

-         ''' Return preTrans scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_PRETRANSPROG,

-                                rpm.RPMTAG_PRETRANS)

+         """ Return preTrans scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_PRETRANSPROG, rpm.RPMTAG_PRETRANS)

  

      @property

      def postun(self):

-         ''' Return postUn scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_POSTUNPROG,

-                                rpm.RPMTAG_POSTUN)

+         """ Return postUn scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_POSTUNPROG, rpm.RPMTAG_POSTUN)

  

      @property

      def preun(self):

-         ''' Return preUn scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_PREUNPROG,

-                                rpm.RPMTAG_PREUN)

+         """ Return preUn scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_PREUNPROG, rpm.RPMTAG_PREUN)

  

      @property

      def post(self):

-         ''' Return post scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_POSTINPROG,

-                                rpm.RPMTAG_POSTIN)

+         """ Return post scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_POSTINPROG, rpm.RPMTAG_POSTIN)

  

      @property

      def pre(self):

-         ''' Return pre scriptlet. '''

-         return self._scriptlet(rpm.RPMTAG_PREINPROG,

-                                rpm.RPMTAG_PREIN)

+         """ Return pre scriptlet. """

+         return self._scriptlet(rpm.RPMTAG_PREINPROG, rpm.RPMTAG_PREIN)

  

      @property

      def filelist(self):

-         ''' List of files in this rpm (expanded). '''

+         """ List of files in this rpm (expanded). """

          self.init()

-         return [x.decode('utf-8') for x in self.header[rpm.RPMTAG_FILENAMES]]

+         return [x.decode("utf-8") for x in self.header[rpm.RPMTAG_FILENAMES]]

  

      @property

      def requires(self):

-         ''' List of requires, also auto-generated for rpm. '''

+         """ List of requires, also auto-generated for rpm. """

          self.init()

-         return [x.decode('utf-8') for x in self.header[rpm.RPMTAG_REQUIRES]]

+         return [x.decode("utf-8") for x in self.header[rpm.RPMTAG_REQUIRES]]

  

      @property

      def provides(self):

-         ''' List of provides, also auto-generated for rpm. '''

+         """ List of provides, also auto-generated for rpm. """

          self.init()

-         return [x.decode('utf-8') for x in self.header[rpm.RPMTAG_PROVIDES]]

+         return [x.decode("utf-8") for x in self.header[rpm.RPMTAG_PROVIDES]]

  

      @property

      def format_requires(self):

-         ''' List of formatted provides. '''

-         return self._format_deps(self.header[rpm.RPMTAG_REQUIRENAME],

-                                  self.header[rpm.RPMTAG_REQUIREVERSION],

-                                  self.header[rpm.RPMTAG_REQUIREFLAGS])

+         """ List of formatted provides. """

+         return self._format_deps(

+             self.header[rpm.RPMTAG_REQUIRENAME],

+             self.header[rpm.RPMTAG_REQUIREVERSION],

+             self.header[rpm.RPMTAG_REQUIREFLAGS],

+         )

  

      @property

      def format_provides(self):

-         ''' List of formatted provides. '''

-         return self._format_deps(self.header[rpm.RPMTAG_PROVIDENAME],

-                                  self.header[rpm.RPMTAG_PROVIDEVERSION],

-                                  self.header[rpm.RPMTAG_PROVIDEFLAGS])

+         """ List of formatted provides. """

+         return self._format_deps(

+             self.header[rpm.RPMTAG_PROVIDENAME],

+             self.header[rpm.RPMTAG_PROVIDEVERSION],

+             self.header[rpm.RPMTAG_PROVIDEFLAGS],

+         )

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+259 -170
@@ -16,7 +16,7 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- ''' Tools for helping Fedora package reviewers '''

+ """ Tools for helping Fedora package reviewers """

  

  

  from __future__ import print_function
@@ -36,23 +36,24 @@ 

  from .review_error import ReviewError

  from .xdg_dirs import XdgDirs

  

- PARSER_SECTION = 'review'

+ PARSER_SECTION = "review"

  

- SESSION_LOG = os.path.join(XdgDirs.cachedir, 'fedora-review.log')

+ SESSION_LOG = os.path.join(XdgDirs.cachedir, "fedora-review.log")

  

  

  def _check_mock_grp():

-     ''' Raise ReviewError unless mock installation is OK. '''

+     """ Raise ReviewError unless mock installation is OK. """

  

-     mock_msg = \

-         'No mock group - mock not installed or mock not in effective' \

-         'groups. Try running  "newgrp" or logging out from all your local ' \

-         'sessions and logging back in. Or disable test using ' \

-         'REVIEW_NO_MOCKGROUP_CHECK, see manpage'

+     mock_msg = (

+         "No mock group - mock not installed or mock not in effective"

+         'groups. Try running  "newgrp" or logging out from all your local '

+         "sessions and logging back in. Or disable test using "

+         "REVIEW_NO_MOCKGROUP_CHECK, see manpage"

+     )

  

-     if 'REVIEW_NO_MOCKGROUP_CHECK' in os.environ:

+     if "REVIEW_NO_MOCKGROUP_CHECK" in os.environ:

          return

-     mock_gid = grp.getgrnam('mock')[2]

+     mock_gid = grp.getgrnam("mock")[2]

      if mock_gid not in os.getgroups():

          raise ReviewError(mock_msg)

  
@@ -60,131 +61,225 @@ 

  def _check_mock_ver():

      """ Returns mock version """

      try:

-         mock_ver = subprocess.check_output(['mock', '--version'],

-                                            universal_newlines=True)

+         mock_ver = subprocess.check_output(

+             ["mock", "--version"], universal_newlines=True

+         )

      except subprocess.CalledProcessError:

-         mock_ver = '0'

+         mock_ver = "0"

      return mock_ver

  

  

  def _mock_options_default():

      """ Returns the default mock options """

-     mock_opts = '--no-cleanup-after --no-clean'

-     if version.parse(_check_mock_ver()) >= version.parse('1.4.1'):

-         mock_opts = '--no-bootstrap-chroot %s' % mock_opts

+     mock_opts = "--no-cleanup-after --no-clean"

+     if version.parse(_check_mock_ver()) >= version.parse("1.4.1"):

+         mock_opts = "--no-bootstrap-chroot %s" % mock_opts

      return mock_opts

  

  

  def _add_modes(modes):

-     ''' Add all mode arguments to the option parser group modes. '''

-     modes.add_argument('-b', '--bug', metavar='<bug>',

-                        help='Operate on fedora bugzilla using its bug number.')

-     modes.add_argument('-n', '--name', metavar='<name>',

-                        help='Use local files <name>.spec and <name>*.src.rpm'

-                        ' in current dir or, when using --rpm-spec, use'

-                        ' <name> as path to srpm.')

-     modes.add_argument('-u', '--url', default=None, dest='url',

-                        metavar='<url>',

-                        help='Use another bugzilla, using complete'

-                        ' url to bug page.')

-     modes.add_argument('--copr-build', default=None,

-                        dest='copr_build_descriptor',

-                        metavar='<build_descriptor>',

-                        help='Use COPR build identified by its ID,'

-                        ' frontend URI, or backend URI. \

-                        Implies --prebuilt.')

-     modes.add_argument('-d', '--display-checks', default=False,

-                        action='store_true', dest='list_checks',

-                        help='List all available checks.')

-     modes.add_argument('-f', '--display-flags', default=False,

-                        action='store_true', dest='list_flags',

-                        help='List all available flags.')

-     modes.add_argument('-g', '--display-plugins', default=False,

-                        action='store_true', dest='list_plugins',

-                        help='List all available plugins.')

-     modes.add_argument('-V', '--version', default=False,

-                        action='store_true',

-                        help='Display version information and exit.')

-     modes.add_argument('-h', '--help', action='help',

-                        help='Display this help message')

+     """ Add all mode arguments to the option parser group modes. """

+     modes.add_argument(

+         "-b",

+         "--bug",

+         metavar="<bug>",

+         help="Operate on fedora bugzilla using its bug number.",

+     )

+     modes.add_argument(

+         "-n",

+         "--name",

+         metavar="<name>",

+         help="Use local files <name>.spec and <name>*.src.rpm"

+         " in current dir or, when using --rpm-spec, use"

+         " <name> as path to srpm.",

+     )

+     modes.add_argument(

+         "-u",

+         "--url",

+         default=None,

+         dest="url",

+         metavar="<url>",

+         help="Use another bugzilla, using complete" " url to bug page.",

+     )

+     modes.add_argument(

+         "--copr-build",

+         default=None,

+         dest="copr_build_descriptor",

+         metavar="<build_descriptor>",

+         help="Use COPR build identified by its ID,"

+         " frontend URI, or backend URI. \

+                        Implies --prebuilt.",

+     )

+     modes.add_argument(

+         "-d",

+         "--display-checks",

+         default=False,

+         action="store_true",

+         dest="list_checks",

+         help="List all available checks.",

+     )

+     modes.add_argument(

+         "-f",

+         "--display-flags",

+         default=False,

+         action="store_true",

+         dest="list_flags",

+         help="List all available flags.",

+     )

+     modes.add_argument(

+         "-g",

+         "--display-plugins",

+         default=False,

+         action="store_true",

+         dest="list_plugins",

+         help="List all available plugins.",

+     )

+     modes.add_argument(

+         "-V",

+         "--version",

+         default=False,

+         action="store_true",

+         help="Display version information and exit.",

+     )

+     modes.add_argument("-h", "--help", action="help", help="Display this help message")

  

  

  def _add_optionals(optional):

-     ''' Add all optional arguments to option parser group optionals. '''

- 

-     optional.add_argument('-B', '--no-colors', action='store_false',

-                           help='No colors in output',

-                           default=True, dest='use_colors')

-     optional.add_argument('-c', '--cache', action='store_true',

-                           dest='cache',

-                           help='Do not redownload files from bugzilla,'

-                           ' use the ones in the cache.')

-     optional.add_argument('-D', '--define', metavar='<flag>',

-                           action='append', dest='flags', default=[],

-                           help='Define a flag like --define EPEL7 or '

-                           ' -D EPEL7=1')

-     optional.add_argument('-L', '--local-repo', metavar='<rpm directory>',

-                           dest='repo',

-                           help='directory with rpms to install together with'

-                           ' reviewed package during build and install phases.')

-     optional.add_argument('-m', '--mock-config', metavar='<config>',

-                           dest='mock_config',

-                           help='Configuration to use for the mock build,'

-                           " defaults to 'default' i. e.,"

-                           ' /etc/mock/default.cfg')

-     optional.add_argument('--no-report', action='store_true',

-                           help='Do not print review report.')

-     optional.add_argument('--no-build', action='store_true',

-                           dest='nobuild',

-                           help='Do not rebuild or install the srpm, use last'

-                           ' built one in mock. Implies --cache')

-     optional.add_argument('-o', '--mock-options', metavar='<mock options>',

-                           default=_mock_options_default(),

-                           dest='mock_options',

-                           help=('Options to specify to mock for the build,'

-                                 ' defaults to %s' % _mock_options_default()))

-     optional.add_argument('--other-bz', default=None,

-                           metavar='<bugzilla url>', dest='other_bz',

-                           help='Alternative bugzilla URL')

-     optional.add_argument('-P', '--plugins',

-                           metavar='<plugin>',

-                           dest='plugins_arg', default=None,

-                           help='List of plugins to enable or disable hard'

-                                ' e. g., "Java:off,C/C++"')

-     optional.add_argument('-p', '--prebuilt', action='store_true',

-                           dest='prebuilt', default=False,

-                           help='When using -n <name>, use'

-                           ' prebuilt rpms in current directory.')

-     optional.add_argument('-s', '--single', metavar='<test>',

-                           help='Single test to run, as named by '

-                           '--display-checks.')

-     optional.add_argument('-r', '--rpm-spec', action='store_true',

-                           dest='rpm_spec', default=False,

-                           help='Take spec file from srpm instead of separate'

-                           'url.')

-     optional.add_argument('-v', '--verbose', action='store_true',

-                           help='Show more output.', default=False,

-                           dest='verbose')

-     optional.add_argument('-x', '--exclude',

-                           dest='exclude', metavar='"test,..."',

-                           help='Comma-separated list of tests to exclude.')

-     optional.add_argument('-k', '--checksum', dest='checksum',

-                           default='sha256',

-                           choices=['md5', 'sha1', 'sha224', 'sha256',

-                                    'sha384', 'sha512'],

-                           help='Algorithm used for checksum')

+     """ Add all optional arguments to option parser group optionals. """

+ 

+     optional.add_argument(

+         "-B",

+         "--no-colors",

+         action="store_false",

+         help="No colors in output",

+         default=True,

+         dest="use_colors",

+     )

+     optional.add_argument(

+         "-c",

+         "--cache",

+         action="store_true",

+         dest="cache",

+         help="Do not redownload files from bugzilla," " use the ones in the cache.",

+     )

+     optional.add_argument(

+         "-D",

+         "--define",

+         metavar="<flag>",

+         action="append",

+         dest="flags",

+         default=[],

+         help="Define a flag like --define EPEL7 or " " -D EPEL7=1",

+     )

+     optional.add_argument(

+         "-L",

+         "--local-repo",

+         metavar="<rpm directory>",

+         dest="repo",

+         help="directory with rpms to install together with"

+         " reviewed package during build and install phases.",

+     )

+     optional.add_argument(

+         "-m",

+         "--mock-config",

+         metavar="<config>",

+         dest="mock_config",

+         help="Configuration to use for the mock build,"

+         " defaults to 'default' i. e.,"

+         " /etc/mock/default.cfg",

+     )

+     optional.add_argument(

+         "--no-report", action="store_true", help="Do not print review report."

+     )

+     optional.add_argument(

+         "--no-build",

+         action="store_true",

+         dest="nobuild",

+         help="Do not rebuild or install the srpm, use last"

+         " built one in mock. Implies --cache",

+     )

+     optional.add_argument(

+         "-o",

+         "--mock-options",

+         metavar="<mock options>",

+         default=_mock_options_default(),

+         dest="mock_options",

+         help=(

+             "Options to specify to mock for the build,"

+             " defaults to %s" % _mock_options_default()

+         ),

+     )

+     optional.add_argument(

+         "--other-bz",

+         default=None,

+         metavar="<bugzilla url>",

+         dest="other_bz",

+         help="Alternative bugzilla URL",

+     )

+     optional.add_argument(

+         "-P",

+         "--plugins",

+         metavar="<plugin>",

+         dest="plugins_arg",

+         default=None,

+         help="List of plugins to enable or disable hard" ' e. g., "Java:off,C/C++"',

+     )

+     optional.add_argument(

+         "-p",

+         "--prebuilt",

+         action="store_true",

+         dest="prebuilt",

+         default=False,

+         help="When using -n <name>, use" " prebuilt rpms in current directory.",

+     )

+     optional.add_argument(

+         "-s",

+         "--single",

+         metavar="<test>",

+         help="Single test to run, as named by " "--display-checks.",

+     )

+     optional.add_argument(

+         "-r",

+         "--rpm-spec",

+         action="store_true",

+         dest="rpm_spec",

+         default=False,

+         help="Take spec file from srpm instead of separate" "url.",

+     )

+     optional.add_argument(

+         "-v",

+         "--verbose",

+         action="store_true",

+         help="Show more output.",

+         default=False,

+         dest="verbose",

+     )

+     optional.add_argument(

+         "-x",

+         "--exclude",

+         dest="exclude",

+         metavar='"test,..."',

+         help="Comma-separated list of tests to exclude.",

+     )

+     optional.add_argument(

+         "-k",

+         "--checksum",

+         dest="checksum",

+         default="sha256",

+         choices=["md5", "sha1", "sha224", "sha256", "sha384", "sha512"],

+         help="Algorithm used for checksum",

+     )

  

  

  def _make_log_dir():

-     ''' Create the log dir, unless it's already there. '''

+     """ Create the log dir, unless it's already there. """

      try:

          os.makedirs(os.path.dirname(SESSION_LOG))

      except OSError as exc:

          if exc.errno == errno.EEXIST:

              pass

          else:

-             raise ReviewError('Cannot create log directory: ' +

-                               SESSION_LOG)

+             raise ReviewError("Cannot create log directory: " + SESSION_LOG)

  

  

  def _parse_plugins(args):
@@ -193,25 +288,21 @@ 

          args.plugins = {}

          return

      _dict = {}

-     for p in args.plugins_arg.split(','):

+     for p in args.plugins_arg.split(","):

          p = p.strip()

-         if ':' in p:

-             plugin, suffix = p.split(':')

-             _dict[plugin] = False if suffix == 'off' else True

+         if ":" in p:

+             plugin, suffix = p.split(":")

+             _dict[plugin] = False if suffix == "off" else True

          else:

              _dict[p] = True

      args.plugins = _dict

  

  

  class ColoredFormatter(logging.Formatter):

-     ''' Formatter usable for colorizing terminal output acccording to presets

-     '''

+     """ Formatter usable for colorizing terminal output acccording to presets

+     """

  

-     COLORS = {

-         'WARNING': ansi.blue,

-         'CRITICAL': ansi.red,

-         'ERROR': ansi.red

-     }

+     COLORS = {"WARNING": ansi.blue, "CRITICAL": ansi.red, "ERROR": ansi.red}

  

      def __init__(self, fmt=None, datefmt=None, use_color=True):

          logging.Formatter.__init__(self, fmt, datefmt)
@@ -221,13 +312,13 @@ 

          lname = record.levelname

          ret = logging.Formatter.format(self, record)

          if not ret.startswith(lname):

-             ret = lname + ': ' + ret

+             ret = lname + ": " + ret

          if self.use_color and lname in self.COLORS:

              ret = self.COLORS[lname](ret)

          return ret

  

  

- class _Settings(object):                         # pylint: disable=R0902

+ class _Settings(object):  # pylint: disable=R0902

      """

      FedoraReview singleton Config Setting based on command line options.

      All config values are accessed as attributes.
@@ -240,19 +331,18 @@ 

      """

  

      class SettingsError(ReviewError):

-         ''' Illegal options from user. '''

+         """ Illegal options from user. """

+ 

          def __init__(self):

-             ReviewError.__init__(self, 'Bad options!!', 2, True)

+             ReviewError.__init__(self, "Bad options!!", 2, True)

  

-     defaults = {

-         'bz_url': 'https://bugzilla.redhat.com',

-     }

+     defaults = {"bz_url": "https://bugzilla.redhat.com"}

  

      def __init__(self):

-         '''Constructor of the Settings object.

+         """Constructor of the Settings object.

          This instanciate the Settings object and load into the _dict

          attributes the default configuration which each available option.

-         '''

+         """

          for key, value in self.defaults.items():

              setattr(self, key, value)

          self._dict = self.defaults
@@ -278,46 +368,46 @@ 

          return self._dict.get(my_key)

  

      def _fix_mock_options(self):

-         '''

+         """

          Update resultdir, uniqueext and configdir from mock_options.

-         '''

+         """

          self.resultdir = None

          self.uniqueext = None

          self.configdir = None

          if not self.mock_options:

              return

-         m = re.search('--uniqueext=([^ ]+)', self.mock_options)

-         self.uniqueext = '-' + m.groups()[0] if m else None

-         m = re.search('--resultdir=([^ ]+)', self.mock_options)

+         m = re.search("--uniqueext=([^ ]+)", self.mock_options)

+         self.uniqueext = "-" + m.groups()[0] if m else None

+         m = re.search("--resultdir=([^ ]+)", self.mock_options)

          self.resultdir = m.groups()[0] if m else None

-         m = re.search('--configdir=([^ ]+)', self.mock_options)

+         m = re.search("--configdir=([^ ]+)", self.mock_options)

          self.configdir = m.groups()[0] if m else None

-         if 'no-cleanup-after' not in self.mock_options:

-             self.mock_options += ' --no-cleanup-after'

-         if 'no-cleanup-after' not in self.mock_options:

-             self.mock_options += ' --no-cleanup-after'

-         if not re.search('clean($|[ ])', self.mock_options):

-             self.mock_options += ' --no-clean'

+         if "no-cleanup-after" not in self.mock_options:

+             self.mock_options += " --no-cleanup-after"

+         if "no-cleanup-after" not in self.mock_options:

+             self.mock_options += " --no-cleanup-after"

+         if not re.search("clean($|[ ])", self.mock_options):

+             self.mock_options += " --no-clean"

  

      def init(self, force=False):

-         ''' Delayed setup, to be called when sys.argv is ok...'''

+         """ Delayed setup, to be called when sys.argv is ok..."""

  

          if self.init_done and not force:

              return

  

          self.do_logger_setup()

-         for opt in ['--assign', '--login', '--user', '-a', '-i', '-l']:

+         for opt in ["--assign", "--login", "--user", "-a", "-i", "-l"]:

              if opt in sys.argv:

                  print(self.BZ_OPTS_MESSAGE)

                  self.init_done = True

                  raise self.SettingsError()

          parser = argparse.ArgumentParser(

-             description='Review a package using Fedora Guidelines',

-             add_help=False)

+             description="Review a package using Fedora Guidelines", add_help=False

+         )

  

-         mode = parser.add_argument_group('Operation mode - one is required')

+         mode = parser.add_argument_group("Operation mode - one is required")

          modes = mode.add_mutually_exclusive_group(required=True)

-         optionals = parser.add_argument_group('General options')

+         optionals = parser.add_argument_group("General options")

          _add_modes(modes)

          _add_optionals(optionals)

          try:
@@ -344,16 +434,16 @@ 

  

      @property

      def current_bz_url(self):

-         ''' Effective value of --bz-url, not empty. '''

+         """ Effective value of --bz-url, not empty. """

          return self.other_bz if self.other_bz else self.bz_url

  

      def dump(self):

-         ''' Debug output of all settings. '''

+         """ Debug output of all settings. """

          if not self.log:

              return

          self.log.debug("Active settings after processing options")

          for k, v in vars(self).items():

-             if k in ['_dict', 'mock_config_options', 'log']:

+             if k in ["_dict", "mock_config_options", "log"]:

                  continue

              try:

                  self.log.debug("    " + k + ": " + v.__str__())
@@ -361,17 +451,16 @@ 

                  self.log.debug("    %s: not printable", k)

  

      def do_logger_setup(self, lvl=None):

-         ''' Setup Python logging. lvl is a logging.* thing like

+         """ Setup Python logging. lvl is a logging.* thing like

          logging.DEBUG. If None, respects REVIEW_LOGLEVEL environment

          variable, defaulting to logging.INFO.

-         '''

+         """

          msg = None

          if not lvl:

-             if 'REVIEW_LOGLEVEL' in os.environ:

+             if "REVIEW_LOGLEVEL" in os.environ:

                  try:

                      # pylint: disable=eval-used

-                     lvl = eval('logging.' +

-                                os.environ['REVIEW_LOGLEVEL'].upper())

+                     lvl = eval("logging." + os.environ["REVIEW_LOGLEVEL"].upper())

                  except (ValueError, SyntaxError):

                      msg = "Cannot set loglevel from REVIEW_LOGLEVEL"

                      lvl = logging.INFO
@@ -380,23 +469,23 @@ 

  

          if not self._log_config_done:

              _make_log_dir()

-             logging.basicConfig(level=logging.DEBUG,

-                                 format='%(asctime)s %(name)-12s'

-                                        ' %(levelname)-8s %(message)s',

-                                 datefmt='%m-%d %H:%M',

-                                 filename=SESSION_LOG,

-                                 filemode='w')

+             logging.basicConfig(

+                 level=logging.DEBUG,

+                 format="%(asctime)s %(name)-12s" " %(levelname)-8s %(message)s",

+                 datefmt="%m-%d %H:%M",

+                 filename=SESSION_LOG,

+                 filemode="w",

+             )

          self._log_config_done = True

  

          self.log_level = lvl

          if lvl == logging.DEBUG:

              self.verbose = True

-         self.log = logging.getLogger('')

+         self.log = logging.getLogger("")

          # define a Handler which writes INFO  or higher to sys.stderr

          console = logging.StreamHandler()

          console.setLevel(lvl)

-         formatter = ColoredFormatter('%(message)s',

-                                      "%H:%M:%S", self.use_colors)

+         formatter = ColoredFormatter("%(message)s", "%H:%M:%S", self.use_colors)

          console.setFormatter(formatter)

          if self._con_handler:

              self.log.removeHandler(self._con_handler)
@@ -408,7 +497,7 @@ 

          return True

  

      def get_logger(self):

-         ''' Return the application logger instance. '''

+         """ Return the application logger instance. """

          if not self.log:

              self.do_logger_setup()

          return self.log

file modified
+35 -40
@@ -16,9 +16,9 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  import os.path

  import shutil
@@ -32,7 +32,7 @@ 

  

  

  class Source(HelpersMixin):

-     ''' A source defined in the specfile.

+     """ A source defined in the specfile.

      Attributes:

           - tag: as defined in specfile e. g., 'Source0'

           - url: complete url, possibly file://
@@ -43,16 +43,16 @@ 

             or None.

           - is_url: True if url is (or should be) downloadable.

  

-     '''

+     """

  

      def __init__(self, tag, url):

- 

          def my_logger(cache):

-             ''' Default logger logs info messages. '''

+             """ Default logger logs info messages. """

              if cache:

                  path = urlparse(url).path

-                 self.log.info("Using cached data for (%s): %s",

-                               tag, os.path.basename(path))

+                 self.log.info(

+                     "Using cached data for (%s): %s", tag, os.path.basename(path)

+                 )

              else:

                  self.log.info("Downloading (%s): %s", tag, url)

  
@@ -62,83 +62,77 @@ 

          self.tag = tag

          self.downloaded = True

          self.local_src = None

-         self.is_url = urlparse(url)[0] != ''

+         self.is_url = urlparse(url)[0] != ""

          if self.is_url:  # This is a URL, Download it

              self.url = url

              if Settings.cache:

-                 cached = os.path.join(ReviewDirs.upstream,

-                                       url.rsplit('/', 1)[1])

+                 cached = os.path.join(ReviewDirs.upstream, url.rsplit("/", 1)[1])

                  if os.path.exists(cached):

                      self.log.info("Using cached upstream: %s", cached)

                      self.filename = cached

                      return

-                 self.log.warning(

-                     "No cache found for %s, downloading anyway.",

-                     cached)

+                 self.log.warning("No cache found for %s, downloading anyway.", cached)

              try:

-                 self.filename = self._get_file(url,

-                                                ReviewDirs.upstream,

-                                                my_logger)

+                 self.filename = self._get_file(url, ReviewDirs.upstream, my_logger)

              except DownloadError as ex:

-                 self.log.debug('Download error on %s, : %s', url, str(ex),

-                                exc_info=True)

-                 self.log.warning('Cannot download url: %s', url)

+                 self.log.debug(

+                     "Download error on %s, : %s", url, str(ex), exc_info=True

+                 )

+                 self.log.warning("Cannot download url: %s", url)

                  self.downloaded = False

                  # get the filename

-                 url = urlparse(url)[2].split('/')[-1]

+                 url = urlparse(url)[2].split("/")[-1]

  

          if not self.is_url or not self.downloaded:  # A local file in the SRPM

              local_src = os.path.join(ReviewDirs.startdir, url)

              if os.path.isfile(local_src):

-                 self.log.info(

-                     "Using local file %s as %s", url, tag)

+                 self.log.info("Using local file %s as %s", url, tag)

                  srcdir = ReviewDirs.startdir

                  self.local_src = local_src

              else:

                  self.log.info("No upstream for (%s): %s", tag, url)

                  srcdir = ReviewDirs.srpm_unpacked

              self.filename = os.path.join(srcdir, url)

-             self.url = 'file://' + self.filename

+             self.url = "file://" + self.filename

  

      # True if the source is a local file in srpm, false if a downloaded

      # url or tarball provided by user.

-     local = property(lambda self: (not self.is_url or not self.downloaded) and

-                      not self.local_src)

+     local = property(

+         lambda self: (not self.is_url or not self.downloaded) and not self.local_src

+     )

  

      # True if downloadable, but the uri couldn't be accessed.

      is_failed = property(lambda self: self.is_url and not self.downloaded)

  

      def check_source_checksum(self):

-         ''' Check source with upstream source using checksumming. '''

-         self.log.debug("Checking source %s : %s", Settings.checksum,

-                        self.filename)

+         """ Check source with upstream source using checksumming. """

+         self.log.debug("Checking source %s : %s", Settings.checksum, self.filename)

          if self.downloaded:

              return self._checksum(self.filename)

          else:

              raise ReviewError(self.tag + ": upstream source not found")

  

      def is_archive(self):

-         ''' Return true if source can be assumed to be an archive file. '''

-         filename = self.filename.split('/')[-1]

-         for i in ('.tar.gz',

-                   '.tar.bz2', '.tar.lzma', '.tar.xz', '.zip', '.7z'):

+         """ Return true if source can be assumed to be an archive file. """

+         filename = self.filename.split("/")[-1]

+         for i in (".tar.gz", ".tar.bz2", ".tar.lzma", ".tar.xz", ".zip", ".7z"):

              if filename.endswith(i):

                  return True

          return False

  

      def extract(self):

-         ''' Extract the source into a directory under upstream-unpacked,

+         """ Extract the source into a directory under upstream-unpacked,

              available in the extract_dir property. Sources which not

              could be extracted e. g., plain files are copied to the

              extract-dir.

-         '''

+         """

          if not os.path.isfile(self.filename):

-             raise ReviewError("%s file %s is missing in src.rpm."

-                               " Conditional source inclusion?" %

-                               (self.tag, self.filename))

+             raise ReviewError(

+                 "%s file %s is missing in src.rpm."

+                 " Conditional source inclusion?" % (self.tag, self.filename)

+             )

  

-         self.extract_dir = os.path.join(ReviewDirs.upstream_unpacked,

-                                         self.tag)

+         self.extract_dir = os.path.join(ReviewDirs.upstream_unpacked, self.tag)

          if os.path.exists(self.extract_dir):

              return

          os.mkdir(self.extract_dir)
@@ -154,4 +148,5 @@ 

              self.extract()

          return self.extract_dir

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+93 -85
@@ -15,9 +15,9 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''

+ """

  Spec file management.

- '''

+ """

  

  import re

  import sys
@@ -31,22 +31,22 @@ 

  

  

  def _lines_in_string(s, raw):

-     ''' Return either plain s (raw) or stripped, non-empty item list. '''

+     """ Return either plain s (raw) or stripped, non-empty item list. """

      if raw:

          return s

-     return [l.strip() for l in s.split('\n') if l]

+     return [l.strip() for l in s.split("\n") if l]

  

  

  class _Null(object):

-     ''' Dummy sink. '''

+     """ Dummy sink. """

  

      def write(self, s):

-         ''' Like /dev/null. '''

+         """ Like /dev/null. """

          pass

  

  

  class SpecFile(object):

-     '''

+     """

      Wrapper class for getting information from a .spec file.'

      All get_* methods operates on the python binding to the spec,

      whereas the find_* methods works on the raw lines of spec data.
@@ -54,27 +54,26 @@ 

         - filename: spec path

         - lines: list of all lines in spec file

         - spec: rpm python spec object.

-     '''

+     """

+ 

      # pylint: disable=W0212,W0201

  

      def __init__(self, filename, flags=None):

- 

          def update_macros():

-             ''' Update build macros from mock target configuration. '''

-             macros = ['%dist', '%rhel', '%fedora', '%_build_arch', '%_arch']

+             """ Update build macros from mock target configuration. """

+             macros = ["%dist", "%rhel", "%fedora", "%_build_arch", "%_arch"]

              for macro in macros:

                  expanded = Mock.get_macro(macro, self, flags)

-                 if not expanded.startswith('%'):

+                 if not expanded.startswith("%"):

                      rpm.delMacro(macro[1:])

                      rpm.addMacro(macro[1:], expanded)

  

          def parse_spec():

-             ''' Let rpm parse the spec and build spec.spec (sic!). '''

+             """ Let rpm parse the spec and build spec.spec (sic!). """

              try:

                  self.spec = rpm.TransactionSet().parseSpec(self.filename)

              except Exception as ex:

-                 raise SpecParseReviewError(

-                     "Can't parse specfile: " + ex.__str__())

+                 raise SpecParseReviewError("Can't parse specfile: " + ex.__str__())

  

          self.log = Settings.get_logger()

          self.filename = filename
@@ -86,37 +85,40 @@ 

          parse_spec()

          sys.stdout = stdout

          self._packages = None

-         self.name_vers_rel = [self.expand_tag(rpm.RPMTAG_NAME).decode('utf-8'),

-                               self.expand_tag(rpm.RPMTAG_VERSION).decode('utf-8'),

-                               '*']

+         self.name_vers_rel = [

+             self.expand_tag(rpm.RPMTAG_NAME).decode("utf-8"),

+             self.expand_tag(rpm.RPMTAG_VERSION).decode("utf-8"),

+             "*",

+         ]

          update_macros()

          parse_spec()

-         self.name_vers_rel[2] = self.expand_tag(rpm.RPMTAG_RELEASE).decode('utf-8')

+         self.name_vers_rel[2] = self.expand_tag(rpm.RPMTAG_RELEASE).decode("utf-8")

  

      name = property(lambda self: self.name_vers_rel[0])

      version = property(lambda self: self.name_vers_rel[1])

      release = property(lambda self: self.name_vers_rel[2])

  

      def _get_packages(self):

-         ''' Return list of all packages, except empty or not built. '''

+         """ Return list of all packages, except empty or not built. """

  

          def check_pkg_path(pkg):

-             ''' Check that pkg is available (built or supplied w -p).'''

+             """ Check that pkg is available (built or supplied w -p)."""

              nvr = self.get_package_nvr(pkg)

              try:

                  return Mock.get_package_rpm_path(nvr)

              except ReviewError:

-                 self.log.warning("Package %s-%s-%s not built",

-                                  nvr.name, nvr.version, nvr.release)

+                 self.log.warning(

+                     "Package %s-%s-%s not built", nvr.name, nvr.version, nvr.release

+                 )

                  return None

  

-         pkgs = [p.header[rpm.RPMTAG_NAME].decode('utf-8') for p in self.spec.packages]

+         pkgs = [p.header[rpm.RPMTAG_NAME].decode("utf-8") for p in self.spec.packages]

          pkgs = [p for p in pkgs if not self.get_files(p) is None]

          return [p for p in pkgs if check_pkg_path(p)]

  

      # pylint: disable=W1401

      def _get_lines(self, filename):

-         r''' Read line from specfile, fold \ continuation lines. '''

+         r""" Read line from specfile, fold \ continuation lines. """

          with open(filename, "r") as f:

              lines = f.readlines()

          last = None
@@ -126,36 +128,36 @@ 

                  self.lines[last] += line

              else:

                  self.lines.append(line)

-             if line.endswith('\\'):

+             if line.endswith("\\"):

                  last = len(self.lines) - 1

                  self.lines[last] = self.lines[last][:-1]

              else:

                  last = None

  

      def _process_fonts_pkg(self):

-         ''' If found, expand %_font_pkg macro. '''

+         """ If found, expand %_font_pkg macro. """

          expanded = []

          for l in self.lines:

-             if '%_font_pkg' not in l:

+             if "%_font_pkg" not in l:

                  expanded.append(l)

              else:

-                 expanded.extend(rpm.expandMacro(l).split('\n'))

+                 expanded.extend(rpm.expandMacro(l).split("\n"))

          self.lines = expanded

  

      def _get_pkg_by_name(self, pkg_name):

-         '''

+         """

          Return package with given name. pgk_name == None

          -> base package, not existing name -> KeyError

-         '''

+         """

          if not pkg_name:

              return self.spec.packages[0]

          for p in self.spec.packages:

-             if p.header[rpm.RPMTAG_NAME].decode('utf-8') == pkg_name:

+             if p.header[rpm.RPMTAG_NAME].decode("utf-8") == pkg_name:

                  return p

-         raise KeyError(pkg_name + ': no such package')

+         raise KeyError(pkg_name + ": no such package")

  

-     def _get_sources(self, _type='Source'):

-         ''' Get SourceX/PatchX lines with macros resolved '''

+     def _get_sources(self, _type="Source"):

+         """ Get SourceX/PatchX lines with macros resolved """

  

          result = {}

          for (url, num, flags) in self.spec.sources:
@@ -165,56 +167,63 @@ 

                  continue

              tag = srctype + str(num)

              try:

-                 result[tag] = \

-                     self.spec.sourceHeader.format(unquote(url))

+                 result[tag] = self.spec.sourceHeader.format(unquote(url))

              except Exception:

-                 raise SpecParseReviewError("Cannot parse %s url %s"

-                                            % (tag, url))

+                 raise SpecParseReviewError("Cannot parse %s url %s" % (tag, url))

          return result

  

      def _parse_files_pkg_name(self, line):

-         ''' Figure out the package name in a %files line. '''

+         """ Figure out the package name in a %files line. """

          line = rpm.expandMacro(line)

          tokens = line.split()

-         assert tokens.pop(0) == '%files'

+         assert tokens.pop(0) == "%files"

          while tokens:

              token = tokens.pop(0)

-             if token == '-n':

+             if token == "-n":

                  name = tokens.pop(0)

-                 if name.startswith('-'):

+                 if name.startswith("-"):

                      name = name[1:]

                  return name

-             elif token == '-f':

+             elif token == "-f":

                  tokens.pop(0)

              else:

-                 return self.base_package.decode() + '-' + token

+                 return self.base_package.decode() + "-" + token

  

          return self.base_package.decode()

  

      def _parse_files(self, pkg_name):

-         ''' Parse and return the %files section for pkg_name.

+         """ Parse and return the %files section for pkg_name.

              Return [] for empty file list, None for no matching %files.

-         '''

+         """

          if not pkg_name:

              pkg_name = self.name

          lines = None

          for line in [l.strip() for l in self.lines]:

              if lines is None:

-                 if line.startswith('%files'):

+                 if line.startswith("%files"):

                      name = self._parse_files_pkg_name(line)

                      if pkg_name.endswith(name):

                          lines = []

                  continue

              line = rpm.expandMacro(line)

-             if line.startswith('%{gem_'):

+             if line.startswith("%{gem_"):

                  # Nasty F17/EPEL fix where  %gem_*  are not defined.

                  lines.append(line)

-             elif line.startswith('%'):

-                 token = re.split(r'\s|\(', line)[0]

-                 if token not in ['%ghost', '%doc', '%docdir', '%license',

-                                  '%verify', '%attr', '%config', '%dir',

-                                  '%defattr', '%exclude']:

-                         break

+             elif line.startswith("%"):

+                 token = re.split(r"\s|\(", line)[0]

+                 if token not in [

+                     "%ghost",

+                     "%doc",

+                     "%docdir",

+                     "%license",

+                     "%verify",

+                     "%attr",

+                     "%config",

+                     "%dir",

+                     "%defattr",

+                     "%exclude",

+                 ]:

+                     break

                  else:

                      lines.append(line)

              elif line:
@@ -223,27 +232,27 @@ 

  

      @property

      def base_package(self):

-         ''' Base package name, normally %{name} unless -n is used. '''

+         """ Base package name, normally %{name} unless -n is used. """

          return self.spec.packages[0].header[rpm.RPMTAG_NAME]

  

      @property

      def sources_by_tag(self):

-         ''' Return dict of source_url[tag]. '''

-         return self._get_sources('Source')

+         """ Return dict of source_url[tag]. """

+         return self._get_sources("Source")

  

      @property

      def patches_by_tag(self):

-         ''' Return dict of patch_url[tag]. '''

-         return self._get_sources('Patch')

+         """ Return dict of patch_url[tag]. """

+         return self._get_sources("Patch")

  

      def expand_tag(self, tag, pkg_name=None):

-         '''

+         """

          Return value of given tag in the spec file, or None. Parameters:

            - tag: tag as listed by rpm --querytags, case-insensitive or

              a  constant like rpm.RPMTAG_NAME.

            - package: A subpackage, as listed by get_packages(), defaults

              to the source package.

-         '''

+         """

          if not pkg_name:

              header = self.spec.sourceHeader

          else:
@@ -257,42 +266,41 @@ 

  

      @property

      def packages(self):

-         ''' Return list of package names built by this spec. '''

+         """ Return list of package names built by this spec. """

          if self._packages is None:

              self._packages = self._get_packages()

          return self._packages

  

      @property

      def build_requires(self):

-         ''' Return the list of build requirements. '''

-         return [x.decode('utf-8')

-                 for x in self.spec.sourceHeader[rpm.RPMTAG_REQUIRES]]

+         """ Return the list of build requirements. """

+         return [x.decode("utf-8") for x in self.spec.sourceHeader[rpm.RPMTAG_REQUIRES]]

  

      def get_requires(self, pkg_name=None):

-         ''' Return list of requirements i. e., Requires: '''

+         """ Return list of requirements i. e., Requires: """

          package = self._get_pkg_by_name(pkg_name)

-         return [x.decode('utf-8')

-                 for x in package.header[rpm.RPMTAG_REQUIRES]]

+         return [x.decode("utf-8") for x in package.header[rpm.RPMTAG_REQUIRES]]

  

      def get_package_nvr(self, pkg_name=None):

-         ''' Return object with name, version, release for a package. '''

+         """ Return object with name, version, release for a package. """

          # pylint: disable=W0201

  

          class NVR(object):

-             ''' Simple name-version-release container. '''

+             """ Simple name-version-release container. """

+ 

              pass

  

          package = self._get_pkg_by_name(pkg_name)

          nvr = NVR()

-         nvr.version = package.header[rpm.RPMTAG_VERSION].decode('utf-8')

-         nvr.release = package.header[rpm.RPMTAG_RELEASE].decode('utf-8')

-         nvr.name = package.header[rpm.RPMTAG_NAME].decode('utf-8')

+         nvr.version = package.header[rpm.RPMTAG_VERSION].decode("utf-8")

+         nvr.release = package.header[rpm.RPMTAG_RELEASE].decode("utf-8")

+         nvr.name = package.header[rpm.RPMTAG_NAME].decode("utf-8")

          return nvr

  

      def get_files(self, pkg_name=None):

-         ''' Return %files section for base or specified package.

+         """ Return %files section for base or specified package.

              Returns [] for empty section, None for not found.

-         '''

+         """

          try:

              files = self._get_pkg_by_name(pkg_name).fileList

          except AttributeError:
@@ -301,16 +309,15 @@ 

              return self._parse_files(pkg_name)

          if files is None:

              return None

-         return [l for l in [f.decode('utf-8').strip()

-                             for f in files.split(b'\n')] if l]

+         return [l for l in [f.decode("utf-8").strip() for f in files.split(b"\n")] if l]

  

      def get_section(self, section, raw=False):

-         '''

+         """

          Get a section in the spec file ex. %install, %clean etc. If

          raw is True, returns single string verbatim from spec.

          Otherwise returns list of stripped and non-empty lines.

-         '''

-         if section.startswith('%'):

+         """

+         if section.startswith("%"):

              section = section[1:]

          try:

              section = getattr(self.spec, section)
@@ -319,11 +326,11 @@ 

          return _lines_in_string(section, raw) if section else None

  

      def find_re(self, regex, flags=re.IGNORECASE):

-         '''

+         """

          Return first raw line in spec matching regex or None.

            - regex: compiled regex or string.

            - flags: used when regex is a string to control search.

-         '''

+         """

          if isinstance(regex, str):

              regex = re.compile(regex, flags)

          for line in self.lines:
@@ -332,16 +339,17 @@ 

          return None

  

      def find_all_re(self, regex, skip_changelog=False):

-         ''' Return list of all raw lines in spec matching regex or []. '''

+         """ Return list of all raw lines in spec matching regex or []. """

          if isinstance(regex, str):

              regex = re.compile(regex, re.IGNORECASE)

          result = []

          for line in self.lines:

              if skip_changelog:

-                 if line.lower().strip().startswith('%changelog'):

+                 if line.lower().strip().startswith("%changelog"):

                      break

              if regex.search(line):

                  result.append(line.strip())

          return result

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+21 -23
@@ -16,9 +16,9 @@ 

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

  

- '''

+ """

  Tools for helping Fedora package reviewers

- '''

+ """

  

  import os.path

  import shutil
@@ -32,7 +32,7 @@ 

  

  

  class SRPMFile(HelpersMixin):

-     ''' Models the srpm and it's methods. '''

+     """ Models the srpm and it's methods. """

  

      def __init__(self, filename):

          HelpersMixin.__init__(self)
@@ -40,7 +40,7 @@ 

          self._prebuilt_info = None

          self._unpacked_src = None

          self.filename = filename

-         self.name = os.path.basename(filename).rsplit('-', 2)[0]

+         self.name = os.path.basename(filename).rsplit("-", 2)[0]

          self.unpack()

  

      def unpack(self, src=None):
@@ -52,11 +52,10 @@ 

          oldpwd = os.getcwd()

          os.chdir(wdir)

          src = src if src else self.filename

-         cmd = 'rpm2cpio ' + src + ' | cpio -u -i -m --quiet'

+         cmd = "rpm2cpio " + src + " | cpio -u -i -m --quiet"

          rc = call(cmd, shell=True)

          if rc != 0:

-             self.log.warn(

-                 "Cannot unpack %s into %s", self.filename, wdir)

+             self.log.warn("Cannot unpack %s into %s", self.filename, wdir)

          else:

              self._unpacked_src = wdir

          os.chdir(oldpwd)
@@ -65,40 +64,39 @@ 

          """ Extract a named source and return containing directory. """

          self.filename = os.path.basename(path)

          self.unpack(path)

-         files = glob(os.path.join(self._unpacked_src, '*'))

+         files = glob(os.path.join(self._unpacked_src, "*"))

          if self.filename not in [os.path.basename(f) for f in files]:

-             self.log.error(

-                 'Trying to unpack non-existing source: %s', path)

+             self.log.error("Trying to unpack non-existing source: %s", path)

              return None

-         extract_dir = os.path.join(self._unpacked_src,

-                                    self.filename + '-extract')

+         extract_dir = os.path.join(self._unpacked_src, self.filename + "-extract")

          if os.path.exists(extract_dir):

              return extract_dir

          else:

              os.mkdir(extract_dir)

-         rv = self.rpmdev_extract(os.path.join(self._unpacked_src,

-                                               self.filename),

-                                  extract_dir)

+         rv = self.rpmdev_extract(

+             os.path.join(self._unpacked_src, self.filename), extract_dir

+         )

          if not rv:

-             self.log.debug("Cannot unpack %s, so probably not an "

-                            "archive. Copying instead", self.filename)

-             shutil.copy(os.path.join(self._unpacked_src, self.filename),

-                         extract_dir)

+             self.log.debug(

+                 "Cannot unpack %s, so probably not an " "archive. Copying instead",

+                 self.filename,

+             )

+             shutil.copy(os.path.join(self._unpacked_src, self.filename), extract_dir)

          return extract_dir

  

      def check_source_checksum(self, path):

-         '''Return checksum for archive. '''

+         """Return checksum for archive. """

          filename = os.path.basename(path)

          self.unpack(self.filename)

          if not self._unpacked_src:

              self.log.warn("check_source_checksum: Cannot unpack (?)")

              return "ERROR"

-         src_files = glob(self._unpacked_src + '/*')

+         src_files = glob(self._unpacked_src + "/*")

          if not src_files:

-             self.log.warn('No unpacked sources found (!)')

+             self.log.warn("No unpacked sources found (!)")

              return "ERROR"

          if filename not in [os.path.basename(f) for f in src_files]:

-             self.log.warn('Cannot find source: %s', filename)

+             self.log.warn("Cannot find source: %s", filename)

              return "ERROR"

          path = os.path.join(self._unpacked_src, filename)

          self.log.debug("Checking %s for %s", Settings.checksum, path)

file modified
+19 -19
@@ -13,10 +13,10 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  # (C) 2011 - Tim Lauridsen <timlau@@fedoraproject.org>

- '''

+ """

  Tools handling resources identified with an url (download only).

  No xmlrpc involved, for better or worse.

- '''

+ """

  import os.path

  from six.moves.urllib.request import urlretrieve

  
@@ -36,48 +36,48 @@ 

          AbstractBug.__init__(self)

          self.check_options()

          self.bug_url = url

-         if not url.startswith('http'):

+         if not url.startswith("http"):

              self.bug_url = os.path.normpath(self.bug_url)

  

      def _find_urls_by_ending(self, pattern):

          """ Locate url based on links ending in .src.rpm and .spec.

          """

-         if self.bug_url.startswith('file://'):

-             tmpfile = self.bug_url.replace('file://', '')

+         if self.bug_url.startswith("file://"):

+             tmpfile = self.bug_url.replace("file://", "")

          else:

              tmpfile = urlretrieve(self.bug_url)[0]

          soup = BeautifulSoup(open(tmpfile), features="lxml")

-         links = soup.findAll('a')

-         hrefs = [l.get('href') for l in links if l.get('href')]

+         links = soup.findAll("a")

+         hrefs = [l.get("href") for l in links if l.get("href")]

          found = []

          for href in reversed(hrefs):

-             href = href.encode('ascii', 'ignore').decode('ascii')

-             if '?' in href:

-                 href = href[0: href.find('?')]

-             if not href.startswith(('http://', 'https://')):

-                 href = self.bug_url + '/' + href

+             href = href.encode("ascii", "ignore").decode("ascii")

+             if "?" in href:

+                 href = href[0 : href.find("?")]

+             if not href.startswith(("http://", "https://")):

+                 href = self.bug_url + "/" + href

              if href.endswith(pattern):

                  found.append(href)

          return found

  

      def find_srpm_url(self):

-         urls = self._find_urls_by_ending('.src.rpm')

+         urls = self._find_urls_by_ending(".src.rpm")

          if not urls:

-             raise self.BugError('Cannot find source rpm URL')

+             raise self.BugError("Cannot find source rpm URL")

          self.srpm_url = urls[0]

  

      def find_spec_url(self):

-         urls = self._find_urls_by_ending('.spec')

+         urls = self._find_urls_by_ending(".spec")

          if not urls:

-             raise self.BugError('Cannot find spec file URL')

+             raise self.BugError("Cannot find spec file URL")

          self.spec_url = urls[0]

  

      def get_location(self):

          return self.bug_url

  

-     def check_options(self):                     # pylint: disable=R0201

-         ''' Raise error if Settings  combination is invalid. '''

-         AbstractBug.do_check_options('--url', ['prebuilt', 'other_bz'])

+     def check_options(self):  # pylint: disable=R0201

+         """ Raise error if Settings  combination is invalid. """

+         AbstractBug.do_check_options("--url", ["prebuilt", "other_bz"])

  

  

  # vim: set expandtab ts=4 sw=4:

file modified
+22 -19
@@ -1,9 +1,9 @@ 

  #

- '''

+ """

  Create the file version if it does not exist.

  In any case, exec this file, providing symbols defined

  there on module level, redefining the 'unknown' defaults.

- '''

+ """

  

  import os.path

  import os
@@ -16,50 +16,53 @@ 

  

  from FedoraReview.review_error import ReviewError

  

- __version__ = 'Unknown'

- BUILD_FULL = 'Unknown (no version file nor git info)'

+ __version__ = "Unknown"

+ BUILD_FULL = "Unknown (no version file nor git info)"

  BUILD_DATE = "Unknown"

  BUILD_ID = "Unknown"

  

  

  class VersionError(ReviewError):

-     ''' If we cannot deduce the version. '''

+     """ If we cannot deduce the version. """

+ 

      pass

  

  

  def _setup():

-     ''' Setup  the 'version' file from version.tmpl. '''

+     """ Setup  the 'version' file from version.tmpl. """

      try:

-         line = check_output(['git', 'log', '--pretty=format:%h %ci', '-1'], universal_newlines=True)

+         line = check_output(

+             ["git", "log", "--pretty=format:%h %ci", "-1"], universal_newlines=True

+         )

      except:

          raise VersionError("No version file and git not available.")

      words = line.split()

      commit = words.pop(0)

      date = words.pop(0)

-     time = ' '.join(words)

+     time = " ".join(words)

      try:

-         with open('version.tmpl') as f:

+         with open("version.tmpl") as f:

              template = f.read()

      except:

-         raise VersionError('Cannot read version.tmpl')

+         raise VersionError("Cannot read version.tmpl")

  

-     template = template.replace('@date@', date)

-     template = template.replace('@time@', time)

-     template = template.replace('@commit@', commit)

-     template = template.replace('@host@', socket.gethostname())

+     template = template.replace("@date@", date)

+     template = template.replace("@time@", time)

+     template = template.replace("@commit@", commit)

+     template = template.replace("@host@", socket.gethostname())

      try:

-         with open('version', 'w') as f:

+         with open("version", "w") as f:

              f.write(template)

      except:

-         raise VersionError('Cannot write to version file')

+         raise VersionError("Cannot write to version file")

  

  

  def _init():

-     ''' Possibly create version file, read and export it. '''

+     """ Possibly create version file, read and export it. """

      old_wd = os.getcwd()

      here = os.path.dirname(os.path.realpath(__file__))

      os.chdir(here)

-     version_path = os.path.join(here, 'version')

+     version_path = os.path.join(here, "version")

      if not os.path.exists(version_path):

          _setup()

      with open(version_path) as f:
@@ -68,6 +71,6 @@ 

      return version_script

  

  

- exec(_init())                                    # pylint: disable=W0122

+ exec(_init())  # pylint: disable=W0122

  

  # vim: set expandtab ts=4 sw=4;

file modified
+17 -17
@@ -15,21 +15,21 @@ 

  #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

  #

  

- '''

+ """

  python interface to XDG directories, implemented as-needed.

- '''

+ """

  

  import os

  import os.path

  

  

  class _XdgDirs(object):

-     ''' Methods to retrieve XDG standard paths. '''

+     """ Methods to retrieve XDG standard paths. """

  

-     APPNAME = 'fedora-review'

+     APPNAME = "fedora-review"

  

      def _get_dir(self, path, app_dir=False):

-         ''' Return a dir, create if not existing. '''

+         """ Return a dir, create if not existing. """

          if app_dir:

              path = os.path.join(path, self.APPNAME)

          if not os.path.exists(path):
@@ -37,27 +37,27 @@ 

          return path

  

      def get_configdir(self, app_dir=False):

-         ''' Return XDG config dir, with possible app dir appended. '''

-         if 'XDG_CONFIG_HOME' in os.environ:

-             path = os.environ['XDG_CONFIG_HOME']

+         """ Return XDG config dir, with possible app dir appended. """

+         if "XDG_CONFIG_HOME" in os.environ:

+             path = os.environ["XDG_CONFIG_HOME"]

          else:

-             path = os.path.expanduser('~/.config')

+             path = os.path.expanduser("~/.config")

          return self._get_dir(path, app_dir)

  

      def get_cachedir(self, app_dir=False):

-         ''' Return XDG cache dir, with possible app dir appended. '''

-         if 'XDG_CACHE_HOME' in os.environ:

-             path = os.environ['XDG_CACHE_HOME']

+         """ Return XDG cache dir, with possible app dir appended. """

+         if "XDG_CACHE_HOME" in os.environ:

+             path = os.environ["XDG_CACHE_HOME"]

          else:

-             path = os.path.expanduser('~/.cache')

+             path = os.path.expanduser("~/.cache")

          return self._get_dir(path, app_dir)

  

      def get_datadir(self, app_dir=False):

-         ''' Return XDG data dir, with possible app dir appended. '''

-         if 'XDG_DATA_HOME' in os.environ:

-             path = os.environ['XDG_DATA_HOME']

+         """ Return XDG data dir, with possible app dir appended. """

+         if "XDG_DATA_HOME" in os.environ:

+             path = os.environ["XDG_DATA_HOME"]

          else:

-             path = os.path.expanduser('~/.local/share')

+             path = os.path.expanduser("~/.local/share")

          return self._get_dir(path, app_dir)

  

      datadir = property(lambda self: self.get_datadir())

file modified
+1 -1
@@ -1,2 +1,2 @@ 

- ''' Required to make python import from top directory '''

+ """ Required to make python import from top directory """

  pass

file modified
+3 -2
@@ -37,13 +37,14 @@ 

  

  # Load from site lib

  from distutils.sysconfig import get_python_lib

- sitedir = os.path.join(get_python_lib(), 'FedoraReview')

+ 

+ sitedir = os.path.join(get_python_lib(), "FedoraReview")

  if os.path.exists(sitedir):

      sys.path.insert(0, sitedir)

  

  # Load from development lib

  here = os.path.dirname(os.path.realpath(__file__))

- srcdir = os.path.join(here, 'FedoraReview')

+ srcdir = os.path.join(here, "FedoraReview")

  if os.path.exists(srcdir):

      sys.path.insert(0, srcdir)

  

file modified
+1 -3
@@ -1,5 +1,5 @@ 

  #!/usr/bin/python -tt

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  # vim: set expandtab: ts=4:sw=4:

  #

  #    This program is free software; you can redistribute it and/or modify
@@ -24,5 +24,3 @@ 

  review = ReviewHelper()

  rc = review.run()

  sys.exit(rc)

- 

- 

file modified
+42 -44
@@ -16,9 +16,9 @@ 

  #    MA  02110-1301 USA.

  #

  # pylint: disable=C0103,R0904,R0913

- '''

+ """

  Base class for FedoraReview tests

- '''

+ """

  

  from __future__ import print_function

  import os
@@ -30,78 +30,76 @@ 

  

  from six.moves.urllib.request import urlopen

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  from FedoraReview import Mock, ReviewDirs, Settings

  from FedoraReview.checks import Checks

  from FedoraReview.review_helper import ReviewHelper

  

  STARTDIR = os.getcwd()

  

- VERSION = '0.7.0'

+ VERSION = "0.7.0"

  

- RELEASE = '28'

+ RELEASE = "28"

  

  try:

-     urlopen('http://bugzilla.redhat.com')

+     urlopen("http://bugzilla.redhat.com")

      NO_NET = False

  except IOError:

      NO_NET = True

  

- FAST_TEST = 'REVIEW_FAST_TEST' in os.environ

+ FAST_TEST = "REVIEW_FAST_TEST" in os.environ

  

- FEDORA = os.path.exists('/etc/fedora-release')

+ FEDORA = os.path.exists("/etc/fedora-release")

  

  

  class FR_TestCase(unittest.TestCase):

-     ''' Common base class for all tests. '''

+     """ Common base class for all tests. """

  

      BUILDROOT = "fedora-%s-i386" % RELEASE

-     BASE_URL = 'https://fedorahosted.org/releases/F/e/FedoraReview/'

+     BASE_URL = "https://fedorahosted.org/releases/F/e/FedoraReview/"

  

      @staticmethod

      def abs_file_url(path):

-         ''' Absolute path -> file: url. '''

-         return 'file://' + os.path.abspath(path)

+         """ Absolute path -> file: url. """

+         return "file://" + os.path.abspath(path)

  

      def setUp(self):

          self.log = Settings.get_logger()

          self.startdir = os.getcwd()

  

      def tearDown(self):

-         if 'REVIEW_TEST_GIT_STATUS' in os.environ:

+         if "REVIEW_TEST_GIT_STATUS" in os.environ:

              print()

-             subprocess.call('git status -uno | grep  "modified:"',

-                             shell=True)

+             subprocess.call('git status -uno | grep  "modified:"', shell=True)

          os.chdir(self.startdir)

  

-     def init_test(self, cd, argv=None, wd=None,

-                   buildroot=None, options=None):

-         '''

+     def init_test(self, cd, argv=None, wd=None, buildroot=None, options=None):

+         """

          Initiate a test which runs in directory cd

          kwargs:

             argv: fed to sys.argv and eventually to Settings

                   fedora-review is prepended and mock_root appended.

             wd:   review directory, cleared.

-            options: mock-options'''

+            options: mock-options"""

  

          cd = os.path.abspath(cd)

          os.chdir(cd)

          if not wd:

              wd = os.getcwd()

-         ReviewDirs.workdir_setup(wd, 'testing')

+         ReviewDirs.workdir_setup(wd, "testing")

          if not argv:

              argv = []

          args = argv

-         args.insert(0, 'fedora-review')

+         args.insert(0, "fedora-review")

          br = buildroot if buildroot else self.BUILDROOT

          args.append("--mock-config=" + br)

          opts = []

          if NO_NET:

-             opts.append('--offline')

+             opts.append("--offline")

          if options:

              opts.append(options)

          if opts:

-             argv.append('--mock-options=' + ' '.join(opts))

+             argv.append("--mock-options=" + " ".join(opts))

          sys.argv = argv

          Settings.init(True)

          Mock.clear_builddir()
@@ -109,59 +107,59 @@ 

  

      @staticmethod

      def run_single_check(bug, check_name, run_build=False):

-         ''' Run a single check, return check.'''

+         """ Run a single check, return check."""

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

          checks.set_single_check(check_name)

          if run_build:

-             checks['CheckBuild'].run()

+             checks["CheckBuild"].run()

          check = checks[check_name]

          check.run()

          return check

  

      def run_spec(self, spec):

-         ''' Run all tests for a test spec.... '''

+         """ Run all tests for a test spec.... """

          # pylint: disable=C0111,W0212

  

          class Null(object):

              def write(self, msg):

                  pass

  

-         argv = ['-rn', spec.testcase, '-x', 'generic-large-docs',

-                 '--no-build']

+         argv = ["-rn", spec.testcase, "-x", "generic-large-docs", "--no-build"]

          argv.extend(spec.args)

          self.init_test(spec.testcase, wd=spec.workdir, argv=argv)

          helper = ReviewHelper()

          Mock.clear_builddir()

-         if os.path.exists('BUILD'):

-             if os.path.islink('BUILD'):

-                 os.unlink('BUILD')

+         if os.path.exists("BUILD"):

+             if os.path.islink("BUILD"):

+                 os.unlink("BUILD")

              else:

-                 shutil.rmtree('BUILD')

+                 shutil.rmtree("BUILD")

          stdout = sys.stdout

          sys.stdout = Null()

-         rc = helper.run('review.txt')

+         rc = helper.run("review.txt")

          self.assertEqual(rc, 0)

          sys.stdout = stdout

          checkdict = helper.checks.get_checks()

          for check in checkdict.values():

              self.assertTrue(check.is_run)

              if check.is_passed or check.is_pending or check.is_failed:

-                 self.assertIn(check.group, spec.groups_ok,

-                               check.name + ': group is ' + check.group)

+                 self.assertIn(

+                     check.group,

+                     spec.groups_ok,

+                     check.name + ": group is " + check.group,

+                 )

          for (what, check) in spec.expected:

              state = checkdict[check].state

-             if what in ['pass', 'fail', 'pending']:

-                 self.assertEqual(state, what,

-                                  check + ': state is ' + str(state))

-             elif what == 'na':

-                 self.assertEqual(state, None,

-                                  check + ': state is ' + str(state))

-             elif what.startswith == 'in_attachment':

-                 self.assertIn(what.split(':')[1],

-                               checkdict[check].attachments[0].text)

+             if what in ["pass", "fail", "pending"]:

+                 self.assertEqual(state, what, check + ": state is " + str(state))

+             elif what == "na":

+                 self.assertEqual(state, None, check + ": state is " + str(state))

+             elif what.startswith == "in_attachment":

+                 self.assertIn(what.split(":")[1], checkdict[check].attachments[0].text)

              else:

                  self.assertFalse(what)

  

+ 

  # vim: set expandtab ts=4 sw=4:

file modified
+8 -8
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by

  #    the Free Software Foundation; either version 2 of the License, or
@@ -15,21 +15,21 @@ 

  #    MA 02110-1301 USA.

  #

  # pylint: disable=C0103,R0904,R0913

- ''' Insert path to package into sys.path. '''

+ """ Insert path to package into sys.path. """

  

  import os

  import sys

  

  from distutils.sysconfig import get_python_lib

  

- if os.path.exists('../src'):

-     SRC_PATH = os.path.abspath('../src')

-     REVIEW_PATH = os.path.abspath('../src/fedora-review')

-     PLUGIN_PATH = os.path.abspath('..')

+ if os.path.exists("../src"):

+     SRC_PATH = os.path.abspath("../src")

+     REVIEW_PATH = os.path.abspath("../src/fedora-review")

+     PLUGIN_PATH = os.path.abspath("..")

  else:

-     SRC_PATH = os.path.join(get_python_lib(), 'FedoraReview')

+     SRC_PATH = os.path.join(get_python_lib(), "FedoraReview")

      PLUGIN_PATH = SRC_PATH

-     REVIEW_PATH = '/usr/bin/fedora-review'

+     REVIEW_PATH = "/usr/bin/fedora-review"

  assert os.path.exists(SRC_PATH), "Can't find src path"

  sys.path.insert(0, SRC_PATH)

  

file modified
+29 -30
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -16,15 +16,15 @@ 

  #    MA  02110-1301 USA.

  #

  # pylint: disable=C0103,R0904,R0913,W0201

- '''

+ """

  Unit checks for automatic test of fedora R review guidelines

- '''

+ """

  

  import os

  import sys

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  from FedoraReview.checks import Checks

  from FedoraReview.name_bug import NameBug

  from FedoraReview.spec_file import SpecFile
@@ -33,12 +33,14 @@ 

  

  

  class TestRChecks(FR_TestCase):

-     ''' Some R specific tests. '''

+     """ Some R specific tests. """

  

-     R_TEST_SRPM = 'https://fedorahosted.org/releases/F/e' \

-                   '/FedoraReview/R-Rdummypkg-1.0-2.fc15.src.rpm'

-     R_TEST_SPEC = FR_TestCase.BASE_URL + 'R-Rdummypkg.spec'

-     R_TEST_SRC  = FR_TestCase.BASE_URL + 'Rdummypkg_1.0.tar.gz'

+     R_TEST_SRPM = (

+         "https://fedorahosted.org/releases/F/e"

+         "/FedoraReview/R-Rdummypkg-1.0-2.fc15.src.rpm"

+     )

+     R_TEST_SPEC = FR_TestCase.BASE_URL + "R-Rdummypkg.spec"

+     R_TEST_SRC = FR_TestCase.BASE_URL + "Rdummypkg_1.0.tar.gz"

  

      def setUp(self):

          if not srcpath.PLUGIN_PATH in sys.path:
@@ -46,7 +48,7 @@ 

          self.startdir = os.getcwd()

  

      def test_good_R_spec(self):

-         ''' test R spec, expected to pass. '''

+         """ test R spec, expected to pass. """

          # pylint: disable=F0401,R0201,C0111

  

          from plugins.R import RCheckInstallSection
@@ -58,16 +60,15 @@ 

              def is_applicable(self):

                  return True

  

-         self.init_test('test-R',

-                         argv=['-rpn', 'R-Rdummypkg', '--no-build'])

-         spec = SpecFile(os.path.join(os.getcwd(), 'R-Rdummypkg.spec'))

+         self.init_test("test-R", argv=["-rpn", "R-Rdummypkg", "--no-build"])

+         spec = SpecFile(os.path.join(os.getcwd(), "R-Rdummypkg.spec"))

          check = ApplicableRCheckInstallSection(ChecksMockup())

          check.checks.spec = spec

          check.run()

          self.assertTrue(check.is_passed)

  

      def test_bad_R_spec(self):

-         ''' test R spec, expected to fail. '''

+         """ test R spec, expected to fail. """

          # pylint: disable=F0401,R0201,C0111

  

          from plugins.R import RCheckInstallSection
@@ -79,39 +80,37 @@ 

              def is_applicable(self):

                  return True

  

-         self.init_test('test-R',

-                         argv=['-rpn', 'R-Rdummypkg', '--no-build'])

-         spec = SpecFile(os.path.join(os.getcwd(), 'R-Rdummypkg-bad.spec'))

+         self.init_test("test-R", argv=["-rpn", "R-Rdummypkg", "--no-build"])

+         spec = SpecFile(os.path.join(os.getcwd(), "R-Rdummypkg-bad.spec"))

          check = ApplicableRCheckInstallSection(ChecksMockup())

          check.checks.spec = spec

          check.run()

          note = check.result.output_extra

          self.assertTrue(check.is_failed)

-         self.assertTrue('directory creation' in note)

-         self.assertTrue('removal of *.o and *.so' in note)

-         self.assertTrue('removal of the R.css file' in note)

-         self.assertTrue('R CMD INSTALL function' in note)

+         self.assertTrue("directory creation" in note)

+         self.assertTrue("removal of *.o and *.so" in note)

+         self.assertTrue("removal of the R.css file" in note)

+         self.assertTrue("R CMD INSTALL function" in note)

  

-     @unittest.skipIf(FAST_TEST, 'slow test disabled by REVIEW_FAST_TEST')

+     @unittest.skipIf(FAST_TEST, "slow test disabled by REVIEW_FAST_TEST")

      def test_all_checks(self):

-         ''' Run all automated review checks'''

-         self.init_test('test-R',

-                         argv=['-rpn', 'R-Rdummypkg', '--no-build'])

-         self.bug = NameBug('R-Rdummypkg')

+         """ Run all automated review checks"""

+         self.init_test("test-R", argv=["-rpn", "R-Rdummypkg", "--no-build"])

+         self.bug = NameBug("R-Rdummypkg")

          self.bug.find_urls()

          self.bug.download_files()

          self.checks = Checks(self.bug.spec_file, self.bug.srpm_file)

          self.checks.run_checks(writedown=False)

          for check in self.checks.checkdict.values():

-             #if not os.path.exists('test-R/rpms-unpacked'):

+             # if not os.path.exists('test-R/rpms-unpacked'):

              #    os.mkdir('test-R/rpms-unpacked')

              if check.is_passed or check.is_pending or check.is_failed:

-                 ok_groups = ['Generic.build', 'Generic', 'Generic.should', 'R']

+                 ok_groups = ["Generic.build", "Generic", "Generic.should", "R"]

                  self.assertIn(check.group, ok_groups)

-             #shutil.rmtree('test-R/rpms-unpacked')

+             # shutil.rmtree('test-R/rpms-unpacked')

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+34 -32
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -17,16 +17,16 @@ 

  #

  # pylint: disable=C0103,R0904,R0913

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for bugzilla bug handling

- '''

+ """

  

  import os

  import os.path

  import sys

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  

  from FedoraReview.bugzilla_bug import BugzillaBug

  
@@ -34,51 +34,53 @@ 

  

  

  class TestBugzilla(FR_TestCase):

-     ''' Test the bugzilla-specific parts. '''

-     TEST_BUG = '672280'

+     """ Test the bugzilla-specific parts. """

  

-     @unittest.skipIf(NO_NET, 'No network available')

+     TEST_BUG = "672280"

+ 

+     @unittest.skipIf(NO_NET, "No network available")

      def test_find_urls(self):

-         ''' See that we can find URLs in bugzilla's bug page. '''

-         self.init_test('bugzilla',

-                        argv=['-b', self.TEST_BUG], wd='python-test')

+         """ See that we can find URLs in bugzilla's bug page. """

+         self.init_test("bugzilla", argv=["-b", self.TEST_BUG], wd="python-test")

          self.bug = BugzillaBug(self.TEST_BUG)

          rc = self.bug.find_urls()

          self.assertTrue(rc)

-         home = 'http://timlau.fedorapeople.org/files/test/review-test'

-         self.assertEqual(self.bug.srpm_url,

-                          os.path.join(home,

-                                       'python-test-1.0-1.fc14.src.rpm'))

-         self.assertEqual(self.bug.spec_url,

-                          os.path.join(home, 'python-test.spec'))

+         home = "http://timlau.fedorapeople.org/files/test/review-test"

+         self.assertEqual(

+             self.bug.srpm_url, os.path.join(home, "python-test-1.0-1.fc14.src.rpm")

+         )

+         self.assertEqual(self.bug.spec_url, os.path.join(home, "python-test.spec"))

  

-     @unittest.skipIf(NO_NET, 'No network available')

+     @unittest.skipIf(NO_NET, "No network available")

      def test_download_files(self):

-         '''

+         """

          Test that we can download the spec and srpm from a bugzilla report

-         '''

-         self.init_test('bugzilla',

-                        argv=['-b', self.TEST_BUG], wd='python-test')

-         self.bug = BugzillaBug(self.TEST_BUG)    # pylint: disable=W0201

+         """

+         self.init_test("bugzilla", argv=["-b", self.TEST_BUG], wd="python-test")

+         self.bug = BugzillaBug(self.TEST_BUG)  # pylint: disable=W0201

          self.bug.find_urls()

          rc = self.bug.download_files()

          self.assertTrue(rc)

-         self.assertEqual(self.bug.srpm_url,

-                          'http://timlau.fedorapeople.org/files/test'

-                          '/review-test/python-test-1.0-1.fc14.src.rpm')

-         self.assertEqual(self.bug.spec_url,

-                          'http://timlau.fedorapeople.org/files/test/'

-                           'review-test/python-test.spec')

+         self.assertEqual(

+             self.bug.srpm_url,

+             "http://timlau.fedorapeople.org/files/test"

+             "/review-test/python-test-1.0-1.fc14.src.rpm",

+         )

+         self.assertEqual(

+             self.bug.spec_url,

+             "http://timlau.fedorapeople.org/files/test/" "review-test/python-test.spec",

+         )

  

-         cd = os.path.abspath('./srpm')

-         srpm = os.path.join(cd, 'python-test-1.0-1.fc14.src.rpm')

-         spec = os.path.join(cd, 'python-test.spec')

+         cd = os.path.abspath("./srpm")

+         srpm = os.path.join(cd, "python-test-1.0-1.fc14.src.rpm")

+         spec = os.path.join(cd, "python-test.spec")

          self.assertEqual(self.bug.srpm_file, srpm)

          self.assertEqual(self.bug.spec_file, spec)

          self.assertTrue(os.path.exists(srpm))

          self.assertTrue(os.path.exists(spec))

  

- if __name__ == '__main__':

+ 

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+369 -344
@@ -17,399 +17,424 @@ 

  #

  # pylint: disable=C0103,R0904,R0913,W0201,bad-continuation

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit checks for automatic test of fedora review guidelines

- '''

+ """

  

  import sys

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  

  from fr_testcase import FR_TestCase, FEDORA

  

  

  class Testspec(object):

-     ''' Simple container for testdata. '''

+     """ Simple container for testdata. """

+ 

      pass

  

  

  class TestChecks(FR_TestCase):

-     ''' Some complete tests, all results checked.'''

+     """ Some complete tests, all results checked."""

  

      def test_ruby_racc(self):

-         ''' Run automated generic + ruby tests. '''

+         """ Run automated generic + ruby tests. """

          spec = Testspec()

          spec.args = []

-         spec.testcase = 'ruby-racc'

-         spec.workdir = 'ruby-racc'

-         spec.groups_ok = ['Generic.build', 'Generic', 'Generic.should', 'Ruby']

-         spec.expected = [('na', 'CheckResultdir'),

-                         ('pending', 'CheckBuild'),

-                         ('na', 'CheckDaemonCompileFlags'),

-                         ('pass', 'CheckRpmlint'),

-                         ('pass', 'CheckPackageInstalls'),

-                         ('pass', 'CheckRpmlintInstalled'),

-                         ('pending', 'CheckObeysFHS'),

-                         ('pass', 'CheckFileRequires'),

-                         ('pass', 'CheckUTF8Filenames'),

-                         ('fail', 'RubyCheckNotRequiresRubyAbi'),

-                         ('fail', 'RubyCheckRequiresRubyRelease'),

-                         ('pending', 'CheckNoConflicts'),

-                         ('pass', 'RubyCheckBuildArchitecture'),

-                         ('pending', 'CheckTestSuites'),

-                         ('pending', 'CheckBuildroot'),

-                         ('pending', 'CheckNaming'),

-                         ('pending', 'CheckFinalRequiresProvides'),

-                         ('pass', 'CheckDistTag'),

-                         ('pending', 'CheckSupportAllArchs'),

-                         ('pass', 'CheckFilePermissions'),

-                         ('pending', 'CheckLatestVersionIsPackaged'),

-                         ('pending', 'CheckObsoletesForRename'),

-                         ('fail', 'NonGemCheckUsesMacros'),

-                         ('pending', 'CheckClean'),

-                         ('pending', 'CheckCleanBuildroot'),

-                         ('pass', 'CheckDescMacros'),

-                         ('pending', 'NonGemCheckFilePlacement'),

-                         ('pending', 'CheckSpecDescTranslation'),

-                         ('pending', 'CheckUseGlobal'),

-                         ('pending', 'CheckDefattr'),

-                         ('pending', 'CheckGuidelines'),

-                         ('pass', 'NonGemCheckRequiresProperDevel'),

-                         ('pass', 'CheckSourceUrl'),

-                         ('pending', 'generic-excludearch'),

-                         ('pass', 'RubyCheckTestsRun'),

-                         ('pass', 'CheckOwnOther'),

-                         ('na', 'CheckFullVerReqSub'),

-                         ('pending', 'CheckApprovedLicense'),

-                         ('pending', 'CheckDocRuntime'),

-                         ('pass', 'CheckFileDuplicates'),

-                         ('pass', 'CheckSourceMD5'),

-                         ('pending', 'CheckBundledLibs'),

-                         ('fail', 'CheckBuildInMock'),

- # Disable for now due to F18/F19 differences

- #                         ('pass' if FEDORA else 'pending',

- #                                    'CheckOwnDirs'),

-                         ('na', 'CheckSourceComment'),

-                         ('pending', 'CheckTimeStamps'),

-                         ('fail', 'CheckRelocatable'),

-                         ('pending', 'CheckLicenseUpstream'),

-                         ('pending', 'CheckSystemdScripts'),

-                         ('pending', 'CheckMacros'),

-                         ('pending', 'CheckFunctionAsDescribed'),

-                         ('fail', 'CheckLicensInDoc'),

-                         ('pending', 'CheckRequires'),

-                         ('pending', 'CheckCodeAndContent'),

-                         ('pass', 'CheckNameCharset'),

-                         ('pass', 'CheckIllegalSpecTags'),

-                         ('pass', 'CheckSpecName'),

-                         ('pending', 'CheckDevelFilesInDevel'),

-                         ('pending', 'CheckSpecLegibility'),

-                         ('na', 'CheckBuildCompilerFlags'),

-                         ('pending', 'CheckContainsLicenseText'),

-                         ('pending', 'CheckDesktopFile'),

-                         ('pending', 'CheckLicenseField'),

-                         ('pending', 'CheckPatchComments'),

-                         ('pending', 'CheckChangelogFormat'),

-                         ('pass', 'CheckSourceDownloads'),

-                         ('na', 'generic-large-data'),

-                         ('pass', 'generic-srv-opt')]

+         spec.testcase = "ruby-racc"

+         spec.workdir = "ruby-racc"

+         spec.groups_ok = ["Generic.build", "Generic", "Generic.should", "Ruby"]

+         spec.expected = [

+             ("na", "CheckResultdir"),

+             ("pending", "CheckBuild"),

+             ("na", "CheckDaemonCompileFlags"),

+             ("pass", "CheckRpmlint"),

+             ("pass", "CheckPackageInstalls"),

+             ("pass", "CheckRpmlintInstalled"),

+             ("pending", "CheckObeysFHS"),

+             ("pass", "CheckFileRequires"),

+             ("pass", "CheckUTF8Filenames"),

+             ("fail", "RubyCheckNotRequiresRubyAbi"),

+             ("fail", "RubyCheckRequiresRubyRelease"),

+             ("pending", "CheckNoConflicts"),

+             ("pass", "RubyCheckBuildArchitecture"),

+             ("pending", "CheckTestSuites"),

+             ("pending", "CheckBuildroot"),

+             ("pending", "CheckNaming"),

+             ("pending", "CheckFinalRequiresProvides"),

+             ("pass", "CheckDistTag"),

+             ("pending", "CheckSupportAllArchs"),

+             ("pass", "CheckFilePermissions"),

+             ("pending", "CheckLatestVersionIsPackaged"),

+             ("pending", "CheckObsoletesForRename"),

+             ("fail", "NonGemCheckUsesMacros"),

+             ("pending", "CheckClean"),

+             ("pending", "CheckCleanBuildroot"),

+             ("pass", "CheckDescMacros"),

+             ("pending", "NonGemCheckFilePlacement"),

+             ("pending", "CheckSpecDescTranslation"),

+             ("pending", "CheckUseGlobal"),

+             ("pending", "CheckDefattr"),

+             ("pending", "CheckGuidelines"),

+             ("pass", "NonGemCheckRequiresProperDevel"),

+             ("pass", "CheckSourceUrl"),

+             ("pending", "generic-excludearch"),

+             ("pass", "RubyCheckTestsRun"),

+             ("pass", "CheckOwnOther"),

+             ("na", "CheckFullVerReqSub"),

+             ("pending", "CheckApprovedLicense"),

+             ("pending", "CheckDocRuntime"),

+             ("pass", "CheckFileDuplicates"),

+             ("pass", "CheckSourceMD5"),

+             ("pending", "CheckBundledLibs"),

+             ("fail", "CheckBuildInMock"),

+             # Disable for now due to F18/F19 differences

+             #                         ('pass' if FEDORA else 'pending',

+             #                                    'CheckOwnDirs'),

+             ("na", "CheckSourceComment"),

+             ("pending", "CheckTimeStamps"),

+             ("fail", "CheckRelocatable"),

+             ("pending", "CheckLicenseUpstream"),

+             ("pending", "CheckSystemdScripts"),

+             ("pending", "CheckMacros"),

+             ("pending", "CheckFunctionAsDescribed"),

+             ("fail", "CheckLicensInDoc"),

+             ("pending", "CheckRequires"),

+             ("pending", "CheckCodeAndContent"),

+             ("pass", "CheckNameCharset"),

+             ("pass", "CheckIllegalSpecTags"),

+             ("pass", "CheckSpecName"),

+             ("pending", "CheckDevelFilesInDevel"),

+             ("pending", "CheckSpecLegibility"),

+             ("na", "CheckBuildCompilerFlags"),

+             ("pending", "CheckContainsLicenseText"),

+             ("pending", "CheckDesktopFile"),

+             ("pending", "CheckLicenseField"),

+             ("pending", "CheckPatchComments"),

+             ("pending", "CheckChangelogFormat"),

+             ("pass", "CheckSourceDownloads"),

+             ("na", "generic-large-data"),

+             ("pass", "generic-srv-opt"),

+         ]

          self.run_spec(spec)

  

      def test_rubygem_fssm(self):

-         ''' Run automated generic + rubygem tests. '''

+         """ Run automated generic + rubygem tests. """

          spec = Testspec()

          spec.args = []

-         spec.testcase = 'rubygem-fssm'

-         spec.workdir = 'rubygem-fssm'

-         spec.groups_ok = ['Generic.build', 'Generic', 'Generic.should', 'Ruby']

-         spec.expected = [('pending', 'CheckBuild'),

-                         ('na', 'CheckDaemonCompileFlags'),

-                         ('pass', 'CheckRpmlint'),

-                         ('pass', 'CheckPackageInstalls'),

-                         ('pass', 'CheckRpmlintInstalled'),

-                         ('fail', 'GemCheckRequiresRubygems'),

-                         ('pending', 'CheckObeysFHS'),

-                         ('pass', 'GemCheckProperName'),

-                         ('pass', 'CheckFileRequires'),

-                         ('pass', 'GemCheckUsesMacros'),

-                         ('pending', 'CheckSupportAllArchs'),

-                         ('pending', 'GemCheckFilePlacement'),

-                         ('pass', 'RubyCheckBuildArchitecture'),

-                         ('pending', 'CheckTestSuites'),

-                         ('pass', 'CheckBuildroot'),

-                         ('pending', 'CheckNaming'),

-                         ('pending', 'CheckFinalRequiresProvides'),

-                         ('pass', 'CheckDistTag'),

-                         ('pass', 'CheckFilePermissions'),

-                         ('pending', 'CheckLatestVersionIsPackaged'),

-                         ('pending', 'CheckObsoletesForRename'),

-                         ('pass', 'CheckClean'),

-                         ('pass', 'CheckCleanBuildroot'),

-                         ('pass', 'CheckDescMacros'),

-                         ('pass', 'CheckSourceDownloads'),

-                         ('pending', 'CheckSpecDescTranslation'),

-                         ('pass', 'CheckUseGlobal'),

-                         ('pass', 'GemCheckRequiresProperDevel'),

-                         ('pending', 'CheckGuidelines'),

-                         ('na', 'CheckDefattr'),

-                         ('pass', 'CheckSourceUrl'),

-                         ('pending', 'generic-excludearch'),

-                         ('pass', 'RubyCheckTestsRun'),

-                         ('pass', 'CheckUTF8Filenames'),

-                         ('pending', 'CheckLicenseInSubpackages'),

-                         ('pass', 'CheckOwnOther'),

-                         ('pass', 'CheckFullVerReqSub'),

-                         ('pending', 'CheckApprovedLicense'),

-                         ('pending', 'CheckDocRuntime'),

-                         ('pass', 'GemCheckSetsGemName'),

-                         ('pass', 'CheckSourceMD5'),

-                         ('pending', 'CheckBundledLibs'),

-                         ('fail', 'CheckBuildInMock'),

-                         ('pending', 'CheckOwnDirs'),

-                         ('fail', 'RubyCheckNotRequiresRubyAbi'),

-                         ('fail', 'RubyCheckRequiresRubyRelease'),

-                         ('fail', 'GemCheckGemInstallMacro'),

-                         ('pass', 'GemCheckGemExtdirMacro'),

-                         ('pass', 'CheckMakeinstall'),

-                         ('na', 'CheckSourceComment'),

-                         ('pending', 'CheckTimeStamps'),

-                         ('pass', 'CheckFileDuplicates'),

-                         ('pass', 'CheckRelocatable'),

-                         ('pending', 'CheckLicenseUpstream'),

-                         ('pending', 'CheckSystemdScripts'),

-                         ('pending', 'CheckMacros'),

-                         ('pending', 'CheckFunctionAsDescribed'),

-                         ('fail', 'CheckLicensInDoc'),

-                         ('pending', 'CheckRequires'),

-                         ('pending', 'CheckCodeAndContent'),

-                         ('pass', 'CheckNameCharset'),

-                         ('pass', 'GemCheckExcludesGemCache'),

-                         ('pass', 'CheckIllegalSpecTags'),

-                         ('pass', 'CheckSpecName'),

-                         ('pending', 'CheckNoConflicts'),

-                         ('pass', 'GemCheckDoesntHaveNonGemSubpackage'),

-                         ('pending', 'CheckSpecLegibility'),

-                         ('pending', 'CheckContainsLicenseText'),

-                         ('pending', 'CheckDesktopFile'),

-                         ('pending', 'CheckDevelFilesInDevel'),

-                         ('fail', 'CheckNoNameConflict'),

-                         ('pending', 'CheckChangelogFormat'),

-                         ('na', 'generic-large-data'),

-                         ('pass', 'generic-srv-opt')]

+         spec.testcase = "rubygem-fssm"

+         spec.workdir = "rubygem-fssm"

+         spec.groups_ok = ["Generic.build", "Generic", "Generic.should", "Ruby"]

+         spec.expected = [

+             ("pending", "CheckBuild"),

+             ("na", "CheckDaemonCompileFlags"),

+             ("pass", "CheckRpmlint"),

+             ("pass", "CheckPackageInstalls"),

+             ("pass", "CheckRpmlintInstalled"),

+             ("fail", "GemCheckRequiresRubygems"),

+             ("pending", "CheckObeysFHS"),

+             ("pass", "GemCheckProperName"),

+             ("pass", "CheckFileRequires"),

+             ("pass", "GemCheckUsesMacros"),

+             ("pending", "CheckSupportAllArchs"),

+             ("pending", "GemCheckFilePlacement"),

+             ("pass", "RubyCheckBuildArchitecture"),

+             ("pending", "CheckTestSuites"),

+             ("pass", "CheckBuildroot"),

+             ("pending", "CheckNaming"),

+             ("pending", "CheckFinalRequiresProvides"),

+             ("pass", "CheckDistTag"),

+             ("pass", "CheckFilePermissions"),

+             ("pending", "CheckLatestVersionIsPackaged"),

+             ("pending", "CheckObsoletesForRename"),

+             ("pass", "CheckClean"),

+             ("pass", "CheckCleanBuildroot"),

+             ("pass", "CheckDescMacros"),

+             ("pass", "CheckSourceDownloads"),

+             ("pending", "CheckSpecDescTranslation"),

+             ("pass", "CheckUseGlobal"),

+             ("pass", "GemCheckRequiresProperDevel"),

+             ("pending", "CheckGuidelines"),

+             ("na", "CheckDefattr"),

+             ("pass", "CheckSourceUrl"),

+             ("pending", "generic-excludearch"),

+             ("pass", "RubyCheckTestsRun"),

+             ("pass", "CheckUTF8Filenames"),

+             ("pending", "CheckLicenseInSubpackages"),

+             ("pass", "CheckOwnOther"),

+             ("pass", "CheckFullVerReqSub"),

+             ("pending", "CheckApprovedLicense"),

+             ("pending", "CheckDocRuntime"),

+             ("pass", "GemCheckSetsGemName"),

+             ("pass", "CheckSourceMD5"),

+             ("pending", "CheckBundledLibs"),

+             ("fail", "CheckBuildInMock"),

+             ("pending", "CheckOwnDirs"),

+             ("fail", "RubyCheckNotRequiresRubyAbi"),

+             ("fail", "RubyCheckRequiresRubyRelease"),

+             ("fail", "GemCheckGemInstallMacro"),

+             ("pass", "GemCheckGemExtdirMacro"),

+             ("pass", "CheckMakeinstall"),

+             ("na", "CheckSourceComment"),

+             ("pending", "CheckTimeStamps"),

+             ("pass", "CheckFileDuplicates"),

+             ("pass", "CheckRelocatable"),

+             ("pending", "CheckLicenseUpstream"),

+             ("pending", "CheckSystemdScripts"),

+             ("pending", "CheckMacros"),

+             ("pending", "CheckFunctionAsDescribed"),

+             ("fail", "CheckLicensInDoc"),

+             ("pending", "CheckRequires"),

+             ("pending", "CheckCodeAndContent"),

+             ("pass", "CheckNameCharset"),

+             ("pass", "GemCheckExcludesGemCache"),

+             ("pass", "CheckIllegalSpecTags"),

+             ("pass", "CheckSpecName"),

+             ("pending", "CheckNoConflicts"),

+             ("pass", "GemCheckDoesntHaveNonGemSubpackage"),

+             ("pending", "CheckSpecLegibility"),

+             ("pending", "CheckContainsLicenseText"),

+             ("pending", "CheckDesktopFile"),

+             ("pending", "CheckDevelFilesInDevel"),

+             ("fail", "CheckNoNameConflict"),

+             ("pending", "CheckChangelogFormat"),

+             ("na", "generic-large-data"),

+             ("pass", "generic-srv-opt"),

+         ]

          self.run_spec(spec)

  

      def test_rubygem_RedCloth(self):

-         ''' Run automated generic + rubygem tests. '''

+         """ Run automated generic + rubygem tests. """

          spec = Testspec()

          spec.args = []

-         spec.testcase = 'rubygem-RedCloth'

-         spec.workdir = 'rubygem-RedCloth'

-         spec.groups_ok = ['Generic.build', 'Generic', 'Generic.should', 'Ruby']

-         spec.expected = [('pass', 'GemCheckGemInstallMacro'),

-                          ('fail', 'GemCheckGemExtdirMacro')]

+         spec.testcase = "rubygem-RedCloth"

+         spec.workdir = "rubygem-RedCloth"

+         spec.groups_ok = ["Generic.build", "Generic", "Generic.should", "Ruby"]

+         spec.expected = [

+             ("pass", "GemCheckGemInstallMacro"),

+             ("fail", "GemCheckGemExtdirMacro"),

+         ]

          self.run_spec(spec)

  

      def test_logback(self):

-         ''' Run automated generic+ java tests. '''

+         """ Run automated generic+ java tests. """

          spec = Testspec()

          spec.args = []

-         spec.testcase = 'logback'

-         spec.workdir = 'logback'

-         spec.groups_ok = ['Generic.build', 'Generic', 'Generic.should',

-                           'Java', 'Java.guidelines', 'Maven']

-         spec.expected = [('na', 'CheckResultdir'),

-                          ('pending', 'CheckBuild'),

-                          ('na', 'CheckJavaPlugin'),

-                          ('na', 'CheckDaemonCompileFlags'),

-                          ('pass', 'CheckRpmlint'),

-                          ('pass', 'CheckPackageInstalls'),

-                          ('pass', 'CheckRpmlintInstalled'),

-                          ('pending', 'CheckObeysFHS'),

-                          ('pass', 'CheckFileRequires'),

-                          ('pass', 'CheckUTF8Filenames'),

-                          ('pending', 'CheckNoConflicts'),

-                          ('pending', 'CheckTestSuites'),

-                          ('pass', 'CheckBuildroot'),

-                          ('pending', 'CheckNaming'),

-                          ('pending', 'CheckFinalRequiresProvides'),

-                          ('pass', 'CheckDistTag'),

-                          ('pending', 'CheckSupportAllArchs'),

-                          ('pass', 'CheckFilePermissions'),

-                          ('pending', 'CheckLatestVersionIsPackaged'),

-                          ('pending', 'CheckObsoletesForRename'),

-                          ('pass', 'CheckClean'),

-                          ('pass', 'CheckCleanBuildroot'),

-                          ('pass', 'CheckDescMacros'),

-                          ('pending', 'CheckSpecDescTranslation'),

-                          ('pass', 'CheckUseGlobal'),

-                          ('na', 'CheckDefattr'),

-                          ('pending', 'CheckMultipleLicenses'),

-                          ('pending', 'CheckGuidelines'),

-                          ('pass', 'CheckSourceUrl'),

-                          ('pending', 'generic-excludearch'),

-                          ('na', 'CheckAutotoolsObsoletedMacros'),

-                          ('pending', 'CheckLicenseInSubpackages'),

-                          ('pass', 'CheckOwnOther'),

-                          ('pending', 'CheckFullVerReqSub'),

-                          ('pending', 'CheckApprovedLicense'),

-                          ('pending', 'CheckDocRuntime'),

-                          ('pass', 'CheckFileDuplicates'),

-                          ('pass', 'CheckSourceMD5'),

-                          ('pending', 'CheckBundledLibs'),

-                          ('fail', 'CheckBuildInMock'),

-                          ('pass' if FEDORA else 'pending',

-                                      'CheckOwnDirs'),

-                          ('na', 'CheckSourceComment'),

-                          ('pending', 'CheckTimeStamps'),

-                          ('pass', 'CheckRelocatable'),

-                          ('pending', 'CheckLicenseUpstream'),

-                          ('pending', 'CheckSystemdScripts'),

-                          ('pending', 'CheckMacros'),

-                          ('pending', 'CheckFunctionAsDescribed'),

-                          ('fail', 'CheckLicensInDoc'),

-                          ('pending', 'CheckRequires'),

-                          ('pending', 'CheckCodeAndContent'),

-                          ('pass', 'CheckNameCharset'),

-                          ('pass', 'CheckIllegalSpecTags'),

-                          ('pass', 'CheckSpecName'),

-                          ('pending', 'CheckDevelFilesInDevel'),

-                          ('pending', 'CheckSpecLegibility'),

-                          ('na', 'CheckBuildCompilerFlags'),

-                          ('pending', 'CheckContainsLicenseText'),

-                          ('pending', 'CheckDesktopFile'),

-                          ('pending', 'CheckLicenseField'),

-                          ('pending', 'CheckPatchComments'),

-                          ('pending', 'CheckChangelogFormat'),

-                          ('pass', 'CheckSourceDownloads'),

-                          ('na', 'generic-large-data'),

-                          ('pass', 'generic-srv-opt')]

+         spec.testcase = "logback"

+         spec.workdir = "logback"

+         spec.groups_ok = [

+             "Generic.build",

+             "Generic",

+             "Generic.should",

+             "Java",

+             "Java.guidelines",

+             "Maven",

+         ]

+         spec.expected = [

+             ("na", "CheckResultdir"),

+             ("pending", "CheckBuild"),

+             ("na", "CheckJavaPlugin"),

+             ("na", "CheckDaemonCompileFlags"),

+             ("pass", "CheckRpmlint"),

+             ("pass", "CheckPackageInstalls"),

+             ("pass", "CheckRpmlintInstalled"),

+             ("pending", "CheckObeysFHS"),

+             ("pass", "CheckFileRequires"),

+             ("pass", "CheckUTF8Filenames"),

+             ("pending", "CheckNoConflicts"),

+             ("pending", "CheckTestSuites"),

+             ("pass", "CheckBuildroot"),

+             ("pending", "CheckNaming"),

+             ("pending", "CheckFinalRequiresProvides"),

+             ("pass", "CheckDistTag"),

+             ("pending", "CheckSupportAllArchs"),

+             ("pass", "CheckFilePermissions"),

+             ("pending", "CheckLatestVersionIsPackaged"),

+             ("pending", "CheckObsoletesForRename"),

+             ("pass", "CheckClean"),

+             ("pass", "CheckCleanBuildroot"),

+             ("pass", "CheckDescMacros"),

+             ("pending", "CheckSpecDescTranslation"),

+             ("pass", "CheckUseGlobal"),

+             ("na", "CheckDefattr"),

+             ("pending", "CheckMultipleLicenses"),

+             ("pending", "CheckGuidelines"),

+             ("pass", "CheckSourceUrl"),

+             ("pending", "generic-excludearch"),

+             ("na", "CheckAutotoolsObsoletedMacros"),

+             ("pending", "CheckLicenseInSubpackages"),

+             ("pass", "CheckOwnOther"),

+             ("pending", "CheckFullVerReqSub"),

+             ("pending", "CheckApprovedLicense"),

+             ("pending", "CheckDocRuntime"),

+             ("pass", "CheckFileDuplicates"),

+             ("pass", "CheckSourceMD5"),

+             ("pending", "CheckBundledLibs"),

+             ("fail", "CheckBuildInMock"),

+             ("pass" if FEDORA else "pending", "CheckOwnDirs"),

+             ("na", "CheckSourceComment"),

+             ("pending", "CheckTimeStamps"),

+             ("pass", "CheckRelocatable"),

+             ("pending", "CheckLicenseUpstream"),

+             ("pending", "CheckSystemdScripts"),

+             ("pending", "CheckMacros"),

+             ("pending", "CheckFunctionAsDescribed"),

+             ("fail", "CheckLicensInDoc"),

+             ("pending", "CheckRequires"),

+             ("pending", "CheckCodeAndContent"),

+             ("pass", "CheckNameCharset"),

+             ("pass", "CheckIllegalSpecTags"),

+             ("pass", "CheckSpecName"),

+             ("pending", "CheckDevelFilesInDevel"),

+             ("pending", "CheckSpecLegibility"),

+             ("na", "CheckBuildCompilerFlags"),

+             ("pending", "CheckContainsLicenseText"),

+             ("pending", "CheckDesktopFile"),

+             ("pending", "CheckLicenseField"),

+             ("pending", "CheckPatchComments"),

+             ("pending", "CheckChangelogFormat"),

+             ("pass", "CheckSourceDownloads"),

+             ("na", "generic-large-data"),

+             ("pass", "generic-srv-opt"),

+         ]

          self.run_spec(spec)

  

      def test_scriptlets_fail(self):

-         ''' Scriptlet tests mostly expected to fail. '''

+         """ Scriptlet tests mostly expected to fail. """

          spec = Testspec()

-         spec.testcase = 'scriptlets-fail'

-         spec.workdir = 'scriptlets-fail'

-         spec.args = ['-px', 'CheckPackageInstalls,CheckUTF8Filenames']

-         spec.groups_ok = ['Generic.build', 'Generic.should', 'Generic']

-         spec.expected = [('fail', 'CheckGconfSchemaInstall'),

-                          ('fail', 'CheckGtkQueryModules'),

-                          ('fail', 'CheckGioQueryModules'),

-                          ('fail', 'CheckUpdateIconCache'),

-                          ('fail', 'CheckInfoInstall'),

-                          ('fail', 'CheckGlibCompileSchemas'),

-                          ('fail', 'CheckUpdateMimeDatabase'),

-                          ('pending', 'CheckBundledFonts'),

-                          ('pending', 'CheckSourcedirMacroUse'),

-                          ('pending', 'CheckTmpfiles')]

+         spec.testcase = "scriptlets-fail"

+         spec.workdir = "scriptlets-fail"

+         spec.args = ["-px", "CheckPackageInstalls,CheckUTF8Filenames"]

+         spec.groups_ok = ["Generic.build", "Generic.should", "Generic"]

+         spec.expected = [

+             ("fail", "CheckGconfSchemaInstall"),

+             ("fail", "CheckGtkQueryModules"),

+             ("fail", "CheckGioQueryModules"),

+             ("fail", "CheckUpdateIconCache"),

+             ("fail", "CheckInfoInstall"),

+             ("fail", "CheckGlibCompileSchemas"),

+             ("fail", "CheckUpdateMimeDatabase"),

+             ("pending", "CheckBundledFonts"),

+             ("pending", "CheckSourcedirMacroUse"),

+             ("pending", "CheckTmpfiles"),

+         ]

          self.run_spec(spec)

  

      def test_scriptlets_ok(self):

-         ''' Scriptlet tests mostly expected to pass (or pending). '''

+         """ Scriptlet tests mostly expected to pass (or pending). """

          spec = Testspec()

-         spec.testcase = 'scriptlets-ok'

-         spec.workdir = 'scriptlets-ok'

-         spec.args = ['-px', 'CheckPackageInstalls,CheckUTF8Filenames']

-         spec.groups_ok = ['Generic.build', 'Generic.should', 'Generic']

-         spec.expected = [('pending', 'CheckGconfSchemaInstall'),

-                          ('pending', 'CheckGtkQueryModules'),

-                          ('pending', 'CheckGioQueryModules'),

-                          ('pending', 'CheckUpdateIconCache'),

-                          ('pending', 'CheckInfoInstall'),

-                          ('pending', 'CheckGlibCompileSchemas'),

-                          ('pending', 'CheckUpdateMimeDatabase'),

-                          ('pending', 'CheckBundledFonts'),

-                          ('pending', 'CheckSourcedirMacroUse'),

-                          ('pending', 'CheckTmpfiles'),

-                          ('na', 'CheckSourceDownloads')]

+         spec.testcase = "scriptlets-ok"

+         spec.workdir = "scriptlets-ok"

+         spec.args = ["-px", "CheckPackageInstalls,CheckUTF8Filenames"]

+         spec.groups_ok = ["Generic.build", "Generic.should", "Generic"]

+         spec.expected = [

+             ("pending", "CheckGconfSchemaInstall"),

+             ("pending", "CheckGtkQueryModules"),

+             ("pending", "CheckGioQueryModules"),

+             ("pending", "CheckUpdateIconCache"),

+             ("pending", "CheckInfoInstall"),

+             ("pending", "CheckGlibCompileSchemas"),

+             ("pending", "CheckUpdateMimeDatabase"),

+             ("pending", "CheckBundledFonts"),

+             ("pending", "CheckSourcedirMacroUse"),

+             ("pending", "CheckTmpfiles"),

+             ("na", "CheckSourceDownloads"),

+         ]

          self.run_spec(spec)

  

      def test_FreeSOLID(self):

-         ''' Test the FreeSOLID spec. '''

+         """ Test the FreeSOLID spec. """

          spec = Testspec()

          spec.args = []

-         spec.testcase = 'FreeSOLID'

-         spec.workdir = 'FreeSOLID'

-         spec.groups_ok = ['Generic.build', 'Generic.should', 'Generic',

-                           'Generic.autotools', 'C/C++']

-         spec.expected = [('na', 'CheckResultdir'),

-                          ('pending', 'CheckBuild'),

-                          ('na', 'CheckDaemonCompileFlags'),

-                          ('pass', 'CheckRpmlint'),

-                          ('pass', 'CheckPackageInstalls'),

-                          ('pass', 'CheckRpmlintInstalled'),

-                          ('pass', 'CheckParallelMake'),

-                          ('pending', 'CheckObeysFHS'),

-                          ('pass', 'CheckFileRequires'),

-                          ('pass', 'CheckUTF8Filenames'),

-                          ('pending', 'CheckNoConflicts'),

-                          ('pending', 'CheckTestSuites'),

-                          ('pass', 'CheckBuildroot'),

-                          ('pending', 'CheckNaming'),

-                          ('pending', 'CheckFinalRequiresProvides'),

-                          ('na', 'CheckSpecAsInSRPM'),

-                          ('pending', 'CheckScriptletSanity'),

-                          ('pass', 'CheckDistTag'),

-                          ('pending', 'CheckSupportAllArchs'),

-                          ('pass', 'CheckFilePermissions'),

-                          ('pending', 'CheckLatestVersionIsPackaged'),

-                          ('pending', 'CheckObsoletesForRename'),

-                          ('pass', 'CheckClean'),

-                          ('pass', 'CheckCleanBuildroot'),

-                          ('pass', 'CheckDescMacros'),

-                          ('pending', 'CheckSpecDescTranslation'),

-                          ('pass', 'CheckUseGlobal'),

-                          ('pass', 'CheckSoFiles'),

-                          ('na', 'CheckDefattr'),

-                          ('pending', 'CheckGuidelines'),

-                          ('pass', 'CheckSourceUrl'),

-                          ('pending', 'generic-excludearch'),

-                          ('pending', 'CheckLicenseInSubpackages'),

-                          ('pending', 'CheckNoKernelModules'),

-                          ('pass', 'CheckOwnOther'),

-                          ('pass', 'CheckFullVerReqSub'),

-                          ('pending', 'CheckApprovedLicense'),

-                          ('pending', 'CheckDocRuntime'),

-                          ('pass', 'CheckFileDuplicates'),

-                          ('pass', 'CheckSourceMD5'),

-                          ('pending', 'CheckBundledLibs'),

-                          ('fail', 'CheckBuildInMock'),

-                          ('pass', 'CheckLDConfig'),

-                          ('pending', 'CheckNoStaticExecutables'),

-                          ('pass', 'CheckRPATH'),

-                          ('pending', 'CheckUsefulDebuginfo'),

-                          ('na', 'CheckSourceComment'),

-                          ('pending', 'CheckTimeStamps'),

-                          ('pass', 'CheckHeaderFiles'),

-                          ('pass', 'CheckRelocatable'),

-                          ('pending', 'CheckLicenseUpstream'),

-                          ('pending', 'CheckSystemdScripts'),

-                          ('pending', 'CheckMacros'),

-                          ('pending', 'CheckFunctionAsDescribed'),

-                          ('fail', 'CheckLicensInDoc'),

-                          ('pending', 'CheckRequires'),

-                          ('pass', 'CheckPkgConfigFiles'),

-                          ('pending', 'CheckCodeAndContent'),

-                          ('pass', 'CheckNameCharset'),

-                          ('pass', 'CheckLibToolArchives'),

-                          ('pass', 'CheckIllegalSpecTags'),

-                          ('pass', 'CheckAutotoolsObsoletedMacros'),

-                          ('pass', 'CheckSpecName'),

-                          ('pending', 'CheckDevelFilesInDevel'),

-                          ('pending', 'CheckSpecLegibility'),

-                          ('pending', 'CheckBuildCompilerFlags'),

-                          ('pending', 'CheckContainsLicenseText'),

-                          ('pending', 'CheckDesktopFile'),

-                          ('pending', 'CheckLicenseField'),

-                          ('pending', 'CheckPatchComments'),

-                          ('pending', 'CheckChangelogFormat'),

-                          ('pass', 'generic-large-data'),

-                          ('pass', 'generic-srv-opt')]

+         spec.testcase = "FreeSOLID"

+         spec.workdir = "FreeSOLID"

+         spec.groups_ok = [

+             "Generic.build",

+             "Generic.should",

+             "Generic",

+             "Generic.autotools",

+             "C/C++",

+         ]

+         spec.expected = [

+             ("na", "CheckResultdir"),

+             ("pending", "CheckBuild"),

+             ("na", "CheckDaemonCompileFlags"),

+             ("pass", "CheckRpmlint"),

+             ("pass", "CheckPackageInstalls"),

+             ("pass", "CheckRpmlintInstalled"),

+             ("pass", "CheckParallelMake"),

+             ("pending", "CheckObeysFHS"),

+             ("pass", "CheckFileRequires"),

+             ("pass", "CheckUTF8Filenames"),

+             ("pending", "CheckNoConflicts"),

+             ("pending", "CheckTestSuites"),

+             ("pass", "CheckBuildroot"),

+             ("pending", "CheckNaming"),

+             ("pending", "CheckFinalRequiresProvides"),

+             ("na", "CheckSpecAsInSRPM"),

+             ("pending", "CheckScriptletSanity"),

+             ("pass", "CheckDistTag"),

+             ("pending", "CheckSupportAllArchs"),

+             ("pass", "CheckFilePermissions"),

+             ("pending", "CheckLatestVersionIsPackaged"),

+             ("pending", "CheckObsoletesForRename"),

+             ("pass", "CheckClean"),

+             ("pass", "CheckCleanBuildroot"),

+             ("pass", "CheckDescMacros"),

+             ("pending", "CheckSpecDescTranslation"),

+             ("pass", "CheckUseGlobal"),

+             ("pass", "CheckSoFiles"),

+             ("na", "CheckDefattr"),

+             ("pending", "CheckGuidelines"),

+             ("pass", "CheckSourceUrl"),

+             ("pending", "generic-excludearch"),

+             ("pending", "CheckLicenseInSubpackages"),

+             ("pending", "CheckNoKernelModules"),

+             ("pass", "CheckOwnOther"),

+             ("pass", "CheckFullVerReqSub"),

+             ("pending", "CheckApprovedLicense"),

+             ("pending", "CheckDocRuntime"),

+             ("pass", "CheckFileDuplicates"),

+             ("pass", "CheckSourceMD5"),

+             ("pending", "CheckBundledLibs"),

+             ("fail", "CheckBuildInMock"),

+             ("pass", "CheckLDConfig"),

+             ("pending", "CheckNoStaticExecutables"),

+             ("pass", "CheckRPATH"),

+             ("pending", "CheckUsefulDebuginfo"),

+             ("na", "CheckSourceComment"),

+             ("pending", "CheckTimeStamps"),

+             ("pass", "CheckHeaderFiles"),

+             ("pass", "CheckRelocatable"),

+             ("pending", "CheckLicenseUpstream"),

+             ("pending", "CheckSystemdScripts"),

+             ("pending", "CheckMacros"),

+             ("pending", "CheckFunctionAsDescribed"),

+             ("fail", "CheckLicensInDoc"),

+             ("pending", "CheckRequires"),

+             ("pass", "CheckPkgConfigFiles"),

+             ("pending", "CheckCodeAndContent"),

+             ("pass", "CheckNameCharset"),

+             ("pass", "CheckLibToolArchives"),

+             ("pass", "CheckIllegalSpecTags"),

+             ("pass", "CheckAutotoolsObsoletedMacros"),

+             ("pass", "CheckSpecName"),

+             ("pending", "CheckDevelFilesInDevel"),

+             ("pending", "CheckSpecLegibility"),

+             ("pending", "CheckBuildCompilerFlags"),

+             ("pending", "CheckContainsLicenseText"),

+             ("pending", "CheckDesktopFile"),

+             ("pending", "CheckLicenseField"),

+             ("pending", "CheckPatchComments"),

+             ("pending", "CheckChangelogFormat"),

+             ("pass", "generic-large-data"),

+             ("pass", "generic-srv-opt"),

+         ]

          self.run_spec(spec)

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+49 -45
@@ -17,74 +17,78 @@ 

  #

  # pylint: disable=C0103,R0904,R0913,W0212

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for bugzilla bug handling

- '''

+ """

  

  

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  import FedoraReview.deps as deps

  

  from fr_testcase import FEDORA

  

- DEPLIST_OK = {"bash",

-                   "python",

-                   "fedora-packager",

-                   "python",

-                   "python-BeautifulSoup",

-                   "python",

-                   "python-bugzilla",

-                   "python-kitchen",

-                   "python-straight-plugin",

-                   "packagedb-cli",

-                   "rpm-python",

-                   "devscripts-minimal"}

- 

- 

- DIRLIST_OK = {"/usr/share/doc/ruby-racc-1.4.5",

-                   "/usr/share/doc/ruby-racc-1.4.5/doc.en",

-                   "/usr/share/doc/ruby-racc-1.4.5/doc.ja",

-                   "/usr/share/ruby/vendor_ruby/racc"}

- DIRLIST_PKG = 'ruby-racc/ruby-racc/results/ruby-racc-1.4.5-9.fc17.noarch.rpm'

- 

- OWNERS_OK = {'rpm', 'yum', 'fedora-repos'}

+ DEPLIST_OK = {

+     "bash",

+     "python",

+     "fedora-packager",

+     "python",

+     "python-BeautifulSoup",

+     "python",

+     "python-bugzilla",

+     "python-kitchen",

+     "python-straight-plugin",

+     "packagedb-cli",

+     "rpm-python",

+     "devscripts-minimal",

+ }

+ 

+ 

+ DIRLIST_OK = {

+     "/usr/share/doc/ruby-racc-1.4.5",

+     "/usr/share/doc/ruby-racc-1.4.5/doc.en",

+     "/usr/share/doc/ruby-racc-1.4.5/doc.ja",

+     "/usr/share/ruby/vendor_ruby/racc",

+ }

+ DIRLIST_PKG = "ruby-racc/ruby-racc/results/ruby-racc-1.4.5-9.fc17.noarch.rpm"

+ 

+ OWNERS_OK = {"rpm", "yum", "fedora-repos"}

  

  

  class TestDeps(unittest.TestCase):

-     ''' Low-level, true unit tests. '''

+     """ Low-level, true unit tests. """

  

-     @unittest.skipIf(not FEDORA, 'Fedora-only test')

+     @unittest.skipIf(not FEDORA, "Fedora-only test")

      def test_list_deps(self):

-         ''' Test listing of package deps. '''

-         deplist = deps.list_deps('fedora-review')

-         if 'yum-utils' in deplist:              # F18-> F19 changes.

-             deplist.remove('yum-utils')

+         """ Test listing of package deps. """

+         deplist = deps.list_deps("fedora-review")

+         if "yum-utils" in deplist:  # F18-> F19 changes.

+             deplist.remove("yum-utils")

          self.assertEqual(set(deplist), DEPLIST_OK)

  

-     @unittest.skipIf(not FEDORA, 'Fedora-only test')

+     @unittest.skipIf(not FEDORA, "Fedora-only test")

      def test_resolve(self):

-         ''' Test resolving symbols -> packages. '''

-         pkgs = deps.resolve(['config(rpm)', 'perl'])

-         self.assertEqual({'rpm', 'perl'}, set(pkgs))

+         """ Test resolving symbols -> packages. """

+         pkgs = deps.resolve(["config(rpm)", "perl"])

+         self.assertEqual({"rpm", "perl"}, set(pkgs))

  

-     @unittest.skipIf(not FEDORA, 'Fedora-only test')

+     @unittest.skipIf(not FEDORA, "Fedora-only test")

      def test_list_dirs(self):

-         ''' Test listing of package dirs. '''

+         """ Test listing of package dirs. """

          dirlist = deps.list_dirs(DIRLIST_PKG)

          self.assertEqual(set(dirlist), DIRLIST_OK)

  

-     @unittest.skipIf(not FEDORA, 'Fedora-only test')

+     @unittest.skipIf(not FEDORA, "Fedora-only test")

      def test_list_owners(self):

-         ''' Test listing of file owner(s). '''

-         owners = deps.list_owners(['/var/lib/rpm', '/etc/yum.repos.d/'])

-         if 'generic-release' in owners:  # F18 madness

-             owners.remove('generic-release')

+         """ Test listing of file owner(s). """

+         owners = deps.list_owners(["/var/lib/rpm", "/etc/yum.repos.d/"])

+         if "generic-release" in owners:  # F18 madness

+             owners.remove("generic-release")

          self.assertEqual(set(owners), OWNERS_OK)

  

-     @unittest.skipIf(not FEDORA, 'Fedora-only test')

+     @unittest.skipIf(not FEDORA, "Fedora-only test")

      def test_list_paths(self):

-         ''' test list_paths method. '''

-         paths = deps.list_paths('fedora-release')

-         self.assertTrue('/etc/fedora-release' in paths)

+         """ test list_paths method. """

+         paths = deps.list_paths("fedora-release")

+         self.assertTrue("/etc/fedora-release" in paths)

file modified
+31 -26
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -16,7 +16,7 @@ 

  #    MA  02110-1301 USA.

  #

  # pylint: disable=C0103,R0904,R0913

- ''' Unit tests for creating dist '''

+ """ Unit tests for creating dist """

  

  import os

  import os.path
@@ -35,44 +35,49 @@ 

  

  

  def _proper_dist_os():

-     ''' Return true if we can create a dist on this OS. '''

-     uname_r = check_output(['uname', '-r']).decode('utf-8')

-     if 'el6' in uname_r:

+     """ Return true if we can create a dist on this OS. """

+     uname_r = check_output(["uname", "-r"]).decode("utf-8")

+     if "el6" in uname_r:

          return False

      return True

  

  

  class TestDist(FR_TestCase):

-     ''' Test creating installation artifacts. '''

+     """ Test creating installation artifacts. """

  

-     @unittest.skipIf(not _proper_dist_os(),

-                      'Cannot make a dist (bad os)')

-     @unittest.skipIf('MAKE_RELEASE' in os.environ,

-                  'Skipping make_release test when called from make_release')

+     @unittest.skipIf(not _proper_dist_os(), "Cannot make a dist (bad os)")

+     @unittest.skipIf(

+         "MAKE_RELEASE" in os.environ,

+         "Skipping make_release test when called from make_release",

+     )

      def test_tarballs(self):

-         ''' Test  make_release_script. '''

-         os.chdir('..')

-         check_call('./make_release -q >/dev/null', shell=True)

-         self.assertEqual(len(glob('dist/*')), 4)

+         """ Test  make_release_script. """

+         os.chdir("..")

+         check_call("./make_release -q >/dev/null", shell=True)

+         self.assertEqual(len(glob("dist/*")), 4)

          lint = check_output(

-                     'rpmlint -f test/rpmlint.conf dist/*spec dist/*rpm',

-                     shell=True, universal_newlines=True)

-         self.assertIn('0 error', lint)

-         self.assertIn('0 warning', lint)

+             "rpmlint -f test/rpmlint.conf dist/*spec dist/*rpm",

+             shell=True,

+             universal_newlines=True,

+         )

+         self.assertIn("0 error", lint)

+         self.assertIn("0 warning", lint)

  

      @staticmethod

      def dogfood():

-         '''

+         """

          Run fedora-review on itself (not found by discover et. al.)

-         '''

-         os.chdir('..')

-         check_call('./try-fedora-review -m fedora-%s-i386'  % RELEASE +

-                        ' -o "--without tests"' +

-                        ' -rn dist/fedora-review*.src.rpm',

-                    shell=True)

+         """

+         os.chdir("..")

+         check_call(

+             "./try-fedora-review -m fedora-%s-i386" % RELEASE

+             + ' -o "--without tests"'

+             + " -rn dist/fedora-review*.src.rpm",

+             shell=True,

+         )

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+3 -3
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -16,7 +16,7 @@ 

  #    MA  02110-1301 USA.

  #

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit test variables - the very existence of this file is significant,

  if it can be imported we are in testing mode.

- '''

+ """

file modified
+62 -61
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -17,9 +17,9 @@ 

  #

  # pylint: disable=C0103,R0904,R0913

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for utilities

- '''

+ """

  

  import os

  import sys
@@ -27,7 +27,7 @@ 

  

  from subprocess import check_call

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  from FedoraReview.checks import Checks

  from FedoraReview.name_bug import NameBug

  
@@ -35,99 +35,100 @@ 

  

  

  class TestExt(FR_TestCase):

-     ''' Tests for externally loaded plugins and scripts. '''

+     """ Tests for externally loaded plugins and scripts. """

  

      def setUp(self):

          FR_TestCase.setUp(self)

-         os.environ['REVIEW_EXT_DIRS'] = os.getcwd() + '/api'

-         os.environ['XDG_DATA_HOME'] = os.getcwd()

+         os.environ["REVIEW_EXT_DIRS"] = os.getcwd() + "/api"

+         os.environ["XDG_DATA_HOME"] = os.getcwd()

  

      def tearDown(self):

-         del os.environ['XDG_DATA_HOME']

-         del os.environ['REVIEW_EXT_DIRS']

+         del os.environ["XDG_DATA_HOME"]

+         del os.environ["REVIEW_EXT_DIRS"]

          FR_TestCase.tearDown(self)

  

      @staticmethod

      def test_display():

-         ''' Test  -d cli option. '''

-         os.chdir('test_ext')

-         check_call(srcpath.REVIEW_PATH + ' -d | grep test1 >/dev/null',

-                    shell=True)

+         """ Test  -d cli option. """

+         os.chdir("test_ext")

+         check_call(srcpath.REVIEW_PATH + " -d | grep test1 >/dev/null", shell=True)

  

      @staticmethod

      def test_single():

-         ''' Test  -s test cli option. '''

-         os.chdir('test_ext')

-         check_call(srcpath.REVIEW_PATH + ' -n python-test'

-                    ' -s unittest-test1'

-                    ' --cache --no-build >/dev/null',

-                    shell=True)

+         """ Test  -s test cli option. """

+         os.chdir("test_ext")

+         check_call(

+             srcpath.REVIEW_PATH + " -n python-test"

+             " -s unittest-test1"

+             " --cache --no-build >/dev/null",

+             shell=True,

+         )

  

      def test_exclude(self):

-         ''' Test  -x test cli option. '''

-         self.init_test('test_ext', argv=['-b', '1'], wd='review-python-test')

-         os.chdir('..')

-         check_call(srcpath.REVIEW_PATH + ' -pn python-test'

-                    '  -x unittest-test1' +

-                    ' -m ' + self.BUILDROOT +

-                    ' --cache --no-build >/dev/null',

-                    shell=True)

+         """ Test  -x test cli option. """

+         self.init_test("test_ext", argv=["-b", "1"], wd="review-python-test")

+         os.chdir("..")

+         check_call(

+             srcpath.REVIEW_PATH + " -pn python-test"

+             "  -x unittest-test1"

+             + " -m "

+             + self.BUILDROOT

+             + " --cache --no-build >/dev/null",

+             shell=True,

+         )

  

      def test_sh_api(self):

-         ''' Basic shell API test. '''

-         self.init_test('test_ext',

-                        argv=['-pn', 'python-test', '--cache',

-                               '--no-build'],

-                        wd='review-python-test')

-         bug = NameBug('python-test')

+         """ Basic shell API test. """

+         self.init_test(

+             "test_ext",

+             argv=["-pn", "python-test", "--cache", "--no-build"],

+             wd="review-python-test",

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         checks.checkdict['CreateEnvCheck'].run()

-         checks.checkdict['unittest-test2'].run()

-         self.assertTrue(checks.checkdict['unittest-test2'].is_pending)

+         checks.checkdict["CreateEnvCheck"].run()

+         checks.checkdict["unittest-test2"].run()

+         self.assertTrue(checks.checkdict["unittest-test2"].is_pending)

  

      def test_sh_attach(self):

-         ''' Test shell attachments. '''

+         """ Test shell attachments. """

  

-         self.init_test('test_ext',

-                        argv=['-rn', 'python-test', '--no-build'])

-         bug = NameBug('python-test')

+         self.init_test("test_ext", argv=["-rn", "python-test", "--no-build"])

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

-         checks['CreateEnvCheck'].run()

-         check = checks['test-attachments']

+         checks["CreateEnvCheck"].run()

+         check = checks["test-attachments"]

          check.run()

          self.assertEqual(len(check.result.attachments), 2)

-         a1 = filter(lambda a: 'attachment 1' in a.text,

-                     check.result.attachments)[0]

-         a2 = filter(lambda a: 'attachment 2' in a.text,

-                     check.result.attachments)[0]

-         self.assertEqual('Heading 1', a1.header)

+         a1 = filter(lambda a: "attachment 1" in a.text, check.result.attachments)[0]

+         a2 = filter(lambda a: "attachment 2" in a.text, check.result.attachments)[0]

+         self.assertEqual("Heading 1", a1.header)

          self.assertEqual(8, a1.order_hint)

-         self.assertEqual('Heading 2', a2.header)

+         self.assertEqual("Heading 2", a2.header)

          self.assertEqual(9, a2.order_hint)

  

      def test_srv_opt(self):

-         ''' Test check of no files in /srv, /opt and /usr/local. '''

-         self.init_test('srv-opt',

-                        argv=['-rn', 'dummy', '--cache',

-                               '--no-build'])

-         os.chdir('..')

-         bug = NameBug('dummy')

+         """ Test check of no files in /srv, /opt and /usr/local. """

+         self.init_test("srv-opt", argv=["-rn", "dummy", "--cache", "--no-build"])

+         os.chdir("..")

+         bug = NameBug("dummy")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         check = checks.checkdict['CheckBuildCompleted'].run()

-         check = checks.checkdict['CreateEnvCheck'].run()

-         check = checks.checkdict['generic-srv-opt']

+         check = checks.checkdict["CheckBuildCompleted"].run()

+         check = checks.checkdict["CreateEnvCheck"].run()

+         check = checks.checkdict["generic-srv-opt"]

          check.run()

-         self.assertTrue('/srv' in check.result.output_extra)

-         self.assertTrue('/opt' in check.result.output_extra)

-         self.assertTrue('/usr/local' in check.result.output_extra)

+         self.assertTrue("/srv" in check.result.output_extra)

+         self.assertTrue("/opt" in check.result.output_extra)

+         self.assertTrue("/usr/local" in check.result.output_extra)

  

- if __name__ == '__main__':

+ 

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+384 -379
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -17,9 +17,9 @@ 

  #

  # pylint: disable=C0103,R0904,R0913,W0212

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for bugzilla bug handling

- '''

+ """

  

  import glob

  import logging
@@ -33,11 +33,11 @@ 

  import unittest2 as unittest

  

  try:

-     from subprocess import check_output          # pylint: disable=E0611

+     from subprocess import check_output  # pylint: disable=E0611

  except ImportError:

      from FedoraReview.el_compat import check_output

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  from FedoraReview import AbstractCheck, Mock, ReviewDirs

  from FedoraReview import ReviewError, Settings

  
@@ -58,38 +58,38 @@ 

  

  

  class TestMisc(FR_TestCase):

-     ''' Low-level, true unit tests. '''

+     """ Low-level, true unit tests. """

  

      def setUp(self):

          if not srcpath.PLUGIN_PATH in sys.path:

              sys.path.append(srcpath.PLUGIN_PATH)

-         sys.argv = ['fedora-review', '-b', '1']

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

          self.log = Settings.get_logger()

          self.helpers = HelpersMixin()

-         self.srpm_file = os.path.join(os.path.abspath('.'),

-                                       'test_misc',

-                                       'python-test-1.0-1.fc17.src.rpm')

+         self.srpm_file = os.path.join(

+             os.path.abspath("."), "test_misc", "python-test-1.0-1.fc17.src.rpm"

+         )

          self.startdir = os.getcwd()

          Mock.reset()

  

      def test_version(self):

-         ''' Test version and update-version. '''

-         vers_path = os.path.join(

-                             srcpath.SRC_PATH, 'FedoraReview', 'version')

+         """ Test version and update-version. """

+         vers_path = os.path.join(srcpath.SRC_PATH, "FedoraReview", "version")

          if os.path.exists(vers_path):

              os.unlink(vers_path)

          import FedoraReview.version

+ 

          reload(FedoraReview.version)

          self.assertTrue(os.path.exists(vers_path))

          self.assertEqual(FedoraReview.__version__, VERSION)

  

      def test_rpm_source(self):

-         ''' Test a rpm datasource. '''

-         self.init_test('test_misc',

-                        argv=['-rpn', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

+         """ Test a rpm datasource. """

+         self.init_test(

+             "test_misc", argv=["-rpn", "python-test", "--cache", "--no-build"]

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)
@@ -97,18 +97,20 @@ 

          files = src.get_filelist()

          self.assertEqual(len(files), 11)

          rpms = src.get_all()

-         self.assertEqual(rpms, ['python-test'])

-         rpm_pkg = src.get('python-test')

-         self.assertEqual(rpm_pkg.header['name'], 'python-test')

-         all_files = src.find_all('*')

+         self.assertEqual(rpms, ["python-test"])

+         rpm_pkg = src.get("python-test")

+         self.assertEqual(rpm_pkg.header["name"], "python-test")

+         all_files = src.find_all("*")

          self.assertEqual(len(all_files), 11)

  

      def test_buildsrc(self):

-         ''' Test a BuildFilesData  datasource. '''

-         self.init_test('perl',

-                        argv=['-rpn', 'perl-RPM-Specfile', '--no-build'],

-                        wd='perl-RPM-Specfile')

-         bug = NameBug('perl-RPM-Specfile')

+         """ Test a BuildFilesData  datasource. """

+         self.init_test(

+             "perl",

+             argv=["-rpn", "perl-RPM-Specfile", "--no-build"],

+             wd="perl-RPM-Specfile",

+         )

+         bug = NameBug("perl-RPM-Specfile")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)  # pylint: disable=W0612
@@ -116,15 +118,15 @@ 

          files = src.get_filelist()

          self.assertEqual(len(files), 8)

          root = src.get_all()

-         expected_root = os.getcwd() + '/BUILD/RPM-Specfile-1.51'

+         expected_root = os.getcwd() + "/BUILD/RPM-Specfile-1.51"

          self.assertEqual(src.get_all(), [expected_root])

          root = src.get()

          self.assertEqual(root, expected_root)

-         all_files = src.find_all('*')

+         all_files = src.find_all("*")

          self.assertEqual(len(all_files), 8)

  

      def test_generic_static(self):

-         ''' test generic static -a checks  '''

+         """ test generic static -a checks  """

          # pylint: disable=F0401,R0201,C0111,W0613

  

          from plugins.generic import CheckStaticLibs
@@ -133,7 +135,6 @@ 

              pass

  

          class RpmsMockup(object):

- 

              def find(self, what, where):

                  return True

  
@@ -141,21 +142,17 @@ 

                  return RpmFile("python-test", "1.0", "1.fc" + RELEASE)

  

          class ApplicableCheckStaticLibs(CheckStaticLibs):

- 

              def is_applicable(self):

                  return True

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

          check = ApplicableCheckStaticLibs(ChecksMockup())

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'python-test.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "python-test.spec"))

          check.checks.rpms = RpmsMockup()

          check.run()

  

      def test_ccpp_gnulib(self):

-         ''' test ccpp bundled gnulib  '''

+         """ test ccpp bundled gnulib  """

          # pylint: disable=F0401,R0201,C0111,W0613

  

          from plugins.ccpp import CheckBundledGnulib
@@ -171,19 +168,16 @@ 

              def is_applicable(self):

                  return True

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

          check = ApplicableCheckBundledGnulib(ChecksMockup())

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'python-test.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "python-test.spec"))

          check.checks.buildsrc = BuildSrcMockup()

          check.checks.rpms = RpmDataSource(check.checks.spec)

          check.run()

          self.assertTrue(check.is_failed)

  

      def test_disabled(self):

-         ''' test normally disabled checks  '''

+         """ test normally disabled checks  """

          # pylint: disable=F0401,R0201,C0111,W0613,W0201

  

          from plugins.generic_should import CheckSourceComment
@@ -191,19 +185,15 @@ 

          from FedoraReview.datasrc import SourcesDataSource

  

          class ChecksMockup(object):

- 

              def __init__(self):

- 

                  class Data(object):

                      pass

  

                  self.data = Data()

  

-         self.init_test('test_misc',

-                        argv=['-pn', 'disabled', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-pn", "disabled", "--cache", "--no-build"])

          checks = ChecksMockup()

-         checks.spec = SpecFile(os.path.join(os.getcwd(), 'disabled.spec'))

+         checks.spec = SpecFile(os.path.join(os.getcwd(), "disabled.spec"))

          checks.sources = SourcesDataSource(checks.spec)

          check = CheckSourceComment(checks)

          check.run()
@@ -213,7 +203,7 @@ 

          self.assertTrue(check.is_pending)

  

      def test_hardened_build(self):

-         ''' test %global _hardened_build  '''

+         """ test %global _hardened_build  """

          # pylint: disable=F0401,R0201,C0111,W0613

  

          from plugins.generic import CheckDaemonCompileFlags
@@ -222,27 +212,22 @@ 

              pass

  

          class RpmsMockup(object):

- 

              def find_all(self, what):

-                 return ['a_file']

+                 return ["a_file"]

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

          check = CheckDaemonCompileFlags(ChecksMockup())

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'python-test.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "python-test.spec"))

          check.checks.rpms = RpmsMockup()

          check.checks.log = self.log

          check.run()

          self.assertTrue(check.is_passed)

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'disabled.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "disabled.spec"))

          check.run()

          self.assertTrue(check.is_failed)

  

      def test_rm_buildroot(self):

-         ''' test rm -rf $BUILDROOT/a_path '''

+         """ test rm -rf $BUILDROOT/a_path """

          # pylint: disable=F0401,R0201,C0111,W0613,W0201

  

          from plugins.generic import CheckCleanBuildroot
@@ -250,30 +235,27 @@ 

          class ChecksMockup(object):

              pass

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

          checks = ChecksMockup()

          checks.log = self.log

          checks.flags = flags

          check = CheckCleanBuildroot(checks)

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'rm_buildroot.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "rm_buildroot.spec"))

          check.run()

          self.assertTrue(check.is_passed)

  

      def test_autotools(self):

-         ''' test ccpp static -a checs  '''

+         """ test ccpp static -a checs  """

          # pylint: disable=F0401,R0201,C0111,W0613,W0201

  

          from plugins.generic_autotools import CheckAutotoolsObsoletedMacros

  

          class BuildSrcMockup(object):

              def __init__(self):

-                 self.containers = ['configure.ac']

+                 self.containers = ["configure.ac"]

  

              def find_all(self, what):

-                 return ["configure.ac"] if what.endswith('ac') else []

+                 return ["configure.ac"] if what.endswith("ac") else []

  

              def is_available(self):

                  return True
@@ -285,55 +267,56 @@ 

              def find(self, what, where):

                  return True

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

          checks_mockup = ChecksMockup()

          checks_mockup.log = self.log

          checks_mockup.buildsrc = BuildSrcMockup()

          check = CheckAutotoolsObsoletedMacros(checks_mockup)

-         check.checks.spec = SpecFile(os.path.join(os.getcwd(),

-                                                   'gc.spec'))

+         check.checks.spec = SpecFile(os.path.join(os.getcwd(), "gc.spec"))

          check.checks.rpms = RpmsMockup()

          check.run()

          note = check.result.output_extra

          self.assertTrue(check.is_failed)

-         self.assertTrue('Some obsoleted macros' in note)

+         self.assertTrue("Some obsoleted macros" in note)

          self.assertEqual(len(check.result.attachments), 1)

-         self.assertIn('AC_PROG_LIBTOOL found in: configure.ac:519',

-                       check.result.attachments[0].text)

-         self.assertIn('AM_CONFIG_HEADER found in: configure.ac:29',

-                       check.result.attachments[0].text)

+         self.assertIn(

+             "AC_PROG_LIBTOOL found in: configure.ac:519",

+             check.result.attachments[0].text,

+         )

+         self.assertIn(

+             "AM_CONFIG_HEADER found in: configure.ac:29",

+             check.result.attachments[0].text,

+         )

  

      def test_flags_1(self):

-         ''' test a flag defined in python, set by user' '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build', '-D', 'EPEL7'])

-         bug = NameBug('python-test')

+         """ test a flag defined in python, set by user' """

+         self.init_test(

+             "test_misc",

+             argv=["-n", "python-test", "--cache", "--no-build", "-D", "EPEL7"],

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         self.assertTrue(checks.flags['EPEL7'])

+         self.assertTrue(checks.flags["EPEL7"])

  

      def test_flags_2(self):

-         ''' Flag defined in python, not set by user' '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

+         """ Flag defined in python, not set by user' """

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         self.assertFalse(checks.flags['EPEL7'])

+         self.assertFalse(checks.flags["EPEL7"])

  

      def test_flags_3(self):

-         ''' Flag not defined , set by user' '''

+         """ Flag not defined , set by user' """

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build', '-D', 'EPEL8'])

-         bug = NameBug('python-test')

+         self.init_test(

+             "test_misc",

+             argv=["-n", "python-test", "--cache", "--no-build", "-D", "EPEL8"],

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          with self.assertRaises(ReviewError):
@@ -341,65 +324,63 @@ 

              checks = Checks(bug.spec_file, bug.srpm_file)

  

      def test_flags_4(self):

-         ''' Flag defined in shell script , set by user to value '''

- 

-         os.environ['XDG_DATA_HOME'] = os.getcwd()

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build', '-D', 'EPEL6=foo'])

-         bug = NameBug('python-test')

+         """ Flag defined in shell script , set by user to value """

+ 

+         os.environ["XDG_DATA_HOME"] = os.getcwd()

+         self.init_test(

+             "test_misc",

+             argv=["-n", "python-test", "--cache", "--no-build", "-D", "EPEL6=foo"],

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         self.assertEqual(str(checks.flags['EPEL6']), 'foo')

+         self.assertEqual(str(checks.flags["EPEL6"]), "foo")

  

      def test_source_file(self):

          """ Test the SourceFile class """

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

-         source = Source('Source0',

-                         self.BASE_URL + 'python-test-1.0.tar.gz')

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

+         source = Source("Source0", self.BASE_URL + "python-test-1.0.tar.gz")

          # source exists and source.filename point to the right location?

-         expected = os.path.abspath('upstream/python-test-1.0.tar.gz')

+         expected = os.path.abspath("upstream/python-test-1.0.tar.gz")

          self.assertEqual(source.filename, expected)

          self.assertEqual(source.is_archive(), True)

          self.assertTrue(os.path.exists(source.filename))

-         self.assertEqual(source.check_source_checksum(),

-                          "7ef644ee4eafa62cfa773cad4056cdcea592e27dacd5ae"

-                          "b4e8b11f51f5bf60d3")

+         self.assertEqual(

+             source.check_source_checksum(),

+             "7ef644ee4eafa62cfa773cad4056cdcea592e27dacd5ae" "b4e8b11f51f5bf60d3",

+         )

          source.extract()

-         self.assertTrue(os.path.exists(ReviewDirs.upstream_unpacked +

-                                        '/Source0/python-test-1.0'))

+         self.assertTrue(

+             os.path.exists(ReviewDirs.upstream_unpacked + "/Source0/python-test-1.0")

+         )

          source.log.setLevel(logging.ERROR)

-         source = Source('Source0', 'http://nowhere.internet/a_file.txt')

+         source = Source("Source0", "http://nowhere.internet/a_file.txt")

          self.assertFalse(source.downloaded)

  

      def test_sources_data(self):

-         ''' Test a SourcesDataSource. '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

+         """ Test a SourcesDataSource. """

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

-         checks.set_single_check('CheckSourceMD5')

-         check = checks['CheckSourceMD5']

+         checks.set_single_check("CheckSourceMD5")

+         check = checks["CheckSourceMD5"]

          check.run()

          result = check.result

-         self.log.debug('test_source, result : ' + result.result)

+         self.log.debug("test_source, result : " + result.result)

          if result.output_extra:

              self.log.debug("Result extra text: " + result.output_extra)

          self.assertTrue(check.is_passed)

-         paths = check.checks.sources.find_all_re('.*[.]py')

+         paths = check.checks.sources.find_all_re(".*[.]py")

          files = [os.path.basename(p) for p in paths]

-         self.assertEqual(set(files), {'setup.py', '__init__.py'})

+         self.assertEqual(set(files), {"setup.py", "__init__.py"})

          files = check.checks.sources.get_filelist()

          self.assertEqual(len(files), 10)

  

      def test_review_helper(self):

-         ''' Test review_helper error handling. '''

+         """ Test review_helper error handling. """

          # pylint: disable=C0111,W0212

  

          class Null(object):
@@ -407,50 +388,51 @@ 

                  pass

  

          loglevel = None

-         argv = ['-rn', 'foo', '--no-build']

-         self.init_test('.', argv)

+         argv = ["-rn", "foo", "--no-build"]

+         self.init_test(".", argv)

          helper = ReviewHelper()

          stdout = sys.stdout

          sys.stdout = Null()

          helper.log.setLevel(logging.CRITICAL)

-         rc = helper.run('review.txt')

+         rc = helper.run("review.txt")

          sys.stdout = stdout

          if loglevel:

-             os.environ['REVIEW_LOGLEVEL'] = loglevel

+             os.environ["REVIEW_LOGLEVEL"] = loglevel

          self.assertEqual(rc, 2)

  

      def test_review_dir(self):

-         ''' Test ReviewDir setup functions. '''

-         self.init_test('.', argv=['-n', 'python-test', '--no-build'])

+         """ Test ReviewDir setup functions. """

+         self.init_test(".", argv=["-n", "python-test", "--no-build"])

          from FedoraReview.review_dirs import _ReviewDirs

-         os.chdir('review_dir')

-         check_output('rm -rf testdirs; mkdir testdirs', shell=True)

-         ReviewDirs.workdir_setup('testdirs', 'testing')

-         check_output(['touch', 'results/dummy.rpm'])

-         os.chdir('..')

+ 

+         os.chdir("review_dir")

+         check_output("rm -rf testdirs; mkdir testdirs", shell=True)

+         ReviewDirs.workdir_setup("testdirs", "testing")

+         check_output(["touch", "results/dummy.rpm"])

+         os.chdir("..")

          rd = _ReviewDirs()

-         rd.workdir_setup('testdirs')

-         self.assertEqual(len(glob.glob('*')), 7)

-         self.assertEqual(os.path.basename(os.getcwd()), 'testdirs')

-         self.assertTrue(os.path.exists('results/dummy.rpm'))

-         self.assertEqual(glob.glob('BUILD/*'), ['BUILD/pkg-1.0'])

+         rd.workdir_setup("testdirs")

+         self.assertEqual(len(glob.glob("*")), 7)

+         self.assertEqual(os.path.basename(os.getcwd()), "testdirs")

+         self.assertTrue(os.path.exists("results/dummy.rpm"))

+         self.assertEqual(glob.glob("BUILD/*"), ["BUILD/pkg-1.0"])

  

      def test_mock_configdir(self):

-         ''' Test internal scanning of --configdir option. '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test'],

-                        buildroot='default',

-                        options='--configdir=mock-config')

+         """ Test internal scanning of --configdir option. """

+         self.init_test(

+             "test_misc",

+             argv=["-n", "python-test"],

+             buildroot="default",

+             options="--configdir=mock-config",

+         )

          Mock.reset()

          Mock._get_root()

-         self.assertEqual(Mock.mock_root, 'fedora-12-i786')

+         self.assertEqual(Mock.mock_root, "fedora-12-i786")

  

      def test_mock_clear(self):

-         ''' test mock.clear_builddir(). '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

-         wdir = Mock.get_builddir('BUILD')

+         """ test mock.clear_builddir(). """

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache", "--no-build"])

+         wdir = Mock.get_builddir("BUILD")

          len1 = len(glob.glob(os.path.join(wdir, "*")))

          s = "cd {}; ln -sf foo bar || :".format(wdir)

          check_output(s, shell=True)
@@ -458,32 +440,32 @@ 

          len2 = len(glob.glob(os.path.join(wdir, "*")))

          self.assertEqual(len2, len1)

  

-     @unittest.skipIf(FAST_TEST, 'slow test disabled by REVIEW_FAST_TEST')

+     @unittest.skipIf(FAST_TEST, "slow test disabled by REVIEW_FAST_TEST")

      def test_mock_uniqueext(self):

-         ''' Test --uniqueext option. '''

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_test('mock-uniqueext',

-                        argv=['-cn', 'python-test'],

-                        options='--uniqueext=hugo')

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

-         bug = NameBug('python-test')

+         """ Test --uniqueext option. """

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_test(

+             "mock-uniqueext", argv=["-cn", "python-test"], options="--uniqueext=hugo"

+         )

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

          Mock.init()

-         for dirt in glob.glob('results/*.*'):

+         for dirt in glob.glob("results/*.*"):

              os.unlink(dirt)

-         check = checks.checkdict['CheckBuild']

+         check = checks.checkdict["CheckBuild"]

          check.run()

          self.assertTrue(check.is_passed)

-         results = glob.glob('results/*.rpm')

+         results = glob.glob("results/*.rpm")

          self.assertEqual(len(results), 2)

-         for dirt in glob.glob('results/*.*'):

+         for dirt in glob.glob("results/*.*"):

              os.unlink(dirt)

  

      def test_java_spec(self):

-         ''' Test the ChecktestSkip check. '''

+         """ Test the ChecktestSkip check. """

          # pylint: disable=F0401,R0201,C0111,,W0613

  

          from plugins.java import CheckJavaPlugin
@@ -503,388 +485,411 @@ 

              def is_applicable(self):

                  return True

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--no-build'])

-         spec = SpecFile(os.path.join(os.getcwd(), 'jettison.spec'))

+         self.init_test("test_misc", argv=["-n", "python-test", "--no-build"])

+         spec = SpecFile(os.path.join(os.getcwd(), "jettison.spec"))

          check = ApplicableCheckJavaPlugin(ChecksMockup())

          check.checks.spec = spec

          check.run()

          self.assertTrue(check.is_failed)

  

      def test_spec_file(self):

-         ''' Test the SpecFile class'''

+         """ Test the SpecFile class"""

  

          def fix_usr_link(path):

-             ''' Convert absolute paths to /usr/path. '''

-             if not '/' in path:

+             """ Convert absolute paths to /usr/path. """

+             if not "/" in path:

                  return path

-             lead = path.split('/')[1]

-             if lead in ['bin', 'sbin', 'lib', 'lib64']:

-                 return '/usr' + path

+             lead = path.split("/")[1]

+             if lead in ["bin", "sbin", "lib", "lib64"]:

+                 return "/usr" + path

              return path

  

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--no-build'])

-         spec = SpecFile(os.path.join(os.getcwd(), 'python-test.spec'))

-         self.assertEqual(spec.name, 'python-test')

-         self.assertEqual(spec.version, '1.0')

-         dist = Mock.get_macro('%dist', None, {})

-         self.assertEqual(spec.release, '1' + dist)

-         self.assertEqual(spec.expand_tag('Release').decode('utf-8'), '1' + dist)

-         self.assertEqual(spec.expand_tag('License').decode('utf-8'), 'GPLv2+')

-         self.assertEqual(spec.expand_tag('Group').decode('utf-8'), 'Development/Languages')

+         self.init_test("test_misc", argv=["-n", "python-test", "--no-build"])

+         spec = SpecFile(os.path.join(os.getcwd(), "python-test.spec"))

+         self.assertEqual(spec.name, "python-test")

+         self.assertEqual(spec.version, "1.0")

+         dist = Mock.get_macro("%dist", None, {})

+         self.assertEqual(spec.release, "1" + dist)

+         self.assertEqual(spec.expand_tag("Release").decode("utf-8"), "1" + dist)

+         self.assertEqual(spec.expand_tag("License").decode("utf-8"), "GPLv2+")

+         self.assertEqual(

+             spec.expand_tag("Group").decode("utf-8"), "Development/Languages"

+         )

          # Test rpm value not there

-         self.assertEqual(spec.expand_tag('PreReq').decode('utf-8'), None)

+         self.assertEqual(spec.expand_tag("PreReq").decode("utf-8"), None)

          # Test get sections

-         expected = ['rm -rf $RPM_BUILD_ROOT']

-         self.assertEqual(spec.get_section('%clean'), expected)

-         expected = '%{__python} setup.py build'

-         expected = ['LANG=C', 'export LANG', 'unset DISPLAY',

-                    '/usr/bin/python setup.py build']

- 

-         build = spec.get_section('%build')

+         expected = ["rm -rf $RPM_BUILD_ROOT"]

+         self.assertEqual(spec.get_section("%clean"), expected)

+         expected = "%{__python} setup.py build"

+         expected = [

+             "LANG=C",

+             "export LANG",

+             "unset DISPLAY",

+             "/usr/bin/python setup.py build",

+         ]

+ 

+         build = spec.get_section("%build")

          build = [fix_usr_link(b) for b in build]

-         self.assertIn(''.join(build), ''.join(expected))

-         install = spec.get_section('%install')

+         self.assertIn("".join(build), "".join(expected))

+         install = spec.get_section("%install")

          install = [fix_usr_link(x) for x in install]

-         expected = ['LANG=C', 'export LANG', 'unset DISPLAY',

-                     'rm -rf $RPM_BUILD_ROOT',

-                     '/usr/bin/python setup.py install -O1 --skip-build'

-                     ' --root $RPM_BUILD_ROOT']

-         self.assertIn(''.join(install), ''.join(expected))

+         expected = [

+             "LANG=C",

+             "export LANG",

+             "unset DISPLAY",

+             "rm -rf $RPM_BUILD_ROOT",

+             "/usr/bin/python setup.py install -O1 --skip-build"

+             " --root $RPM_BUILD_ROOT",

+         ]

+         self.assertIn("".join(install), "".join(expected))

  

          # Test get_sources (return the Source/Patch lines with macros resolved)

-         expected = {'Source0': 'http://timlau.fedorapeople.org/'

-                     'files/test/review-test/python-test-1.0.tar.gz'}

+         expected = {

+             "Source0": "http://timlau.fedorapeople.org/"

+             "files/test/review-test/python-test-1.0.tar.gz"

+         }

          self.assertEqual(spec.sources_by_tag, expected)

-         expected = ['%defattr(-,root,root,-)',

-                     '%doc COPYING',

-                     rpm.expandMacro('%{python_sitelib}') + '/*']

+         expected = [

+             "%defattr(-,root,root,-)",

+             "%doc COPYING",

+             rpm.expandMacro("%{python_sitelib}") + "/*",

+         ]

          self.assertEqual(spec.get_files(), expected)

  

          # Test find

-         regex = re.compile(r'^Release\s*:\s*(.*)')

+         regex = re.compile(r"^Release\s*:\s*(.*)")

          res = spec.find_re(regex)

          if res:

-             self.assertEqual(res.split(':')[1].strip(), '1%{?dist}')

+             self.assertEqual(res.split(":")[1].strip(), "1%{?dist}")

          else:

              self.assertTrue(False)

  

-     @unittest.skipIf(FAST_TEST, 'slow test disabled by REVIEW_FAST_TEST')

+     @unittest.skipIf(FAST_TEST, "slow test disabled by REVIEW_FAST_TEST")

      def test_mockbuild(self):

          """ Test the SRPMFile class """

-         self.init_test('mockbuild', argv=['-rn', 'python-test'])

+         self.init_test("mockbuild", argv=["-rn", "python-test"])

          srpm = SRPMFile(self.srpm_file)

          # install the srpm

          srpm.unpack()

          self.assertTrue(srpm._unpacked_src is not None)

          src_dir = srpm._unpacked_src

-         src_files = glob.glob(os.path.expanduser(src_dir) + '/*')

+         src_files = glob.glob(os.path.expanduser(src_dir) + "/*")

          src_files = [os.path.basename(f) for f in src_files]

-         self.assertTrue('python-test-1.0.tar.gz' in src_files)

+         self.assertTrue("python-test-1.0.tar.gz" in src_files)

          self.log.info("Starting mock build (patience...)")

          Mock.clear_builddir()

          Mock.build(srpm.filename)

-         rpms = glob.glob(os.path.join(Mock.resultdir,

-                                       'python-test-1.0-1*noarch.rpm'))

+         rpms = glob.glob(os.path.join(Mock.resultdir, "python-test-1.0-1*noarch.rpm"))

          self.assertEqual(1, len(rpms))

  

      def test_checksum_command_line(self):

-         ''' Default checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1', '-k', 'sha1']

+         """ Default checksum test. """

+         sys.argv = ["fedora-review", "-b", "1", "-k", "sha1"]

          Settings.init(True)

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum, '5315b33321883c15c19445871cd335f7f698a2aa')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(checksum, "5315b33321883c15c19445871cd335f7f698a2aa")

  

      def test_md5(self):

-         ''' MD5 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ MD5 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'md5'

+         Settings.checksum = "md5"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum, '4a1c937e62192753c550221876613f86')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(checksum, "4a1c937e62192753c550221876613f86")

  

      def test_sha1(self):

-         ''' SHA1 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ SHA1 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'sha1'

+         Settings.checksum = "sha1"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum, '5315b33321883c15c19445871cd335f7f698a2aa')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(checksum, "5315b33321883c15c19445871cd335f7f698a2aa")

  

      def test_sha224(self):

-         ''' SHA2 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ SHA2 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'sha224'

+         Settings.checksum = "sha224"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum,

-             '01959559db8ef8d596ff824fe207fc0345be67df6b8a51942214adb7')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(

+             checksum, "01959559db8ef8d596ff824fe207fc0345be67df6b8a51942214adb7"

+         )

  

      def test_sha256(self):

-         ''' SHA2 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ SHA2 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'sha256'

+         Settings.checksum = "sha256"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum,

-             'd8669d49c8557ac47681f9b85e322849fa84186a8683c93959a590d6e7b9ae29')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(

+             checksum, "d8669d49c8557ac47681f9b85e322849fa84186a8683c93959a590d6e7b9ae29"

+         )

  

      def test_sha384(self):

-         ''' SHA3 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ SHA3 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'sha384'

+         Settings.checksum = "sha384"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum,

-            '3d6a580100b1e8a40dc41892f6b289ff13c0b489b8079d8b7'

-            'c01a17c67b88bf77283f784b4e8dacac6572050df8c948e')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(

+             checksum,

+             "3d6a580100b1e8a40dc41892f6b289ff13c0b489b8079d8b7"

+             "c01a17c67b88bf77283f784b4e8dacac6572050df8c948e",

+         )

  

      def test_sha512(self):

-         ''' SHA5 checksum test. '''

-         sys.argv = ['fedora-review', '-b', '1']

+         """ SHA5 checksum test. """

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         Settings.checksum = 'sha512'

+         Settings.checksum = "sha512"

          helpers = HelpersMixin()

-         checksum = helpers._checksum('scantailor.desktop')

-         self.assertEqual(checksum,

-             '77a138fbd918610d55d9fd22868901bd189d987f17701498'

-             '164badea88dd6f5612c118fc9e66d7b57f802bf0cddadc1c'

-             'ec54674ee1c3df2ddfaf1cac4007ac26')

- 

-     @unittest.skipIf(NO_NET, 'No network available')

+         checksum = helpers._checksum("scantailor.desktop")

+         self.assertEqual(

+             checksum,

+             "77a138fbd918610d55d9fd22868901bd189d987f17701498"

+             "164badea88dd6f5612c118fc9e66d7b57f802bf0cddadc1c"

+             "ec54674ee1c3df2ddfaf1cac4007ac26",

+         )

+ 

+     @unittest.skipIf(NO_NET, "No network available")

      def test_bugzilla_bug(self):

-         ''' Scanning of bugzilla bugpage test. '''

-         subprocess.check_call('mkdir -p tmp/python-test || :', shell=True)

-         self.init_test('tmp',

-                        argv=['-b', '817268'],

-                        wd='python-test')

-         bug = BugzillaBug('817268')

+         """ Scanning of bugzilla bugpage test. """

+         subprocess.check_call("mkdir -p tmp/python-test || :", shell=True)

+         self.init_test("tmp", argv=["-b", "817268"], wd="python-test")

+         bug = BugzillaBug("817268")

          bug.find_urls()

-         expected = 'http://dl.dropbox.com/u/17870887/python-faces-0.11.7-2' \

-                   '/python-faces-0.11.7-2.fc16.src.rpm'

+         expected = (

+             "http://dl.dropbox.com/u/17870887/python-faces-0.11.7-2"

+             "/python-faces-0.11.7-2.fc16.src.rpm"

+         )

          self.assertEqual(expected, bug.srpm_url)

-         expected = 'http://dl.dropbox.com/u/17870887/python-faces-0.11.7-2/' \

-                    'python-faces.spec'

+         expected = (

+             "http://dl.dropbox.com/u/17870887/python-faces-0.11.7-2/"

+             "python-faces.spec"

+         )

          self.assertEqual(expected, bug.spec_url)

          self.assertEqual(None, bug.spec_file)

          self.assertEqual(None, bug.srpm_file)

  

      def test_rpm_spec(self):

-         ''' Internal -r check. '''

-         self.init_test('test_misc',

-                        argv=['-rn', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

+         """ Internal -r check. """

+         self.init_test(

+             "test_misc", argv=["-rn", "python-test", "--cache", "--no-build"]

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

-         expected = 'test/test_misc/python-test-1.0-1.fc17.src.rpm'

+         expected = "test/test_misc/python-test-1.0-1.fc17.src.rpm"

          self.assertTrue(bug.srpm_url.endswith(expected))

-         expected = 'test/test_misc/srpm-unpacked/python-test.spec'

+         expected = "test/test_misc/srpm-unpacked/python-test.spec"

          self.assertTrue(bug.spec_url.endswith(expected))

  

      def test_md5sum_diff_ok(self):

-         ''' Complete MD5sum test expected to pass. '''

-         self.init_test('md5sum-diff-ok',

-                        argv=['-rpn', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

+         """ Complete MD5sum test expected to pass. """

+         self.init_test(

+             "md5sum-diff-ok", argv=["-rpn", "python-test", "--cache", "--no-build"]

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

-         checks.set_single_check('CheckSourceMD5')

-         check = checks['CheckSourceMD5']

+         checks.set_single_check("CheckSourceMD5")

+         check = checks["CheckSourceMD5"]

          check.run()

          self.assertTrue(check.is_passed)

-         expected = 'diff -r shows no differences'

+         expected = "diff -r shows no differences"

          self.assertTrue(expected in check.result.attachments[0].text)

  

      def test_md5sum_diff_fail(self):

-         ''' Complete MD5sum test expected to fail. '''

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_test('md5sum-diff-fail',

-                        argv=['-rpn', 'python-test', '--cache',

-                              '--no-build'])

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

-         bug = NameBug('python-test')

+         """ Complete MD5sum test expected to fail. """

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_test(

+             "md5sum-diff-fail", argv=["-rpn", "python-test", "--cache", "--no-build"]

+         )

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

+         bug = NameBug("python-test")

          bug.find_urls()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

-         checks.set_single_check('CheckSourceMD5')

-         check = checks['CheckSourceMD5']

+         checks.set_single_check("CheckSourceMD5")

+         check = checks["CheckSourceMD5"]

          check.run()

          self.assertTrue(check.is_failed)

-         expected = 'diff -r also reports differences'

+         expected = "diff -r also reports differences"

          self.assertTrue(expected in check.result.attachments[0].text)

  

      def test_dirty_resultdir(self):

-         ''' Test that non-empty resultdir quits. '''

-         self.init_test('test_misc',

-                        argv=['-n', 'python-test', '--cache'])

-         bug = NameBug('python-test')

+         """ Test that non-empty resultdir quits. """

+         self.init_test("test_misc", argv=["-n", "python-test", "--cache"])

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file).get_checks()

-         checks.set_single_check('CheckResultdir')

-         check = checks['CheckResultdir']

-         if not os.path.exists('results.bak'):

-             os.makedirs('results.bak')

-         for dirt in glob.glob('results/*.*'):

-             shutil.move(dirt, 'results.bak')

+         checks.set_single_check("CheckResultdir")

+         check = checks["CheckResultdir"]

+         if not os.path.exists("results.bak"):

+             os.makedirs("results.bak")

+         for dirt in glob.glob("results/*.*"):

+             shutil.move(dirt, "results.bak")

          check.run()

          self.assertTrue(check.is_na)

  

          try:

-             subprocess.check_call('touch results/orvar.rpm', shell=True)

+             subprocess.check_call("touch results/orvar.rpm", shell=True)

          except OSError:

              pass

          self.assertRaises(ReviewError, check.run)

          Settings.nobuild = True

          check.run()

          self.assertTrue(check.is_na)

-         os.unlink('results/orvar.rpm')

-         for dirt in glob.glob('results.bak/*'):

-             shutil.move(dirt, 'results')

+         os.unlink("results/orvar.rpm")

+         for dirt in glob.glob("results.bak/*"):

+             shutil.move(dirt, "results")

  

      def test_prebuilt_sources(self):

-         ''' Local built RPM:s (-n) test. '''

-         self.init_test('test_misc',

-                        argv=['-cn', 'python-test', '--prebuilt'])

+         """ Local built RPM:s (-n) test. """

+         self.init_test("test_misc", argv=["-cn", "python-test", "--prebuilt"])

          ReviewDirs.startdir = os.getcwd()

-         bug = NameBug('python-test')

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         subprocess.check_call('touch orvar.rpm', shell=True)

+         subprocess.check_call("touch orvar.rpm", shell=True)

          rpms = Mock.get_package_rpm_paths(checks.spec)

          self.assertEqual(len(rpms), 1)

  

      def test_bad_specfile(self):

-         ''' Specfile with syntactic errors test. '''

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_test('bad-spec',

-                        argv=['-n', 'python-test', '-p', '--cache',

-                              '--no-build', '-D', 'DISTTAG=fc19'])

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

-         bug = NameBug('python-test')

-         check = self.run_single_check(bug, 'CheckSpecAsInSRPM')

+         """ Specfile with syntactic errors test. """

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_test(

+             "bad-spec",

+             argv=[

+                 "-n",

+                 "python-test",

+                 "-p",

+                 "--cache",

+                 "--no-build",

+                 "-D",

+                 "DISTTAG=fc19",

+             ],

+         )

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

+         bug = NameBug("python-test")

+         check = self.run_single_check(bug, "CheckSpecAsInSRPM")

          self.assertTrue(check.is_failed)

-         self.assertTrue('#TestTag' in check.result.attachments[0].text)

+         self.assertTrue("#TestTag" in check.result.attachments[0].text)

  

      def test_desktop_file_bug(self):

-         ''' desktop file handling test. '''

+         """ desktop file handling test. """

  

-         self.init_test('desktop-file',

-                        argv=['-n', 'python-test', '--cache',

-                              '--no-build'])

-         bug = NameBug('python-test')

-         check = self.run_single_check(bug, 'CheckDesktopFileInstall', True)

+         self.init_test(

+             "desktop-file", argv=["-n", "python-test", "--cache", "--no-build"]

+         )

+         bug = NameBug("python-test")

+         check = self.run_single_check(bug, "CheckDesktopFileInstall", True)

          self.assertTrue(check.is_passed)

  

      def test_check_dict(self):

-         ''' CheckDict component test. '''

+         """ CheckDict component test. """

  

          class TestCheck(AbstractCheck):

-             ''' Check mockup. '''

+             """ Check mockup. """

+ 

              def run(self):

                  pass

  

              @staticmethod

              # pylint: disable=E0202

              def name():

-                 ''' return test's name.'''

-                 return 'foo'

+                 """ return test's name."""

+                 return "foo"

  

-         c = TestCheck('a-sourcefile')

+         c = TestCheck("a-sourcefile")

          l = _CheckDict()

          l.add(c)

          self.assertEqual(len(l), 1)

          self.assertEqual(c.checkdict, l)

-         c1 = TestCheck('sourcefile-1')

-         c1.name = 'test1'

-         c2 = TestCheck('sourcefile-2')

-         c2.name = 'test2'

+         c1 = TestCheck("sourcefile-1")

+         c1.name = "test1"

+         c2 = TestCheck("sourcefile-2")

+         c2.name = "test2"

          l.extend([c1, c2])

          self.assertEqual(len(l), 3)

-         self.assertEqual(l['test1'].name, c1.name)

-         self.assertEqual(l['test2'].name, c2.name)

-         self.assertEqual(l['test1'], c1)

-         self.assertEqual(l['test2'], c2)

-         self.assertEqual(l['test2'].checkdict, l)

-         l.set_single_check('test1')

+         self.assertEqual(l["test1"].name, c1.name)

+         self.assertEqual(l["test2"].name, c2.name)

+         self.assertEqual(l["test1"], c1)

+         self.assertEqual(l["test2"], c2)

+         self.assertEqual(l["test2"].checkdict, l)

+         l.set_single_check("test1")

          self.assertEqual(len(l), 1)

-         self.assertEqual(l['test1'], c1)

+         self.assertEqual(l["test1"], c1)

  

      def test_1_unversioned_so(self):

-         ''' Handling unversioned-sofile, expected to fail. '''

-         self.init_test('unversioned-so',

-                        argv=['-rpn', 'python-test'])

-         bug = NameBug('python-test')

-         check = self.run_single_check(bug, 'CheckSoFiles')

+         """ Handling unversioned-sofile, expected to fail. """

+         self.init_test("unversioned-so", argv=["-rpn", "python-test"])

+         bug = NameBug("python-test")

+         check = self.run_single_check(bug, "CheckSoFiles")

          self.assertTrue(check.is_failed)

  

      def test_1_unversioned_so_private(self):

-         ''' Handling unversioned-sofile, expected to fail. '''

-         self.init_test('unversioned-so-private',

-                        argv=['-rpn', 'python-test'])

-         bug = NameBug('python-test')

-         check = self.run_single_check(bug, 'CheckSoFiles')

+         """ Handling unversioned-sofile, expected to fail. """

+         self.init_test("unversioned-so-private", argv=["-rpn", "python-test"])

+         bug = NameBug("python-test")

+         check = self.run_single_check(bug, "CheckSoFiles")

          self.assertTrue(check.is_pending)

  

-     @unittest.skipIf(FAST_TEST, 'slow test disabled by REVIEW_FAST_TEST')

+     @unittest.skipIf(FAST_TEST, "slow test disabled by REVIEW_FAST_TEST")

      def test_local_repo(self):

-         ''' Local repo with prebuilt rpms test. '''

-         self.init_test('test_misc',

-                        argv=['-rn', 'python-test', '--local-repo',

-                              'repo', '--cache'])

-         bug = NameBug('python-test')

+         """ Local repo with prebuilt rpms test. """

+         self.init_test(

+             "test_misc", argv=["-rn", "python-test", "--local-repo", "repo", "--cache"]

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         check = checks.checkdict['CheckPackageInstalls']

+         check = checks.checkdict["CheckPackageInstalls"]

          check.run()

          self.assertTrue(check.is_passed)

  

      def test_bad_specname(self):

-         ''' Specfile with bad name test. '''

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_test('bad-specname',

-                        argv=['-rn', 'python-test', '--cache'])

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

-         bug = NameBug('python-test')

+         """ Specfile with bad name test. """

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_test("bad-specname", argv=["-rn", "python-test", "--cache"])

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         check = checks.checkdict['CheckSpecAsInSRPM']

+         check = checks.checkdict["CheckSpecAsInSRPM"]

          check.run()

          self.assertTrue(check.is_failed)

-         self.assertIn('Bad spec filename:', check.result.output_extra)

+         self.assertIn("Bad spec filename:", check.result.output_extra)

  

      def test_perl_module(self):

-         ''' test basic perl python + shell test '''

-         self.init_test('perl',

-                        argv=['-rpn', 'perl-RPM-Specfile', '--no-build'])

-         bug = NameBug('perl-RPM-Specfile')

+         """ test basic perl python + shell test """

+         self.init_test("perl", argv=["-rpn", "perl-RPM-Specfile", "--no-build"])

+         bug = NameBug("perl-RPM-Specfile")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         checks.checkdict['CreateEnvCheck'].run()

-         check = checks.checkdict['PerlCheckBuildRequires']

+         checks.checkdict["CreateEnvCheck"].run()

+         check = checks.checkdict["PerlCheckBuildRequires"]

          check.run()

          self.assertTrue(check.is_pending)

-         check = checks.checkdict['perl-url-tag']

+         check = checks.checkdict["perl-url-tag"]

          check.run()

          self.assertTrue(check.is_pending)

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+97 -97
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -17,9 +17,9 @@ 

  #

  # pylint: disable=C0103,R0904,R0913,W0212

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for bugzilla bug handling

- '''

+ """

  

  import os

  import os.path
@@ -28,7 +28,7 @@ 

  from glob import glob

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  

  try:

      from subprocess import check_output
@@ -46,70 +46,69 @@ 

  

  

  class TestOptions(FR_TestCase):

-     ''' One test per command line option. '''

+     """ One test per command line option. """

  

      def init_opt_test(self, argv=None, cd=None, wd=None, root=None):

-         ''' Setup an options test. '''

-         cd = cd if cd else 'options'

+         """ Setup an options test. """

+         cd = cd if cd else "options"

          argv = argv if argv else []

          FR_TestCase.init_test(self, cd, argv, wd, buildroot=root)

  

      def test_name(self):

          """ Test -name option """

-         self.init_opt_test(['-n', 'python-test', '--cache'])

+         self.init_opt_test(["-n", "python-test", "--cache"])

          bug = NameBug(Settings.name)

  

          bug.find_urls()

-         expected = self.abs_file_url('./python-test-1.0-1.fc17.src.rpm')

+         expected = self.abs_file_url("./python-test-1.0-1.fc17.src.rpm")

          self.assertEqual(expected, bug.srpm_url)

-         expected = self.abs_file_url('./python-test.spec')

+         expected = self.abs_file_url("./python-test.spec")

          self.assertEqual(expected, bug.spec_url)

  

          bug.download_files()

-         expected = os.path.abspath('./python-test-1.0-1.fc17.src.rpm')

+         expected = os.path.abspath("./python-test-1.0-1.fc17.src.rpm")

          self.assertEqual(expected, bug.srpm_file)

-         expected = os.path.abspath('./python-test.spec')

+         expected = os.path.abspath("./python-test.spec")

          self.assertEqual(expected, bug.spec_file)

  

-     @unittest.skipIf(NO_NET, 'No network available')

+     @unittest.skipIf(NO_NET, "No network available")

      def test_bug(self):

          """ Test -bug option """

-         self.init_opt_test(['-b', '818805'])

+         self.init_opt_test(["-b", "818805"])

          bug = BugzillaBug(Settings.bug)

  

          bug.find_urls()

-         home = 'http://leamas.fedorapeople.org/openerp-client'

-         expected = os.path.join(home,

-                                 'openerp-client-6.1-2.fc16.src.rpm')

+         home = "http://leamas.fedorapeople.org/openerp-client"

+         expected = os.path.join(home, "openerp-client-6.1-2.fc16.src.rpm")

          self.assertEqual(expected, bug.srpm_url)

-         expected = os.path.join(home, 'openerp-client.spec')

+         expected = os.path.join(home, "openerp-client.spec")

          self.assertEqual(expected, bug.spec_url)

  

          bug.download_files()

-         expected = os.path.abspath(

-                                 'srpm/openerp-client-6.1-2.fc16.src.rpm')

+         expected = os.path.abspath("srpm/openerp-client-6.1-2.fc16.src.rpm")

          self.assertEqual(expected, bug.srpm_file)

-         expected = os.path.abspath('srpm/openerp-client.spec')

+         expected = os.path.abspath("srpm/openerp-client.spec")

          self.assertEqual(expected, bug.spec_file)

  

-     @unittest.skipIf(NO_NET, 'No network available')

+     @unittest.skipIf(NO_NET, "No network available")

      def test_url(self):

          """ Test -url option """

          self.init_opt_test(

-             ['-u', 'https://bugzilla.redhat.com/show_bug.cgi?id=1199184'])

+             ["-u", "https://bugzilla.redhat.com/show_bug.cgi?id=1199184"]

+         )

          bug = UrlBug(Settings.url)

  

          bug.find_urls()

-         home = 'https://leamas.fedorapeople.org/fedora-review/testdata'

-         expected = os.path.join(home, 'DecodeIR-2.45-1.fc21.src.rpm')

+         home = "https://leamas.fedorapeople.org/fedora-review/testdata"

+         expected = os.path.join(home, "DecodeIR-2.45-1.fc21.src.rpm")

          self.assertEqual(expected, bug.srpm_url)

-         expected = os.path.join(home, 'DecodeIR.spec')

+         expected = os.path.join(home, "DecodeIR.spec")

          self.assertEqual(expected, bug.spec_url)

  

          bug.download_files()

-         expected = os.path.abspath('srpm/DecodeIR-2.45-1.fc21.src.rpm')

+         expected = os.path.abspath("srpm/DecodeIR-2.45-1.fc21.src.rpm")

          self.assertEqual(expected, bug.srpm_file)

-         expected = os.path.abspath('srpm/DecodeIR.spec')

+         expected = os.path.abspath("srpm/DecodeIR.spec")

          self.assertEqual(expected, bug.spec_file)

  

      def test_display(self):
@@ -117,7 +116,6 @@ 

          # pylint: disable=C0111

  

          class Logger(object):

- 

              def __init__(self):

                  self.lines = []

  
@@ -127,7 +125,8 @@ 

          if not srcpath.PLUGIN_PATH in sys.path:

              sys.path.append(srcpath.PLUGIN_PATH)

          from FedoraReview.review_helper import ReviewHelper

-         sys.argv = ['fedora-review', '-d', '--no-build']

+ 

+         sys.argv = ["fedora-review", "-d", "--no-build"]

          Settings.init(True)

          helper = ReviewHelper()

          stdout = sys.stdout
@@ -138,145 +137,146 @@ 

          self.assertTrue(len(logger.lines) > 20)

  

      def test_git_source(self):

-         ''' test use of local source0 tarball '''

+         """ test use of local source0 tarball """

  

-         self.init_test('git-source',

-                        argv= ['-rpn', 'get-flash-videos', '--cache'],

-                        wd='get-flash-videos',

-                        buildroot='fedora-%s-i386' % RELEASE)

-         os.chdir('..')

+         self.init_test(

+             "git-source",

+             argv=["-rpn", "get-flash-videos", "--cache"],

+             wd="get-flash-videos",

+             buildroot="fedora-%s-i386" % RELEASE,

+         )

+         os.chdir("..")

  

-         bug = NameBug('get-flash-videos')

+         bug = NameBug("get-flash-videos")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         #if not Mock.is_installed('rpmbuild'):

+         # if not Mock.is_installed('rpmbuild'):

          #    Mock.install(['rpmbuild'])

-         #check = checks.checkdict['CheckBuildCompleted']

-         #check.run()

-         check = checks.checkdict['CheckSourceMD5']

+         # check = checks.checkdict['CheckBuildCompleted']

+         # check.run()

+         check = checks.checkdict["CheckSourceMD5"]

          check.run()

          self.assertTrue(check.is_passed)

-         self.assertIn('Using local file',

-                       check.result.attachments[0].text)

+         self.assertIn("Using local file", check.result.attachments[0].text)

  

      def test_version(self):

          """ test --version option. """

-         cmd = srcpath.REVIEW_PATH + ' --version'

+         cmd = srcpath.REVIEW_PATH + " --version"

          output = check_output(cmd, shell=True)

-         output = output.decode('utf-8')

-         self.assertIn('fedora-review', output)

+         output = output.decode("utf-8")

+         self.assertIn("fedora-review", output)

          self.assertIn(VERSION, output)

  

-     @unittest.skipIf(NO_NET, 'No network available')

-     @unittest.skipIf(FAST_TEST, 'slow test disabled by REVIEW_FAST_TEST')

+     @unittest.skipIf(NO_NET, "No network available")

+     @unittest.skipIf(FAST_TEST, "slow test disabled by REVIEW_FAST_TEST")

      def test_cache(self):

-         ''' --cache option test. '''

+         """ --cache option test. """

+ 

          def get_mtime(pattern):

-             '''¸Return mtime for first path matching pattern. '''

+             """¸Return mtime for first path matching pattern. """

              pattern = os.path.join(os.getcwd(), pattern)

              path = glob(pattern)[0]

              return os.stat(path).st_mtime

  

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_opt_test(['-b', '1079967'], 'options')

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_opt_test(["-b", "1079967"], "options")

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

          bug = BugzillaBug(Settings.bug)

          bug.find_urls()

          bug.download_files()

-         srpm_org_time = get_mtime('srpm/fedwatch*.src.rpm')

+         srpm_org_time = get_mtime("srpm/fedwatch*.src.rpm")

          Checks(bug.spec_file, bug.srpm_file)

-         upstream_org_time = get_mtime('upstream/fedwatch*.gz')

+         upstream_org_time = get_mtime("upstream/fedwatch*.gz")

          del bug

  

          os.chdir(self.startdir)

-         loglevel = os.environ['REVIEW_LOGLEVEL']

-         os.environ['REVIEW_LOGLEVEL'] = 'ERROR'

-         self.init_opt_test(['-cb', '1079967'], 'options')

-         os.environ['REVIEW_LOGLEVEL'] = loglevel

+         loglevel = os.environ["REVIEW_LOGLEVEL"]

+         os.environ["REVIEW_LOGLEVEL"] = "ERROR"

+         self.init_opt_test(["-cb", "1079967"], "options")

+         os.environ["REVIEW_LOGLEVEL"] = loglevel

          bug = BugzillaBug(Settings.bug)

          bug.find_urls()

          bug.download_files()

-         srpm_new_time = get_mtime('srpm/fedwatch*.src.rpm')

+         srpm_new_time = get_mtime("srpm/fedwatch*.src.rpm")

          Checks(bug.spec_file, bug.srpm_file)

-         upstream_new_time = get_mtime('upstream/fedwatch*.gz')

+         upstream_new_time = get_mtime("upstream/fedwatch*.gz")

  

-         self.assertEqual(upstream_org_time, upstream_new_time, 'upstream')

-         self.assertEqual(srpm_org_time, srpm_new_time, 'srpm')

+         self.assertEqual(upstream_org_time, upstream_new_time, "upstream")

+         self.assertEqual(srpm_org_time, srpm_new_time, "srpm")

  

      def test_mock_options(self):

-         ''' test -o/--mock-options and -m/mock-config '''

-         nextrelease = '%d' % (int(RELEASE) + 1)

+         """ test -o/--mock-options and -m/mock-config """

+         nextrelease = "%d" % (int(RELEASE) + 1)

          v = nextrelease if RELEASE in self.BUILDROOT else RELEASE

-         buildroot = 'fedora-%s-i386' % v

-         self.init_test('mock-options',

-                        argv = ['-n', 'python-test', '--cache'],

-                        options='--resultdir=results --uniqueext=foo',

-                        buildroot=buildroot)

-         bug = NameBug('python-test')

+         buildroot = "fedora-%s-i386" % v

+         self.init_test(

+             "mock-options",

+             argv=["-n", "python-test", "--cache"],

+             options="--resultdir=results --uniqueext=foo",

+             buildroot=buildroot,

+         )

+         bug = NameBug("python-test")

          bug.find_urls()

          bug.download_files()

-         mock_cmd = ' '.join(Mock._mock_cmd())

+         mock_cmd = " ".join(Mock._mock_cmd())

          Mock._get_root()

-         self.assertIn('-r ' + buildroot, mock_cmd)

-         self.assertEqual(Mock.mock_root, buildroot + '-foo')

+         self.assertIn("-r " + buildroot, mock_cmd)

+         self.assertEqual(Mock.mock_root, buildroot + "-foo")

  

      def test_prebuilt(self):

-         ''' test --name --prebuilt '''

+         """ test --name --prebuilt """

  

-         argv = ['-rpn', 'python-spiffgtkwidgets', '--cache']

-         self.init_test('prebuilt', argv=argv)

-         bug = NameBug('python-spiffgtkwidgets')

+         argv = ["-rpn", "python-spiffgtkwidgets", "--cache"]

+         self.init_test("prebuilt", argv=argv)

+         bug = NameBug("python-spiffgtkwidgets")

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         check = checks.checkdict['CheckBuild']

+         check = checks.checkdict["CheckBuild"]

          check.run()

          self.assertTrue(check.is_pending)

-         self.assertIn('Using prebuilt packages',

-                        check.result.output_extra)

+         self.assertIn("Using prebuilt packages", check.result.output_extra)

  

      def test_rpm_spec(self):

          """ Test --rpm-spec/-r option """

-         self.init_opt_test(['-rn', 'python-test', '--cache'], 'options')

+         self.init_opt_test(["-rn", "python-test", "--cache"], "options")

          bug = NameBug(Settings.name)

          bug.find_urls()

  

-         expected = self.abs_file_url('python-test-1.0-1.fc17.src.rpm')

+         expected = self.abs_file_url("python-test-1.0-1.fc17.src.rpm")

          self.assertEqual(expected, bug.srpm_url)

-         expected = self.abs_file_url('srpm-unpacked/python-test.spec')

+         expected = self.abs_file_url("srpm-unpacked/python-test.spec")

          self.assertEqual(expected, bug.spec_url)

  

          bug.download_files()

-         expected = os.path.abspath('python-test-1.0-1.fc17.src.rpm')

+         expected = os.path.abspath("python-test-1.0-1.fc17.src.rpm")

          self.assertEqual(expected, bug.srpm_file)

-         expected = os.path.abspath('srpm-unpacked/python-test.spec')

+         expected = os.path.abspath("srpm-unpacked/python-test.spec")

          self.assertEqual(expected, bug.spec_file)

  

      def test_single(self):

-         ''' test --single/-s option '''

-         self.init_opt_test(['-n', 'python-test', '-s', 'CheckRequires',

-                             '--cache'])

+         """ test --single/-s option """

+         self.init_opt_test(["-n", "python-test", "-s", "CheckRequires", "--cache"])

          bug = NameBug(Settings.name)

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         check = checks.checkdict['CheckRequires']

-         self.assertEqual(check.name, 'CheckRequires')

+         check = checks.checkdict["CheckRequires"]

+         self.assertEqual(check.name, "CheckRequires")

  

      def test_exclude(self):

-         ''' test --exclude/-x option. '''

-         self.init_opt_test(['-n', 'python-test', '-x', 'CheckRequires',

-                             '--cache'])

+         """ test --exclude/-x option. """

+         self.init_opt_test(["-n", "python-test", "-x", "CheckRequires", "--cache"])

          bug = NameBug(Settings.name)

          bug.find_urls()

          bug.download_files()

          checks = Checks(bug.spec_file, bug.srpm_file)

-         self.assertTrue(checks.checkdict['CheckRequires'].result is None)

+         self.assertTrue(checks.checkdict["CheckRequires"].result is None)

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+21 -24
@@ -1,4 +1,4 @@ 

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  

  #    This program is free software; you can redistribute it and/or modify

  #    it under the terms of the GNU General Public License as published by
@@ -17,9 +17,9 @@ 

  #

  # pylint: disable=C0103,R0904,R0913

  # (C) 2011 - Tim Lauridsen <timlau@fedoraproject.org>

- '''

+ """

  Unit tests for bugzilla bug handling

- '''

+ """

  

  import os.path

  import re
@@ -27,7 +27,7 @@ 

  

  import unittest2 as unittest

  

- import srcpath                                   # pylint: disable=W0611

+ import srcpath  # pylint: disable=W0611

  from FedoraReview.name_bug import NameBug

  from FedoraReview.spec_file import SpecFile

  
@@ -37,28 +37,27 @@ 

  

  

  class TestRegressions(FR_TestCase):

-     ''' Test some regressions. '''

+     """ Test some regressions. """

  

      def setUp(self):

          FR_TestCase.setUp(self)

-         sys.argv = ['fedora-review', '-b', '1']

+         sys.argv = ["fedora-review", "-b", "1"]

          Settings.init(True)

-         self.spec_file = os.path.join(os.path.abspath('.'),

-                                       'test_regressions',

-                                       'test_107_1.spec')

-         self.srpm_file = os.path.join(os.path.abspath('.'),

-                                       'test_regressions',

-                                       'test_107_1-1.0-1.fc17.src.rpm')

+         self.spec_file = os.path.join(

+             os.path.abspath("."), "test_regressions", "test_107_1.spec"

+         )

+         self.srpm_file = os.path.join(

+             os.path.abspath("."), "test_regressions", "test_107_1-1.0-1.fc17.src.rpm"

+         )

          Mock.reset()

  

      def test_107_changelog_skipping(self):

          """ Test the case when sourceX is name and we use f-r -n so

          that file gets mixed up with a directory

          """

-         self.init_test('test_regressions',

-                        argv=['-rn', self.srpm_file])

+         self.init_test("test_regressions", argv=["-rn", self.srpm_file])

          spec = SpecFile(self.spec_file)

-         regex = re.compile('initial fedora')

+         regex = re.compile("initial fedora")

          self.assertEqual(len(spec.find_all_re(regex)), 2)

          self.assertEqual(len(spec.find_all_re(regex, True)), 1)

  
@@ -66,27 +65,25 @@ 

          """ Test the case when there is no space in %config line between

          the file and macro itself

          """

-         self.init_test('test_regressions',

-                        argv=['-rn', self.srpm_file, '--cache'])

+         self.init_test("test_regressions", argv=["-rn", self.srpm_file, "--cache"])

          bug = NameBug(self.srpm_file)

-         check = self.run_single_check(bug, 'CheckNoConfigInUsr')

+         check = self.run_single_check(bug, "CheckNoConfigInUsr")

          self.assertTrue(check.is_failed)

  

      def test_107_source_same_as_name(self):

          """ Test the case when Source is equal to %{name}

          """

-         srpm_file = os.path.join(os.path.abspath('.'),

-                                       'test_regressions',

-                                       'test_107_2-1.0-1.fc17.src.rpm')

-         self.init_test('test_regressions',

-                        argv=['-rn', srpm_file, '--cache'])

+         srpm_file = os.path.join(

+             os.path.abspath("."), "test_regressions", "test_107_2-1.0-1.fc17.src.rpm"

+         )

+         self.init_test("test_regressions", argv=["-rn", srpm_file, "--cache"])

          bug = NameBug(srpm_file)

          bug.find_urls()

          self.assertNotEqual(None, bug.srpm_file)

          self.assertNotEqual(None, bug.spec_file)

  

  

- if __name__ == '__main__':

+ if __name__ == "__main__":

      if len(sys.argv) > 1:

          suite = unittest.TestSuite()

          for test in sys.argv[1:]:

file modified
+16 -7
@@ -1,5 +1,5 @@ 

  #!/usr/bin/python -tt

- #-*- coding: utf-8 -*-

+ # -*- coding: utf-8 -*-

  # vim: set expandtab: ts=4:sw=4:

  #

  # Script to run a fedora-review installation from wherever it is
@@ -20,7 +20,7 @@ 

  

  main_dir = os.path.dirname(os.path.realpath(__file__))

  

- pkg_dir = os.path.join(main_dir, 'src')

+ pkg_dir = os.path.join(main_dir, "src")

  sys.path.insert(0, pkg_dir)

  

  try:
@@ -30,13 +30,22 @@ 

  

  from FedoraReview.review_helper import ReviewHelper

  

- cmd = ["git", "--git-dir", os.path.join(main_dir, '.git'), "rev-parse", "--abbrev-ref", "HEAD"]

+ cmd = [

+     "git",

+     "--git-dir",

+     os.path.join(main_dir, ".git"),

+     "rev-parse",

+     "--abbrev-ref",

+     "HEAD",

+ ]

  cur_branch = check_output(cmd).strip()

  if cur_branch == "master":

-     print("\033[91mYou are running fedora-review from 'master' branch. This "

-           "is probably not what you want to do. Master branch is equal to "

-           "latest stable release. For development/bugreporting use "

-           "'devel' branch. See CONTRIBUTE file for more details\033[0m")

+     print(

+         "\033[91mYou are running fedora-review from 'master' branch. This "

+         "is probably not what you want to do. Master branch is equal to "

+         "latest stable release. For development/bugreporting use "

+         "'devel' branch. See CONTRIBUTE file for more details\033[0m"

+     )

  

  review = ReviewHelper()

  rc = review.run()

file modified
+4 -3
@@ -12,13 +12,14 @@ 

  import sys

  

  here = os.path.dirname(os.path.realpath(__file__))

- os.chdir(os.path.join(here, 'src', 'FedoraReview'))

+ os.chdir(os.path.join(here, "src", "FedoraReview"))

  if not os.access(os.getcwd(), os.W_OK):

      print("I cannot write into " + os.getcwd() + ", giving up")

      sys.exit(1)

- if os.path.exists('version'):

-     os.remove('version')

+ if os.path.exists("version"):

+     os.remove("version")

  

  sys.path.insert(0, os.getcwd())

  import version

+ 

  sys.exit(0)

This is just 3 simple commits, I will not change anything manually until this is in. This has a large potential to diverge, so please merge soon before doing other changes.

rebased onto 9136da4

5 years ago

Pull-Request has been merged by ngompa

5 years ago
Metadata
Changes Summary 65
+3 -0
file changed
Makefile
+3 -3
file changed
koji-download-scratch
+75 -69
file changed
plugins/R.py
+1 -1
file changed
plugins/__init__.py
+159 -120
file changed
plugins/ccpp.py
+7 -4
file changed
plugins/fonts.py
+928 -732
file changed
plugins/generic.py
+48 -58
file changed
plugins/generic_autotools.py
+159 -141
file changed
plugins/generic_build.py
+346 -287
file changed
plugins/generic_should.py
+12 -9
file changed
plugins/haskell.py
+19 -10
file changed
plugins/java.py
+8 -7
file changed
plugins/ocaml.py
+18 -16
file changed
plugins/perl.py
+4 -3
file changed
plugins/php.py
+54 -36
file changed
plugins/python.py
+157 -122
file changed
plugins/ruby.py
+118 -120
file changed
plugins/shell_api.py
+23 -22
file changed
plugins/sugar_activity.py
+20 -22
file changed
setup.py
+10 -10
file changed
src/FedoraReview/__init__.py
+48 -45
file changed
src/FedoraReview/abstract_bug.py
+19 -18
file changed
src/FedoraReview/ansi.py
+11 -12
file changed
src/FedoraReview/bugzilla_bug.py
+69 -64
file changed
src/FedoraReview/check_base.py
+82 -82
file changed
src/FedoraReview/checks.py
+27 -26
file changed
src/FedoraReview/copr_bug.py
+129 -109
file changed
src/FedoraReview/create_review.py
+44 -46
file changed
src/FedoraReview/datasrc.py
+105 -58
file changed
src/FedoraReview/deps.py
+69 -52
file changed
src/FedoraReview/download_scratch.py
+8 -6
file changed
src/FedoraReview/el_compat.py
+38 -33
file changed
src/FedoraReview/helpers_mixin.py
+196 -184
file changed
src/FedoraReview/mock.py
+14 -16
file changed
src/FedoraReview/name_bug.py
+24 -23
file changed
src/FedoraReview/registry.py
+56 -59
file changed
src/FedoraReview/reports.py
+53 -49
file changed
src/FedoraReview/review_dirs.py
+4 -3
file changed
src/FedoraReview/review_error.py
+58 -61
file changed
src/FedoraReview/review_helper.py
+49 -50
file changed
src/FedoraReview/rpm_file.py
+259 -170
file changed
src/FedoraReview/settings.py
+35 -40
file changed
src/FedoraReview/source.py
+93 -85
file changed
src/FedoraReview/spec_file.py
+21 -23
file changed
src/FedoraReview/srpm_file.py
+19 -19
file changed
src/FedoraReview/url_bug.py
+22 -19
file changed
src/FedoraReview/version.py
+17 -17
file changed
src/FedoraReview/xdg_dirs.py
+1 -1
file changed
src/__init__.py
+3 -2
file changed
src/fedora-create-review
+1 -3
file changed
src/fedora-review
+42 -44
file changed
test/fr_testcase.py
+8 -8
file changed
test/srcpath.py
+29 -30
file changed
test/test_R_checks.py
+34 -32
file changed
test/test_bugzilla.py
+369 -344
file changed
test/test_checks.py
+49 -45
file changed
test/test_deps.py
+31 -26
file changed
test/test_dist.py
+3 -3
file changed
test/test_env.py
+62 -61
file changed
test/test_ext.py
+384 -379
file changed
test/test_misc.py
+97 -97
file changed
test/test_options.py
+21 -24
file changed
test/test_regressions.py
+16 -7
file changed
try-fedora-review
+4 -3
file changed
update-version