summaryrefslogtreecommitdiff
path: root/tests/random.c
blob: 19c23b0cb2c8cfa3665b7817d808ce7983da1ee2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "../src/random.c"

#include <stdlib.h>

#include "../src/testing.h"



static int
test_random_bytes(void) {
	int rc = -1;

	test_start("random_bytes()");

	{
		testing("we get to pick the size that comes out");

		enum {
			LEN = 256,
		};
		u8 arr[LEN] = { 0 };

		for (size_t n = 0; n < LEN; n++) {
			if (random_bytes(n, &arr)) {
				logerr("random_bytes()");
				goto out;
			}
			for (size_t i = n; i < LEN; i++) {
				assert(arr[i] == 0);
			}
		}

		test_ok();
	}

	{
		testing("we always get a new value as a result");

		enum {
			LEN = 64,
		};
		u8 arr1[LEN] = { 0 };
		u8 arr2[LEN] = { 0 };

		if (random_bytes(LEN, &arr1)) {
			logerr("random_bytes()");
			goto out;
		}

		const size_t attempts = 10;
		for (size_t n = 0; n < attempts; n++) {
			if (random_bytes(LEN, &arr2)) {
				logerr("random_bytes()");
				goto out;
			}
			assert(memcmp(arr1, arr2, LEN) != 0);
		}

		test_ok();
	}

	rc = 0;
out:
	return rc;
}


int
main(void) {
	int rc = EXIT_FAILURE;

	if (random_init()) {
		logerr("random_init()");
		goto out;
	}

	if (test_random_bytes()) {
		logerr("test_random_bytes()");
		goto out;
	}

	rc = EXIT_SUCCESS;
out:
	if (random_end()) {
		if (rc == EXIT_SUCCESS) {
			rc = EXIT_FAILURE;
		}
	}
	return rc;
}