aboutsummaryrefslogtreecommitdiff
path: root/test/validation/api/random/random.c
blob: 481ceb303a72af0cf1946281068af1b9a626a6d0 (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* Copyright (c) 2015-2018, Linaro Limited
 * All rights reserved.
 *
 * SPDX-License-Identifier:     BSD-3-Clause
 */

#include <odp_api.h>
#include <odp_cunit_common.h>

static void random_test_get_size(void)
{
	/* odp_random_data may fail to return data on every call (i.e. lack of
	 * entropy). Therefore loop with some sane loop timeout value. Note that
	 * it is not required for implementation to return data in the "timeout"
	 * amount of steps. Rather it is a way for preventing the test to loop
	 * forever.
	 * Also note that the timeout value here is chosen completely
	 * arbitrarily (although considered sane) and neither platforms or
	 * applications are not required to use it.
	 */
	int32_t ret, timeout_ns = 1 * ODP_TIME_MSEC_IN_NS, sleep_ns = 100;
	uint32_t bytes = 0;
	uint8_t buf[32];

	do {
		ret = odp_random_data(buf + bytes, sizeof(buf) - bytes,
				      ODP_RANDOM_BASIC);
		bytes += ret;
		if (ret < 0 || bytes >= sizeof(buf))
			break;
		odp_time_wait_ns(sleep_ns);
		timeout_ns -= sleep_ns;
	} while (timeout_ns > 0);

	CU_ASSERT(ret > 0);
	CU_ASSERT(bytes == (int32_t)sizeof(buf));
}

static void random_test_kind(void)
{
	int32_t rc;
	uint8_t buf[4096];
	uint32_t buf_size = sizeof(buf);
	odp_random_kind_t max_kind = odp_random_max_kind();

	rc = odp_random_data(buf, buf_size, max_kind);
	CU_ASSERT(rc > 0);

	switch (max_kind) {
	case ODP_RANDOM_BASIC:
		rc = odp_random_data(buf, 4, ODP_RANDOM_CRYPTO);
		CU_ASSERT(rc < 0);
		/* Fall through */

	case ODP_RANDOM_CRYPTO:
		rc = odp_random_data(buf, 4, ODP_RANDOM_TRUE);
		CU_ASSERT(rc < 0);
		break;

	default:
		break;
	}
}

static void random_test_repeat(void)
{
	uint8_t buf1[1024];
	uint8_t buf2[1024];
	int32_t rc;
	uint64_t seed1 = 12345897;
	uint64_t seed2 = seed1;

	rc = odp_random_test_data(buf1, sizeof(buf1), &seed1);
	CU_ASSERT(rc == sizeof(buf1));

	rc = odp_random_test_data(buf2, sizeof(buf2), &seed2);
	CU_ASSERT(rc == sizeof(buf2));

	CU_ASSERT(seed1 == seed2);
	CU_ASSERT(memcmp(buf1, buf2, sizeof(buf1)) == 0);
}

odp_testinfo_t random_suite[] = {
	ODP_TEST_INFO(random_test_get_size),
	ODP_TEST_INFO(random_test_kind),
	ODP_TEST_INFO(random_test_repeat),
	ODP_TEST_INFO_NULL,
};

odp_suiteinfo_t random_suites[] = {
	{"Random", NULL, NULL, random_suite},
	ODP_SUITE_INFO_NULL,
};

int main(int argc, char *argv[])
{
	int ret;

	/* parse common options: */
	if (odp_cunit_parse_options(argc, argv))
		return -1;

	ret = odp_cunit_register(random_suites);

	if (ret == 0)
		ret = odp_cunit_run();

	return ret;
}