1 #include "config.h"
2 #include "ntp.h"
3 
4 #include "unity.h"
5 #include "unity_fixture.h"
6 
7 TEST_GROUP(random);
8 
TEST_SETUP(random)9 TEST_SETUP(random) {}
10 
TEST_TEAR_DOWN(random)11 TEST_TEAR_DOWN(random) {}
12 
13 /* leftover from testing ntp_random()
14  * random(3) is 31 bits.
15  */
TEST(random,random32)16 TEST(random, random32) {
17 	uint32_t ones = 0;
18 	uint32_t zeros = RAND_MAX;
19 
20 	/* This is just a crude sanity check.
21 	 * It could fail when working correctly,
22 	 * but the chances are pretty small.
23 	 * It won't be reproducible.  ;)
24 	 * You can test this code by making the loop count smaller.
25 	 */
26 	for (int i=0; i<99; i++) {
27 		uint32_t sample = random();
28 		ones |= sample;
29 		zeros &= sample;
30 	}
31 
32 	/* RAND_MAX on FreeBSD is 0x7ffffffd */
33 	TEST_ASSERT_EQUAL_INT32(0x7fffffff, ones);
34 	TEST_ASSERT_EQUAL_INT32(0, zeros);
35 }
36 
TEST(random,random_bytes)37 TEST(random, random_bytes) {
38 #define BYTES 100
39 	unsigned char zeros[BYTES];  /* collected zeros */
40 	unsigned char ones[BYTES];   /* collected ones */
41 	unsigned char clear[BYTES];  /* expected all zeros */
42 	unsigned char full[BYTES];   /* expected all ones */
43 
44 	for (int j=0; j<BYTES; j++) {
45 		zeros[j] = ~0;
46 		ones[j] = 0;
47 		clear[j] = 0;
48 		full[j] = ~0;
49 	}
50 
51 	/* This is just a crude sanity check.
52 	 * It could fail when working correctly,
53 	 * but the chances are pretty small.
54 	 * It won't be reproducible.  ;)
55 	 * You can test this code by making the loop count smaller.
56 	 */
57 	for (int i=0; i<99; i++) {
58 		unsigned char sample[BYTES];
59 		ntp_RAND_bytes(&sample[0], BYTES);
60 		for (int j=0; j<BYTES; j++) {
61 			zeros[j] &= ~sample[j];
62 			ones[j] |= sample[j];
63 		}
64 	}
65 
66 	TEST_ASSERT_EQUAL_MEMORY(full, ones, BYTES);
67 	TEST_ASSERT_EQUAL_MEMORY(clear, zeros, BYTES);
68 }
69 
TEST_GROUP_RUNNER(random)70 TEST_GROUP_RUNNER(random) {
71 	RUN_TEST_CASE(random, random32);
72 	RUN_TEST_CASE(random, random_bytes);
73 }
74