1# Copyright 2014 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import imp
6import os.path
7import sys
8import unittest
9
10from mojom.generate import module as mojom
11from mojom.generate import translate
12from mojom.parse import ast
13
14
15class TranslateTest(unittest.TestCase):
16  """Tests |parser.Parse()|."""
17
18  def testSimpleArray(self):
19    """Tests a simple int32[]."""
20    # pylint: disable=W0212
21    self.assertEquals(translate._MapKind("int32[]"), "a:i32")
22
23  def testAssociativeArray(self):
24    """Tests a simple uint8{string}."""
25    # pylint: disable=W0212
26    self.assertEquals(translate._MapKind("uint8{string}"), "m[s][u8]")
27
28  def testLeftToRightAssociativeArray(self):
29    """Makes sure that parsing is done from right to left on the internal kinds
30       in the presence of an associative array."""
31    # pylint: disable=W0212
32    self.assertEquals(translate._MapKind("uint8[]{string}"), "m[s][a:u8]")
33
34  def testTranslateSimpleUnions(self):
35    """Makes sure that a simple union is translated correctly."""
36    tree = ast.Mojom(None, ast.ImportList(), [
37        ast.Union(
38            "SomeUnion", None,
39            ast.UnionBody([
40                ast.UnionField("a", None, None, "int32"),
41                ast.UnionField("b", None, None, "string")
42            ]))
43    ])
44
45    translation = translate.OrderedModule(tree, "mojom_tree", [])
46    self.assertEqual(1, len(translation.unions))
47
48    union = translation.unions[0]
49    self.assertTrue(isinstance(union, mojom.Union))
50    self.assertEqual("SomeUnion", union.mojom_name)
51    self.assertEqual(2, len(union.fields))
52    self.assertEqual("a", union.fields[0].mojom_name)
53    self.assertEqual(mojom.INT32.spec, union.fields[0].kind.spec)
54    self.assertEqual("b", union.fields[1].mojom_name)
55    self.assertEqual(mojom.STRING.spec, union.fields[1].kind.spec)
56
57  def testMapKindRaisesWithDuplicate(self):
58    """Verifies _MapTreeForType() raises when passed two values with the same
59       name."""
60    methods = [
61        ast.Method('dup', None, None, ast.ParameterList(), None),
62        ast.Method('dup', None, None, ast.ParameterList(), None)
63    ]
64    with self.assertRaises(Exception):
65      translate._ElemsOfType(methods, ast.Method, 'scope')
66
67  def testAssociatedKinds(self):
68    """Tests type spec translation of associated interfaces and requests."""
69    # pylint: disable=W0212
70    self.assertEquals(
71        translate._MapKind("asso<SomeInterface>?"), "?asso:x:SomeInterface")
72    self.assertEquals(
73        translate._MapKind("asso<SomeInterface&>?"), "?asso:r:x:SomeInterface")
74