[lldb] Remove uses of six module (NFC)

With lldb (& llvm) requiring Python 3.6+, use of the `six` module can be removed.

Differential Revision: https://reviews.llvm.org/D131304
This commit is contained in:
Dave Lee 2022-08-05 13:35:20 -06:00
parent 256ba7738e
commit 56f9cfe30c
35 changed files with 114 additions and 209 deletions

View File

@ -157,7 +157,7 @@ public:
for x in range(*key.indices(self.__len__())): for x in range(*key.indices(self.__len__())):
list.append(self.__getitem__(x)) list.append(self.__getitem__(x))
return list return list
if not (isinstance(key,six.integer_types)): if not (isinstance(key, int)):
raise TypeError('must be int') raise TypeError('must be int')
key = key * self.item_size # SBData uses byte-based indexes, but we want to use itemsize-based indexes here key = key * self.item_size # SBData uses byte-based indexes, but we want to use itemsize-based indexes here
error = SBError() error = SBError()

View File

@ -84,8 +84,6 @@ void name ## _set(type *t, int index, type val) {
import uuid import uuid
import re import re
import os import os
import six
%} %}
// Include the version of swig that was used to generate this interface. // Include the version of swig that was used to generate this interface.

View File

@ -1,10 +1,8 @@
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
import six
import lldb import lldb
@six.add_metaclass(ABCMeta) class ScriptedProcess(metaclass=ABCMeta):
class ScriptedProcess:
""" """
The base class for a scripted process. The base class for a scripted process.
@ -193,8 +191,7 @@ class ScriptedProcess:
""" """
return None return None
@six.add_metaclass(ABCMeta) class ScriptedThread(metaclass=ABCMeta):
class ScriptedThread:
""" """
The base class for a scripted thread. The base class for a scripted thread.

View File

@ -33,8 +33,7 @@ class PythonObjectSyntheticChildProvider(object):
def gen_child(self, name, value): def gen_child(self, name, value):
data = None data = None
type = None type = None
import six if isinstance(value, int):
if isinstance(value, six.integer_types):
data = lldb.SBData.CreateDataFromUInt64Array( data = lldb.SBData.CreateDataFromUInt64Array(
self.bo, self.ps, [value]) self.bo, self.ps, [value])
type = self.value.target.GetBasicType(lldb.eBasicTypeLong) type = self.value.target.GetBasicType(lldb.eBasicTypeLong)

View File

@ -10,26 +10,12 @@ to see a description of the supported command line arguments.
# Python modules: # Python modules:
import io import io
# Third party modules
import six
def _encoded_read(old_read, encoding):
def impl(size):
result = old_read(size)
# If this is Python 2 then we need to convert the resulting `unicode` back
# into a `str` before returning
if six.PY2:
result = result.encode(encoding)
return result
return impl
def _encoded_write(old_write, encoding): def _encoded_write(old_write, encoding):
def impl(s): def impl(s):
# If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it # If we were asked to write a `bytes` decode it as unicode before
# as unicode before attempting to write. # attempting to write.
if isinstance(s, six.binary_type): if isinstance(s, bytes):
s = s.decode(encoding, "replace") s = s.decode(encoding, "replace")
# Filter unreadable characters, Python 3 is stricter than python 2 about them. # Filter unreadable characters, Python 3 is stricter than python 2 about them.
import re import re
@ -38,9 +24,8 @@ def _encoded_write(old_write, encoding):
return impl return impl
''' '''
Create a Text I/O file object that can be written to with either unicode strings or byte strings Create a Text I/O file object that can be written to with either unicode strings
under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the or byte strings.
native string type for the current Python version
''' '''
@ -60,8 +45,6 @@ def open(
errors=errors, errors=errors,
newline=newline, newline=newline,
closefd=closefd) closefd=closefd)
new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding)
new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding) new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
setattr(wrapped_file, 'read', new_read)
setattr(wrapped_file, 'write', new_write) setattr(wrapped_file, 'write', new_write)
return wrapped_file return wrapped_file

View File

