Currently the code always calls kunit_do_assertion() even though it does nothing when `pass` is true. This change moves the `if(!(pass))` check into the macro instead and renames the function to kunit_do_failed_assertion(). I feel this a bit easier to read and understand. This has the potential upside of avoiding a function call that does nothing most of the time (assuming your tests are passing) but comes with the downside of generating a bit more code and branches. We try to mitigate the branches by tagging them with `unlikely()`. This also means we don't have to initialize structs that we don't need, which will become a tiny bit more expensive if we switch over to using static variables to try and reduce stack usage. (There's runtime code to check if the variable has been initialized yet or not).
Showing the changes to include (1 of 2 files). Show all
Unified · Split
| @@ -12,6 +12,7 @@ · 11 unmodified lines | |||
| 12 | #include <kunit/assert.h> | 12 | #include <kunit/assert.h> |
| 13 | #include <kunit/try-catch.h> | 13 | #include <kunit/try-catch.h> |
| 14 | 14 | ||
| 15 | #include <linux/compiler.h> | ||
| 15 | #include <linux/container_of.h> | 16 | #include <linux/container_of.h> |
| 16 | #include <linux/err.h> | 17 | #include <linux/err.h> |
| 17 | #include <linux/init.h> | 18 | #include <linux/init.h> |
| @@ -770,18 +771,18 @@ void __printf(2, 3) kunit_log_append(char *log, const char *fmt, ...); · 752 unmodified lines | |||
| 770 | */ | 771 | */ |
| 771 | #define KUNIT_SUCCEED(test) do {} while (0) | 772 | #define KUNIT_SUCCEED(test) do {} while (0) |
| 772 | 773 | ||
| 773 | void kunit_do_assertion(struct kunit *test, | 774 | void kunit_do_failed_assertion(struct kunit *test, |
| 774 | struct kunit_assert *assert, | 775 | struct kunit_assert *assert, |
| 775 | bool pass, | 776 | const char *fmt, ...); |
| 776 | const char *fmt, ...); | ||
| 777 | 777 | ||
| 778 | #define KUNIT_ASSERTION(test, pass, assert_class, INITIALIZER, fmt, ...) do { \ | 778 | #define KUNIT_ASSERTION(test, pass, assert_class, INITIALIZER, fmt, ...) do { \ |
| 779 | struct assert_class __assertion = INITIALIZER; \ | 779 | if (unlikely(!(pass))) { \ |
| 780 | kunit_do_assertion(test, \ | 780 | struct assert_class __assertion = INITIALIZER; \ |
| 781 | &__assertion.assert, \ | 781 | kunit_do_failed_assertion(test, \ |
| 782 | pass, \ | 782 | &__assertion.assert, \ |
| 783 | fmt, \ | 783 | fmt, \ |
| 784 | ##__VA_ARGS__); \ | 784 | ##__VA_ARGS__); \ |
| 785 | } \ | ||
| 785 | } while (0) | 786 | } while (0) |
| 786 | 787 | ||
| 787 | 788 | ||