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 'Empty string', 26 (0x00000000, ''), 27 'Single character strings', 28 (0x00000001, '\0'), 29 (0x00010040, '\1'), 30 (0x003F0F82, '?'), 31 'Non-printable strings', 32 (0xD3556087, '\0\0\0\1\1\1\1'), 33 'General strings', 34 (0x63D43D8C, 'Pigweed?'), 35 (0x79AB6494, 'Pigweed!Pigweed!Pigweed!Pigweed!Pigweed!Pigweed!'), 36]) 37 38 39def _define_py_test(ctx: Context): 40 expected_id, name = ctx.test_case 41 return lambda self: self.assertEqual(expected_id, ids.calculate(name)) 42 43 44IdsTest = _TESTS.python_tests('IdsTest', _define_py_test) 45 46_CC_HEADER = """\ 47#include <string_view> 48 49#include "gtest/gtest.h" 50#include "pw_rpc/internal/hash.h" 51 52namespace pw::rpc::internal { 53 54using namespace std::string_view_literals; 55""" 56 57_CC_FOOTER = '} // namespace pw::rpc::internal' 58 59 60def _cc_test(ctx: Context) -> Iterator[str]: 61 expected_id, name = ctx.test_case 62 63 yield f'TEST(RpcIds, {ctx.cc_name()}) {{' 64 yield f' EXPECT_EQ(0x{expected_id:08x}u,' 65 yield f' Hash({generated_tests.cc_string(name)}sv));' 66 yield '}' 67 68 69if __name__ == '__main__': 70 args = generated_tests.parse_test_generation_args() 71 if args.generate_cc_test: 72 _TESTS.cc_tests(args.generate_cc_test, _cc_test, _CC_HEADER, 73 _CC_FOOTER) 74 else: 75 unittest.main() 76