@ -1,47 +1,31 @@
import binascii import binascii
import six
import shlex import shlex
if six.PY2:
import commands
get_command_output = commands.getoutput
get_command_status_output = commands.getstatusoutput
cmp_ = cmp
else:
def get_command_status_output(command):
try:
import subprocess import subprocess
return (
0,
subprocess.check_output(
command,
shell=True,
universal_newlines=True).rstrip())
except subprocess.CalledProcessError as e:
return (e.returncode, e.output)
def get_command_output(command): def get_command_output(command):
return get_command_status_output(command)[1] try:
return subprocess.check_output(
command,
shell=True,
universal_newlines=True).rstrip()
except subprocess.CalledProcessError as e:
return e.output
cmp_ = lambda x, y: (x > y) - (x < y) def bitcast_to_string(b: bytes) -> str:
"""
Take a bytes object and return a string. The returned string contains the
exact same bytes as the input object. (latin1 <-> unicode transformation is
an identity operation for the first 256 code points).
"""
return b.decode("latin1")
def bitcast_to_string(b): def bitcast_to_bytes(s: str) -> bytes:
""" """
Take a string(PY2) or a bytes(PY3) object and return a string. The returned Take a string and return a bytes object. The returned object contains the
string contains the exact same bytes as the input object (latin1 <-> unicode exact same bytes as the input string. (latin1 <-> unicode transformation isi
transformation is an identity operation for the first 256 code points). an identity operation for the first 256 code points).
""" """
return b if six.PY2 else b.decode("latin1") return s.encode("latin1")
def bitcast_to_bytes(s):
"""
Take a string and return a string(PY2) or a bytes(PY3) object. The returned
object contains the exact same bytes as the input string. (latin1 <->
unicode transformation is an identity operation for the first 256 code
points).
"""
return s if six.PY2 else s.encode("latin1")
def unhexlify(hexstr): def unhexlify(hexstr):
"""Hex-decode a string. The result is always a string.""" """Hex-decode a string. The result is always a string."""

View File

@ -13,7 +13,6 @@ import tempfile
import subprocess import subprocess
# Third-party modules # Third-party modules
import six
import unittest2 import unittest2
# LLDB modules # LLDB modules
@ -71,7 +70,6 @@ def _check_expected_version(comparison, expected, actual):
LooseVersion(expected_str)) LooseVersion(expected_str))
_re_pattern_type = type(re.compile(''))
def _match_decorator_property(expected, actual): def _match_decorator_property(expected, actual):
if expected is None: if expected is None:
return True return True
@ -82,7 +80,7 @@ def _match_decorator_property(expected, actual):
if isinstance(expected, no_match): if isinstance(expected, no_match):
return not _match_decorator_property(expected.item, actual) return not _match_decorator_property(expected.item, actual)
if isinstance(expected, (_re_pattern_type,) + six.string_types): if isinstance(expected, (re.Pattern, str)):
return re.search(expected, actual) is not None return re.search(expected, actual) is not None
if hasattr(expected, "__iter__"): if hasattr(expected, "__iter__"):
@ -131,7 +129,7 @@ def expectedFailureIfFn(expected_fn, bugnumber=None):
# the first way, the first argument will be the actual function because decorators are # the first way, the first argument will be the actual function because decorators are
# weird like that. So this is basically a check that says "which syntax was the original # weird like that. So this is basically a check that says "which syntax was the original
# function decorated with?" # function decorated with?"
if six.callable(bugnumber): if callable(bugnumber):
return expectedFailure_impl(bugnumber) return expectedFailure_impl(bugnumber)
else: else:
return expectedFailure_impl return expectedFailure_impl
@ -162,7 +160,7 @@ def skipTestIfFn(expected_fn, bugnumber=None):
# the first way, the first argument will be the actual function because decorators are # the first way, the first argument will be the actual function because decorators are
# weird like that. So this is basically a check that says "how was the # weird like that. So this is basically a check that says "how was the
# decorator used" # decorator used"
if six.callable(bugnumber): if callable(bugnumber):
return skipTestIfFn_impl(bugnumber) return skipTestIfFn_impl(bugnumber)
else: else:
return skipTestIfFn_impl return skipTestIfFn_impl
@ -249,7 +247,7 @@ def _decorateTest(mode,
mode_str, reason_str) mode_str, reason_str)
else: else:
reason_str = "{} unconditionally".format(mode_str) reason_str = "{} unconditionally".format(mode_str)
if bugnumber is not None and not six.callable(bugnumber): if bugnumber is not None and not callable(bugnumber):
reason_str = reason_str + " [" + str(bugnumber) + "]" reason_str = reason_str + " [" + str(bugnumber) + "]"
return reason_str return reason_str
@ -463,7 +461,7 @@ def expectedFlakey(expected_fn, bugnumber=None):
# the first way, the first argument will be the actual function because decorators are # the first way, the first argument will be the actual function because decorators are
# weird like that. So this is basically a check that says "which syntax was the original # weird like that. So this is basically a check that says "which syntax was the original
# function decorated with?" # function decorated with?"
if six.callable(bugnumber): if callable(bugnumber):
return expectedFailure_impl(bugnumber) return expectedFailure_impl(bugnumber)
else: else:
return expectedFailure_impl return expectedFailure_impl

View File

@ -36,7 +36,6 @@ import sys
import tempfile import tempfile
# Third-party modules # Third-party modules
import six
import unittest2 import unittest2
# LLDB Modules # LLDB Modules

View File

@ -4,9 +4,6 @@ from __future__ import absolute_import
import os import os
import sys import sys
# Third-party modules
import six
# LLDB Modules # LLDB Modules
import lldb import lldb
from .lldbtest import * from .lldbtest import *
@ -72,7 +69,7 @@ class PExpectTest(TestBase):
self.assertNotIn('\n', cmd) self.assertNotIn('\n', cmd)
# If 'substrs' is a string then this code would just check that every # If 'substrs' is a string then this code would just check that every
# character of the string is in the output. # character of the string is in the output.
assert not isinstance(substrs, six.string_types), \ assert not isinstance(substrs, str), \
"substrs must be a collection of strings" "substrs must be a collection of strings"
self.child.sendline(cmd) self.child.sendline(cmd)

