#!/usr/bin/env python
#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""This file contains unit tests for utils."""

import unittest

from vts.utils.python.library.elf import utils as elf_utils


# SLEB input data are generated by:
# $ llvm-mc -filetype=obj <<EOF | obj2yaml | grep 'Content:' | awk '{print $2}'
# > .sleb128 15
# > .sleb128 -15
# > EOF

# Test data: SLEB128 encoded byte stream
_SLEB_INPUT_DATA = bytes(bytearray.fromhex('0F71FF00800180800280807EFFFFFFFF'
                                           '0F8180808070FFFFFFFFFFFFFFFFFF00'
                                           '8180808080808080807F808080808080'
                                           '8080807F'))

# Reference output: [(value, length)]
_SLEB_OUTPUT_DATA = [
    (0xF, 1),
    (-0xF, 1),
    (0x7F, 2),
    (0x80, 2),
    (0x8000, 3),
    (-0x8000, 3),
    (0xFFFFFFFF, 5),
    (-0xFFFFFFFF, 5),
    (0x7FFFFFFFFFFFFFFF, 10),
    (-0x7FFFFFFFFFFFFFFF, 10),
    (-0x8000000000000000, 10),
]


class UtilsTest(unittest.TestCase):
    """Unit tests for vts.utils.python.library.elf.utils."""

    def testDecodeSLEB128(self):
        """Test if DecodeSLEB128 decodes correctly."""
        result = []
        cur = 0
        while cur < len(_SLEB_INPUT_DATA):
            val, num = elf_utils.DecodeSLEB128(_SLEB_INPUT_DATA, cur)
            cur += num
            result.append((val, num))
        self.assertEqual(result, _SLEB_OUTPUT_DATA)


if __name__ == '__main__':
    unittest.main()
