1# Copyright 2017, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Utility functions for unit tests."""
16
17# pylint: disable=line-too-long
18
19import os
20
21import constants
22import unittest_constants as uc
23
24def assert_strict_equal(test_class, first, second):
25    """Check for strict equality and strict equality of nametuple elements.
26
27    assertEqual considers types equal to their subtypes, but we want to
28    not consider set() and frozenset() equal for testing.
29    """
30    # Allow 2 lists with different order but the same content equal.
31    if isinstance(first, list) and isinstance(second, list):
32        first.sort()
33        second.sort()
34    test_class.assertEqual(first, second)
35    # allow byte and unicode string equality.
36    if not (isinstance(first, str) and
37            isinstance(second, str)):
38        test_class.assertIsInstance(first, type(second))
39        test_class.assertIsInstance(second, type(first))
40    # Recursively check elements of namedtuples for strict equals.
41    if isinstance(first, tuple) and hasattr(first, '_fields'):
42        # pylint: disable=invalid-name
43        for f in first._fields:
44            assert_strict_equal(test_class, getattr(first, f),
45                                getattr(second, f))
46
47def assert_equal_testinfos(test_class, test_info_a, test_info_b):
48    """Check that the passed in TestInfos are equal."""
49    # Use unittest.assertEqual to do checks when None is involved.
50    if test_info_a is None or test_info_b is None:
51        test_class.assertEqual(test_info_a, test_info_b)
52        return
53
54    for attr in test_info_a.__dict__:
55        test_info_a_attr = getattr(test_info_a, attr)
56        test_info_b_attr = getattr(test_info_b, attr)
57        test_class.assertEqual(test_info_a_attr, test_info_b_attr,
58                               msg=('TestInfo.%s mismatch: %s != %s' %
59                                    (attr, test_info_a_attr, test_info_b_attr)))
60
61def assert_equal_testinfo_sets(test_class, test_info_set_a, test_info_set_b):
62    """Check that the sets of TestInfos are equal."""
63    test_class.assertEqual(len(test_info_set_a), len(test_info_set_b),
64                           msg=('mismatch # of TestInfos: %d != %d' %
65                                (len(test_info_set_a), len(test_info_set_b))))
66    # Iterate over a set and pop them out as you compare them.
67    while test_info_set_a:
68        test_info_a = test_info_set_a.pop()
69        test_info_b_to_remove = None
70        for test_info_b in test_info_set_b:
71            try:
72                assert_equal_testinfos(test_class, test_info_a, test_info_b)
73                test_info_b_to_remove = test_info_b
74                break
75            except AssertionError:
76                pass
77        if test_info_b_to_remove:
78            test_info_set_b.remove(test_info_b_to_remove)
79        else:
80            # We haven't found a match, raise an assertion error.
81            raise AssertionError('No matching TestInfo (%s) in [%s]' %
82                                 (test_info_a, ';'.join([str(t) for t in test_info_set_b])))
83
84
85def isfile_side_effect(value):
86    """Mock return values for os.path.isfile."""
87    if value == '/%s/%s' % (uc.CC_MODULE_DIR, constants.MODULE_CONFIG):
88        return True
89    if value == '/%s/%s' % (uc.MODULE_DIR, constants.MODULE_CONFIG):
90        return True
91    if value.endswith('.cc'):
92        return True
93    if value.endswith('.cpp'):
94        return True
95    if value.endswith('.java'):
96        return True
97    if value.endswith('.kt'):
98        return True
99    if value.endswith(uc.INT_NAME + '.xml'):
100        return True
101    if value.endswith(uc.GTF_INT_NAME + '.xml'):
102        return True
103    return False
104
105
106def realpath_side_effect(path):
107    """Mock return values for os.path.realpath."""
108    return os.path.join(uc.ROOT, path)
109