int_sqrt_kunit.c 2.2 KB

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