port python2.x code to python3.x 72/291072/4
authorbiao716.wang <biao716.wang@samsung.com>
Fri, 7 Apr 2023 10:05:23 +0000 (19:05 +0900)
committerbiao716.wang <biao716.wang@samsung.com>
Fri, 7 Apr 2023 10:27:26 +0000 (19:27 +0900)
Change-Id: Idfc8ead4ce6f0e80bd4f0fbaee77cbc6fa3ba0a7
Signed-off-by: biao716.wang <biao716.wang@samsung.com>
20 files changed:
debian/control
debian/rules
imgdiff/cleanup.py
imgdiff/diff.py
imgdiff/info.py
imgdiff/trivial.py
imgdiff/unified.py
imgdiff/unpack.py
itest/case.py
itest/conf/__init__.py
itest/loader.py
itest/main.py
setup.py
spm/cli.py
tests/functional/base.py
tests/functional/test_in_project.py
tests/functional/test_setup_teardown.py
tests/functional/test_simple.py
tests/functional/test_xunit.py
tests/unit/test_xmlparser.py

index b24241f..b822e97 100644 (file)
@@ -2,26 +2,26 @@ Source: itest-core
 Section: devel
 Priority: extra
 Maintainer: Junchun Guan <junchunx.guan@intel.com>
-Build-Depends: debhelper, python (>= 2.6), python-setuptools
+Build-Depends: debhelper, python3, python3-setuptools, dh-python, python3-all
 Standards-Version: 3.8.0
-X-Python-Version: >= 2.6
+X-Python-Version: >= 3
 Homepage: http://www.tizen.org
 
 Package: itest-core
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends},
- python-pexpect, python-coverage, python-jinja2, python-unittest2, spm
+Depends: ${misc:Depends}, ${python3:Depends},
+ python3-pexpect, python3-coverage, python3-jinja2, python3-unittest2, spm
 Description: functional test framework for gbs and mic
 
 Package: spm
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends},
- python-jinja2, python-yaml
+Depends: ${misc:Depends}, ${python3:Depends},
+ python3-jinja2, python3-yaml
 Description: Smart package management tool on Linux
  A wrapper of yum, apt-get, zypper command. Support Redhat, Debian, SuSE
 
 Package: nosexcase
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends},
- itest-core, python-nose
+Depends: ${misc:Depends}, ${python3:Depends},
+ itest-core, python3-nose
 Description: A nose plugin that supports running test cases defined in XML format
index 37dbe9d..7aa69e7 100644 (file)
@@ -1,10 +1,10 @@
 #!/usr/bin/make -f
 
 %:
-       dh $@
+       dh $@ --with python3 --buildsystem=pybuild
 
 override_dh_auto_install:
-       python setup.py install --root=debian/tmp --prefix=/usr
+       python3 setup.py install --root=debian/tmp --prefix=/usr
 
 override_dh_auto_test:
        @echo 'Skipping autotests'
index 4296954..f9a5d9c 100644 (file)
@@ -13,7 +13,7 @@ def umount(path):
         return
 
     cmd = ['sudo', 'umount', '-l', path]
-    print "Umounting", path, "..."
+    print("Umounting", path, "...")
     return call(cmd)
 
 
@@ -21,7 +21,7 @@ def loopdel(val):
     '''Release loop dev at val
     '''
     devloop, filename = val.split(':', 1)
-    print "Releasing %s(%s)" % (devloop, filename), "..."
+    print("Releasing %s(%s)" % (devloop, filename), "...")
 
 
 def main():
@@ -40,7 +40,7 @@ def main():
         if key in handler:
             handler[key](val)
         else:
-            print >> sys.stderr, "Have no idea to release:", line,
+            print("Have no idea to release:", line, end=' ', file=sys.stderr)
 
 
 if __name__ == '__main__':
index b677cab..1390f01 100644 (file)
@@ -6,7 +6,7 @@ import re
 import os
 import sys
 import argparse
-from itertools import imap, ifilter
+
 
 from imgdiff.trivial import Conf, Rules
 from imgdiff.unified import parse
