#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import cStringIO
import logging
import os
import sys
import textwrap
import unittest

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT_DIR)

try:
  from collections import OrderedDict  # pylint: disable=E0611
except ImportError:
  SIMPLEJSON_PATH = os.path.join(ROOT_DIR, os.pardir, os.pardir, 'third_party')
  sys.path.insert(0, SIMPLEJSON_PATH)
  from simplejson import OrderedDict

import dmprof
from find_runtime_symbols import FUNCTION_SYMBOLS
from find_runtime_symbols import SOURCEFILE_SYMBOLS
from find_runtime_symbols import TYPEINFO_SYMBOLS


class SymbolMappingCacheTest(unittest.TestCase):
  class MockBucketSet(object):
    def __init__(self, addresses):
      self._addresses = addresses

    def iter_addresses(self, symbol_type):  # pylint: disable=W0613
      for address in self._addresses:
        yield address

  class MockSymbolFinder(object):
    def __init__(self, mapping):
      self._mapping = mapping

    def find(self, address_list):
      result = OrderedDict()
      for address in address_list:
        result[address] = self._mapping[address]
      return result

  _TEST_FUNCTION_CACHE = textwrap.dedent("""\
      1 0x0000000000000001
      7fc33eebcaa4 __gnu_cxx::new_allocator::allocate
      7fc33ef69242 void DispatchToMethod
      """)

  _EXPECTED_TEST_FUNCTION_CACHE = textwrap.dedent("""\
      1 0x0000000000000001
      7fc33eebcaa4 __gnu_cxx::new_allocator::allocate
      7fc33ef69242 void DispatchToMethod
      2 0x0000000000000002
      7fc33ef7bc3e std::map::operator[]
      7fc34411f9d5 WTF::RefCounted::operator new
      """)

  _TEST_FUNCTION_ADDRESS_LIST1 = [
      0x1, 0x7fc33eebcaa4, 0x7fc33ef69242]

  _TEST_FUNCTION_ADDRESS_LIST2 = [
      0x1, 0x2, 0x7fc33eebcaa4, 0x7fc33ef69242, 0x7fc33ef7bc3e, 0x7fc34411f9d5]

  _TEST_FUNCTION_DICT = {