[CodeHealth] Migrate multiple python unit tests to Python3

Bug: 1223892
Change-Id: I72d8a2acbd7d47eb85a1fdcf461b374f79eea342
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3065476
Reviewed-by: Dirk Pranke <dpranke@google.com>
Commit-Queue: Victor Vianna <victorvianna@google.com>
Cr-Commit-Position: refs/heads/main@{#917178}
NOKEYCHECK=True
GitOrigin-RevId: 02442ef0cb33cdbf2c38a70f2ea10263c5f81204
diff --git a/development/scripts/PRESUBMIT.py b/development/scripts/PRESUBMIT.py
index 414635f..8d98b9a 100644
--- a/development/scripts/PRESUBMIT.py
+++ b/development/scripts/PRESUBMIT.py
@@ -20,7 +20,10 @@
       output_api,
       input_api.PresubmitLocalPath(),
       files_to_check=[r'.+_test\.py$'],
-      files_to_skip=[])
+      files_to_skip=[],
+      run_on_python2=False,
+      run_on_python3=True,
+      skip_shebang_check=True)
 
   output.extend(input_api.RunTests(py_tests, False))
 
diff --git a/development/scripts/stack.py b/development/scripts/stack.py
index 5672af6..8b70781 100755
--- a/development/scripts/stack.py
+++ b/development/scripts/stack.py
@@ -44,58 +44,58 @@
 
 def PrintUsage():
   """Print usage and exit with error."""
-  print
-  print "  usage: " + sys.argv[0] + " [options] [FILE]"
-  print
-  print "  --symbols-dir=path"
-  print "       the path to a symbols dir, such as"
-  print "       =/tmp/out/target/product/dream/symbols"
-  print
-  print "  --chrome-symbols-dir=path"
-  print "       the path to a Chrome symbols dir (can be absolute or relative"
-  print "       to src), such as =out/Debug/lib.unstripped"
-  print
-  print "  --output-directory=path"
-  print "       the path to the build output directory, such as out/Debug."
-  print "       Ignored if --chrome-symbols-dir is passed."
-  print
-  print "  --apks-directory=path"
-  print "       Overrides the default apks directory. Useful if a bundle APKS"
-  print "       file has been unzipped into a temporary directory."
-  print
-  print "  --symbols-zip=path"
-  print "       the path to a symbols zip file, such as"
-  print "       =dream-symbols-12345.zip"
-  print
-  print "  --more-info"
-  print "  --less-info"
-  print "       Change the level of detail in the output."
-  print "       --more-info is slower and more verbose, but more functions will"
-  print "       be fully qualified with namespace/classname and have full"
-  print "       argument information. Also, the 'stack data' section will be"
-  print "       printed."
-  print
-  print "  --arch=arm|arm64|x64|x86|mips"
-  print "       the target architecture"
-  print
-  print "  --fallback-monochrome"
-  print "       fallback to monochrome instead of chrome if fail to detect"
-  print "       shared lib which is loaded from APK, this doesn't work for"
-  print "       component build."
-  print
-  print "  --quiet"
-  print "       Show less logging"
-  print
-  print "  --verbose"
-  print "       enable extra logging, particularly for debugging failed"
-  print "       symbolization"
-  print
-  print "  FILE should contain a stack trace in it somewhere"
-  print "       the tool will find that and re-print it with"
-  print "       source files and line numbers.  If you don't"
-  print "       pass FILE, or if file is -, it reads from"
-  print "       stdin."
-  print
+  print()
+  print("  usage: " + sys.argv[0] + " [options] [FILE]")
+  print()
+  print("  --symbols-dir=path")
+  print("       the path to a symbols dir, such as")
+  print("       =/tmp/out/target/product/dream/symbols")
+  print()
+  print("  --chrome-symbols-dir=path")
+  print("       the path to a Chrome symbols dir (can be absolute or relative")
+  print("       to src), such as =out/Debug/lib.unstripped")
+  print()
+  print("  --output-directory=path")
+  print("       the path to the build output directory, such as out/Debug.")
+  print("       Ignored if --chrome-symbols-dir is passed.")
+  print()
+  print("  --apks-directory=path")
+  print("       Overrides the default apks directory. Useful if a bundle APKS")
+  print("       file has been unzipped into a temporary directory.")
+  print()
+  print("  --symbols-zip=path")
+  print("       the path to a symbols zip file, such as")
+  print("       =dream-symbols-12345.zip")
+  print()
+  print("  --more-info")
+  print("  --less-info")
+  print("       Change the level of detail in the output.")
+  print("       --more-info is slower and more verbose, but more functions")
+  print("       will be fully qualified with namespace/classname and have full")
+  print("       argument information. Also, the 'stack data' section will be")
+  print("       printed.")
+  print()
+  print("  --arch=arm|arm64|x64|x86|mips")
+  print("       the target architecture")
+  print()
+  print("  --fallback-monochrome")
+  print("       fallback to monochrome instead of chrome if fail to detect")
+  print("       shared lib which is loaded from APK, this doesn't work for")
+  print("       component build.")
+  print()
+  print("  --quiet")
+  print("       Show less logging")
+  print()
+  print("  --verbose")
+  print("       enable extra logging, particularly for debugging failed")
+  print("       symbolization")
+  print()
+  print("  FILE should contain a stack trace in it somewhere")
+  print("       the tool will find that and re-print it with")
+  print("       source files and line numbers.  If you don't")
+  print("       pass FILE, or if file is -, it reads from")
+  print("       stdin.")
+  print()
   sys.exit(1)
 
 def UnzipSymbols(symbolfile, symdir=None):
