Exemple #1
0
 def key_to_str(self, key, fmt=None):
     if fmt is not None:
         if fmt.get('hex', False):
             safe_repr = SafeRepr()
             safe_repr.convert_to_hex = True
             return safe_repr(key)
     return '%r' % (key,)
def test_py3_str_slicing(params, use_str):
    # Note: much simpler in python because __repr__ is required to return str
    # (which is actually unicode).
    safe_repr = SafeRepr()
    safe_repr.locale_preferred_encoding = 'ascii'
    safe_repr.sys_stdout_encoding = params.get('sys_stdout_encoding', 'ascii')

    safe_repr.maxother_outer = params['maxother_outer']

    if not use_str:

        class MyObj(object):

            def __repr__(self):
                return params['input']

        safe_repr_input = MyObj()
    else:
        safe_repr_input = params['input']
    expected_output = params['output']
    computed = safe_repr(safe_repr_input)
    expected = repr(expected_output)
    if use_str:
        expected = repr(expected)
    assert repr(computed) == expected

    # Check that we can json-encode the return.
    assert json.dumps(computed)
def test_no_repr():

    class MyBytes(object):

        def __init__(self, contents):
            self.contents = contents
            self.errored = None

        def __iter__(self):
            return iter(self.contents)

        def decode(self, encoding):
            self.errored = 'decode called'
            raise RuntimeError('Should not be called.')

        def __repr__(self):
            self.errored = '__repr__ called'
            raise RuntimeError('Should not be called.')

        def __getitem__(self, *args):
            return self.contents.__getitem__(*args)

        def __len__(self):
            return len(self.contents)

    safe_repr = SafeRepr()
    safe_repr.string_types = (MyBytes,)
    safe_repr.bytes = MyBytes
    obj = b'f' * (safe_repr.maxstring_outer * 10)
    my_bytes = MyBytes(obj)
    raw_value_repr = safe_repr(my_bytes)
    assert not my_bytes.errored
Exemple #4
0
 def key_to_str(self, key, fmt=None):
     if fmt is not None:
         if fmt.get('hex', False):
             safe_repr = SafeRepr()
             safe_repr.convert_to_hex = True
             return safe_repr(key)
     return '%r' % (key,)
Exemple #5
0
    def get_var_data(self, fmt=None, **safe_repr_custom_attrs):
        '''
        :param dict fmt:
            Format expected by the DAP (keys: 'hex': bool, 'rawString': bool)
        '''
        timer = Timer()
        safe_repr = SafeRepr()
        if fmt is not None:
            safe_repr.convert_to_hex = fmt.get('hex', False)
            safe_repr.raw_value = fmt.get('rawString', False)
        for key, val in safe_repr_custom_attrs.items():
            setattr(safe_repr, key, val)

        type_name, _type_qualifier, _is_exception_on_eval, resolver, value = get_variable_details(
            self.value, to_string=safe_repr)

        is_raw_string = type_name in ('str', 'bytes', 'bytearray')

        attributes = []

        if is_raw_string:
            attributes.append('rawString')

        name = self.name

        if self._is_return_value:
            attributes.append('readOnly')
            name = '(return) %s' % (name, )

        elif name in (TOO_LARGE_ATTR, GENERATED_LEN_ATTR_NAME):
            attributes.append('readOnly')

        try:
            if self.value.__class__ == DAPGrouper:
                type_name = ''
        except:
            pass  # Ignore errors accessing __class__.

        var_data = {
            'name': name,
            'value': value,
            'type': type_name,
        }

        if self.evaluate_name is not None:
            var_data['evaluateName'] = self.evaluate_name

        if resolver is not None:  # I.e.: it's a container
            var_data['variablesReference'] = self.get_variable_reference()
        else:
            var_data[
                'variablesReference'] = 0  # It's mandatory (although if == 0 it doesn't have children).

        if len(attributes) > 0:
            var_data['presentationHint'] = {'attributes': attributes}

        timer.report_if_compute_repr_attr_slow('', name, type_name)
        return var_data
