1 /* SPDX-License-Identifier: GPL-2.0-only */ 2 /* 3 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved. 4 * 5 * kselftest_harness.h: simple C unit test helper. 6 * 7 * See documentation in Documentation/dev-tools/kselftest.rst 8 * 9 * API inspired by code.google.com/p/googletest 10 */ 11 12 /** 13 * DOC: example 14 * 15 * .. code-block:: c 16 * 17 * #include "../kselftest_harness.h" 18 * 19 * TEST(standalone_test) { 20 * do_some_stuff; 21 * EXPECT_GT(10, stuff) { 22 * stuff_state_t state; 23 * enumerate_stuff_state(&state); 24 * TH_LOG("expectation failed with state: %s", state.msg); 25 * } 26 * more_stuff; 27 * ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!"); 28 * last_stuff; 29 * EXPECT_EQ(0, last_stuff); 30 * } 31 * 32 * FIXTURE(my_fixture) { 33 * mytype_t *data; 34 * int awesomeness_level; 35 * }; 36 * FIXTURE_SETUP(my_fixture) { 37 * self->data = mytype_new(); 38 * ASSERT_NE(NULL, self->data); 39 * } 40 * FIXTURE_TEARDOWN(my_fixture) { 41 * mytype_free(self->data); 42 * } 43 * TEST_F(my_fixture, data_is_good) { 44 * EXPECT_EQ(1, is_my_data_good(self->data)); 45 * } 46 * 47 * TEST_HARNESS_MAIN 48 */ 49 50 #ifndef __KSELFTEST_HARNESS_H 51 #define __KSELFTEST_HARNESS_H 52 53 #ifndef _GNU_SOURCE 54 #define _GNU_SOURCE 55 #endif 56 #include <asm/types.h> 57 #include <ctype.h> 58 #include <errno.h> 59 #include <stdbool.h> 60 #include <stdint.h> 61 #include <stdio.h> 62 #include <stdlib.h> 63 #include <string.h> 64 #include <sys/mman.h> 65 #include <sys/types.h> 66 #include <sys/wait.h> 67 #include <unistd.h> 68 #include <setjmp.h> 69 70 #include "kselftest.h" 71 72 #define TEST_TIMEOUT_DEFAULT 30 73 74 /* Utilities exposed to the test definitions */ 75 #ifndef TH_LOG_STREAM 76 # define TH_LOG_STREAM stderr 77 #endif 78 79 #ifndef TH_LOG_ENABLED 80 # define TH_LOG_ENABLED 1 81 #endif 82 83 /** 84 * TH_LOG() 85 * 86 * @fmt: format string 87 * @...: optional arguments 88 * 89 * .. code-block:: c 90 * 91 * TH_LOG(format, ...) 92 * 93 * Optional debug logging function available for use in tests. 94 * Logging may be enabled or disabled by defining TH_LOG_ENABLED. 95 * E.g., #define TH_LOG_ENABLED 1 96 * 97 * If no definition is provided, logging is enabled by default. 98 */ 99 #define TH_LOG(fmt, ...) do { \ 100 if (TH_LOG_ENABLED) \ 101 __TH_LOG(fmt, ##__VA_ARGS__); \ 102 } while (0) 103 104 /* Unconditional logger for internal use. */ 105 #define __TH_LOG(fmt, ...) \ 106 fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \ 107 __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__) 108 109 /** 110 * SKIP() 111 * 112 * @statement: statement to run after reporting SKIP 113 * @fmt: format string 114 * @...: optional arguments 115 * 116 * .. code-block:: c 117 * 118 * SKIP(statement, fmt, ...); 119 * 120 * This forces a "pass" after reporting why something is being skipped 121 * and runs "statement", which is usually "return" or "goto skip". 122 */ 123 #define SKIP(statement, fmt, ...) do { \ 124 snprintf(_metadata->results->reason, \ 125 sizeof(_metadata->results->reason), fmt, ##__VA_ARGS__); \ 126 if (TH_LOG_ENABLED) { \ 127 fprintf(TH_LOG_STREAM, "# SKIP %s\n", \ 128 _metadata->results->reason); \ 129 } \ 130 _metadata->exit_code = KSFT_SKIP; \ 131 _metadata->trigger = 0; \ 132 statement; \ 133 } while (0) 134 135 /** 136 * TEST() - Defines the test function and creates the registration 137 * stub 138 * 139 * @test_name: test name 140 * 141 * .. code-block:: c 142 * 143 * TEST(name) { implementation } 144 * 145 * Defines a test by name. 146 * Names must be unique and tests must not be run in parallel. The 147 * implementation containing block is a function and scoping should be treated 148 * as such. Returning early may be performed with a bare "return;" statement. 149 * 150 * EXPECT_* and ASSERT_* are valid in a TEST() { } context. 151 */ 152 #define TEST(test_name) __TEST_IMPL(test_name, -1) 153 154 /** 155 * TEST_SIGNAL() 156 * 157 * @test_name: test name 158 * @signal: signal number 159 * 160 * .. code-block:: c 161 * 162 * TEST_SIGNAL(name, signal) { implementation } 163 * 164 * Defines a test by name and the expected term signal. 165 * Names must be unique and tests must not be run in parallel. The 166 * implementation containing block is a function and scoping should be treated 167 * as such. Returning early may be performed with a bare "return;" statement. 168 * 169 * EXPECT_* and ASSERT_* are valid in a TEST() { } context. 170 */ 171 #define TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal) 172 173 #define __TEST_IMPL(test_name, _signal) \ 174 static void test_name(struct __test_metadata *_metadata); \ 175 static inline void wrapper_##test_name( \ 176 struct __test_metadata *_metadata, \ 177 struct __fixture_variant_metadata *variant) \ 178 { \ 179 _metadata->setup_completed = true; \ 180 if (setjmp(_metadata->env) == 0) \ 181 test_name(_metadata); \ 182 __test_check_assert(_metadata); \ 183 } \ 184 static struct __test_metadata _##test_name##_object = \ 185 { .name = #test_name, \ 186 .fn = &wrapper_##test_name, \ 187 .fixture = &_fixture_global, \ 188 .termsig = _signal, \ 189 .timeout = TEST_TIMEOUT_DEFAULT, }; \ 190 static void __attribute__((constructor)) _register_##test_name(void) \ 191 { \ 192 __register_test(&_##test_name##_object); \ 193 } \ 194 static void test_name( \ 195 struct __test_metadata __attribute__((unused)) *_metadata) 196 197 /** 198 * FIXTURE_DATA() - Wraps the struct name so we have one less 199 * argument to pass around 200 * 201 * @datatype_name: datatype name 202 * 203 * .. code-block:: c 204 * 205 * FIXTURE_DATA(datatype_name) 206 * 207 * Almost always, you want just FIXTURE() instead (see below). 208 * This call may be used when the type of the fixture data 209 * is needed. In general, this should not be needed unless 210 * the *self* is being passed to a helper directly. 211 */ 212 #define FIXTURE_DATA(datatype_name) struct _test_data_##datatype_name 213 214 /** 215 * FIXTURE() - Called once per fixture to setup the data and 216 * register 217 * 218 * @fixture_name: fixture name 219 * 220 * .. code-block:: c 221 * 222 * FIXTURE(fixture_name) { 223 * type property1; 224 * ... 225 * }; 226 * 227 * Defines the data provided to TEST_F()-defined tests as *self*. It should be 228 * populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN(). 229 */ 230 #define FIXTURE(fixture_name) \ 231 FIXTURE_VARIANT(fixture_name); \ 232 static struct __fixture_metadata _##fixture_name##_fixture_object = \ 233 { .name = #fixture_name, }; \ 234 static void __attribute__((constructor)) \ 235 _register_##fixture_name##_data(void) \ 236 { \ 237 __register_fixture(&_##fixture_name##_fixture_object); \ 238 } \ 239 FIXTURE_DATA(fixture_name) 240 241 /** 242 * FIXTURE_SETUP() - Prepares the setup function for the fixture. 243 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly. 244 * 245 * @fixture_name: fixture name 246 * 247 * .. code-block:: c 248 * 249 * FIXTURE_SETUP(fixture_name) { implementation } 250 * 251 * Populates the required "setup" function for a fixture. An instance of the 252 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the 253 * implementation. 254 * 255 * ASSERT_* are valid for use in this context and will prempt the execution 256 * of any dependent fixture tests. 257 * 258 * A bare "return;" statement may be used to return early. 259 */ 260 #define FIXTURE_SETUP(fixture_name) \ 261 void fixture_name##_setup( \ 262 struct __test_metadata __attribute__((unused)) *_metadata, \ 263 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \ 264 const FIXTURE_VARIANT(fixture_name) \ 265 __attribute__((unused)) *variant) 266 267 /** 268 * FIXTURE_TEARDOWN() 269 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly. 270 * 271 * @fixture_name: fixture name 272 * 273 * .. code-block:: c 274 * 275 * FIXTURE_TEARDOWN(fixture_name) { implementation } 276 * 277 * Populates the required "teardown" function for a fixture. An instance of the 278 * datatype defined with FIXTURE_DATA() will be exposed as *self* for the 279 * implementation to clean up. 280 * 281 * A bare "return;" statement may be used to return early. 282 */ 283 #define FIXTURE_TEARDOWN(fixture_name) \ 284 static const bool fixture_name##_teardown_parent; \ 285 __FIXTURE_TEARDOWN(fixture_name) 286 287 /** 288 * FIXTURE_TEARDOWN_PARENT() 289 * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly. 290 * 291 * @fixture_name: fixture name 292 * 293 * .. code-block:: c 294 * 295 * FIXTURE_TEARDOWN_PARENT(fixture_name) { implementation } 296 * 297 * Same as FIXTURE_TEARDOWN() but run this code in a parent process. This 298 * enables the test process to drop its privileges without impacting the 299 * related FIXTURE_TEARDOWN_PARENT() (e.g. to remove files from a directory 300 * where write access was dropped). 301 * 302 * To make it possible for the parent process to use *self*, share (MAP_SHARED) 303 * the fixture data between all forked processes. 304 */ 305 #define FIXTURE_TEARDOWN_PARENT(fixture_name) \ 306 static const bool fixture_name##_teardown_parent = true; \ 307 __FIXTURE_TEARDOWN(fixture_name) 308 309 #define __FIXTURE_TEARDOWN(fixture_name) \ 310 void fixture_name##_teardown( \ 311 struct __test_metadata __attribute__((unused)) *_metadata, \ 312 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \ 313 const FIXTURE_VARIANT(fixture_name) \ 314 __attribute__((unused)) *variant) 315 316 /** 317 * FIXTURE_VARIANT() - Optionally called once per fixture 318 * to declare fixture variant 319 * 320 * @fixture_name: fixture name 321 * 322 * .. code-block:: c 323 * 324 * FIXTURE_VARIANT(fixture_name) { 325 * type property1; 326 * ... 327 * }; 328 * 329 * Defines type of constant parameters provided to FIXTURE_SETUP(), TEST_F() and 330 * FIXTURE_TEARDOWN as *variant*. Variants allow the same tests to be run with 331 * different arguments. 332 */ 333 #define FIXTURE_VARIANT(fixture_name) struct _fixture_variant_##fixture_name 334 335 /** 336 * FIXTURE_VARIANT_ADD() - Called once per fixture 337 * variant to setup and register the data 338 * 339 * @fixture_name: fixture name 340 * @variant_name: name of the parameter set 341 * 342 * .. code-block:: c 343 * 344 * FIXTURE_VARIANT_ADD(fixture_name, variant_name) { 345 * .property1 = val1, 346 * ... 347 * }; 348 * 349 * Defines a variant of the test fixture, provided to FIXTURE_SETUP() and 350 * TEST_F() as *variant*. Tests of each fixture will be run once for each 351 * variant. 352 */ 353 #define FIXTURE_VARIANT_ADD(fixture_name, variant_name) \ 354 extern const FIXTURE_VARIANT(fixture_name) \ 355 _##fixture_name##_##variant_name##_variant; \ 356 static struct __fixture_variant_metadata \ 357 _##fixture_name##_##variant_name##_object = \ 358 { .name = #variant_name, \ 359 .data = &_##fixture_name##_##variant_name##_variant}; \ 360 static void __attribute__((constructor)) \ 361 _register_##fixture_name##_##variant_name(void) \ 362 { \ 363 __register_fixture_variant(&_##fixture_name##_fixture_object, \ 364 &_##fixture_name##_##variant_name##_object); \ 365 } \ 366 const FIXTURE_VARIANT(fixture_name) \ 367 _##fixture_name##_##variant_name##_variant = 368 369 /** 370 * TEST_F() - Emits test registration and helpers for 371 * fixture-based test cases 372 * 373 * @fixture_name: fixture name 374 * @test_name: test name 375 * 376 * .. code-block:: c 377 * 378 * TEST_F(fixture, name) { implementation } 379 * 380 * Defines a test that depends on a fixture (e.g., is part of a test case). 381 * Very similar to TEST() except that *self* is the setup instance of fixture's 382 * datatype exposed for use by the implementation. 383 * 384 * The _metadata object is shared (MAP_SHARED) with all the potential forked 385 * processes, which enables them to use EXCEPT_*() and ASSERT_*(). 386 * 387 * The *self* object is only shared with the potential forked processes if 388 * FIXTURE_TEARDOWN_PARENT() is used instead of FIXTURE_TEARDOWN(). 389 */ 390 #define TEST_F(fixture_name, test_name) \ 391 __TEST_F_IMPL(fixture_name, test_name, -1, TEST_TIMEOUT_DEFAULT) 392 393 #define TEST_F_SIGNAL(fixture_name, test_name, signal) \ 394 __TEST_F_IMPL(fixture_name, test_name, signal, TEST_TIMEOUT_DEFAULT) 395 396 #define TEST_F_TIMEOUT(fixture_name, test_name, timeout) \ 397 __TEST_F_IMPL(fixture_name, test_name, -1, timeout) 398 399 #define __TEST_F_IMPL(fixture_name, test_name, signal, tmout) \ 400 static void fixture_name##_##test_name( \ 401 struct __test_metadata *_metadata, \ 402 FIXTURE_DATA(fixture_name) *self, \ 403 const FIXTURE_VARIANT(fixture_name) *variant); \ 404 static inline void wrapper_##fixture_name##_##test_name( \ 405 struct __test_metadata *_metadata, \ 406 struct __fixture_variant_metadata *variant) \ 407 { \ 408 /* fixture data is alloced, setup, and torn down per call. */ \ 409 FIXTURE_DATA(fixture_name) self_private, *self = NULL; \ 410 pid_t child = 1; \ 411 int status = 0; \ 412 /* Makes sure there is only one teardown, even when child forks again. */ \ 413 bool *teardown = mmap(NULL, sizeof(*teardown), \ 414 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); \ 415 *teardown = false; \ 416 if (sizeof(*self) > 0) { \ 417 if (fixture_name##_teardown_parent) { \ 418 self = mmap(NULL, sizeof(*self), PROT_READ | PROT_WRITE, \ 419 MAP_SHARED | MAP_ANONYMOUS, -1, 0); \ 420 } else { \ 421 memset(&self_private, 0, sizeof(self_private)); \ 422 self = &self_private; \ 423 } \ 424 } \ 425 if (setjmp(_metadata->env) == 0) { \ 426 /* _metadata and potentially self are shared with all forks. */ \ 427 child = fork(); \ 428 if (child == 0) { \ 429 fixture_name##_setup(_metadata, self, variant->data); \ 430 /* Let setup failure terminate early. */ \ 431 if (_metadata->exit_code) \ 432 _exit(0); \ 433 _metadata->setup_completed = true; \ 434 fixture_name##_##test_name(_metadata, self, variant->data); \ 435 } else if (child < 0 || child != waitpid(child, &status, 0)) { \ 436 ksft_print_msg("ERROR SPAWNING TEST GRANDCHILD\n"); \ 437 _metadata->exit_code = KSFT_FAIL; \ 438 } \ 439 } \ 440 if (child == 0) { \ 441 if (_metadata->setup_completed && !fixture_name##_teardown_parent && \ 442 __sync_bool_compare_and_swap(teardown, false, true)) \ 443 fixture_name##_teardown(_metadata, self, variant->data); \ 444 _exit(0); \ 445 } \ 446 if (_metadata->setup_completed && fixture_name##_teardown_parent && \ 447 __sync_bool_compare_and_swap(teardown, false, true)) \ 448 fixture_name##_teardown(_metadata, self, variant->data); \ 449 munmap(teardown, sizeof(*teardown)); \ 450 if (self && fixture_name##_teardown_parent) \ 451 munmap(self, sizeof(*self)); \ 452 if (WIFEXITED(status)) { \ 453 if (WEXITSTATUS(status)) \ 454 _metadata->exit_code = WEXITSTATUS(status); \ 455 } else if (WIFSIGNALED(status)) { \ 456 /* Forward signal to __wait_for_test(). */ \ 457 kill(getpid(), WTERMSIG(status)); \ 458 } \ 459 __test_check_assert(_metadata); \ 460 } \ 461 static struct __test_metadata *_##fixture_name##_##test_name##_object; \ 462 static void __attribute__((constructor)) \ 463 _register_##fixture_name##_##test_name(void) \ 464 { \ 465 struct __test_metadata *object = mmap(NULL, sizeof(*object), \ 466 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); \ 467 object->name = #test_name; \ 468 object->fn = &wrapper_##fixture_name##_##test_name; \ 469 object->fixture = &_##fixture_name##_fixture_object; \ 470 object->termsig = signal; \ 471 object->timeout = tmout; \ 472 _##fixture_name##_##test_name##_object = object; \ 473 __register_test(object); \ 474 } \ 475 static void fixture_name##_##test_name( \ 476 struct __test_metadata __attribute__((unused)) *_metadata, \ 477 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \ 478 const FIXTURE_VARIANT(fixture_name) \ 479 __attribute__((unused)) *variant) 480 481 /** 482 * TEST_HARNESS_MAIN - Simple wrapper to run the test harness 483 * 484 * .. code-block:: c 485 * 486 * TEST_HARNESS_MAIN 487 * 488 * Use once to append a main() to the test file. 489 */ 490 #define TEST_HARNESS_MAIN \ 491 static void __attribute__((constructor)) \ 492 __constructor_order_last(void) \ 493 { \ 494 if (!__constructor_order) \ 495 __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \ 496 } \ 497 int main(int argc, char **argv) { \ 498 return test_harness_run(argc, argv); \ 499 } 500 501 /** 502 * DOC: operators 503 * 504 * Operators for use in TEST() and TEST_F(). 505 * ASSERT_* calls will stop test execution immediately. 506 * EXPECT_* calls will emit a failure warning, note it, and continue. 507 */ 508 509 /** 510 * ASSERT_EQ() 511 * 512 * @expected: expected value 513 * @seen: measured value 514 * 515 * ASSERT_EQ(expected, measured): expected == measured 516 */ 517 #define ASSERT_EQ(expected, seen) \ 518 __EXPECT(expected, #expected, seen, #seen, ==, 1) 519 520 /** 521 * ASSERT_NE() 522 * 523 * @expected: expected value 524 * @seen: measured value 525 * 526 * ASSERT_NE(expected, measured): expected != measured 527 */ 528 #define ASSERT_NE(expected, seen) \ 529 __EXPECT(expected, #expected, seen, #seen, !=, 1) 530 531 /** 532 * ASSERT_LT() 533 * 534 * @expected: expected value 535 * @seen: measured value 536 * 537 * ASSERT_LT(expected, measured): expected < measured 538 */ 539 #define ASSERT_LT(expected, seen) \ 540 __EXPECT(expected, #expected, seen, #seen, <, 1) 541 542 /** 543 * ASSERT_LE() 544 * 545 * @expected: expected value 546 * @seen: measured value 547 * 548 * ASSERT_LE(expected, measured): expected <= measured 549 */ 550 #define ASSERT_LE(expected, seen) \ 551 __EXPECT(expected, #expected, seen, #seen, <=, 1) 552 553 /** 554 * ASSERT_GT() 555 * 556 * @expected: expected value 557 * @seen: measured value 558 * 559 * ASSERT_GT(expected, measured): expected > measured 560 */ 561 #define ASSERT_GT(expected, seen) \ 562 __EXPECT(expected, #expected, seen, #seen, >, 1) 563 564 /** 565 * ASSERT_GE() 566 * 567 * @expected: expected value 568 * @seen: measured value 569 * 570 * ASSERT_GE(expected, measured): expected >= measured 571 */ 572 #define ASSERT_GE(expected, seen) \ 573 __EXPECT(expected, #expected, seen, #seen, >=, 1) 574 575 /** 576 * ASSERT_NULL() 577 * 578 * @seen: measured value 579 * 580 * ASSERT_NULL(measured): NULL == measured 581 */ 582 #define ASSERT_NULL(seen) \ 583 __EXPECT(NULL, "NULL", seen, #seen, ==, 1) 584 585 /** 586 * ASSERT_TRUE() 587 * 588 * @seen: measured value 589 * 590 * ASSERT_TRUE(measured): measured != 0 591 */ 592 #define ASSERT_TRUE(seen) \ 593 __EXPECT(0, "0", seen, #seen, !=, 1) 594 595 /** 596 * ASSERT_FALSE() 597 * 598 * @seen: measured value 599 * 600 * ASSERT_FALSE(measured): measured == 0 601 */ 602 #define ASSERT_FALSE(seen) \ 603 __EXPECT(0, "0", seen, #seen, ==, 1) 604 605 /** 606 * ASSERT_STREQ() 607 * 608 * @expected: expected value 609 * @seen: measured value 610 * 611 * ASSERT_STREQ(expected, measured): !strcmp(expected, measured) 612 */ 613 #define ASSERT_STREQ(expected, seen) \ 614 __EXPECT_STR(expected, seen, ==, 1) 615 616 /** 617 * ASSERT_STRNE() 618 * 619 * @expected: expected value 620 * @seen: measured value 621 * 622 * ASSERT_STRNE(expected, measured): strcmp(expected, measured) 623 */ 624 #define ASSERT_STRNE(expected, seen) \ 625 __EXPECT_STR(expected, seen, !=, 1) 626 627 /** 628 * EXPECT_EQ() 629 * 630 * @expected: expected value 631 * @seen: measured value 632 * 633 * EXPECT_EQ(expected, measured): expected == measured 634 */ 635 #define EXPECT_EQ(expected, seen) \ 636 __EXPECT(expected, #expected, seen, #seen, ==, 0) 637 638 /** 639 * EXPECT_NE() 640 * 641 * @expected: expected value 642 * @seen: measured value 643 * 644 * EXPECT_NE(expected, measured): expected != measured 645 */ 646 #define EXPECT_NE(expected, seen) \ 647 __EXPECT(expected, #expected, seen, #seen, !=, 0) 648 649 /** 650 * EXPECT_LT() 651 * 652 * @expected: expected value 653 * @seen: measured value 654 * 655 * EXPECT_LT(expected, measured): expected < measured 656 */ 657 #define EXPECT_LT(expected, seen) \ 658 __EXPECT(expected, #expected, seen, #seen, <, 0) 659 660 /** 661 * EXPECT_LE() 662 * 663 * @expected: expected value 664 * @seen: measured value 665 * 666 * EXPECT_LE(expected, measured): expected <= measured 667 */ 668 #define EXPECT_LE(expected, seen) \ 669 __EXPECT(expected, #expected, seen, #seen, <=, 0) 670 671 /** 672 * EXPECT_GT() 673 * 674 * @expected: expected value 675 * @seen: measured value 676 * 677 * EXPECT_GT(expected, measured): expected > measured 678 */ 679 #define EXPECT_GT(expected, seen) \ 680 __EXPECT(expected, #expected, seen, #seen, >, 0) 681 682 /** 683 * EXPECT_GE() 684 * 685 * @expected: expected value 686 * @seen: measured value 687 * 688 * EXPECT_GE(expected, measured): expected >= measured 689 */ 690 #define EXPECT_GE(expected, seen) \ 691 __EXPECT(expected, #expected, seen, #seen, >=, 0) 692 693 /** 694 * EXPECT_NULL() 695 * 696 * @seen: measured value 697 * 698 * EXPECT_NULL(measured): NULL == measured 699 */ 700 #define EXPECT_NULL(seen) \ 701 __EXPECT(NULL, "NULL", seen, #seen, ==, 0) 702 703 /** 704 * EXPECT_TRUE() 705 * 706 * @seen: measured value 707 * 708 * EXPECT_TRUE(measured): 0 != measured 709 */ 710 #define EXPECT_TRUE(seen) \ 711 __EXPECT(0, "0", seen, #seen, !=, 0) 712 713 /** 714 * EXPECT_FALSE() 715 * 716 * @seen: measured value 717 * 718 * EXPECT_FALSE(measured): 0 == measured 719 */ 720 #define EXPECT_FALSE(seen) \ 721 __EXPECT(0, "0", seen, #seen, ==, 0) 722 723 /** 724 * EXPECT_STREQ() 725 * 726 * @expected: expected value 727 * @seen: measured value 728 * 729 * EXPECT_STREQ(expected, measured): !strcmp(expected, measured) 730 */ 731 #define EXPECT_STREQ(expected, seen) \ 732 __EXPECT_STR(expected, seen, ==, 0) 733 734 /** 735 * EXPECT_STRNE() 736 * 737 * @expected: expected value 738 * @seen: measured value 739 * 740 * EXPECT_STRNE(expected, measured): strcmp(expected, measured) 741 */ 742 #define EXPECT_STRNE(expected, seen) \ 743 __EXPECT_STR(expected, seen, !=, 0) 744 745 #ifndef ARRAY_SIZE 746 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) 747 #endif 748 749 /* Support an optional handler after and ASSERT_* or EXPECT_*. The approach is 750 * not thread-safe, but it should be fine in most sane test scenarios. 751 * 752 * Using __bail(), which optionally abort()s, is the easiest way to early 753 * return while still providing an optional block to the API consumer. 754 */ 755 #define OPTIONAL_HANDLER(_assert) \ 756 for (; _metadata->trigger; _metadata->trigger = \ 757 __bail(_assert, _metadata)) 758 759 #define is_signed_type(var) (!!(((__typeof__(var))(-1)) < (__typeof__(var))1)) 760 761 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \ 762 /* Avoid multiple evaluation of the cases */ \ 763 __typeof__(_expected) __exp = (_expected); \ 764 __typeof__(_seen) __seen = (_seen); \ 765 if (!(__exp _t __seen)) { \ 766 /* Report with actual signedness to avoid weird output. */ \ 767 switch (is_signed_type(__exp) * 2 + is_signed_type(__seen)) { \ 768 case 0: { \ 769 unsigned long long __exp_print = (uintptr_t)__exp; \ 770 unsigned long long __seen_print = (uintptr_t)__seen; \ 771 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \ 772 _expected_str, __exp_print, #_t, \ 773 _seen_str, __seen_print); \ 774 break; \ 775 } \ 776 case 1: { \ 777 unsigned long long __exp_print = (uintptr_t)__exp; \ 778 long long __seen_print = (intptr_t)__seen; \ 779 __TH_LOG("Expected %s (%llu) %s %s (%lld)", \ 780 _expected_str, __exp_print, #_t, \ 781 _seen_str, __seen_print); \ 782 break; \ 783 } \ 784 case 2: { \ 785 long long __exp_print = (intptr_t)__exp; \ 786 unsigned long long __seen_print = (uintptr_t)__seen; \ 787 __TH_LOG("Expected %s (%lld) %s %s (%llu)", \ 788 _expected_str, __exp_print, #_t, \ 789 _seen_str, __seen_print); \ 790 break; \ 791 } \ 792 case 3: { \ 793 long long __exp_print = (intptr_t)__exp; \ 794 long long __seen_print = (intptr_t)__seen; \ 795 __TH_LOG("Expected %s (%lld) %s %s (%lld)", \ 796 _expected_str, __exp_print, #_t, \ 797 _seen_str, __seen_print); \ 798 break; \ 799 } \ 800 } \ 801 _metadata->exit_code = KSFT_FAIL; \ 802 /* Ensure the optional handler is triggered */ \ 803 _metadata->trigger = 1; \ 804 } \ 805 } while (0); OPTIONAL_HANDLER(_assert) 806 807 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \ 808 const char *__exp = (_expected); \ 809 const char *__seen = (_seen); \ 810 if (!(strcmp(__exp, __seen) _t 0)) { \ 811 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \ 812 _metadata->exit_code = KSFT_FAIL; \ 813 _metadata->trigger = 1; \ 814 } \ 815 } while (0); OPTIONAL_HANDLER(_assert) 816 817 /* List helpers */ 818 #define __LIST_APPEND(head, item) \ 819 { \ 820 /* Circular linked list where only prev is circular. */ \ 821 if (head == NULL) { \ 822 head = item; \ 823 item->next = NULL; \ 824 item->prev = item; \ 825 return; \ 826 } \ 827 if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \ 828 item->next = NULL; \ 829 item->prev = head->prev; \ 830 item->prev->next = item; \ 831 head->prev = item; \ 832 } else { \ 833 item->next = head; \ 834 item->next->prev = item; \ 835 item->prev = item; \ 836 head = item; \ 837 } \ 838 } 839 840 struct __test_results { 841 char reason[1024]; /* Reason for test result */ 842 }; 843 844 struct __test_metadata; 845 struct __fixture_variant_metadata; 846 847 /* Contains all the information about a fixture. */ 848 struct __fixture_metadata { 849 const char *name; 850 struct __test_metadata *tests; 851 struct __fixture_variant_metadata *variant; 852 struct __fixture_metadata *prev, *next; 853 } _fixture_global __attribute__((unused)) = { 854 .name = "global", 855 .prev = &_fixture_global, 856 }; 857 858 struct __test_xfail { 859 struct __fixture_metadata *fixture; 860 struct __fixture_variant_metadata *variant; 861 struct __test_metadata *test; 862 struct __test_xfail *prev, *next; 863 }; 864 865 /** 866 * XFAIL_ADD() - mark variant + test case combination as expected to fail 867 * @fixture_name: name of the fixture 868 * @variant_name: name of the variant 869 * @test_name: name of the test case 870 * 871 * Mark a combination of variant + test case for a given fixture as expected 872 * to fail. Tests marked this way will report XPASS / XFAIL return codes, 873 * instead of PASS / FAIL,and use respective counters. 874 */ 875 #define XFAIL_ADD(fixture_name, variant_name, test_name) \ 876 static struct __test_xfail \ 877 _##fixture_name##_##variant_name##_##test_name##_xfail = \ 878 { \ 879 .fixture = &_##fixture_name##_fixture_object, \ 880 .variant = &_##fixture_name##_##variant_name##_object, \ 881 }; \ 882 static void __attribute__((constructor)) \ 883 _register_##fixture_name##_##variant_name##_##test_name##_xfail(void) \ 884 { \ 885 _##fixture_name##_##variant_name##_##test_name##_xfail.test = \ 886 _##fixture_name##_##test_name##_object; \ 887 __register_xfail(&_##fixture_name##_##variant_name##_##test_name##_xfail); \ 888 } 889 890 static struct __fixture_metadata *__fixture_list = &_fixture_global; 891 static int __constructor_order; 892 893 #define _CONSTRUCTOR_ORDER_FORWARD 1 894 #define _CONSTRUCTOR_ORDER_BACKWARD -1 895 896 static inline void __register_fixture(struct __fixture_metadata *f) 897 { 898 __LIST_APPEND(__fixture_list, f); 899 } 900 901 struct __fixture_variant_metadata { 902 const char *name; 903 const void *data; 904 struct __test_xfail *xfails; 905 struct __fixture_variant_metadata *prev, *next; 906 }; 907 908 static inline void 909 __register_fixture_variant(struct __fixture_metadata *f, 910 struct __fixture_variant_metadata *variant) 911 { 912 __LIST_APPEND(f->variant, variant); 913 } 914 915 /* Contains all the information for test execution and status checking. */ 916 struct __test_metadata { 917 const char *name; 918 void (*fn)(struct __test_metadata *, 919 struct __fixture_variant_metadata *); 920 pid_t pid; /* pid of test when being run */ 921 struct __fixture_metadata *fixture; 922 int termsig; 923 int exit_code; 924 int trigger; /* extra handler after the evaluation */ 925 int timeout; /* seconds to wait for test timeout */ 926 bool timed_out; /* did this test timeout instead of exiting? */ 927 bool aborted; /* stopped test due to failed ASSERT */ 928 bool setup_completed; /* did setup finish? */ 929 jmp_buf env; /* for exiting out of test early */ 930 struct __test_results *results; 931 struct __test_metadata *prev, *next; 932 }; 933 934 static inline bool __test_passed(struct __test_metadata *metadata) 935 { 936 return metadata->exit_code != KSFT_FAIL && 937 metadata->exit_code <= KSFT_SKIP; 938 } 939 940 /* 941 * Since constructors are called in reverse order, reverse the test 942 * list so tests are run in source declaration order. 943 * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html 944 * However, it seems not all toolchains do this correctly, so use 945 * __constructor_order to detect which direction is called first 946 * and adjust list building logic to get things running in the right 947 * direction. 948 */ 949 static inline void __register_test(struct __test_metadata *t) 950 { 951 __LIST_APPEND(t->fixture->tests, t); 952 } 953 954 static inline void __register_xfail(struct __test_xfail *xf) 955 { 956 __LIST_APPEND(xf->variant->xfails, xf); 957 } 958 959 static inline int __bail(int for_realz, struct __test_metadata *t) 960 { 961 /* if this is ASSERT, return immediately. */ 962 if (for_realz) { 963 t->aborted = true; 964 longjmp(t->env, 1); 965 } 966 /* otherwise, end the for loop and continue. */ 967 return 0; 968 } 969 970 static inline void __test_check_assert(struct __test_metadata *t) 971 { 972 if (t->aborted) 973 abort(); 974 } 975 976 struct __test_metadata *__active_test; 977 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext) 978 { 979 struct __test_metadata *t = __active_test; 980 981 /* Sanity check handler execution environment. */ 982 if (!t) { 983 fprintf(TH_LOG_STREAM, 984 "# no active test in SIGALRM handler!?\n"); 985 abort(); 986 } 987 if (sig != SIGALRM || sig != info->si_signo) { 988 fprintf(TH_LOG_STREAM, 989 "# %s: SIGALRM handler caught signal %d!?\n", 990 t->name, sig != SIGALRM ? sig : info->si_signo); 991 abort(); 992 } 993 994 t->timed_out = true; 995 // signal process group 996 kill(-(t->pid), SIGKILL); 997 } 998 999 void __wait_for_test(struct __test_metadata *t) 1000 { 1001 struct sigaction action = { 1002 .sa_sigaction = __timeout_handler, 1003 .sa_flags = SA_SIGINFO, 1004 }; 1005 struct sigaction saved_action; 1006 /* 1007 * Sets status so that WIFEXITED(status) returns true and 1008 * WEXITSTATUS(status) returns KSFT_FAIL. This safe default value 1009 * should never be evaluated because of the waitpid(2) check and 1010 * SIGALRM handling. 1011 */ 1012 int status = KSFT_FAIL << 8; 1013 int child; 1014 1015 if (sigaction(SIGALRM, &action, &saved_action)) { 1016 t->exit_code = KSFT_FAIL; 1017 fprintf(TH_LOG_STREAM, 1018 "# %s: unable to install SIGALRM handler\n", 1019 t->name); 1020 return; 1021 } 1022 __active_test = t; 1023 t->timed_out = false; 1024 alarm(t->timeout); 1025 child = waitpid(t->pid, &status, 0); 1026 if (child == -1 && errno != EINTR) { 1027 t->exit_code = KSFT_FAIL; 1028 fprintf(TH_LOG_STREAM, 1029 "# %s: Failed to wait for PID %d (errno: %d)\n", 1030 t->name, t->pid, errno); 1031 return; 1032 } 1033 1034 alarm(0); 1035 if (sigaction(SIGALRM, &saved_action, NULL)) { 1036 t->exit_code = KSFT_FAIL; 1037 fprintf(TH_LOG_STREAM, 1038 "# %s: unable to uninstall SIGALRM handler\n", 1039 t->name); 1040 return; 1041 } 1042 __active_test = NULL; 1043 1044 if (t->timed_out) { 1045 t->exit_code = KSFT_FAIL; 1046 fprintf(TH_LOG_STREAM, 1047 "# %s: Test terminated by timeout\n", t->name); 1048 } else if (WIFEXITED(status)) { 1049 if (WEXITSTATUS(status) == KSFT_SKIP || 1050 WEXITSTATUS(status) == KSFT_XPASS || 1051 WEXITSTATUS(status) == KSFT_XFAIL) { 1052 t->exit_code = WEXITSTATUS(status); 1053 } else if (t->termsig != -1) { 1054 t->exit_code = KSFT_FAIL; 1055 fprintf(TH_LOG_STREAM, 1056 "# %s: Test exited normally instead of by signal (code: %d)\n", 1057 t->name, 1058 WEXITSTATUS(status)); 1059 } else { 1060 switch (WEXITSTATUS(status)) { 1061 /* Success */ 1062 case KSFT_PASS: 1063 t->exit_code = KSFT_PASS; 1064 break; 1065 /* Failure */ 1066 default: 1067 t->exit_code = KSFT_FAIL; 1068 fprintf(TH_LOG_STREAM, 1069 "# %s: Test failed\n", 1070 t->name); 1071 } 1072 } 1073 } else if (WIFSIGNALED(status)) { 1074 t->exit_code = KSFT_FAIL; 1075 if (WTERMSIG(status) == SIGABRT) { 1076 fprintf(TH_LOG_STREAM, 1077 "# %s: Test terminated by assertion\n", 1078 t->name); 1079 } else if (WTERMSIG(status) == t->termsig) { 1080 t->exit_code = KSFT_PASS; 1081 } else { 1082 fprintf(TH_LOG_STREAM, 1083 "# %s: Test terminated unexpectedly by signal %d\n", 1084 t->name, 1085 WTERMSIG(status)); 1086 } 1087 } else { 1088 t->exit_code = KSFT_FAIL; 1089 fprintf(TH_LOG_STREAM, 1090 "# %s: Test ended in some other way [%u]\n", 1091 t->name, 1092 status); 1093 } 1094 } 1095 1096 static void test_harness_list_tests(void) 1097 { 1098 struct __fixture_variant_metadata *v; 1099 struct __fixture_metadata *f; 1100 struct __test_metadata *t; 1101 1102 for (f = __fixture_list; f; f = f->next) { 1103 v = f->variant; 1104 t = f->tests; 1105 1106 if (f == __fixture_list) 1107 fprintf(stderr, "%-20s %-25s %s\n", 1108 "# FIXTURE", "VARIANT", "TEST"); 1109 else 1110 fprintf(stderr, "--------------------------------------------------------------------------------\n"); 1111 1112 do { 1113 fprintf(stderr, "%-20s %-25s %s\n", 1114 t == f->tests ? f->name : "", 1115 v ? v->name : "", 1116 t ? t->name : ""); 1117 1118 v = v ? v->next : NULL; 1119 t = t ? t->next : NULL; 1120 } while (v || t); 1121 } 1122 } 1123 1124 static int test_harness_argv_check(int argc, char **argv) 1125 { 1126 int opt; 1127 1128 while ((opt = getopt(argc, argv, "hlF:f:V:v:t:T:r:")) != -1) { 1129 switch (opt) { 1130 case 'f': 1131 case 'F': 1132 case 'v': 1133 case 'V': 1134 case 't': 1135 case 'T': 1136 case 'r': 1137 break; 1138 case 'l': 1139 test_harness_list_tests(); 1140 return KSFT_SKIP; 1141 case 'h': 1142 default: 1143 fprintf(stderr, 1144 "Usage: %s [-h|-l] [-t|-T|-v|-V|-f|-F|-r name]\n" 1145 "\t-h print help\n" 1146 "\t-l list all tests\n" 1147 "\n" 1148 "\t-t name include test\n" 1149 "\t-T name exclude test\n" 1150 "\t-v name include variant\n" 1151 "\t-V name exclude variant\n" 1152 "\t-f name include fixture\n" 1153 "\t-F name exclude fixture\n" 1154 "\t-r name run specified test\n" 1155 "\n" 1156 "Test filter options can be specified " 1157 "multiple times. The filtering stops\n" 1158 "at the first match. For example to " 1159 "include all tests from variant 'bla'\n" 1160 "but not test 'foo' specify '-T foo -v bla'.\n" 1161 "", argv[0]); 1162 return opt == 'h' ? KSFT_SKIP : KSFT_FAIL; 1163 } 1164 } 1165 1166 return KSFT_PASS; 1167 } 1168 1169 static bool test_enabled(int argc, char **argv, 1170 struct __fixture_metadata *f, 1171 struct __fixture_variant_metadata *v, 1172 struct __test_metadata *t) 1173 { 1174 unsigned int flen = 0, vlen = 0, tlen = 0; 1175 bool has_positive = false; 1176 int opt; 1177 1178 optind = 1; 1179 while ((opt = getopt(argc, argv, "F:f:V:v:t:T:r:")) != -1) { 1180 has_positive |= islower(opt); 1181 1182 switch (tolower(opt)) { 1183 case 't': 1184 if (!strcmp(t->name, optarg)) 1185 return islower(opt); 1186 break; 1187 case 'f': 1188 if (!strcmp(f->name, optarg)) 1189 return islower(opt); 1190 break; 1191 case 'v': 1192 if (!strcmp(v->name, optarg)) 1193 return islower(opt); 1194 break; 1195 case 'r': 1196 if (!tlen) { 1197 flen = strlen(f->name); 1198 vlen = strlen(v->name); 1199 tlen = strlen(t->name); 1200 } 1201 if (strlen(optarg) == flen + 1 + vlen + !!vlen + tlen && 1202 !strncmp(f->name, &optarg[0], flen) && 1203 !strncmp(v->name, &optarg[flen + 1], vlen) && 1204 !strncmp(t->name, &optarg[flen + 1 + vlen + !!vlen], tlen)) 1205 return true; 1206 break; 1207 } 1208 } 1209 1210 /* 1211 * If there are no positive tests then we assume user just wants 1212 * exclusions and everything else is a pass. 1213 */ 1214 return !has_positive; 1215 } 1216 1217 void __run_test(struct __fixture_metadata *f, 1218 struct __fixture_variant_metadata *variant, 1219 struct __test_metadata *t) 1220 { 1221 struct __test_xfail *xfail; 1222 char test_name[1024]; 1223 const char *diagnostic; 1224 int child; 1225 1226 /* reset test struct */ 1227 t->exit_code = KSFT_PASS; 1228 t->trigger = 0; 1229 t->aborted = false; 1230 t->setup_completed = false; 1231 memset(t->env, 0, sizeof(t->env)); 1232 memset(t->results->reason, 0, sizeof(t->results->reason)); 1233 1234 snprintf(test_name, sizeof(test_name), "%s%s%s.%s", 1235 f->name, variant->name[0] ? "." : "", variant->name, t->name); 1236 1237 ksft_print_msg(" RUN %s ...\n", test_name); 1238 1239 /* Make sure output buffers are flushed before fork */ 1240 fflush(stdout); 1241 fflush(stderr); 1242 1243 child = fork(); 1244 if (child < 0) { 1245 ksft_print_msg("ERROR SPAWNING TEST CHILD\n"); 1246 t->exit_code = KSFT_FAIL; 1247 } else if (child == 0) { 1248 setpgrp(); 1249 t->fn(t, variant); 1250 _exit(t->exit_code); 1251 } else { 1252 t->pid = child; 1253 __wait_for_test(t); 1254 } 1255 ksft_print_msg(" %4s %s\n", 1256 __test_passed(t) ? "OK" : "FAIL", test_name); 1257 1258 /* Check if we're expecting this test to fail */ 1259 for (xfail = variant->xfails; xfail; xfail = xfail->next) 1260 if (xfail->test == t) 1261 break; 1262 if (xfail) 1263 t->exit_code = __test_passed(t) ? KSFT_XPASS : KSFT_XFAIL; 1264 1265 if (t->results->reason[0]) 1266 diagnostic = t->results->reason; 1267 else if (t->exit_code == KSFT_PASS || t->exit_code == KSFT_FAIL) 1268 diagnostic = NULL; 1269 else 1270 diagnostic = "unknown"; 1271 1272 ksft_test_result_code(t->exit_code, test_name, 1273 diagnostic ? "%s" : NULL, diagnostic); 1274 } 1275 1276 static int test_harness_run(int argc, char **argv) 1277 { 1278 struct __fixture_variant_metadata no_variant = { .name = "", }; 1279 struct __fixture_variant_metadata *v; 1280 struct __fixture_metadata *f; 1281 struct __test_results *results; 1282 struct __test_metadata *t; 1283 int ret; 1284 unsigned int case_count = 0, test_count = 0; 1285 unsigned int count = 0; 1286 unsigned int pass_count = 0; 1287 1288 ret = test_harness_argv_check(argc, argv); 1289 if (ret != KSFT_PASS) 1290 return ret; 1291 1292 for (f = __fixture_list; f; f = f->next) { 1293 for (v = f->variant ?: &no_variant; v; v = v->next) { 1294 unsigned int old_tests = test_count; 1295 1296 for (t = f->tests; t; t = t->next) 1297 if (test_enabled(argc, argv, f, v, t)) 1298 test_count++; 1299 1300 if (old_tests != test_count) 1301 case_count++; 1302 } 1303 } 1304 1305 results = mmap(NULL, sizeof(*results), PROT_READ | PROT_WRITE, 1306 MAP_SHARED | MAP_ANONYMOUS, -1, 0); 1307 1308 ksft_print_header(); 1309 ksft_set_plan(test_count); 1310 ksft_print_msg("Starting %u tests from %u test cases.\n", 1311 test_count, case_count); 1312 for (f = __fixture_list; f; f = f->next) { 1313 for (v = f->variant ?: &no_variant; v; v = v->next) { 1314 for (t = f->tests; t; t = t->next) { 1315 if (!test_enabled(argc, argv, f, v, t)) 1316 continue; 1317 count++; 1318 t->results = results; 1319 __run_test(f, v, t); 1320 t->results = NULL; 1321 if (__test_passed(t)) 1322 pass_count++; 1323 else 1324 ret = 1; 1325 } 1326 } 1327 } 1328 munmap(results, sizeof(*results)); 1329 1330 ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED", 1331 pass_count, count); 1332 ksft_exit(ret == 0); 1333 1334 /* unreachable */ 1335 return KSFT_FAIL; 1336 } 1337 1338 static void __attribute__((constructor)) __constructor_order_first(void) 1339 { 1340 if (!__constructor_order) 1341 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD; 1342 } 1343 1344 #endif /* __KSELFTEST_HARNESS_H */ 1345