@@ -147,7 +147,7 @@
         "apks-directory=", "symbols-dir=", "symbols-zip=", "arch=",
         "fallback-monochrome", "verbose", "quiet", "help",
     ])
-  except getopt.GetoptError, _:
+  except getopt.GetoptError:
     PrintUsage()
 
   zip_arg = None
diff --git a/development/scripts/stack_core.py b/development/scripts/stack_core.py
index d05a659..4cea454 100755
--- a/development/scripts/stack_core.py
+++ b/development/scripts/stack_core.py
@@ -111,38 +111,39 @@
 def PrintTraceLines(trace_lines):
   """Print back trace."""
   maxlen = min(80, max(map(lambda tl: len(tl[1]), trace_lines)))
-  print
-  print 'Stack Trace:'
-  print '  RELADDR   ' + 'FUNCTION'.ljust(maxlen) + '  FILE:LINE'
+  print()
+  print('Stack Trace:')
+  print('  RELADDR   ' + 'FUNCTION'.ljust(maxlen) + '  FILE:LINE')
   for tl in trace_lines:
     (addr, symbol_with_offset, location) = tl
     normalized = os.path.normpath(location)
-    print '  %8s  %s  %s' % (addr, symbol_with_offset.ljust(maxlen), normalized)
+    print('  %8s  %s  %s' % (addr, symbol_with_offset.ljust(maxlen),
+        normalized))
   return
 
 
 def PrintValueLines(value_lines):
   """Print stack data values."""
   maxlen = min(80, max(map(lambda tl: len(tl[2]), value_lines)))
-  print
-  print 'Stack Data:'
-  print '  ADDR      VALUE     ' + 'FUNCTION'.ljust(maxlen) + '  FILE:LINE'
+  print()
+  print('Stack Data:')
+  print('  ADDR      VALUE     ' + 'FUNCTION'.ljust(maxlen) + '  FILE:LINE')
   for vl in value_lines:
     (addr, value, symbol_with_offset, location) = vl
-    print '  %8s  %8s  %s  %s' % (addr, value, symbol_with_offset.ljust(maxlen),
-                                  location)
+    print('  %8s  %8s  %s  %s' % (addr, value, symbol_with_offset.ljust(maxlen),
+                                  location))
   return
 
 
 def PrintJavaLines(java_lines):
   """Print java stderr lines."""
-  print
+  print()
   print('Java stderr from crashing pid '
         '(may identify underlying Java exception):')
   for l in java_lines:
     if l.startswith('at'):
-      print ' ',
-    print l
+      print(' ')
+    print(l)
 
 def PrintOutput(trace_lines, value_lines, java_lines, more_info):
   if trace_lines:
@@ -159,8 +160,8 @@
     PrintJavaLines(java_lines)
 
 def PrintDivider():