def test_raw():
    safe_repr = SafeRepr()
    safe_repr.raw_value = True
    obj = b'\xed\xbd\xbf\xff\xfe\xfa\xfd'
    raw_value_repr = safe_repr(obj)
    assert isinstance(raw_value_repr, str)  # bytes on py2, str on py3
    if IS_PY2:
        assert raw_value_repr == obj.decode('latin1').encode('utf-8')
    else:
        assert raw_value_repr == obj.decode('latin1')
Exemple #7
0
def test_raw():
    safe_repr = SafeRepr()
    safe_repr.raw_value = True
    obj = b'\xed\xbd\xbf\xff\xfe\xfa\xfd'
    raw_value_repr = safe_repr(obj)
    assert isinstance(raw_value_repr, str)  # bytes on py2, str on py3
    if IS_PY2:
        assert raw_value_repr == obj.decode('latin1').encode('utf-8')
    else:
        assert raw_value_repr == obj.decode('latin1')
def test_py2_bytes_slicing(params, use_str):
    safe_repr = SafeRepr()
    safe_repr.locale_preferred_encoding = 'ascii'
    safe_repr.sys_stdout_encoding = params.get('sys_stdout_encoding', 'ascii')

    safe_repr.maxother_outer = params['maxother_outer']

    # This is the encoding that we expect back (because json needs to be able to encode it
    # later on, so, the return from SafeRepr must always be utf-8 regardless of the input).
    encoding = 'utf-8'

    if not use_str:

        class MyObj(object):

            def __repr__(self):
                ret = params['input']
                if isinstance(ret, unicode):
                    ret = ret.encode(encoding)
                return ret

        safe_repr_input = MyObj()
    else:
        safe_repr_input = params['input']

    computed = safe_repr(safe_repr_input)

    if use_str:
        expected_output = params['output_str']
    else:
        expected_output = params['output']

    expect_unicode = False
    if isinstance(expected_output, unicode):
        expect_unicode = True
    if isinstance(expected_output, tuple) and isinstance(expected_output[0], unicode):
        expect_unicode = True

    if expect_unicode:
        computed = computed.decode(encoding)
        if isinstance(expected_output, tuple):
            assert computed in expected_output
        else:
            assert computed == expected_output
    else:
        if isinstance(expected_output, tuple):
            assert computed in expected_output
        else:
            assert computed == expected_output

    # Check that we can json-encode the return.
    assert json.dumps(computed)
Exemple #9
0
    def get_var_data(self, fmt=None):
        '''
        :param dict fmt:
            Format expected by the DAP (keys: 'hex': bool, 'rawString': bool)
        '''
        safe_repr = SafeRepr()
        if fmt is not None:
            safe_repr.convert_to_hex = fmt.get('hex', False)
            safe_repr.raw_value = fmt.get('rawString', False)

        type_name, _type_qualifier, _is_exception_on_eval, resolver, value = get_variable_details(
            self.value, to_string=safe_repr)

        is_raw_string = type_name in ('str', 'unicode', 'bytes', 'bytearray')

        attributes = []

        if is_raw_string:
            attributes.append('rawString')

        name = self.name

        if self._is_return_value:
            attributes.append('readOnly')
            name = '(return) %s' % (name, )

        elif name in (TOO_LARGE_ATTR, '__len__'):
            attributes.append('readOnly')

        var_data = {
            'name': name,
            'value': value,
            'type': type_name,
        }

        if self.evaluate_name is not None:
            var_data['evaluateName'] = self.evaluate_name

        if resolver is not None:  # I.e.: it's a container
            var_data['variablesReference'] = self.get_variable_reference()
        else:
            var_data[
                'variablesReference'] = 0  # It's mandatory (although if == 0 it doesn't have children).

        if len(attributes) > 0:
            var_data['presentationHint'] = {'attributes': attributes}

        return var_data
    def get_var_data(self, fmt=None):
        '''
        :param dict fmt:
            Format expected by the DAP (keys: 'hex': bool, 'rawString': bool)
        '''
        safe_repr = SafeRepr()
        if fmt is not None:
            safe_repr.convert_to_hex = fmt.get('hex', False)
            safe_repr.raw_value = fmt.get('rawString', False)

        type_name, _type_qualifier, _is_exception_on_eval, resolver, value = get_variable_details(
            self.value, to_string=safe_repr)

        is_raw_string = type_name in ('str', 'unicode', 'bytes', 'bytearray')

        attributes = []

        if is_raw_string:
            attributes.append('rawString')

        name = self.name

        if self._is_return_value:
            attributes.append('readOnly')
            name = '(return) %s' % (name,)

        elif name in (TOO_LARGE_ATTR, '__len__'):
            attributes.append('readOnly')

        var_data = {
            'name': name,
            'value': value,
            'type': type_name,
        }

        if self.evaluate_name is not None:
            var_data['evaluateName'] = self.evaluate_name

        if resolver is not None:  # I.e.: it's a container
            var_data['variablesReference'] = self.get_variable_reference()
        else:
            var_data['variablesReference'] = 0  # It's mandatory (although if == 0 it doesn't have children).

        if len(attributes) > 0:
            var_data['presentationHint'] = {'attributes': attributes}

        return var_data
