1 /*
2  * Copyright (c) 2023 Basalte bv
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <string.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/ztest.h>
10 
11 #include <pb_encode.h>
12 #include <pb_decode.h>
13 
14 #include <proto/simple.pb.h>
15 #include <proto/complex.pb.h>
16 
17 #include "lib.h"
18 
ZTEST(nanopb_tests,test_nanopb_simple)19 ZTEST(nanopb_tests, test_nanopb_simple)
20 {
21 	uint8_t buffer[SimpleMessage_size];
22 	SimpleMessage msg = SimpleMessage_init_zero;
23 
24 	for (size_t i = 0; i < sizeof(msg.buffer); ++i) {
25 		msg.buffer[i] = i;
26 	}
27 
28 	pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
29 
30 	zassert_true(pb_encode(&ostream, SimpleMessage_fields, &msg),
31 		     "Encoding failed: %s", PB_GET_ERROR(&ostream));
32 
33 	/* Sanity check, clear data */
34 	memset(&msg, 0, sizeof(SimpleMessage));
35 
36 	pb_istream_t istream = pb_istream_from_buffer(buffer, ostream.bytes_written);
37 
38 	zassert_true(pb_decode(&istream, SimpleMessage_fields, &msg),
39 		     "Decoding failed: %s", PB_GET_ERROR(&ostream));
40 
41 	for (size_t i = 0; i < sizeof(msg.buffer); ++i) {
42 		zassert_equal(msg.buffer[i], i);
43 	}
44 }
45 
ZTEST(nanopb_tests,test_nanopb_nested)46 ZTEST(nanopb_tests, test_nanopb_nested)
47 {
48 	uint8_t buffer[ComplexMessage_size];
49 	ComplexMessage msg = ComplexMessage_init_zero;
50 
51 	msg.has_nested = true;
52 	msg.nested.id = 42;
53 	strcpy(msg.nested.name, "Test name");
54 
55 	pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
56 
57 	zassert_true(pb_encode(&ostream, ComplexMessage_fields, &msg),
58 		     "Encoding failed: %s", PB_GET_ERROR(&ostream));
59 
60 	/* Sanity check, clear data */
61 	memset(&msg, 0, sizeof(ComplexMessage));
62 
63 	pb_istream_t istream = pb_istream_from_buffer(buffer, ostream.bytes_written);
64 
65 	zassert_true(pb_decode(&istream, ComplexMessage_fields, &msg),
66 		     "Decoding failed: %s", PB_GET_ERROR(&istream));
67 
68 	zassert_equal(42, msg.nested.id);
69 	zassert_true(msg.has_nested);
70 	zassert_str_equal(msg.nested.name, "Test name");
71 }
72 
ZTEST(nanopb_tests,test_nanopb_lib)73 ZTEST(nanopb_tests, test_nanopb_lib)
74 {
75 	SimpleMessage msg = SimpleMessage_init_zero;
76 
77 	lib_fill_message(&msg);
78 
79 	for (size_t i = 0; i < sizeof(msg.buffer); ++i) {
80 		zassert_equal(msg.buffer[i], sizeof(msg.buffer) - i);
81 	}
82 }
83 
84 ZTEST_SUITE(nanopb_tests, NULL, NULL, NULL, NULL, NULL);
85