1 // SPDX-License-Identifier: GPL-2.0+ 2 /* 3 * Test cases for API provided by cmdline.c 4 */ 5 6 #include <kunit/test.h> 7 #include <linux/kernel.h> 8 #include <linux/random.h> 9 #include <linux/string.h> 10 11 static const char *cmdline_test_strings[] = { 12 "\"\"", "" , "=" , "\"-", "," , "-," , ",-" , "-" , 13 "+," , "--", ",,", "''" , "\"\",", "\",\"", "-\"\"", "\"", 14 }; 15 16 static const int cmdline_test_values[] = { 17 1, 1, 1, 1, 2, 3, 2, 3, 18 1, 3, 2, 1, 1, 1, 3, 1, 19 }; 20 21 static void cmdline_do_one_test(struct kunit *test, const char *in, int rc, int offset) 22 { 23 const char *fmt = "Pattern: %s"; 24 const char *out = in; 25 int dummy; 26 int ret; 27 28 ret = get_option((char **)&out, &dummy); 29 30 KUNIT_EXPECT_EQ_MSG(test, ret, rc, fmt, in); 31 KUNIT_EXPECT_PTR_EQ_MSG(test, out, in + offset, fmt, in); 32 } 33 34 static void cmdline_test_noint(struct kunit *test) 35 { 36 unsigned int i = 0; 37 38 do { 39 const char *str = cmdline_test_strings[i]; 40 int rc = 0; 41 int offset; 42 43 /* Only first and leading '-' will advance the pointer */ 44 offset = !!(*str == '-'); 45 cmdline_do_one_test(test, str, rc, offset); 46 } while (++i < ARRAY_SIZE(cmdline_test_strings)); 47 } 48 49 static void cmdline_test_lead_int(struct kunit *test) 50 { 51 unsigned int i = 0; 52 char in[32]; 53 54 do { 55 const char *str = cmdline_test_strings[i]; 56 int rc = cmdline_test_values[i]; 57 int offset; 58 59 sprintf(in, "%u%s", get_random_int() % 256, str); 60 /* Only first '-' after the number will advance the pointer */ 61 offset = strlen(in) - strlen(str) + !!(rc == 2); 62 cmdline_do_one_test(test, in, rc, offset); 63 } while (++i < ARRAY_SIZE(cmdline_test_strings)); 64 } 65 66 static void cmdline_test_tail_int(struct kunit *test) 67 { 68 unsigned int i = 0; 69 char in[32]; 70 71 do { 72 const char *str = cmdline_test_strings[i]; 73 /* When "" or "-" the result will be valid integer */ 74 int rc = strcmp(str, "") ? (strcmp(str, "-") ? 0 : 1) : 1; 75 int offset; 76 77 sprintf(in, "%s%u", str, get_random_int() % 256); 78 /* 79 * Only first and leading '-' not followed by integer 80 * will advance the pointer. 81 */ 82 offset = rc ? strlen(in) : !!(*str == '-'); 83 cmdline_do_one_test(test, in, rc, offset); 84 } while (++i < ARRAY_SIZE(cmdline_test_strings)); 85 } 86 87 static struct kunit_case cmdline_test_cases[] = { 88 KUNIT_CASE(cmdline_test_noint), 89 KUNIT_CASE(cmdline_test_lead_int), 90 KUNIT_CASE(cmdline_test_tail_int), 91 {} 92 }; 93 94 static struct kunit_suite cmdline_test_suite = { 95 .name = "cmdline", 96 .test_cases = cmdline_test_cases, 97 }; 98 kunit_test_suite(cmdline_test_suite); 99 100 MODULE_LICENSE("GPL"); 101