1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include <kunit/test.h>
4 #include <linux/limits.h>
5 #include <linux/math.h>
6 #include <linux/module.h>
7 #include <linux/string.h>
8 
9 struct test_case_params {
10 	unsigned long x;
11 	unsigned long expected_result;
12 	const char *name;
13 };
14 
15 static const struct test_case_params params[] = {
16 	{ 0, 0, "edge case: square root of 0" },
17 	{ 1, 1, "perfect square: square root of 1" },
18 	{ 2, 1, "non-perfect square: square root of 2" },
19 	{ 3, 1, "non-perfect square: square root of 3" },
20 	{ 4, 2, "perfect square: square root of 4" },
21 	{ 5, 2, "non-perfect square: square root of 5" },
22 	{ 6, 2, "non-perfect square: square root of 6" },
23 	{ 7, 2, "non-perfect square: square root of 7" },
24 	{ 8, 2, "non-perfect square: square root of 8" },
25 	{ 9, 3, "perfect square: square root of 9" },
26 	{ 15, 3, "non-perfect square: square root of 15 (N-1 from 16)" },
27 	{ 16, 4, "perfect square: square root of 16" },
28 	{ 17, 4, "non-perfect square: square root of 17 (N+1 from 16)" },
29 	{ 80, 8, "non-perfect square: square root of 80 (N-1 from 81)" },
30 	{ 81, 9, "perfect square: square root of 81" },
31 	{ 82, 9, "non-perfect square: square root of 82 (N+1 from 81)" },
32 	{ 255, 15, "non-perfect square: square root of 255 (N-1 from 256)" },
33 	{ 256, 16, "perfect square: square root of 256" },
34 	{ 257, 16, "non-perfect square: square root of 257 (N+1 from 256)" },
35 	{ 2147483648, 46340, "large input: square root of 2147483648" },
36 	{ 4294967295, 65535, "edge case: ULONG_MAX for 32-bit" },
37 };
38 
39 static void get_desc(const struct test_case_params *tc, char *desc)
40 {
41 	strscpy(desc, tc->name, KUNIT_PARAM_DESC_SIZE);
42 }
43 
44 KUNIT_ARRAY_PARAM(int_sqrt, params, get_desc);
45 
46 static void int_sqrt_test(struct kunit *test)
47 {
48 	const struct test_case_params *tc = (const struct test_case_params *)test->param_value;
49 
50 	KUNIT_EXPECT_EQ(test, tc->expected_result, int_sqrt(tc->x));
51 }
52 
53 static struct kunit_case math_int_sqrt_test_cases[] = {
54 	KUNIT_CASE_PARAM(int_sqrt_test, int_sqrt_gen_params),
55 	{}
56 };
57 
58 static struct kunit_suite int_sqrt_test_suite = {
59 	.name = "math-int_sqrt",
60 	.test_cases = math_int_sqrt_test_cases,
61 };
62 
63 kunit_test_suites(&int_sqrt_test_suite);
64 
65 MODULE_DESCRIPTION("math.int_sqrt KUnit test suite");
66 MODULE_LICENSE("GPL");
67