View File

@ -5,9 +5,6 @@ from __future__ import absolute_import
# System modules # System modules
import itertools import itertools
# Third-party modules
import six
# LLDB modules # LLDB modules
import lldb import lldb
@ -39,10 +36,10 @@ __name_lookup = {
def translate(values): def translate(values):
if isinstance(values, six.integer_types): if isinstance(values, int):
# This is a value from the platform enumeration, translate it. # This is a value from the platform enumeration, translate it.
return __name_lookup[values] return __name_lookup[values]
elif isinstance(values, six.string_types): elif isinstance(values, str):
# This is a raw string, return it. # This is a raw string, return it.
return [values] return [values]
elif hasattr(values, "__iter__"): elif hasattr(values, "__iter__"):

View File

@ -9,10 +9,7 @@ import re
import subprocess import subprocess
import sys import sys
import os import os
from urllib.parse import urlparse
# Third-party modules
import six
from six.moves.urllib import parse as urlparse
# LLDB modules # LLDB modules
from . import configuration from . import configuration
@ -62,7 +59,7 @@ def android_device_api():
if not hasattr(android_device_api, 'result'): if not hasattr(android_device_api, 'result'):
assert configuration.lldb_platform_url is not None assert configuration.lldb_platform_url is not None
device_id = None device_id = None
parsed_url = urlparse.urlparse(configuration.lldb_platform_url) parsed_url = urlparse(configuration.lldb_platform_url)
host_name = parsed_url.netloc.split(":")[0] host_name = parsed_url.netloc.split(":")[0]
if host_name != 'localhost': if host_name != 'localhost':
device_id = host_name device_id = host_name

View File

@ -48,9 +48,6 @@ import traceback
# Third-party modules # Third-party modules
import unittest2 import unittest2
from six import add_metaclass
from six import StringIO as SixStringIO
import six
# LLDB modules # LLDB modules
import lldb import lldb
@ -320,7 +317,7 @@ class ValueCheck:
child_error = "Checking child with index " + str(i) + ":\n" + error_msg child_error = "Checking child with index " + str(i) + ":\n" + error_msg
expected_child.check_value(test_base, actual_child, child_error) expected_child.check_value(test_base, actual_child, child_error)
class recording(SixStringIO): class recording(io.StringIO):
""" """
A nice little context manager for recording the debugger interactions into A nice little context manager for recording the debugger interactions into
our session object. If trace flag is ON, it also emits the interactions our session object. If trace flag is ON, it also emits the interactions
@ -328,8 +325,8 @@ class recording(SixStringIO):
""" """
def __init__(self, test, trace): def __init__(self, test, trace):
"""Create a SixStringIO instance; record the session obj and trace flag.""" """Create a io.StringIO instance; record the session obj and trace flag."""
SixStringIO.__init__(self) io.StringIO.__init__(self)
# The test might not have undergone the 'setUp(self)' phase yet, so that # The test might not have undergone the 'setUp(self)' phase yet, so that
# the attribute 'session' might not even exist yet. # the attribute 'session' might not even exist yet.
self.session = getattr(test, "session", None) if test else None self.session = getattr(test, "session", None) if test else None
@ -338,7 +335,7 @@ class recording(SixStringIO):
def __enter__(self): def __enter__(self):
""" """
Context management protocol on entry to the body of the with statement. Context management protocol on entry to the body of the with statement.
Just return the SixStringIO object. Just return the io.StringIO object.
""" """
return self return self
@ -346,7 +343,7 @@ class recording(SixStringIO):
""" """
Context management protocol on exit from the body of the with statement. Context management protocol on exit from the body of the with statement.
If trace is ON, it emits the recordings into stderr. Always add the If trace is ON, it emits the recordings into stderr. Always add the
recordings to our session object. And close the SixStringIO object, too. recordings to our session object. And close the io.StringIO object, too.
""" """
if self.trace: if self.trace:
print(self.getvalue(), file=sys.stderr) print(self.getvalue(), file=sys.stderr)
@ -355,8 +352,7 @@ class recording(SixStringIO):
self.close() self.close()
@add_metaclass(abc.ABCMeta) class _BaseProcess(object, metaclass=abc.ABCMeta):
class _BaseProcess(object):
@abc.abstractproperty @abc.abstractproperty
def pid(self): def pid(self):
@ -945,7 +941,7 @@ class Base(unittest2.TestCase):
Hooks are executed in a first come first serve manner. Hooks are executed in a first come first serve manner.
""" """
if six.callable(hook): if callable(hook):
with recording(self, traceAlways) as sbuf: with recording(self, traceAlways) as sbuf:
print( print(
"Adding tearDown hook:", "Adding tearDown hook:",
@ -1691,8 +1687,7 @@ class LLDBTestCaseFactory(type):
# methods when a new class is loaded # methods when a new class is loaded
@add_metaclass(LLDBTestCaseFactory) class TestBase(Base, metaclass=LLDBTestCaseFactory):
class TestBase(Base):
""" """
This abstract base class is meant to be subclassed. It provides default This abstract base class is meant to be subclassed. It provides default
implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(), implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
@ -2230,7 +2225,7 @@ FileCheck output:
def expect( def expect(
self, self,
str, string,
msg=None, msg=None,
patterns=None, patterns=None,
startstr=None, startstr=None,
@ -2264,9 +2259,9 @@ FileCheck output:
client is expecting the output of the command not to match the golden client is expecting the output of the command not to match the golden
input. input.
Finally, the required argument 'str' represents the lldb command to be Finally, the required argument 'string' represents the lldb command to be
sent to the command interpreter. In case the keyword argument 'exe' is sent to the command interpreter. In case the keyword argument 'exe' is
set to False, the 'str' is treated as a string to be matched/not-matched set to False, the 'string' is treated as a string to be matched/not-matched
against the golden input. against the golden input.
""" """
# Catch cases where `expect` has been miscalled. Specifically, prevent # Catch cases where `expect` has been miscalled. Specifically, prevent
@ -2280,9 +2275,9 @@ FileCheck output:
assert False, "expect() missing a matcher argument" assert False, "expect() missing a matcher argument"
# Check `patterns` and `substrs` are not accidentally given as strings. # Check `patterns` and `substrs` are not accidentally given as strings.
assert not isinstance(patterns, six.string_types), \ assert not isinstance(patterns, str), \
"patterns must be a collection of strings" "patterns must be a collection of strings"
assert not isinstance(substrs, six.string_types), \ assert not isinstance(substrs, str), \
"substrs must be a collection of strings" "substrs must be a collection of strings"
trace = (True if traceAlways else trace) trace = (True if traceAlways else trace)
@ -2292,7 +2287,7 @@ FileCheck output:
# Pass the assert message along since it provides more semantic # Pass the assert message along since it provides more semantic
# info. # info.
self.runCmd( self.runCmd(
str, string,
msg=msg, msg=msg,
trace=( trace=(
True if trace else False), True if trace else False),
@ -2305,13 +2300,13 @@ FileCheck output:
# If error is True, the API client expects the command to fail! # If error is True, the API client expects the command to fail!
if error: if error:
self.assertFalse(self.res.Succeeded(), self.assertFalse(self.res.Succeeded(),
"Command '" + str + "' is expected to fail!") "Command '" + string + "' is expected to fail!")
else: else:
# No execution required, just compare str against the golden input. # No execution required, just compare string against the golden input.
if isinstance(str, lldb.SBCommandReturnObject): if isinstance(string, lldb.SBCommandReturnObject):
output = str.GetOutput() output = string.GetOutput()
else: else:
output = str output = string
with recording(self, trace) as sbuf: with recording(self, trace) as sbuf:
print("looking at:", output, file=sbuf) print("looking at:", output, file=sbuf)
@ -2322,7 +2317,7 @@ FileCheck output:
# To be used as assert fail message and/or trace content # To be used as assert fail message and/or trace content
log_lines = [ log_lines = [
"{}:".format("Ran command" if exe else "Checking string"), "{}:".format("Ran command" if exe else "Checking string"),
"\"{}\"".format(str), "\"{}\"".format(string),
# Space out command and output # Space out command and output
"", "",
] ]

View File

@ -9,16 +9,13 @@ from __future__ import absolute_import
# System modules # System modules
import errno import errno
import io
import os import os
import re import re
import sys import sys
import subprocess import subprocess
from typing import Dict from typing import Dict
# Third-party modules
from six import StringIO as SixStringIO
import six
# LLDB modules # LLDB modules
import lldb import lldb
from . import lldbtest_config from . import lldbtest_config
@ -111,7 +108,7 @@ def disassemble(target, function_or_symbol):
It returns the disassembly content in a string object. It returns the disassembly content in a string object.
""" """
buf = SixStringIO() buf = io.StringIO()
insts = function_or_symbol.GetInstructions(target) insts = function_or_symbol.GetInstructions(target)
for i in insts: for i in insts:
print(i, file=buf) print(i, file=buf)
@ -1080,7 +1077,7 @@ def get_stack_frames(thread):
def print_stacktrace(thread, string_buffer=False): def print_stacktrace(thread, string_buffer=False):
"""Prints a simple stack trace of this thread.""" """Prints a simple stack trace of this thread."""
output = SixStringIO() if string_buffer else sys.stdout output = io.StringIO() if string_buffer else sys.stdout
target = thread.GetProcess().GetTarget() target = thread.GetProcess().GetTarget()
depth = thread.GetNumFrames() depth = thread.GetNumFrames()
@ -1142,7 +1139,7 @@ def print_stacktrace(thread, string_buffer=False):
def print_stacktraces(process, string_buffer=False): def print_stacktraces(process, string_buffer=False):
"""Prints the stack traces of all the threads.""" """Prints the stack traces of all the threads."""
output = SixStringIO() if string_buffer else sys.stdout output = io.StringIO() if string_buffer else sys.stdout
print("Stack traces for " + str(process), file=output) print("Stack traces for " + str(process), file=output)
@ -1258,7 +1255,7 @@ def get_args_as_string(frame, showFuncName=True):
def print_registers(frame, string_buffer=False): def print_registers(frame, string_buffer=False):
"""Prints all the register sets of the frame.""" """Prints all the register sets of the frame."""
output = SixStringIO() if string_buffer else sys.stdout output = io.StringIO() if string_buffer else sys.stdout
print("Register sets for " + str(frame), file=output) print("Register sets for " + str(frame), file=output)
@ -1344,7 +1341,7 @@ class BasicFormatter(object):
def format(self, value, buffer=None, indent=0): def format(self, value, buffer=None, indent=0):
if not buffer: if not buffer:
output = SixStringIO() output = io.StringIO()
else: else:
output = buffer output = buffer
# If there is a summary, it suffices. # If there is a summary, it suffices.
@ -1374,7 +1371,7 @@ class ChildVisitingFormatter(BasicFormatter):
def format(self, value, buffer=None): def format(self, value, buffer=None):
if not buffer: if not buffer:
output = SixStringIO() output = io.StringIO()
else: else:
output = buffer output = buffer
@ -1401,7 +1398,7 @@ class RecursiveDecentFormatter(BasicFormatter):
def format(self, value, buffer=None): def format(self, value, buffer=None):
if not buffer: if not buffer:
output = SixStringIO() output = io.StringIO()
else: else:
output = buffer output = buffer
@ -1511,7 +1508,7 @@ class PrintableRegex(object):
def skip_if_callable(test, mycallable, reason): def skip_if_callable(test, mycallable, reason):
if six.callable(mycallable): if callable(mycallable):
if mycallable(test): if mycallable(test):
test.skipTest(reason) test.skipTest(reason)
return True return True

View File

@ -59,8 +59,7 @@ class GdbRemoteTestCaseFactory(type):
return super(GdbRemoteTestCaseFactory, cls).__new__( return super(GdbRemoteTestCaseFactory, cls).__new__(
cls, name, bases, newattrs) cls, name, bases, newattrs)
@add_metaclass(GdbRemoteTestCaseFactory) class GdbRemoteTestCaseBase(Base, metaclass=GdbRemoteTestCaseFactory):
class GdbRemoteTestCaseBase(Base):
# Default time out in seconds. The timeout is increased tenfold under Asan. # Default time out in seconds. The timeout is increased tenfold under Asan.
DEFAULT_TIMEOUT = 20 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) DEFAULT_TIMEOUT = 20 * (10 if ('ASAN_OPTIONS' in os.environ) else 1)

View File

@ -8,7 +8,6 @@ import os
import os.path import os.path
import platform import platform
import re import re
import six
import socket import socket
import subprocess import subprocess
from lldbsuite.support import seven from lldbsuite.support import seven
@ -803,7 +802,7 @@ def process_is_running(pid, unknown_value=True):
If we don't know how to check running process ids on the given OS: If we don't know how to check running process ids on the given OS:
return the value provided by the unknown_value arg. return the value provided by the unknown_value arg.
""" """
if not isinstance(pid, six.integer_types): if not isinstance(pid, int):
raise Exception( raise Exception(
"pid must be an integral type (actual type: %s)" % str( "pid must be an integral type (actual type: %s)" % str(
type(pid))) type(pid)))
@ -878,7 +877,7 @@ class Server(object):
@staticmethod @staticmethod
def _checksum(packet): def _checksum(packet):
checksum = 0 checksum = 0
for c in six.iterbytes(packet): for c in iter(packet):
checksum += c checksum += c
return checksum % 256 return checksum % 256

View File

@ -429,7 +429,7 @@ ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
// Reloading modules requires a different syntax in Python 2 and Python 3. // Reloading modules requires a different syntax in Python 2 and Python 3.
// This provides a consistent syntax no matter what version of Python. // This provides a consistent syntax no matter what version of Python.
run_string.Clear(); run_string.Clear();
run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')", run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
m_dictionary_name.c_str()); m_dictionary_name.c_str());
PyRun_SimpleString(run_string.GetData()); PyRun_SimpleString(run_string.GetData());

View File

@ -7,8 +7,6 @@ from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil from lldbsuite.test import lldbutil
import six
class ListenToModuleLoadedEvents (TestBase): class ListenToModuleLoadedEvents (TestBase):
NO_DEBUG_INFO_TESTCASE = True NO_DEBUG_INFO_TESTCASE = True

View File

@ -1,7 +1,3 @@
import six
def command(debugger, command, result, internal_dict): def command(debugger, command, result, internal_dict):
result.PutCString(six.u("hello world A")) result.PutCString("hello world A")
return None return None

View File

@ -1,7 +1,3 @@
import six
def command(debugger, command, result, internal_dict): def command(debugger, command, result, internal_dict):
result.PutCString(six.u("hello world B")) result.PutCString("hello world B")
return None return None

View File

@ -11,8 +11,6 @@ from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil from lldbsuite.test import lldbutil
import six
class ProcessLaunchTestCase(TestBase): class ProcessLaunchTestCase(TestBase):
NO_DEBUG_INFO_TESTCASE = True NO_DEBUG_INFO_TESTCASE = True

View File

@ -3,7 +3,6 @@ from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *
from lldbsuite.test.gdbclientutils import * from lldbsuite.test.gdbclientutils import *
from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase
from lldbsuite.support import seven
class MyResponder(MockGDBServerResponder): class MyResponder(MockGDBServerResponder):
""" """

View File

@ -2,8 +2,6 @@
Test basics of Minidump debugging. Test basics of Minidump debugging.
""" """
from six import iteritems
import shutil import shutil
import lldb import lldb
@ -327,7 +325,7 @@ class MiniDumpNewTestCase(TestBase):
expected_stack = {1: 'bar', 2: 'foo', 3: '_start'} expected_stack = {1: 'bar', 2: 'foo', 3: '_start'}
self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack)) self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack))
for index, name in iteritems(expected_stack): for index, name in expected_stack.items():
frame = thread.GetFrameAtIndex(index) frame = thread.GetFrameAtIndex(index)
self.assertTrue(frame.IsValid()) self.assertTrue(frame.IsValid())
function_name = frame.GetFunctionName() function_name = frame.GetFunctionName()

