[PATCH v2 1/2] kunit: add extra assertions to KUnit test cases

Malte Wechter <[email protected]>
Newsgroups org.kernel.vger.rust-for-linux,org.kernel.vger.linux-kernel,org.kernel.vger.linux-kselftest
Message-ID <[email protected]>
add extra assertions for each individual test case, that checks that
both `debug_locks` and `TAINT_WARN` are intact after the test is run.
The assertions are optional behind CONFIG_KUNIT_EXTRA_ASSERTS.

Signed-off-by: Malte Wechter <[email protected]>
---
 lib/kunit/Kconfig     | 12 ++++++++++++
 lib/kunit/try-catch.c | 23 ++++++++++++++++++++++-
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/lib/kunit/Kconfig b/lib/kunit/Kconfig
index 94ff8e4089bfb..38801f7493669 100644
--- a/lib/kunit/Kconfig
+++ b/lib/kunit/Kconfig
@@ -142,4 +142,16 @@ config KUNIT_UML_PCI
 
 	  If unsure, say N.
 
+config KUNIT_EXTRA_ASSERTS
+	bool "Enable extra assertions in KUnit tests"
+	depends on LOCKDEP
+	default n
+	help
+		Enables all extra assertions for KUnit which includes asserting `TAINT_WARN` and
+		`debug_locks` from lockdep. A KUnit test suite (and test case) is inserted
+		at the start of all KUnit test suites. This makes assertions prior to running any
+		tests, as a pre-test integrity check. Assertions are made after each test case which
+		asserts that each test case did not trigger either `TAINT_WARN` or `debug_locks`.
+
+		If unsure, say N.
 endif # KUNIT
diff --git a/lib/kunit/try-catch.c b/lib/kunit/try-catch.c
index d84a879f0a789..7eea3af4c9671 100644
--- a/lib/kunit/try-catch.c
+++ b/lib/kunit/try-catch.c
@@ -41,6 +41,11 @@ void kunit_try_catch_run(struct kunit_try_catch *try_catch, void *context)
 	struct completion *task_done;
 	int exit_code, time_remaining;
 
+	#ifdef CONFIG_KUNIT_EXTRA_ASSERTS
+	int debug_locks_snapshot = debug_locks;
+	int tainted_warn_snapshot = test_taint(TAINT_WARN);
+	#endif
+
 	try_catch->context = context;
 	try_catch->try_result = 0;
 	task_struct = kthread_create(kunit_generic_run_threadfn_adapter,
@@ -70,7 +75,23 @@ void kunit_try_catch_run(struct kunit_try_catch *try_catch, void *context)
 	put_task_struct(task_struct);
 	exit_code = try_catch->try_result;
 
-	if (!exit_code)
+	#ifdef CONFIG_KUNIT_EXTRA_ASSERTS
+	bool extra_assert = false;
+
+	if (debug_locks_snapshot != debug_locks && !exit_code) {
+		extra_assert = true;
+		try_catch->try_result = -EDEADLK;
+		kunit_err(test, "Test triggered lockdep\n");
+	} else if (tainted_warn_snapshot != test_taint(TAINT_WARN) && !exit_code) {
+		extra_assert = true;
+		try_catch->try_result = -EDEADLK;
+		kunit_err(test, "Test tainted kernel with TAINT_WARN\n");
+	}
+	#else
+	bool extra_assert = false;
+	#endif
+
+	if (!exit_code && !extra_assert)
 		return;
 
 	if (exit_code == -EFAULT)

-- 
2.51.2
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.