|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Space Cubics, LLC. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | +#include <zephyr/ztest.h> |
| 7 | +#include <csp/csp.h> |
| 8 | +#include <csp/csp_crc32.h> |
| 9 | +#include <csp/csp_id.h> |
| 10 | +#include <endian.h> |
| 11 | + |
| 12 | +struct crc_fixture { |
| 13 | + csp_packet_t *buf; |
| 14 | +}; |
| 15 | + |
| 16 | +static struct crc_fixture crc_fixture; |
| 17 | + |
| 18 | +static void *setup(void) |
| 19 | +{ |
| 20 | + csp_init(); |
| 21 | + |
| 22 | + return &crc_fixture; |
| 23 | +} |
| 24 | + |
| 25 | +static void before(void *data) |
| 26 | +{ |
| 27 | + struct crc_fixture *fixture = data; |
| 28 | + |
| 29 | + fixture->buf = csp_buffer_get(0); |
| 30 | + zassert_true(fixture->buf != NULL, NULL); |
| 31 | +} |
| 32 | + |
| 33 | +static void after(void *data) |
| 34 | +{ |
| 35 | + struct crc_fixture *fixture = data; |
| 36 | + |
| 37 | + csp_buffer_free(fixture->buf); |
| 38 | +} |
| 39 | + |
| 40 | +ZTEST_F(crc, test_crc_verify_without_crc) |
| 41 | +{ |
| 42 | + csp_packet_t *packet = fixture->buf; |
| 43 | + int ret; |
| 44 | + |
| 45 | + /* Check size error */ |
| 46 | + packet->length = 0; |
| 47 | + ret = csp_crc32_verify(packet); |
| 48 | + zassert_equal(ret, CSP_ERR_CRC32, "Expected error on size in csp_crc32_verify"); |
| 49 | + |
| 50 | + /* Check without crc */ |
| 51 | + memcpy(packet->data, "Hello", 5); |
| 52 | + packet->length = 5; |
| 53 | + ret = csp_crc32_verify(packet); |
| 54 | + zassert_equal(ret, CSP_ERR_CRC32, "Expected error on crc in csp_crc32_verify"); |
| 55 | +} |
| 56 | + |
| 57 | +ZTEST_F(crc, test_crc_without_header) |
| 58 | +{ |
| 59 | + csp_packet_t *packet = fixture->buf; |
| 60 | + int ret; |
| 61 | + |
| 62 | + memcpy(packet->data, "Hello", 5); |
| 63 | + packet->length = 5; |
| 64 | + |
| 65 | + /* Check without header */ |
| 66 | + csp_crc32_append(packet); |
| 67 | + ret = csp_crc32_verify(packet); |
| 68 | + zassert_equal(CSP_ERR_NONE, ret, "Error on csp_crc32_verify"); |
| 69 | +} |
| 70 | + |
| 71 | +ZTEST_F(crc, test_crc_with_header) |
| 72 | +{ |
| 73 | + csp_packet_t *packet = fixture->buf; |
| 74 | + uint32_t crc; |
| 75 | + int ret; |
| 76 | + |
| 77 | + memcpy(packet->data, "Hello", 5); |
| 78 | + packet->length = 5; |
| 79 | + |
| 80 | + /* Check with header. |
| 81 | + * This simulate CSP_21 define on csp_crc32_append(). |
| 82 | + */ |
| 83 | + csp_id_prepend(packet); |
| 84 | + crc = csp_crc32_memory(packet->frame_begin, packet->frame_length); |
| 85 | + /* Convert to network byte order */ |
| 86 | + crc = htobe32(crc); |
| 87 | + /* Copy checksum to packet */ |
| 88 | + memcpy(&packet->data[packet->length], &crc, sizeof(crc)); |
| 89 | + packet->length += sizeof(crc); |
| 90 | + |
| 91 | + ret = csp_crc32_verify(packet); |
| 92 | + zassert_equal(CSP_ERR_NONE, ret, "Error on csp_crc32_verify"); |
| 93 | +} |
| 94 | + |
| 95 | +ZTEST_SUITE(crc, NULL, setup, before, after, NULL); |
0 commit comments