View File

@ -2,9 +2,6 @@
Test basics of Minidump debugging. Test basics of Minidump debugging.
""" """
from six import iteritems
import lldb import lldb
import os import os
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *

View File

@ -2,9 +2,6 @@
Test basics of mini dump debugging. Test basics of mini dump debugging.
""" """
from six import iteritems
import lldb import lldb
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *
@ -130,7 +127,7 @@ class MiniDumpTestCase(TestBase):
expected_stack = {0: 'bar', 1: 'foo', 2: 'main'} expected_stack = {0: 'bar', 1: 'foo', 2: 'main'}
self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack)) self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack))
for index, name in iteritems(expected_stack): for index, name in expected_stack.items():
frame = thread.GetFrameAtIndex(index) frame = thread.GetFrameAtIndex(index)
self.assertTrue(frame.IsValid()) self.assertTrue(frame.IsValid())
function_name = frame.GetFunctionName() function_name = frame.GetFunctionName()

View File

@ -7,9 +7,6 @@ end up with a dump of the WoW64 layer. In that case, LLDB must do extra work to
get the 32-bit register contexts. get the 32-bit register contexts.
""" """
from six import iteritems
import lldb import lldb
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *

View File

@ -5,6 +5,7 @@ And other SBFrame API tests.
from __future__ import print_function from __future__ import print_function
import io
import lldb import lldb
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *
@ -42,8 +43,7 @@ class FrameAPITestCase(TestBase):
# depth of 3 of the 'c' leaf function. # depth of 3 of the 'c' leaf function.
callsOfA = 0 callsOfA = 0
from six import StringIO as SixStringIO session = io.StringIO()
session = SixStringIO()
while process.GetState() == lldb.eStateStopped: while process.GetState() == lldb.eStateStopped:
thread = lldbutil.get_stopped_thread( thread = lldbutil.get_stopped_thread(
process, lldb.eStopReasonBreakpoint) process, lldb.eStopReasonBreakpoint)

