kunit: test: added concept of initcalls

Added a way to add plugins that require a test module to be loaded
during initialization.

Change-Id: I1d03f8249631a91b0334ccbe0b06889f3678caff
Signed-off-by: Brendan Higgins <brendanhiggins@google.com>
diff --git a/include/test/test.h b/include/test/test.h
index 7d257d3..96bdef04 100644
--- a/include/test/test.h
+++ b/include/test/test.h
@@ -139,6 +139,12 @@
 	struct test_case *test_cases;
 };
 
+struct test_initcall {
+	struct list_head node;
+	int (*init)(struct test_initcall *this, struct test *test);
+	void (*exit)(struct test_initcall *this);
+};
+
 /**
  * struct test - represents a running instance of a test.
  * @priv: for user to store arbitrary data. Commonly used to pass data created
@@ -167,6 +173,19 @@
 
 int test_run_tests(struct test_module *module);
 
+void test_install_initcall(struct test_initcall *initcall);
+
+#define test_pure_initcall(fn) postcore_initcall(fn)
+
+#define test_register_initcall(initcall) \
+		static int register_test_initcall_##initcall(void) \
+		{ \
+			test_install_initcall(&initcall); \
+			\
+			return 0; \
+		} \
+		test_pure_initcall(register_test_initcall_##initcall)
+
 /**
  * module_test() - used to register a &struct test_module with KUnit.
  * @module: a statically allocated &struct test_module.
diff --git a/test/test.c b/test/test.c
index 6fefab3..1c077e9 100644
--- a/test/test.c
+++ b/test/test.c
@@ -3,6 +3,19 @@
 #include <os.h>
 #include <test/test.h>
 
+struct test_global_context {
+	struct list_head initcalls;
+};
+
+static struct test_global_context test_global_context = {
+	.initcalls = LIST_HEAD_INIT(test_global_context.initcalls),
+};
+
+void test_install_initcall(struct test_initcall *initcall)
+{
+	list_add_tail(&initcall->node, &test_global_context.initcalls);
+}
+
 static int test_vprintk_emit(const struct test *test,
 			     int level,
 			     const char *fmt,
@@ -78,8 +91,18 @@
 				   struct test_module *module,
 				   struct test_case *test_case)
 {
+	struct test_initcall *initcall;
 	int ret;
 
+	list_for_each_entry(initcall, &test_global_context.initcalls, node) {
+		ret = initcall->init(initcall, test);
+		if (ret) {
+			test_err(test, "failed to initialize: %d", ret);
+			test->success = false;
+			return;
+		}
+	}
+
 	if (module->init) {
 		ret = module->init(test);
 		if (ret) {
@@ -94,6 +117,12 @@
 
 static void test_case_internal_cleanup(struct test *test)
 {
+	struct test_initcall *initcall;
+
+	list_for_each_entry(initcall, &test_global_context.initcalls, node) {
+		initcall->exit(initcall);
+	}
+
 	test_cleanup(test);
 }