Vinod Polimera | 7528311 | 2022-07-20 17:25:44 +0530 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
| 2 | |
| 3 | #include <commonlib/rational.h> |
| 4 | #include <tests/test.h> |
| 5 | |
| 6 | struct rational_test_param { |
| 7 | unsigned long num, den; |
| 8 | unsigned long max_num, max_den; |
| 9 | unsigned long exp_num, exp_den; |
| 10 | }; |
| 11 | |
| 12 | static const struct rational_test_param test_params[] = { |
| 13 | /* Exceeds bounds, semi-convergent term > half last term */ |
| 14 | { 1230, 10, 100, 20, 100, 1}, |
| 15 | /* Exceeds bounds, semi-convergent term < half last term */ |
| 16 | { 34567, 100, 120, 20, 120, 1}, |
| 17 | /* Closest to zero */ |
| 18 | { 1, 30, 100, 10, 0, 1}, |
| 19 | /* Closest to smallest non-zero */ |
| 20 | { 1, 19, 100, 10, 1, 10}, |
| 21 | /* Exact answer */ |
| 22 | { 1155, 7735, 255, 255, 33, 221}, |
| 23 | /* Convergent */ |
| 24 | { 27, 32, 16, 16, 11, 13}, |
| 25 | /* Convergent, semiconvergent term half convergent term */ |
| 26 | { 67, 54, 17, 18, 5, 4}, |
| 27 | /* Semiconvergent, semiconvergent term half convergent term */ |
| 28 | { 453, 182, 60, 60, 57, 23}, |
| 29 | /* Semiconvergent, numerator limit */ |
| 30 | { 87, 32, 70, 32, 68, 25}, |
| 31 | /* Semiconvergent, demominator limit */ |
| 32 | { 14533, 4626, 15000, 2400, 7433, 2366}, |
| 33 | }; |
| 34 | |
| 35 | static void test_rational(void **state) |
| 36 | { |
| 37 | int i; |
| 38 | unsigned long num = 0, den = 0; |
| 39 | |
| 40 | for (i = 0; i < ARRAY_SIZE(test_params); i++) { |
| 41 | rational_best_approximation(test_params[i].num, test_params[i].den, |
| 42 | test_params[i].max_num, test_params[i].max_den, |
| 43 | &num, &den); |
| 44 | assert_int_equal(num, test_params[i].exp_num); |
| 45 | assert_int_equal(den, test_params[i].exp_den); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | int main(void) |
| 50 | { |
| 51 | const struct CMUnitTest tests[] = { |
| 52 | cmocka_unit_test(test_rational), |
| 53 | }; |
| 54 | |
Jakub Czapiga | ff96823 | 2022-09-06 09:39:56 +0200 | [diff] [blame] | 55 | return cb_run_group_tests(tests, NULL, NULL); |
Vinod Polimera | 7528311 | 2022-07-20 17:25:44 +0530 | [diff] [blame] | 56 | } |
| 57 | |