View File

@ -6,7 +6,7 @@ from __future__ import print_function
import lldb import lldb
import six import io
import sys import sys
from lldbsuite.test.decorators import * from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *
@ -57,8 +57,8 @@ class TestSTTYBeforeAndAfter(TestBase):
child.expect(expect_prompt) child.expect(expect_prompt)
# Turn on loggings for input/output to/from the child. # Turn on loggings for input/output to/from the child.
child.logfile_send = child_send1 = six.StringIO() child.logfile_send = child_send1 = io.StringIO()
child.logfile_read = child_read1 = six.StringIO() child.logfile_read = child_read1 = io.StringIO()
child.sendline('stty -a') child.sendline('stty -a')
child.expect(expect_prompt) child.expect(expect_prompt)
@ -75,8 +75,8 @@ class TestSTTYBeforeAndAfter(TestBase):
child.sendline('quit') child.sendline('quit')
child.expect(expect_prompt) child.expect(expect_prompt)
child.logfile_send = child_send2 = six.StringIO() child.logfile_send = child_send2 = io.StringIO()
child.logfile_read = child_read2 = six.StringIO() child.logfile_read = child_read2 = io.StringIO()
child.sendline('stty -a') child.sendline('stty -a')
child.expect(expect_prompt) child.expect(expect_prompt)

