summaryrefslogtreecommitdiff
path: root/util/test_util_precompile.py
blob: f27f6c4a2f5783420c7ed354f7269f5249937c22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python3
# -*- coding: utf-8 -*-"
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'Unit tests for util_precompile.py'

import pickle
import unittest
import zlib

import util_precompile

class TestUtilPrecompile(unittest.TestCase):
    'Test class for testing various util_precompile.py functions'

    def test_generate_cmsg_line(self):
        'Test generating of cmsgX() lines from format messages/arguments'
        # A tuple of tuples of typical format strings, following the matching
        # number of parameters, the last element is the expected parameter
        # description mask, describing the variety of format specifications in
        # the format string.
        inputs = (('"%s\n', 'errmsgs[rv]', 3),
                  ('%d', 10, 1),
                  ('"no format"', ),
                  ('[%pT CCD state:', '((void *)0)', 7),
                  ('%08x: DIO%c%-2d  %2d %3s%3s%3s%4s ',
                   1, 2, 3, 4, 5, 6, 6, 7, 858984721))
        string_indices = []
        for inp in inputs:
            fmt = inp[0]
            if len(inp) > 1:
                params = inp[1:-1]
                mask = inp[-1]
            else:
                params = []
                mask = None
            blocks = fmt.split('%')[1:]
            line = util_precompile.generate_cmsg_line(
                fmt, params, fmt.split('%')[1:], 'chan', 'func')
            exp_start = 'cmsg%d(chan, ' % len(blocks)
            if params:
                args = '%s' % (', '.join(['(uintptr_t)(%s)' % x
                                          for x in params]))
                exp_end = ', %d, %s);\n' % (mask, args)
            else:
                exp_end = ');\n'
            try:
                self.assertTrue(line.startswith(exp_start))
                self.assertTrue(line.endswith(exp_end))
            except AssertionError:
                print('line: %s\nexp_start: %s\nexp_end: %s' % (
                    line, exp_start, exp_end))
                raise
            line = line.replace(exp_start, '', 1)
            line = line.replace(exp_end, '', 1)
            string_indices.append(int(line))

        # Verify the contents of the generated blob
        zipped = util_precompile.generate_blob()
        dump = zlib.decompress(zipped)
        strings = pickle.loads(dump).split('\0')
        for inp, index in zip(inputs, string_indices):
            string = inp[0]
            self.assertTrue(strings[index] == string)

    def test_tokenize(self):
        'Verify tokenize() function ability to parse vararg string'
        in_tokens = (
            '"simple string"',
            '"another string, with a comma"',
            '"string split" " in two"',
            '"string with \\"escaped\\" double quotes"',
            '(&(const struct hex_buffer_params)'
            '{ .buffer = (ec_efs_ctx.hash), .size = (32) })')
        out_tokens = util_precompile.tokenize(', '.join(in_tokens))
        for in_t, out_t in zip(in_tokens, out_tokens):
            self.assertEqual(in_t, out_t)

    def test_line_processor(self):
        'Test line processor class ability to consolidate preprocessor lines'
        # Reset the string dictionary.
        util_precompile.FMT_DICT = {}
        in_out_tuples = (
            (
                """ cprintf(CC_COMMAND, "Last attempt returned " "%d\\n", rv)

                ;""",

                ' cmsg1(CC_COMMAND, 0, 1, (uintptr_t)(rv));\n'
            ), (
                ' cprintf(CC_COMMAND, "ec_hash_secdata    : %ph\\n", '
                '(&(const struct hex_buffer_params)'
                '{ .buffer = (ec_efs_ctx.hash), .size = (32) }));',
                ' cmsg1(CC_COMMAND, 1, 5, (uintptr_t)((&(const struct '
                'hex_buffer_params)'
                '{ .buffer = (ec_efs_ctx.hash), .size = (32) })));\n'
            ), (
                'struct ec_params_get_cmd_versions {',
                'struct ec_params_get_cmd_versions {',
            ), (
                '  cprints(CC_CCD, "CCD test lab mode %sbled", v '
                '? "ena" : "disa");',
                ' cmsg1(CC_CCD, 2, 3, (uintptr_t)(v ? "ena" : "disa"));\n'
            ), (
                '  cprintf(CC_COMMAND, "%s: deleting var failed!\\n", '
                '__func__);',
                ' cmsg1(CC_COMMAND, 3, 6, (uintptr_t)4);\n'
            ), (
                ' return  cprintf(CC_COMMAND, "%s: done!\\n", __func__);',
                ' return cmsg1(CC_COMMAND, 5, 6, (uintptr_t)4);\n'
            )
        )
        line_processor = util_precompile.LineProcessor()
        for inp, outp in in_out_tuples:
            result = ''
            for line in inp.splitlines():
                section = line_processor.process_preprocessor_line(line)
                if section:
                    result += section
            self.assertEqual(result, outp)
            try:
                string_index = int(outp.split(',')[1])
            except IndexError:
                # This is the line without a print statement.
                continue
            fmt = inp.split(',')[1].strip()
            for key, value in util_precompile.FMT_DICT.items():
                if value == string_index:
                    fmt = fmt.replace('" "', '')
                    fmt = fmt.replace('\\n', '\n')
                    fmt = fmt.strip('"')
                    if 'cprints' in inp:
                        fmt = '[^T' + fmt
                    self.assertEqual(fmt, key)
                    break
            else:
                self.fail('did not find "%s" in the dictionary')


    def test_drop_escapes(self):
        'Verify proper conversion of escape characters'
        insouts = (('\\a\\b\\f\\n\\r\\t\\v\'"\\\\',
                    '\a\b\f\n\r\t\v\'"\\'),
                   ('line \\x1a with two hex escapes \\x1b\\n',
                    'line \x1a with two hex escapes \x1b\n'))
        for i, o in insouts:
            self.assertEqual(o, util_precompile.drop_escapes(i))

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