xref: /linux-6.15/lib/tests/test_sort.c (revision db6fe4d6)
1*db6fe4d6SKees Cook // SPDX-License-Identifier: GPL-2.0-only
2*db6fe4d6SKees Cook 
3*db6fe4d6SKees Cook #include <kunit/test.h>
4*db6fe4d6SKees Cook 
5*db6fe4d6SKees Cook #include <linux/sort.h>
6*db6fe4d6SKees Cook #include <linux/slab.h>
7*db6fe4d6SKees Cook #include <linux/module.h>
8*db6fe4d6SKees Cook 
9*db6fe4d6SKees Cook /* a simple boot-time regression test */
10*db6fe4d6SKees Cook 
11*db6fe4d6SKees Cook #define TEST_LEN 1000
12*db6fe4d6SKees Cook 
cmpint(const void * a,const void * b)13*db6fe4d6SKees Cook static int cmpint(const void *a, const void *b)
14*db6fe4d6SKees Cook {
15*db6fe4d6SKees Cook 	return *(int *)a - *(int *)b;
16*db6fe4d6SKees Cook }
17*db6fe4d6SKees Cook 
test_sort(struct kunit * test)18*db6fe4d6SKees Cook static void test_sort(struct kunit *test)
19*db6fe4d6SKees Cook {
20*db6fe4d6SKees Cook 	int *a, i, r = 1;
21*db6fe4d6SKees Cook 
22*db6fe4d6SKees Cook 	a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL);
23*db6fe4d6SKees Cook 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a);
24*db6fe4d6SKees Cook 
25*db6fe4d6SKees Cook 	for (i = 0; i < TEST_LEN; i++) {
26*db6fe4d6SKees Cook 		r = (r * 725861) % 6599;
27*db6fe4d6SKees Cook 		a[i] = r;
28*db6fe4d6SKees Cook 	}
29*db6fe4d6SKees Cook 
30*db6fe4d6SKees Cook 	sort(a, TEST_LEN, sizeof(*a), cmpint, NULL);
31*db6fe4d6SKees Cook 
32*db6fe4d6SKees Cook 	for (i = 0; i < TEST_LEN - 1; i++)
33*db6fe4d6SKees Cook 		KUNIT_ASSERT_LE(test, a[i], a[i + 1]);
34*db6fe4d6SKees Cook 
35*db6fe4d6SKees Cook 	r = 48;
36*db6fe4d6SKees Cook 
37*db6fe4d6SKees Cook 	for (i = 0; i < TEST_LEN - 1; i++) {
38*db6fe4d6SKees Cook 		r = (r * 725861) % 6599;
39*db6fe4d6SKees Cook 		a[i] = r;
40*db6fe4d6SKees Cook 	}
41*db6fe4d6SKees Cook 
42*db6fe4d6SKees Cook 	sort(a, TEST_LEN - 1, sizeof(*a), cmpint, NULL);
43*db6fe4d6SKees Cook 
44*db6fe4d6SKees Cook 	for (i = 0; i < TEST_LEN - 2; i++)
45*db6fe4d6SKees Cook 		KUNIT_ASSERT_LE(test, a[i], a[i + 1]);
46*db6fe4d6SKees Cook }
47*db6fe4d6SKees Cook 
48*db6fe4d6SKees Cook static struct kunit_case sort_test_cases[] = {
49*db6fe4d6SKees Cook 	KUNIT_CASE(test_sort),
50*db6fe4d6SKees Cook 	{}
51*db6fe4d6SKees Cook };
52*db6fe4d6SKees Cook 
53*db6fe4d6SKees Cook static struct kunit_suite sort_test_suite = {
54*db6fe4d6SKees Cook 	.name = "lib_sort",
55*db6fe4d6SKees Cook 	.test_cases = sort_test_cases,
56*db6fe4d6SKees Cook };
57*db6fe4d6SKees Cook 
58*db6fe4d6SKees Cook kunit_test_suites(&sort_test_suite);
59*db6fe4d6SKees Cook 
60*db6fe4d6SKees Cook MODULE_DESCRIPTION("sort() KUnit test suite");
61*db6fe4d6SKees Cook MODULE_LICENSE("GPL");
62