View File

@ -2,9 +2,10 @@
Test TestBase test functions. Test TestBase test functions.
""" """
import io
from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbtest import *
from lldbsuite.test_event import build_exception from lldbsuite.test_event import build_exception
import six
class TestBuildMethod(Base): class TestBuildMethod(Base):
@ -15,9 +16,9 @@ class TestBuildMethod(Base):
# override the parent trace method # override the parent trace method
def trace(self, *args, **kwargs): def trace(self, *args, **kwargs):
io = six.StringIO() buf = io.StringIO()
print(*args, file=io, **kwargs) print(*args, file=buf, **kwargs)
self._traces.append(io.getvalue()) self._traces.append(buf.getvalue())
def test_build_fails_helpfully(self): def test_build_fails_helpfully(self):
try: try:

View File

@ -3,7 +3,6 @@
from __future__ import print_function from __future__ import print_function
import use_lldb_suite import use_lldb_suite
import six
import sys import sys
import time import time
@ -21,17 +20,17 @@ class ProgressBar(object):
format Format format Format
incremental incremental
""" """
light_block = six.unichr(0x2591).encode("utf-8") light_block = chr(0x2591).encode("utf-8")
solid_block = six.unichr(0x2588).encode("utf-8") solid_block = chr(0x2588).encode("utf-8")
solid_right_arrow = six.unichr(0x25BA).encode("utf-8") solid_right_arrow = chr(0x25BA).encode("utf-8")
def __init__(self, def __init__(self,
start=0, start=0,
end=10, end=10,
width=12, width=12,
fill=six.unichr(0x25C9).encode("utf-8"), fill=chr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"), blank=chr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"), marker=chr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%', format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True): incremental=True):
super(ProgressBar, self).__init__() super(ProgressBar, self).__init__()
@ -91,9 +90,9 @@ class AnimatedProgressBar(ProgressBar):
start=0, start=0,
end=10, end=10,
width=12, width=12,
fill=six.unichr(0x25C9).encode("utf-8"), fill=chr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"), blank=chr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"), marker=chr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%', format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True, incremental=True,
stdout=sys.stdout): stdout=sys.stdout):
@ -129,9 +128,9 @@ class ProgressWithEvents(AnimatedProgressBar):
start=0, start=0,
end=10, end=10,
width=12, width=12,
fill=six.unichr(0x25C9).encode("utf-8"), fill=chr(0x25C9).encode("utf-8"),
blank=six.unichr(0x25CC).encode("utf-8"), blank=chr(0x25CC).encode("utf-8"),
marker=six.unichr(0x25CE).encode("utf-8"), marker=chr(0x25CE).encode("utf-8"),
format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%', format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%',
incremental=True, incremental=True,
stdout=sys.stdout): stdout=sys.stdout):