def test_py3_str_slicing(params):
    # Note: much simpler in python because __repr__ is required to return str
    # (which is actually unicode).
    safe_repr = SafeRepr()
    safe_repr.locale_preferred_encoding = 'ascii'
    safe_repr.sys_stdout_encoding = params.get('sys_stdout_encoding', 'ascii')

    safe_repr.maxother_outer = params['maxother_outer']

    class MyObj(object):

        def __repr__(self):
            return params['input']

    expected_output = params['output']
    computed = safe_repr(MyObj())
    assert repr(computed) == repr(expected_output)

    # Check that we can json-encode the return.
    assert json.dumps(computed)
def test_py2_bytes_slicing(params):
    safe_repr = SafeRepr()
    safe_repr.locale_preferred_encoding = 'ascii'
    safe_repr.sys_stdout_encoding = params.get('sys_stdout_encoding', 'ascii')

    safe_repr.maxother_outer = params['maxother_outer']

    # This is the encoding that we expect back (because json needs to be able to encode it
    # later on, so, the return from SafeRepr must always be utf-8 regardless of the input).
    encoding = 'utf-8'

    class MyObj(object):

        def __repr__(self):
            ret = params['input']
            if isinstance(ret, unicode):
                ret = ret.encode(encoding)
            return ret

    expected_output = params['output']
    computed = safe_repr(MyObj())

    expect_unicode = False
    if isinstance(expected_output, unicode):
        expect_unicode = True
    if isinstance(expected_output, tuple) and isinstance(expected_output[0], unicode):
        expect_unicode = True

    if expect_unicode:
        computed = computed.decode(encoding)
        if isinstance(expected_output, tuple):
            assert computed in expected_output
        else:
            assert computed == expected_output
    else:
        assert repr(computed) == repr(expected_output)

    # Check that we can json-encode the return.
    assert json.dumps(computed)
Exemple #13
0
class SafeReprTestBase(object):

    saferepr = SafeRepr()

    def assert_saferepr(self, value, expected):
        safe = self.saferepr(value)

        if len(safe) != len(expected):
            raise AssertionError(
                'Expected:\n%s\nFound:\n%s\n Expected len: %s Found len: %s' %
                (
                    expected,
                    safe,
                    len(expected),
                    len(safe),
                ))
        assert safe == expected
        return safe

    def assert_unchanged(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr(value, expected)
        assert safe == actual

    def assert_shortened(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr(value, expected)
        assert safe != actual

    def assert_saferepr_regex(self, s, r):
        safe = self.saferepr(s)

        assert re.search(r, safe) is not None
        return safe

    def assert_unchanged_regex(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr_regex(value, expected)
        assert safe == actual

    def assert_shortened_regex(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr_regex(value, expected)
        assert safe != actual
Exemple #14
0
class SafeReprTestBase(object):

    saferepr = SafeRepr()

    def assert_saferepr(self, value, expected):
        safe = self.saferepr(value)

        assert safe == expected
        return safe

    def assert_unchanged(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr(value, expected)
        assert safe == actual

    def assert_shortened(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr(value, expected)
        assert safe != actual

    def assert_saferepr_regex(self, s, r):
        safe = self.saferepr(s)

        assert re.search(r, safe) is not None
        return safe

    def assert_unchanged_regex(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr_regex(value, expected)
        assert safe == actual

    def assert_shortened_regex(self, value, expected):
        actual = repr(value)

        safe = self.assert_saferepr_regex(value, expected)
        assert safe != actual