xref: /aosp_15_r20/external/pigweed/pw_rpc/py/tests/ids_test.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1#!/usr/bin/env python3
2# Copyright 2020 The Pigweed Authors
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may not
5# use this file except in compliance with the License. You may obtain a copy of
6# the License at
7#
8#     https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations under
14# the License.
15"""Tests service and method ID calculation for Python and C++."""
16
17from typing import Iterator
18import unittest
19
20from pw_build.generated_tests import Context, TestGenerator
21from pw_build import generated_tests
22from pw_rpc import ids
23
24_TESTS = TestGenerator(
25    [
26        'Empty string',
27        (0x00000000, ''),
28        'Single character strings',
29        (0x00000001, '\0'),
30        (0x00010040, '\1'),
31        (0x003F0F82, '?'),
32        'Non-printable strings',
33        (0xD3556087, '\0\0\0\1\1\1\1'),
34        'General strings',
35        (0x63D43D8C, 'Pigweed?'),
36        (0x79AB6494, 'Pigweed!Pigweed!Pigweed!Pigweed!Pigweed!Pigweed!'),
37    ]
38)
39
40
41def _define_py_test(ctx: Context):
42    expected_id, name = ctx.test_case
43    return lambda self: self.assertEqual(expected_id, ids.calculate(name))
44
45
46IdsTest = _TESTS.python_tests('IdsTest', _define_py_test)
47
48_CC_HEADER = """\
49#include <string_view>
50
51#include "pw_unit_test/framework.h"
52#include "pw_rpc/internal/hash.h"
53
54namespace pw::rpc::internal {
55
56using namespace std::string_view_literals;
57"""
58
59_CC_FOOTER = '}  // namespace pw::rpc::internal'
60
61
62def _cc_test(ctx: Context) -> Iterator[str]:
63    expected_id, name = ctx.test_case
64
65    yield f'TEST(RpcIds, {ctx.cc_name()}) {{'
66    yield f'    EXPECT_EQ(0x{expected_id:08x}u,'
67    yield f'              Hash({generated_tests.cc_string(name)}sv));'
68    yield '}'
69
70
71if __name__ == '__main__':
72    args = generated_tests.parse_test_generation_args()
73    if args.generate_cc_test:
74        _TESTS.cc_tests(args.generate_cc_test, _cc_test, _CC_HEADER, _CC_FOOTER)
75    else:
76        unittest.main()
77