View File

@ -7,8 +7,6 @@ import re
import unittest import unittest
import warnings import warnings
import six
from unittest2 import result from unittest2 import result
from unittest2.util import ( from unittest2.util import (
safe_repr, safe_str, strclass, safe_repr, safe_str, strclass,
@ -153,7 +151,7 @@ class _AssertRaisesContext(object):
return True return True
expected_regexp = self.expected_regexp expected_regexp = self.expected_regexp
if isinstance(expected_regexp, six.string_types): if isinstance(expected_regexp, str):
expected_regexp = re.compile(expected_regexp) expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)): if not expected_regexp.search(str(exc_value)):
raise self.failureException( raise self.failureException(
@ -173,7 +171,7 @@ class _TypeEqualityDict(object):
def __getitem__(self, key): def __getitem__(self, key):
value = self._store[key] value = self._store[key]
if isinstance(value, six.string_types): if isinstance(value, str):
return getattr(self.testcase, value) return getattr(self.testcase, value)
return value return value
@ -251,9 +249,6 @@ class TestCase(unittest.TestCase):
self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(set, 'assertSetEqual')
self.addTypeEqualityFunc(frozenset, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
if six.PY2:
self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
else:
self.addTypeEqualityFunc(str, 'assertMultiLineEqual') self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
def addTypeEqualityFunc(self, typeobj, function): def addTypeEqualityFunc(self, typeobj, function):
@ -993,9 +988,9 @@ class TestCase(unittest.TestCase):
def assertMultiLineEqual(self, first, second, msg=None): def assertMultiLineEqual(self, first, second, msg=None):
"""Assert that two multi-line strings are equal.""" """Assert that two multi-line strings are equal."""
self.assert_(isinstance(first, six.string_types), ( self.assert_(isinstance(first, str), (
'First argument is not a string')) 'First argument is not a string'))
self.assert_(isinstance(second, six.string_types), ( self.assert_(isinstance(second, str), (
'Second argument is not a string')) 'Second argument is not a string'))
if first != second: if first != second:
@ -1076,7 +1071,7 @@ class TestCase(unittest.TestCase):
try: try:
callable_obj(*args, **kwargs) callable_obj(*args, **kwargs)
except expected_exception as exc_value: except expected_exception as exc_value:
if isinstance(expected_regexp, six.string_types): if isinstance(expected_regexp, str):
expected_regexp = re.compile(expected_regexp) expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)): if not expected_regexp.search(str(exc_value)):
raise self.failureException( raise self.failureException(
@ -1091,7 +1086,7 @@ class TestCase(unittest.TestCase):
def assertRegexpMatches(self, text, expected_regexp, msg=None): def assertRegexpMatches(self, text, expected_regexp, msg=None):
"""Fail the test unless the text matches the regular expression.""" """Fail the test unless the text matches the regular expression."""
if isinstance(expected_regexp, six.string_types): if isinstance(expected_regexp, str):
expected_regexp = re.compile(expected_regexp) expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(text): if not expected_regexp.search(text):
msg = msg or "Regexp didn't match" msg = msg or "Regexp didn't match"
@ -1101,7 +1096,7 @@ class TestCase(unittest.TestCase):
def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
"""Fail the test if the text matches the regular expression.""" """Fail the test if the text matches the regular expression."""
if isinstance(unexpected_regexp, six.string_types): if isinstance(unexpected_regexp, str):
unexpected_regexp = re.compile(unexpected_regexp) unexpected_regexp = re.compile(unexpected_regexp)
match = unexpected_regexp.search(text) match = unexpected_regexp.search(text)
if match: if match:

View File

@ -3,7 +3,6 @@
import sys import sys
import os import os
import types import types
import six
from unittest2 import loader, runner from unittest2 import loader, runner
try: try:
@ -77,7 +76,7 @@ class TestProgram(object):
argv=None, testRunner=None, argv=None, testRunner=None,
testLoader=loader.defaultTestLoader, exit=True, testLoader=loader.defaultTestLoader, exit=True,
verbosity=1, failfast=None, catchbreak=None, buffer=None): verbosity=1, failfast=None, catchbreak=None, buffer=None):
if isinstance(module, six.string_types): if isinstance(module, str):
self.module = __import__(module) self.module = __import__(module)
for part in module.split('.')[1:]: for part in module.split('.')[1:]:
self.module = getattr(self.module, part) self.module = getattr(self.module, part)

View File

@ -2,12 +2,11 @@
import use_lldb_suite import use_lldb_suite
import io
import sys import sys
import traceback import traceback
import unittest import unittest
from six import StringIO as SixStringIO
from unittest2 import util from unittest2 import util
from unittest2.compatibility import wraps from unittest2.compatibility import wraps
@ -65,8 +64,8 @@ class TestResult(unittest.TestResult):
self._mirrorOutput = False self._mirrorOutput = False
if self.buffer: if self.buffer:
if self._stderr_buffer is None: if self._stderr_buffer is None:
self._stderr_buffer = SixStringIO() self._stderr_buffer = io.StringIO()
self._stdout_buffer = SixStringIO() self._stdout_buffer = io.StringIO()
sys.stdout = self._stdout_buffer sys.stdout = self._stdout_buffer
sys.stderr = self._stderr_buffer sys.stderr = self._stderr_buffer

View File

@ -3,7 +3,6 @@
import sys import sys
import unittest import unittest
from unittest2 import case, util from unittest2 import case, util
import six
__unittest = True __unittest = True
@ -50,7 +49,7 @@ class BaseTestSuite(unittest.TestSuite):
self._tests.append(test) self._tests.append(test)
def addTests(self, tests): def addTests(self, tests):
if isinstance(tests, six.string_types): if isinstance(tests, str):
raise TypeError("tests must be an iterable of tests, not a string") raise TypeError("tests must be an iterable of tests, not a string")
for test in tests: for test in tests:
self.addTest(test) self.addTest(test)

View File

@ -1,7 +1,6 @@
import difflib import difflib
import pprint import pprint
import re import re
import six
from copy import deepcopy from copy import deepcopy
@ -543,7 +542,7 @@ class Test_TestCase(unittest2.TestCase, EqualityMixin, HashingMixin):
def runTest(self): def runTest(self):
pass pass
self.assertIsInstance(Foo().id(), six.string_types) self.assertIsInstance(Foo().id(), str)
# "If result is omitted or None, a temporary result object is created # "If result is omitted or None, a temporary result object is created
# and used, but is not made available to the caller. As TestCase owns the # and used, but is not made available to the caller. As TestCase owns the

View File

@ -1,5 +1,4 @@
import unittest2 import unittest2
import six
from unittest2.test.support import LoggingResult from unittest2.test.support import LoggingResult
@ -125,7 +124,7 @@ class Test_FunctionTestCase(unittest2.TestCase):
def test_id(self): def test_id(self):
test = unittest2.FunctionTestCase(lambda: None) test = unittest2.FunctionTestCase(lambda: None)
self.assertIsInstance(test.id(), six.string_types) self.assertIsInstance(test.id(), str)
# "Returns a one-line description of the test, or None if no description # "Returns a one-line description of the test, or None if no description
# has been provided. The default implementation of this method returns # has been provided. The default implementation of this method returns