1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * SPDX-License-Identifier: MPL-2.0
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9  *
10  * See the COPYRIGHT file distributed with this work for additional
11  * information regarding copyright ownership.
12  */
13 
14 /* ! \file */
15 
16 #if HAVE_CMOCKA
17 
18 #include <setjmp.h>
19 #include <stdarg.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #define UNIT_TESTING
25 #include <cmocka.h>
26 
27 #include <isc/crc64.h>
28 #include <isc/print.h>
29 #include <isc/result.h>
30 #include <isc/util.h>
31 
32 #define TEST_INPUT(x) (x), sizeof(x) - 1
33 
34 typedef struct hash_testcase {
35 	const char *input;
36 	size_t input_len;
37 	const char *result;
38 	int repeats;
39 } hash_testcase_t;
40 
41 static void
isc_crc64_init_test(void ** state)42 isc_crc64_init_test(void **state) {
43 	uint64_t crc;
44 
45 	UNUSED(state);
46 
47 	isc_crc64_init(&crc);
48 	assert_int_equal(crc, 0xffffffffffffffffUL);
49 }
50 
51 static void
_crc64(const char * buf,size_t buflen,const char * result,const int repeats)52 _crc64(const char *buf, size_t buflen, const char *result, const int repeats) {
53 	uint64_t crc;
54 
55 	isc_crc64_init(&crc);
56 	assert_int_equal(crc, 0xffffffffffffffffUL);
57 
58 	for (int i = 0; i < repeats; i++) {
59 		isc_crc64_update(&crc, buf, buflen);
60 	}
61 
62 	isc_crc64_final(&crc);
63 
64 	char hex[16 + 1];
65 	snprintf(hex, sizeof(hex), "%016" PRIX64, crc);
66 
67 	assert_memory_equal(hex, result, (result ? strlen(result) : 0));
68 }
69 
70 /* 64-bit cyclic redundancy check */
71 static void
isc_crc64_test(void ** state)72 isc_crc64_test(void **state) {
73 	UNUSED(state);
74 
75 	_crc64(TEST_INPUT(""), "0000000000000000", 1);
76 	_crc64(TEST_INPUT("a"), "CE73F427ACC0A99A", 1);
77 	_crc64(TEST_INPUT("abc"), "048B813AF9F49702", 1);
78 	_crc64(TEST_INPUT("message digest"), "5273F9EA7A357BF4", 1);
79 	_crc64(TEST_INPUT("abcdefghijklmnopqrstuvwxyz"), "59F079F9218BAAA1", 1);
80 	_crc64(TEST_INPUT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"
81 			  "nopqrstuvwxyz0123456789"),
82 	       "A36DA8F71E78B6FB", 1);
83 	_crc64(TEST_INPUT("123456789012345678901234567890123456789"
84 			  "01234567890123456789012345678901234567890"),
85 	       "81E5EB73C8E7874A", 1);
86 }
87 
88 int
main(void)89 main(void) {
90 	const struct CMUnitTest tests[] = {
91 		cmocka_unit_test(isc_crc64_init_test),
92 		cmocka_unit_test(isc_crc64_test),
93 	};
94 
95 	return (cmocka_run_group_tests(tests, NULL, NULL));
96 }
97 
98 #else /* HAVE_CMOCKA */
99 
100 #include <stdio.h>
101 
102 int
main(void)103 main(void) {
104 	printf("1..0 # Skipped: cmocka not available\n");
105 	return (SKIPPED_TEST_EXIT_CODE);
106 }
107 
108 #endif /* if HAVE_CMOCKA */
109