-  print
-  print '-----------------------------------------------------\n'
+  print()
+  print('-----------------------------------------------------\n')
 
 
 def StreamingConvertTrace(_, load_vaddrs, more_info, fallback_monochrome,
@@ -181,13 +182,13 @@
     if not arch_defined:
       arch = _FindAbi(useful_lines)
       if arch:
-        print 'Symbolizing stack using ABI=' + arch
+        print('Symbolizing stack using ABI=' + arch)
         symbol.ARCH = arch
     ResolveCrashSymbol(list(useful_lines), more_info, llvm_symbolizer)
 
   preprocessor = PreProcessLog(load_vaddrs, apks_directory)
   for line in iter(sys.stdin.readline, b''):
-    print line,
+    print(line)
     maybe_line, maybe_so_dir = preprocessor([line])
     useful_lines.extend(maybe_line)
     so_dirs.extend(maybe_so_dir)
@@ -214,7 +215,7 @@
     _FALLBACK_SO = 'libmonochrome.so'
   start = time.time()
 
-  chunks = [lines[i: i+_CHUNK_SIZE] for i in xrange(0, len(lines), _CHUNK_SIZE)]
+  chunks = [lines[i: i+_CHUNK_SIZE] for i in range(0, len(lines), _CHUNK_SIZE)]
 
   use_multiprocessing = len(chunks) > 1 and (
       os.environ.get('STACK_DISABLE_ASYNC') != '1')
@@ -243,7 +244,7 @@
   if not arch_defined:
     arch = _FindAbi(useful_log)
     if arch:
-      print 'Symbolizing stack using ABI:', arch
+      print('Symbolizing stack using ABI:', arch)
       symbol.ARCH = arch
 
   ResolveCrashSymbol(list(useful_log), more_info, llvm_symbolizer)
@@ -276,7 +277,7 @@
       return
     offset = offset_match.group('offset')
     key = '%s:%s' % (lib, offset)
-    if self._shared_libraries_mapping.has_key(key):
+    if key in self._shared_libraries_mapping:
       soname = self._shared_libraries_mapping[key]
     else:
       soname, host_so = _FindSharedLibraryFromAPKs(constants.GetOutDirectory(),
@@ -302,7 +303,7 @@
     Returns:
       address+load_vaddrs[key] if lib ends with /key, otherwise address
     """
-    for key, offset in self._load_vaddrs.iteritems():
+    for key, offset in self._load_vaddrs.items():
       if lib.endswith('/' + key):
         # Add offset to address, and return the result as a hexadecimal string
         # with the same number of digits as the original. This allows the
@@ -320,7 +321,7 @@
     """
     useful_log = []
     for ln in lines:
-      line = unicode(ln, errors='ignore')
+      line = ln.encode().decode(encoding='utf8', errors='ignore')
       if (_PROCESS_INFO_LINE.search(line)
           or _SIGNAL_LINE.search(line)
           or _REGISTER_LINE.search(line)
@@ -417,27 +418,28 @@
       if process_header:
         # Track the last reported pid to find java exceptions.
         pid = _PROCESS_INFO_PID.search(process_header.group(1)).group(1)
-        print process_header.group(1)
+        print(process_header.group(1))
       if signal_header:
-        print signal_header.group(1)
+        print(signal_header.group(1))
       if register_header:
-        print register_header.group(1)
+        print(register_header.group(1))
       if thread_header:
-        print thread_header.group(1)
+        print(thread_header.group(1))
       if dalvik_jni_thread_header:
-        print dalvik_jni_thread_header.group(1)
+        print(dalvik_jni_thread_header.group(1))
       if dalvik_native_thread_header:
-        print dalvik_native_thread_header.group(1)
+        print(dalvik_native_thread_header.group(1))
       if log_fatal_header:
-        print log_fatal_header.group(1)
+        print(log_fatal_header.group(1))
       if misc_header:
-        print misc_header.group(0)
+        print(misc_header.group(0))
       continue
 
     match = _TRACE_LINE.match(line) or _DEBUG_TRACE_LINE.match(line)
     if match:
       frame, code_addr, area, _, symbol_name = match.group(
           'frame', 'address', 'lib', 'symbol_present', 'symbol_name')
+      frame = int(frame)
       logging.debug('Found trace line: %s' % line.strip())
 
       if frame <= last_frame and (trace_lines or value_lines):
@@ -529,7 +531,7 @@
             file_offset = (infoList.header_offset + FILE_NAME_OFFSET +
                            file_name_len + extra_field_len)
             f.seek(file_offset)
-            if offset == file_offset and f.read(4) == "\x7fELF":
+            if offset == file_offset and f.read(4) == b"\x7fELF":
               soname = infoList.filename.replace('crazy.', '')
               sosize = infoList.file_size
               break
diff --git a/development/scripts/stack_test.py b/development/scripts/stack_test.py
index 4444261..4d53fa9 100755
--- a/development/scripts/stack_test.py
+++ b/development/scripts/stack_test.py
@@ -103,7 +103,7 @@
     data = '\x7fELF' + ' ' * (0xE00 - self._num_libraries)
     self._num_libraries += 1
     with open(library, 'wb') as f:
-      f.write(data)
+      f.write(data.encode('utf-8'))
 
   # Build a dummy APK with native libraries in it.
   def _MakeApk(self, apk, libs, apk_dir, out_dir, crazy):
@@ -195,7 +195,7 @@
     actual_tokens = [line.split() for line in output_lines]
 
     self.assertEqual(len(expected_tokens), len(actual_tokens))
-    for i in xrange(len(expected_tokens)):
+    for i in range(len(expected_tokens)):
       self.assertEqual(expected_tokens[i], actual_tokens[i])
 
   def test_BasicDecoding(self):