@@ -54,11 +54,11 @@ def parse_and_mark(stream, conf_filename=None):
     by conf_filename
     '''
     stream = parse(stream)
-    stream = imap(fix_filename, stream)
+    stream = map(fix_filename, stream)
 
     if conf_filename:
         mark_trivial = Mark(conf_filename)
-        stream = imap(mark_trivial, stream)
+        stream = map(mark_trivial, stream)
     return stream
 
 
@@ -74,10 +74,10 @@ def main():
     "Main"
     args = parse_args()
     stream = parse_and_mark(sys.stdin, args.conf_filename)
-    stream = ifilter(nontrivial, stream)
+    stream = filter(nontrivial, stream)
     cnt = 0
     for each in stream:
-        print each
+        print(each)
         cnt += 1
     return cnt
 
index cbc1e06..542359c 100644 (file)
@@ -4,7 +4,7 @@ import re
 import os
 import sys
 from subprocess import check_output, CalledProcessError
-from itertools import ifilter, islice, chain
+from itertools import islice, chain
 
 
 def parted(img):
@@ -163,7 +163,7 @@ class FSTab(dict):
         guess1 = (os.path.join(path, 'etc', 'fstab') for path in paths)
         guess2 = (os.path.join(path, 'fstab') for path in paths)
         guesses = chain(guess1, guess2)
-        exists = ifilter(os.path.exists, guesses)
+        exists = filter(os.path.exists, guesses)
         one = list(islice(exists, 1))
         return cls(one[0]) if one else None
 
@@ -173,7 +173,7 @@ def get_partition_info(img):
     try:
         parts = parted(img)
     except CalledProcessError as err:
-        print >> sys.stderr, err
+        print(err, file=sys.stderr)
         # Sometimes parted could failed with error
         # like this, then we try gdisk.
         # "Error during translation: Invalid or incomplete
index 6517cbc..c78eb61 100644 (file)
@@ -74,9 +74,9 @@ class Rules(object):
         for entry in conf.get('ignoreLines', []):
             files = entry['Files']
             lines = entry['Lines']
-            if isinstance(files, basestring):
+            if isinstance(files, str):
                 files = [files]
-            if isinstance(lines, basestring):
+            if isinstance(lines, str):
                 lines = [lines]
             ignore = IgnoreLines(lines)
             for pat in files:
index 0abba1a..577dd18 100644 (file)
@@ -14,11 +14,11 @@ class LookAhead(object):
         "push token back to this iterable"
         self.stack.append(token)
 
-    def next(self):
+    def __next__(self):
         "next token"
         if self.stack:
             return self.stack.pop()
-        return self.iterable.next()
+        return next(self.iterable)
 
     def __iter__(self):
         "iterable"
@@ -108,7 +108,7 @@ class BinaryFile(MessageParser):
             }
 
 
-MESSAGE_PARSERS = [obj() for name, obj in globals().items()
+MESSAGE_PARSERS = [obj() for name, obj in list(globals().items())
                    if hasattr(obj, '__bases__') and
                    MessageParser in obj.__bases__]
 
@@ -121,7 +121,7 @@ class Message(dict):
     @classmethod
     def parse(cls, stream):
         "Parse message text into dict"
-        line = stream.next()
+        line = next(stream)
         for parser in MESSAGE_PARSERS:
             data = parser.match(line)
             if data:
@@ -159,7 +159,7 @@ class OneFileDiff(dict):
          Sector size (logical/physical): 512B/512B
          Partition Table: gpt
         '''
-        line = stream.next()
+        line = next(stream)
         if not line.startswith('diff '):
             stream.push_back(line)
             return
@@ -169,10 +169,10 @@ class OneFileDiff(dict):
 
         def parse_header(line):
             '''header'''
-            return dict(zip(cols, line.rstrip().split()[1:]))
+            return dict(list(zip(cols, line.rstrip().split()[1:])))
 
-        fromfile = parse_header(stream.next())
-        tofile = parse_header(stream.next())
+        fromfile = parse_header(next(stream))
+        tofile = parse_header(next(stream))
         sections = cls._parse_sections(stream)
         return cls({
             'type': 'onefilediff',
@@ -288,11 +288,11 @@ def parse(stream):
             continue
 
         try:
-            line = stream.next()
+            line = next(stream)
         except StopIteration:
             # one equals None means steam hasn't stop but no one can
             # understand the input. If we are here there must be bug
             # in previous parsing logic
             raise Exception('Unknown error in parsing diff output')
         else:
-            print >> sys.stderr, '[WARN] Unknown diff output:', line,
+            print('[WARN] Unknown diff output:', line, end=' ', file=sys.stderr)
index 56a2b49..7f8dc2f 100644 (file)
@@ -61,17 +61,17 @@ class Mount(object):
                '-o', 'ro,offset=%d' % offset,
                '-t', fstype,
                image, path]
-        print 'Mounting', '%d@%s' % (offset, image), '->', path, '...'
+        print('Mounting', '%d@%s' % (offset, image), '->', path, '...')
         check_call(cmd)
 
     def move(self, source, target):
         '''Remove mount point to another path'''
         self._check_path(target)
         cmd = ['sudo', 'mount', '--make-runbindable', '/']
-        print 'Make runbindable ...', ' '.join(cmd)
+        print('Make runbindable ...', ' '.join(cmd))
         check_call(cmd)
         cmd = ['sudo', 'mount', '-M', source, target]
-        print 'Moving mount point from', source, 'to', target, '...'
+        print('Moving mount point from', source, 'to', target, '...')
         check_call(cmd)
 
 
@@ -96,8 +96,7 @@ class Image(object):
             number = str(part['number'])
             fstype = part['blkid']['type']
             if not self._is_fs_supported(fstype):
-                print >> sys.stderr, \
-                    "ignore partition %s of type %s" % (number, fstype)
+                print("ignore partition %s of type %s" % (number, fstype), file=sys.stderr)
                 continue
 
             path = os.path.join(basedir, 'partx', 'p'+number)
@@ -119,8 +118,8 @@ class Image(object):
             elif 'uuid' in item and item['uuid'] in uuid2temp:
                 source = uuid2temp[item['uuid']]
             else:
-                print >> sys.stderr, "fstab mismatch with partition table:", \
-                    item["entry"]
+                print("fstab mismatch with partition table:", \
+                    item["entry"], file=sys.stderr)
                 return
 
             # remove heading / otherwise the path will reduce to root
@@ -140,9 +139,9 @@ class Image(object):
 
         num2temp, uuid2temp = self._mount_to_temp(basedir, mount)
 
-        fstab = FSTab.guess(num2temp.values())
+        fstab = FSTab.guess(list(num2temp.values()))
         if not fstab:
-            print >> sys.stderr, "Can't find fstab file from image"
+            print("Can't find fstab file from image", file=sys.stderr)
             return
         return self._move_to_root(fstab,
                                   num2temp, uuid2temp,
index de3511a..21f7b9d 100644 (file)
@@ -250,7 +250,7 @@ set -x
     def _make_code(self, name, code):
         """Write `code` into `name`"""
         path = os.path.join(self.meta, name)
-        data = code.encode('utf8') if isinstance(code, unicode) else code
+        data = code.encode('utf8') if isinstance(code, str) else code
         with open(path, 'w') as f:
             f.write(data)
         return path
index 276dd01..abdc46b 100644 (file)
@@ -43,7 +43,7 @@ def load_settings(test_project_root=None):
         settings_py = os.path.join(test_project_root, 'settings.py')
         try:
             mod = imp.load_source('settings', settings_py)
-        except (ImportError, IOError), e:
+        except (ImportError, IOError) as e:
             raise ImportError("Could not import settings '%s' (Is it on "
                               "sys.path?): %s" % (settings_py, e))
         settings.load(mod)
index 365b14c..f80c3d8 100644 (file)
@@ -79,7 +79,7 @@ class FilePattern(object):
         template = jinja2_env.get_template(os.path.basename(name))
         text = template.render()
 
-        if isinstance(text, unicode):
+        if isinstance(text, str):
             text = text.encode('utf8')
             # template returns unicode
             # but xml parser only accepts str
index f088802..ec9d4a1 100644 (file)
@@ -83,7 +83,7 @@ class TestProgram(unittest.TestProgram):
         # additional options
         if opts.with_xunit:
             if not os.access(os.path.dirname(opts.xunit_file), os.W_OK):
-                print >> sys.stderr, "Permission denied:", opts.xunit_file
+                print("Permission denied:", opts.xunit_file, file=sys.stderr)
                 sys.exit(1)
             from itest.result import XunitTestResult
             self.testRunner.resultclass = XunitTestResult
index e6c6932..53ad0d5 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from setuptools import setup
 
 from itest import __version__
index eb51ded..8ead198 100644 (file)
@@ -42,7 +42,7 @@ def install_parser(parser):
         distro.uninstall(args.pkg)
         if args.repo:
             distro.make_repo('tools', args.repo)
-        print distro.check_version(args.pkg)
+        print(distro.check_version(args.pkg))
         distro.clean()
         distro.refresh()
         distro.install(args.pkg)
@@ -120,9 +120,9 @@ def version_parser(parser):
         packages = distro.get_package_dependency(args.pkg)
         if packages:
             for pkg in packages:
-                print distro.check_version(pkg)
+                print(distro.check_version(pkg))
         else:
-            print distro.check_version(args.pkg)
+            print(distro.check_version(args.pkg))
 
     parser.set_defaults(handler=handler)
     return parser
@@ -136,7 +136,7 @@ def main():
     parser.add_argument('-V', '--version',
                         action='version', version=__version__)
     subparsers = parser.add_subparsers(title='subcommands')
-    for name, obj in globals().iteritems():
+    for name, obj in globals().items():
         if name.endswith('_parser') and callable(obj):
             obj(subparsers)
     args = parser.parse_args()
index e498fba..28ad545 100644 (file)
@@ -2,7 +2,7 @@ import os
 import unittest
 import functools
 from subprocess import call
-from cStringIO import StringIO
+from io import StringIO
 
 from mock import patch
 
@@ -61,7 +61,7 @@ class TestBase(unittest.TestCase):
 
     def assertFail(self, *argv):
         exitcode, stderr = runtest(*argv)
-        self.assertNotEquals(0, exitcode,
+        self.assertNotEqual(0, exitcode,
                              format_msg(exitcode, stderr))
 
     def assertWithText(self, argv, text):
@@ -71,5 +71,5 @@ class TestBase(unittest.TestCase):
 
     def assertWithoutText(self, argv, text):
         exitcode, stderr = runtest(*argv)
-        self.assertEquals(-1, stderr.find(text),
+        self.assertEqual(-1, stderr.find(text),
                           format_msg(exitcode, stderr))
index 1dfddfb..2d6b50e 100644 (file)
@@ -1,4 +1,4 @@
-from base import TestBase, cd, PROJ_PATH, PROJ_CASES_PATH, DATA_PATH
+from .base import TestBase, cd, PROJ_PATH, PROJ_CASES_PATH, DATA_PATH
 
 
 class InProjectTest(TestBase):
index 930765e..d54270f 100644 (file)
@@ -1,4 +1,4 @@
-from base import TestBase, CASES_PATH, cd
+from .base import TestBase, CASES_PATH, cd
 
 
 class SetupTeardownTest(TestBase):
index 9d81616..7256d3d 100644 (file)
@@ -1,4 +1,4 @@
-from base import TestBase, CASES_PATH, cd
+from .base import TestBase, CASES_PATH, cd
 
 
 class BasicTest(TestBase):
index 9b39b97..fd29e20 100644 (file)
@@ -2,7 +2,7 @@ import os
 import xml.etree.ElementTree as ET
 
 
-from base import cd, TestBase, runtest, CASES_PATH
+from .base import cd, TestBase, runtest, CASES_PATH
 
 
 class XunitTest(TestBase):
index ad0cb4d..af698e8 100644 (file)
@@ -6,7 +6,7 @@ from itest.xmlparser import Parser
 class TestXMLParser(unittest.TestCase):
 
     def test_simple(self):
-        self.assertEquals({
+        self.assertEqual({
                 'summary': 'test',
                 'steps': 'echo test1\necho test2',
                 },
@@ -19,7 +19,7 @@ echo test2
 </testcase>"""))
 
     def test_tracking(self):
-        self.assertEquals({'tracking': [
+        self.assertEqual({'tracking': [
                     ('change', '90125'),
                     ('ticket', '5150'),
                     ]},
@@ -31,7 +31,7 @@ echo test2
 </testcase>'''))
 
     def test_qa(self):
-        self.assertEquals({'qa': [
+        self.assertEqual({'qa': [
                     ('Are you sure?', 'y'),
                     ('Do you agree?', 'n'),
                     ]},
@@ -52,7 +52,7 @@ echo test2
 </testcase>''')
 
     def test_conditions(self):
-        self.assertEquals({'conditions': {
+        self.assertEqual({'conditions': {
                 'whitelist': [
                     'OpenSuse-64bit',
                     'Ubuntu12.04',
@@ -74,4 +74,4 @@ echo test2
 </testcase>'''))
 
     def test_bad_case(self):
-        self.assertEquals(None, Parser().parse('I am not XML format!'))
+        self.assertEqual(None, Parser().parse('I am not XML format!'))