Skip to contentSkip to conversation

kunit: introduce KUnit, the Linux kernel unit testing framework

PATCH Superseded Brendan Higgins 7 participants 60 messages Jun 17, 2019 – Jul 3, 2019

Subsystems (12)
Documentation VFS Kbuild Kselftest +8 more subsystems

v5 of 18 Superseded Latest is v18 →

lore
Share & tools
lore
#0 lore raw

v5 cover kunit: introduce KUnit, the Linux kernel unit testing framework

## TL;DR

A not so quick follow-up to Stephen's suggestions on PATCH v4. Nothing that really changes any functionality or usage with the minor exception of a couple public functions that Stephen asked me to rename. Nevertheless, a good deal of clean up and fixes. See changes below.

As for our current status, right now we got Reviewed-bys on all patches except:

- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list

However, it would probably be good to get reviews/acks from the subsystem maintainers on:

- [PATCH v5 06/18] kbuild: enable building KUnit
- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list
- [PATCH v5 15/18] Documentation: kunit: add documentation for KUnit
- [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()
- [PATCH v5 18/18] MAINTAINERS: add proc sysctl KUnit test to PROC SYSCTL section

Other than that, I think we should be good to go.

One last thing, I updated the background to include my thoughts on KUnit vs. in kernel testing with kselftest in the background sections as suggested by Frank in the discussion on PATCH v2.

## Background

This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.

Unlike Autotest and kselftest, KUnit is a true unit testing framework; it does not require installing the kernel on a test machine or in a VM (however, KUnit still allows you to run tests on test machines or in VMs if you want[1]) and does not require tests to be written in userspace running on a host kernel. Additionally, KUnit is fast: From invocation to completion KUnit can run several dozen tests in under a second. Currently, the entire KUnit test suite for KUnit runs in under a second from the initial invocation (build time excluded).

KUnit is heavily inspired by JUnit, Python's unittest.mock, and Googletest/Googlemock for C++. KUnit provides facilities for defining unit test cases, grouping related test cases into test suites, providing common infrastructure for running tests, mocking, spying, and much more.

### But wait! Doesn't kselftest support in kernel testing?!

In a previous version of this patchset Frank pointed out that kselftest already supports writing a test that resides in the kernel using the test module feature[2]. LWN did a really great summary on this discussion here[3].

Kselftest has a feature that allows a test module to be loaded into a kernel using the kselftest framework; this does allow someone to write tests against kernel code not directly exposed to userland; however, it does not provide much of a framework around how to structure the tests. The kselftest test module feature just provides a header which has a standardized way of reporting test failures, and then provides infrastructure to load and run the tests using the kselftest test harness.

The kselftest test module does not seem to be opinionated at all in regards to how tests are structured, how they check for failures, how tests are organized. Even in the method it provides for reporting failures is pretty simple; it doesn't have any more advanced failure reporting or logging features. Given what's there, I think it is fair to say that it is not actually a framework, but a feature that makes it possible for someone to do some checks in kernel space.

Furthermore, kselftest test module has very few users. I checked for all the tests that use it using the following grep command:

grep -Hrn -e 'kselftest_module\.h'

and only got three results: lib/test_strscpy.c, lib/test_printf.c, and lib/test_bitmap.c.

So despite kselftest test module's existence, there really is no feature overlap between kselftest and KUnit, save one: that you can use either to write an in-kernel test, but this is a very small feature in comparison to everything that KUnit allows you to do. KUnit is a full x-unit style unit testing framework, whereas kselftest looks a lot more like an end-to-end/functional testing framework, with a feature that makes it possible to write in-kernel tests.

### What's so special about unit testing?

A unit test is supposed to test a single unit of code in isolation, hence the name. There should be no dependencies outside the control of the test; this means no external dependencies, which makes tests orders of magnitudes faster. Likewise, since there are no external dependencies, there are no hoops to jump through to run the tests. Additionally, this makes unit tests deterministic: a failing unit test always indicates a problem. Finally, because unit tests necessarily have finer granularity, they are able to test all code paths easily solving the classic problem of difficulty in exercising error handling code.

### Is KUnit trying to replace other testing frameworks for the kernel?

No. Most existing tests for the Linux kernel are end-to-end tests, which have their place. A well tested system has lots of unit tests, a reasonable number of integration tests, and some end-to-end tests. KUnit is just trying to address the unit test space which is currently not being addressed.

### More information on KUnit

There is a bunch of documentation near the end of this patch set that describes how to use KUnit and best practices for writing unit tests. For convenience I am hosting the compiled docs here[4].

Additionally for convenience, I have applied these patches to a branch[5]. The repo may be cloned with:
git clone https://kunit.googlesource.com/linux
This patchset is on the kunit/rfc/v5.2-rc4/v5 branch.

## Changes Since Last Version

Aside from a couple public function renames, there isn't really anything in here that changes any functionality.

- Went through and fixed a couple of anti-patterns suggested by Stephen Boyd. Things like:
- Dropping an else clause at the end of a function.
- Dropping the comma on the closing sentinel, {}, of a list.
- Inlines a bunch of functions in the test case running logic in patch 01/18 to make it more readable as suggested by Stephen Boyd
- Found and fixed bug in resource deallocation logic in patch 02/18. Bug was discovered as a result of making a change suggested by Stephen Boyd. This does not substantially change how any of the code works conceptually.
- Renamed new_string_stream() to alloc_string_stream() as suggested by Stephen Boyd.
- Made string-stream a KUnit managed object - based on a suggestion made by Stephen Boyd.
- Renamed kunit_new_stream() to alloc_kunit_stream() as suggested by Stephen Boyd.
- Removed the ability to set log level after allocating a kunit_stream, as suggested by Stephen Boyd.

[1] https://google.github.io/kunit-docs/third_party/kernel/docs/usage.html#kunit-on-non-uml-architectures
[2] https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html#test-module
[3] https://lwn.net/Articles/790235/
[4] https://google.github.io/kunit-docs/third_party/kernel/docs/
[5] https://kunit.googlesource.com/linux/+/kunit/rfc/v5.2-rc4/v5

Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#1 lore raw

PATCH v5 1/18 kunit: test: add KUnit test runner core

Add core facilities for defining unit tests; this provides a common way to define test cases, functions that execute code which is under test and determine whether the code under test behaves as expected; this also provides a way to group together related test cases in test suites (here we call them test_modules).

Just define test cases and how to execute them for now; setting expectations on code will be defined later.

---
Changes Since Last Revision:
- Mostly minor fixes suggested by Stephen Boyd
- Biggest change inlines a bunch of functions in the test case running logic to make it more readable as suggested by Stephen Boyd

---
 include/kunit/test.h | 161 +++++++++++++++++++++++++++++++++
 kunit/Kconfig        |  17 ++++
 kunit/Makefile       |   1 +
 kunit/test.c         | 210 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 389 insertions(+)
 create mode 100644 include/kunit/test.h
 create mode 100644 kunit/Kconfig
 create mode 100644 kunit/Makefile
 create mode 100644 kunit/test.c
include/kunit/test.h new file +161 -0
new file mode 100644
index 0000000000000..8476b3d371cb9
@@ -0,0 +1,161 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#ifndef _KUNIT_TEST_H
+#define _KUNIT_TEST_H
+
+#include <linux/types.h>
+
+struct kunit;
+
+/**
+ * struct kunit_case - represents an individual test case.
+ * @run_case: the function representing the actual test case.
+ * @name: the name of the test case.
+ *
+ * A test case is a function with the signature, ``void (*)(struct kunit *)``
+ * that makes expectations (see KUNIT_EXPECT_TRUE()) about code under test. Each
+ * test case is associated with a &struct kunit_module and will be run after the
+ * module's init function and followed by the module's exit function.
+ *
+ * A test case should be static and should only be created with the KUNIT_CASE()
+ * macro; additionally, every array of test cases should be terminated with an
+ * empty test case.
+ *
+ * Example:
+ *
+ * .. code-block:: c
+ *
+ *	void add_test_basic(struct kunit *test)
+ *	{
+ *		KUNIT_EXPECT_EQ(test, 1, add(1, 0));
+ *		KUNIT_EXPECT_EQ(test, 2, add(1, 1));
+ *		KUNIT_EXPECT_EQ(test, 0, add(-1, 1));
+ *		KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX));
+ *		KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN));
+ *	}
+ *
+ *	static struct kunit_case example_test_cases[] = {
+ *		KUNIT_CASE(add_test_basic),
+ *		{}
+ *	};
+ *
+ */
+struct kunit_case {
+	void (*run_case)(struct kunit *test);
+	const char *name;
+
+	/* private: internal use only. */
+	bool success;
+};
+
+/**
+ * KUNIT_CASE - A helper for creating a &struct kunit_case
+ * @test_name: a reference to a test case function.
+ *
+ * Takes a symbol for a function representing a test case and creates a
+ * &struct kunit_case object from it. See the documentation for
+ * &struct kunit_case for an example on how to use it.
+ */
+#define KUNIT_CASE(test_name) { .run_case = test_name, .name = #test_name }
+
+/**
+ * struct kunit_module - describes a related collection of &struct kunit_case s.
+ * @name: the name of the test. Purely informational.
+ * @init: called before every test case.
+ * @exit: called after every test case.
+ * @test_cases: a null terminated array of test cases.
+ *
+ * A kunit_module is a collection of related &struct kunit_case s, such that
+ * @init is called before every test case and @exit is called after every test
+ * case, similar to the notion of a *test fixture* or a *test class* in other
+ * unit testing frameworks like JUnit or Googletest.
+ *
+ * Every &struct kunit_case must be associated with a kunit_module for KUnit to
+ * run it.
+ */
+struct kunit_module {
+	const char name[256];
+	int (*init)(struct kunit *test);
+	void (*exit)(struct kunit *test);
+	struct kunit_case *test_cases;
+};
+
+/**
+ * struct kunit - represents a running instance of a test.
+ * @priv: for user to store arbitrary data. Commonly used to pass data created
+ * in the init function (see &struct kunit_module).
+ *
+ * Used to store information about the current context under which the test is
+ * running. Most of this data is private and should only be accessed indirectly
+ * via public functions; the one exception is @priv which can be used by the
+ * test writer to store arbitrary data.
+ */
+struct kunit {
+	void *priv;
+
+	/* private: internal use only. */
+	const char *name; /* Read only after initialization! */
+	spinlock_t lock; /* Gaurds all mutable test state. */
+	bool success; /* Protected by lock. */
+};
+
+void kunit_init_test(struct kunit *test, const char *name);
+
+int kunit_run_tests(struct kunit_module *module);
+
+/**
+ * module_test() - used to register a &struct kunit_module with KUnit.
+ * @module: a statically allocated &struct kunit_module.
+ *
+ * Registers @module with the test framework. See &struct kunit_module for more
+ * information.
+ */
+#define module_test(module) \
+		static int module_kunit_init##module(void) \
+		{ \
+			return kunit_run_tests(&module); \
+		} \
+		late_initcall(module_kunit_init##module)
+
+void __printf(3, 4) kunit_printk(const char *level,
+				 const struct kunit *test,
+				 const char *fmt, ...);
+
+/**
+ * kunit_info() - Prints an INFO level message associated with the current test.
+ * @test: The test context object.
+ * @fmt: A printk() style format string.
+ *
+ * Prints an info level message associated with the test module being run. Takes
+ * a variable number of format parameters just like printk().
+ */
+#define kunit_info(test, fmt, ...) \
+		kunit_printk(KERN_INFO, test, fmt, ##__VA_ARGS__)
+
+/**
+ * kunit_warn() - Prints a WARN level message associated with the current test.
+ * @test: The test context object.
+ * @fmt: A printk() style format string.
+ *
+ * Prints a warning level message.
+ */
+#define kunit_warn(test, fmt, ...) \
+		kunit_printk(KERN_WARNING, test, fmt, ##__VA_ARGS__)
+
+/**
+ * kunit_err() - Prints an ERROR level message associated with the current test.
+ * @test: The test context object.
+ * @fmt: A printk() style format string.
+ *
+ * Prints an error level message.
+ */
+#define kunit_err(test, fmt, ...) \
+		kunit_printk(KERN_ERR, test, fmt, ##__VA_ARGS__)
+
+#endif /* _KUNIT_TEST_H */
kunit/Kconfig new file +17 -0
new file mode 100644
index 0000000000000..330ae83527c23
@@ -0,0 +1,17 @@
+#
+# KUnit base configuration
+#
+
+menu "KUnit support"
+
+config KUNIT
+	bool "Enable support for unit tests (KUnit)"
+	help
+	  Enables support for kernel unit tests (KUnit), a lightweight unit
+	  testing and mocking framework for the Linux kernel. These tests are
+	  able to be run locally on a developer's workstation without a VM or
+	  special hardware when using UML. Can also be used on most other
+	  architectures. For more information, please see
+	  Documentation/dev-tools/kunit/.
+
+endmenu
kunit/Makefile new file +1 -0
new file mode 100644
index 0000000000000..5efdc4dea2c08
@@ -0,0 +1 @@
+obj-$(CONFIG_KUNIT) +=			test.o
kunit/test.c new file +210 -0

210 lines not on this page · raw message

Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#2 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 15 lines
kunit/test.c new file +9 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>

kunit/test.c line 19

Quoted 10 lines
kunit/test.c new file +10 -0
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

Quoted 28 lines
kunit/test.c new file +28 -0
+
+       return success;
+}
+
+static void kunit_set_success(struct kunit *test, bool success)
+{
+       unsigned long flags;
+
+       spin_lock_irqsave(&test->lock, flags);
+       test->success = success;
+       spin_unlock_irqrestore(&test->lock, flags);
+}
+
+static int kunit_vprintk_emit(int level, const char *fmt, va_list args)
+{
+       return vprintk_emit(0, level, NULL, 0, fmt, args);
+}
+
+static int kunit_printk_emit(int level, const char *fmt, ...)
+{
+       va_list args;
+       int ret;
+
+       va_start(args, fmt);
+       ret = kunit_vprintk_emit(level, fmt, args);
+       va_end(args);
+
+       return ret;

kunit/test.c line 57

Quoted 10 lines
kunit/test.c new file +10 -0
+}
+
+static void kunit_vprintk(const struct kunit *test,
+                         const char *level,
+                         struct va_format *vaf)
+{
+       kunit_printk_emit(level[1] - '0', "\t# %s: %pV", test->name, vaf);
+}
+
+static bool kunit_has_printed_tap_version;

Can you please move this into function local scope in the function below?

Quoted 9 lines
kunit/test.c new file +9 -0
+
+static void kunit_print_tap_version(void)
+{
+       if (!kunit_has_printed_tap_version) {
+               kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");
+               kunit_has_printed_tap_version = true;
+       }
+}
+

[...]

kunit/test.c line 117

Quoted 10 lines
kunit/test.c new file +10 -0
+
+static bool kunit_module_has_succeeded(struct kunit_module *module)
+{
+       const struct kunit_case *test_case;
+       bool success = true;
+
+       for (test_case = module->test_cases; test_case->run_case; test_case++)
+               if (!test_case->success) {
+                       success = false;
+                       break;

Why not 'return false'?

kunit/test.c line 120

Quoted 3 lines
kunit/test.c new file +3 -0
+               }
+
+       return success;

And 'return true'?

Quoted 40 lines
kunit/test.c new file +40 -0
+}
+
+static size_t kunit_module_counter = 1;
+
+static void kunit_print_subtest_end(struct kunit_module *module)
+{
+       kunit_print_ok_not_ok(false,
+                             kunit_module_has_succeeded(module),
+                             kunit_module_counter++,
+                             module->name);
+}
+
+static void kunit_print_test_case_ok_not_ok(struct kunit_case *test_case,
+                                           size_t test_number)
+{
+       kunit_print_ok_not_ok(true,
+                             test_case->success,
+                             test_number,
+                             test_case->name);
+}
+
+void kunit_init_test(struct kunit *test, const char *name)
+{
+       spin_lock_init(&test->lock);
+       test->name = name;
+       test->success = true;
+}
+
+/*
+ * Performs all logic to run a test case.
+ */
+static void kunit_run_case(struct kunit_module *module,
+                          struct kunit_case *test_case)
+{
+       struct kunit test;
+       int ret = 0;
+
+       kunit_init_test(&test, test_case->name);
+
+       if (module->init) {

kunit/test.c line 170

Quoted 10 lines
kunit/test.c new file +10 -0
+               ret = module->init(&test);
+               if (ret) {
+                       kunit_err(&test, "failed to initialize: %d\n", ret);
+                       kunit_set_success(&test, false);
+                       return;
+               }
+       }
+
+       if (!ret)
+               test_case->run_case(&test);

Do we need this if condition? ret can only be set to non-zero above but then we'll exit the function early so it seems unnecessary. Given that, ret should probably be moved into the module->init path.

kunit/test.c line 177

Quoted 7 lines
kunit/test.c new file +7 -0
+
+       if (module->exit)
+               module->exit(&test);
+
+       test_case->success = kunit_get_success(&test);
+}
+

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#3 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 24 lines · Stephen Boyd

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 22 lines
kunit/test.c new file +16 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
Quoted 8 lines

kunit/test.c line 19

Quoted 3 lines
kunit/test.c new file +3 -0
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

Yes, your understanding is correct. It is possible for a user to write a test such that certain elements may be updated in different threads; this would most likely happen in the case where someone wants to make an assertion or an expectation in a thread created by a piece of code under test. Although this should generally be avoided, it is possible, and there are occasionally good reasons to do so, so it is functionality that we should support.

Do you think I should add a comment to this effect?

Quoted 2 lines

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be

As I said above, it is possible that the code under test may spawn a new thread that may make an expectation or an assertion. It is not a super common use case, but it is possible.

Quoted 2 lines

operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

There are instances where someone may want to test a driver which has an interrupt handler in it. I actually have (not the greatest) example here. Now in these cases, I expect someone to use a mock irqchip or some other fake mechanism to trigger the interrupt handler and not actual hardware; technically speaking in this case, it is not going to be accessed from a "real" irq context; however, the code under test should think that it is in an irq context; given that, I figured it is best to just treat it as a real irq context. Does that make sense?

Quoted 33 lines
Quoted 33 lines
kunit/test.c new file +33 -0
+
+       return success;
+}
+
+static void kunit_set_success(struct kunit *test, bool success)
+{
+       unsigned long flags;
+
+       spin_lock_irqsave(&test->lock, flags);
+       test->success = success;
+       spin_unlock_irqrestore(&test->lock, flags);
+}
+
+static int kunit_vprintk_emit(int level, const char *fmt, va_list args)
+{
+       return vprintk_emit(0, level, NULL, 0, fmt, args);
+}
+
+static int kunit_printk_emit(int level, const char *fmt, ...)
+{
+       va_list args;
+       int ret;
+
+       va_start(args, fmt);
+       ret = kunit_vprintk_emit(level, fmt, args);
+       va_end(args);
+
+       return ret;
+}
+
+static void kunit_vprintk(const struct kunit *test,
+                         const char *level,
+                         struct va_format *vaf)
Quoted 8 lines

kunit/test.c line 57

Quoted 5 lines
kunit/test.c new file +5 -0
+{
+       kunit_printk_emit(level[1] - '0', "\t# %s: %pV", test->name, vaf);
+}
+
+static bool kunit_has_printed_tap_version;

Can you please move this into function local scope in the function below?

Sure, that makes sense.

Quoted 10 lines
Quoted 9 lines
kunit/test.c new file +9 -0
+
+static void kunit_print_tap_version(void)
+{
+       if (!kunit_has_printed_tap_version) {
+               kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");
+               kunit_has_printed_tap_version = true;
+       }
+}
+

[...]

Quoted 12 lines

kunit/test.c line 117

Quoted 10 lines
kunit/test.c new file +10 -0
+
+static bool kunit_module_has_succeeded(struct kunit_module *module)
+{
+       const struct kunit_case *test_case;
+       bool success = true;
+
+       for (test_case = module->test_cases; test_case->run_case; test_case++)
+               if (!test_case->success) {
+                       success = false;
+                       break;

Why not 'return false'?

Also a good point. Will fix.

Quoted 5 lines

kunit/test.c line 120

Quoted 3 lines
kunit/test.c new file +3 -0
+               }
+
+       return success;

And 'return true'?

Will fix.

Quoted 46 lines
Quoted 46 lines
kunit/test.c new file +46 -0
+}
+
+static size_t kunit_module_counter = 1;
+
+static void kunit_print_subtest_end(struct kunit_module *module)
+{
+       kunit_print_ok_not_ok(false,
+                             kunit_module_has_succeeded(module),
+                             kunit_module_counter++,
+                             module->name);
+}
+
+static void kunit_print_test_case_ok_not_ok(struct kunit_case *test_case,
+                                           size_t test_number)
+{
+       kunit_print_ok_not_ok(true,
+                             test_case->success,
+                             test_number,
+                             test_case->name);
+}
+
+void kunit_init_test(struct kunit *test, const char *name)
+{
+       spin_lock_init(&test->lock);
+       test->name = name;
+       test->success = true;
+}
+
+/*
+ * Performs all logic to run a test case.
+ */
+static void kunit_run_case(struct kunit_module *module,
+                          struct kunit_case *test_case)
+{
+       struct kunit test;
+       int ret = 0;
+
+       kunit_init_test(&test, test_case->name);
+
+       if (module->init) {
+               ret = module->init(&test);
+               if (ret) {
+                       kunit_err(&test, "failed to initialize: %d\n", ret);
+                       kunit_set_success(&test, false);
+                       return;
+               }
Quoted 8 lines

kunit/test.c line 170

Quoted 4 lines
kunit/test.c new file +4 -0
+       }
+
+       if (!ret)
+               test_case->run_case(&test);

Do we need this if condition? ret can only be set to non-zero above but then we'll exit the function early so it seems unnecessary. Given that, ret should probably be moved into the module->init path.

Whoops. Sorry, another instance of how it evolved over time and I forgot why I did the check. Will fix.

Quoted 7 lines

kunit/test.c line 177

Quoted 7 lines
kunit/test.c new file +7 -0
+
+       if (module->exit)
+               module->exit(&test);
+
+       test_case->success = kunit_get_success(&test);
+}
+

Thanks!

#4 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 42 lines · Brendan Higgins
Quoted 24 lines · Stephen Boyd

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 22 lines
kunit/test.c new file +16 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
Quoted 8 lines

kunit/test.c line 19

Quoted 3 lines
kunit/test.c new file +3 -0
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

Yes, your understanding is correct. It is possible for a user to write a test such that certain elements may be updated in different threads; this would most likely happen in the case where someone wants to make an assertion or an expectation in a thread created by a piece of code under test. Although this should generally be avoided, it is possible, and there are occasionally good reasons to do so, so it is functionality that we should support.

Quoted 8 lines

Do you think I should add a comment to this effect?

Quoted 2 lines

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be

As I said above, it is possible that the code under test may spawn a new thread that may make an expectation or an assertion. It is not a super common use case, but it is possible.

I wonder if it is worth to have then different types of tests based on locking requirements. One with no locking, since it seems you imply most tests would fall under this category, then locking, and another with IRQ context.

If no locking is done at all for all tests which do not require locking, is there any gains at run time? I'm sure it might be minimum but curious.

Quoted 11 lines
Quoted 2 lines

operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

There are instances where someone may want to test a driver which has an interrupt handler in it. I actually have (not the greatest) example here. Now in these cases, I expect someone to use a mock irqchip or some other fake mechanism to trigger the interrupt handler and not actual hardware; technically speaking in this case, it is not going to be accessed from a "real" irq context; however, the code under test should think that it is in an irq context; given that, I figured it is best to just treat it as a real irq context. Does that make sense?

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Luis

#5 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 53 lines · Luis Chamberlain
Quoted 42 lines · Brendan Higgins
Quoted 24 lines · Stephen Boyd

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 22 lines
kunit/test.c new file +16 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
Quoted 8 lines

kunit/test.c line 19

Quoted 3 lines
kunit/test.c new file +3 -0
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

Yes, your understanding is correct. It is possible for a user to write a test such that certain elements may be updated in different threads; this would most likely happen in the case where someone wants to make an assertion or an expectation in a thread created by a piece of code under test. Although this should generally be avoided, it is possible, and there are occasionally good reasons to do so, so it is functionality that we should support.

Quoted 8 lines

Do you think I should add a comment to this effect?

Quoted 2 lines

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be

As I said above, it is possible that the code under test may spawn a new thread that may make an expectation or an assertion. It is not a super common use case, but it is possible.

Quoted 8 lines

I wonder if it is worth to have then different types of tests based on locking requirements. One with no locking, since it seems you imply most tests would fall under this category, then locking, and another with IRQ context.

If no locking is done at all for all tests which do not require locking, is there any gains at run time? I'm sure it might be minimum but curious.

Yeah, I don't think it is worth it.

I don't think we need to be squeezing every ounce of performance out of unit tests, since they are inherently a cost and are not intended to be run in a production deployed kernel as part of normal production usage.

Quoted 12 lines
Quoted 11 lines
Quoted 2 lines

operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

There are instances where someone may want to test a driver which has an interrupt handler in it. I actually have (not the greatest) example here. Now in these cases, I expect someone to use a mock irqchip or some other fake mechanism to trigger the interrupt handler and not actual hardware; technically speaking in this case, it is not going to be accessed from a "real" irq context; however, the code under test should think that it is in an irq context; given that, I figured it is best to just treat it as a real irq context. Does that make sense?

Quoted 4 lines

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Fair enough, I can see the point of not wanting to use irq disabled until we get someone complaining about it, but I think making it thread safe is reasonable. It means there is one less thing to confuse a KUnit user and the only penalty paid is some very minor performance.

#6 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 10 lines · Brendan Higgins
Quoted 4 lines · Luis Chamberlain

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Fair enough, I can see the point of not wanting to use irq disabled until we get someone complaining about it, but I think making it thread safe is reasonable. It means there is one less thing to confuse a KUnit user and the only penalty paid is some very minor performance.

One reason I'm really excited about kunit is speed... so by all means I think we're at a good point to analyze performance optimizationsm if they do make sense.

While on the topic of parallization, what about support for running different test cases in parallel? Or at the very least different kunit modules in parallel. Few questions come up based on this prospect:

* Why not support parallelism from the start?
* Are you opposed to eventually having this added? For instance, there is enough code on lib/test_kmod.c for batching tons of kthreads each one running its own thing for testing purposes which could be used as template.
* If we eventually *did* support it:
- Would logs be skewed?
- Could we have a way to query: give me log for only kunit module named "foo"?

Luis

#7 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 8 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
Quoted 4 lines · Luis Chamberlain

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Quoted 8 lines
Quoted 4 lines

Fair enough, I can see the point of not wanting to use irq disabled until we get someone complaining about it, but I think making it thread safe is reasonable. It means there is one less thing to confuse a KUnit user and the only penalty paid is some very minor performance.

One reason I'm really excited about kunit is speed... so by all means I think we're at a good point to analyze performance optimizationsm if they do make sense.

Yeah, but I think there are much lower hanging fruit than this (as you point out below). I am all for making/keeping KUnit super fast, but I also don't want to waste time with premature optimizations and I think having thread safe expectations and non-thread safe expectations hurts usability.

Still, I am on board with making this a mutex instead of a spinlock for now.

Quoted 5 lines

While on the topic of parallization, what about support for running different test cases in parallel? Or at the very least different kunit modules in parallel. Few questions come up based on this prospect:

* Why not support parallelism from the start?

Just because it is more work and there isn't much to gain from it right now.

Some numbers:
I currently have a collection of 86 test cases in the branch that this patchset is from. I turned on PRINTK_TIME and looked at the first KUnit output and the last. On UML, start time was 0.090000, and end time was 0.090000. Looks like sched_clock is not very good on UML.

Still it seems quite likely that all of these tests run around 0.01 seconds or less on UML: I ran KUnit with only 2 test cases enabled three times and got an average runtime of 1.55867 seconds with a standard deviation of 0.0346747. I then ran it another three times with all test cases enabled and got an average runtime of 1.535 seconds with a standard deviation of 0.0150997. The second average is less, but that doesn't really mean anything because it is well within one standard deviation with a very small sample size. Nevertheless, we can conclude that the actual runtime of those 84 test cases is most likely within one standard deviation, so on the order of 0.01 seconds.

On x86 running on QEMU, first message from KUnit was printed at 0.194251 and the last KUnit message was printed at 0.340915, meaning that all 86 test cases ran in about 0.146664 seconds.

In any case, running KUnit tests in parallel is definitely something I plan on adding it eventually, but it just doesn't really seem worth it right now. I find the incremental build time of the kernel to typically be between 3 and 30 seconds, and a clean build to be between 30 seconds to several minutes, depending on the number of available cores, so I don't think most users would even notice the amount of runtime contributed by the actual unit tests until we start getting into the 1000s of test cases. I don't suspect it will become an issue until we get into the 10,000s of test cases. I think we are a pretty long way off from that.

Quoted 4 lines

* Are you opposed to eventually having this added? For instance, there is enough code on lib/test_kmod.c for batching tons of kthreads each one running its own thing for testing purposes which could be used as template.

I am not opposed to adding it eventually at all. I actually plan on doing so, just not in this patchset. There are a lot of additional features, improvements, and sugar that I really want to add, so much so that most of it doesn't belong in this patchset; I just think this is one of those things that belongs in a follow up. I tried to boil down this patchset to as small as I could while still being useful; this is basically an MVP. Maybe after this patchset gets merged I should post a list of things I have ready for review, or would like to work on, and people can comment on what things they want to see next.

Quoted 2 lines

* If we eventually *did* support it:
- Would logs be skewed?

Probably, before I went with the TAP approach, I was tagging each message with the test case it came from and I could have parsed it and assembled a coherent view of the logs using that; now that I am using TAP conforming output, that won't work. I haven't really thought too hard about how to address it, but there are ways. For the UML users, I am planning on adding a feature to guarantee hermeticity between tests running in different modules by adding a feature that allows a single kernel to be built with all tests included, and then determine which tests get run by passing in command line arguments or something. This way you can get the isolation from running tests in separate environments without increasing the build cost. We could also use this method to achieve parallelism by dispatching multiple kernels at once. That only works for UML, but I imagine you could do something similar for users running tests under qemu.

Quoted 2 lines

- Could we have a way to query: give me log for only kunit module named "foo"?

Yeah, I think that would make sense as part of the hermeticity thing I mentioned above.

Hope that seems reasonable!
_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#8 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 30 lines · Brendan Higgins
Quoted 8 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
Quoted 4 lines · Luis Chamberlain

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Quoted 8 lines
Quoted 4 lines

Fair enough, I can see the point of not wanting to use irq disabled until we get someone complaining about it, but I think making it thread safe is reasonable. It means there is one less thing to confuse a KUnit user and the only penalty paid is some very minor performance.

One reason I'm really excited about kunit is speed... so by all means I think we're at a good point to analyze performance optimizationsm if they do make sense.

Yeah, but I think there are much lower hanging fruit than this (as you point out below). I am all for making/keeping KUnit super fast, but I also don't want to waste time with premature optimizations and I think having thread safe expectations and non-thread safe expectations hurts usability.

Still, I am on board with making this a mutex instead of a spinlock for now.

Quoted 4 lines

While on the topic of parallization, what about support for running different test cases in parallel? Or at the very least different kunit modules in parallel. Few questions come up based on this prospect:

Quoted 7 lines
Quoted 1 line

* Why not support parallelism from the start?

Just because it is more work and there isn't much to gain from it right now.

Some numbers:
I currently have a collection of 86 test cases in the branch that this patchset is from.

Impressive, imagine 86 tests and kunit is not even *merged yet*.

Quoted 3 lines

I turned on PRINTK_TIME and looked at the first
KUnit output and the last. On UML, start time was 0.090000, and end time was 0.090000. Looks like sched_clock is not very good on UML.

Since you have a python thing that kicks tests, what if you just run time on it?

Quoted 11 lines

Still it seems quite likely that all of these tests run around 0.01 seconds or less on UML: I ran KUnit with only 2 test cases enabled three times and got an average runtime of 1.55867 seconds with a standard deviation of 0.0346747. I then ran it another three times with all test cases enabled and got an average runtime of 1.535 seconds with a standard deviation of 0.0150997. The second average is less, but that doesn't really mean anything because it is well within one standard deviation with a very small sample size. Nevertheless, we can conclude that the actual runtime of those 84 test cases is most likely within one standard deviation, so on the order of 0.01 seconds.

Quoted 3 lines

On x86 running on QEMU, first message from KUnit was printed at 0.194251 and the last KUnit message was printed at 0.340915, meaning that all 86 test cases ran in about 0.146664 seconds.

Pretty impressive numbers. But can you blame me for expressing the desire to possibly being able to do better? I am not saying -- let's definitely have parallelism in place *now*. Just wanted to hear out tangibles of why we *don't* want it now.

And.. also, since we are reviewing now, try to target so that the code can later likely get a face lift to support parallelism without requiring much changes.

Quoted 3 lines

In any case, running KUnit tests in parallel is definitely something I plan on adding it eventually, but it just doesn't really seem worth it right now.

Makes sense!

Quoted 8 lines

I find the incremental build time of the kernel to typically be between 3 and 30 seconds, and a clean build to be between 30 seconds to several minutes, depending on the number of available cores, so I don't think most users would even notice the amount of runtime contributed by the actual unit tests until we start getting into the 1000s of test cases. I don't suspect it will become an issue until we get into the 10,000s of test cases. I think we are a pretty long way off from that.

All makes sense, and agreed based on the numbers you are providing. Thanks for the details!

Quoted 5 lines
Quoted 4 lines

* Are you opposed to eventually having this added? For instance, there is enough code on lib/test_kmod.c for batching tons of kthreads each one running its own thing for testing purposes which could be used as template.

Quoted 9 lines

I am not opposed to adding it eventually at all. I actually plan on doing so, just not in this patchset. There are a lot of additional features, improvements, and sugar that I really want to add, so much so that most of it doesn't belong in this patchset; I just think this is one of those things that belongs in a follow up. I tried to boil down this patchset to as small as I could while still being useful; this is basically an MVP. Maybe after this patchset gets merged I should post a list of things I have ready for review, or would like to work on, and people can comment on what things they want to see next.

Groovy.

Quoted 15 lines
Quoted 2 lines

* If we eventually *did* support it:
- Would logs be skewed?

Probably, before I went with the TAP approach, I was tagging each message with the test case it came from and I could have parsed it and assembled a coherent view of the logs using that; now that I am using TAP conforming output, that won't work. I haven't really thought too hard about how to address it, but there are ways. For the UML users, I am planning on adding a feature to guarantee hermeticity between tests running in different modules by adding a feature that allows a single kernel to be built with all tests included, and then determine which tests get run by passing in command line arguments or something. This way you can get the isolation from running tests in separate environments without increasing the build cost. We could also use this method to achieve parallelism by dispatching multiple kernels at once.

Indeed. Or... wait for it... containers... There tools for these sorts of things already. And I'm evaluating such prospects now for some other tests I care for.

Quoted 2 lines

That only works for UML, but I imagine you could do something similar for users running tests under qemu.

Or containers.

Quoted 7 lines
Quoted 2 lines

- Could we have a way to query: give me log for only kunit module named "foo"?

Yeah, I think that would make sense as part of the hermeticity thing I mentioned above.

Hope that seems reasonable!

All groovy. Thanks for the details!

Luis

#9 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 34 lines · Luis Chamberlain
Quoted 32 lines · Brendan Higgins
Quoted 8 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
Quoted 4 lines · Luis Chamberlain

Since its a new architecture and since you seem to imply most tests don't require locking or even IRQs disabled, I think its worth to consider the impact of adding such extreme locking requirements for an initial ramp up.

Quoted 8 lines
Quoted 4 lines

Fair enough, I can see the point of not wanting to use irq disabled until we get someone complaining about it, but I think making it thread safe is reasonable. It means there is one less thing to confuse a KUnit user and the only penalty paid is some very minor performance.

One reason I'm really excited about kunit is speed... so by all means I think we're at a good point to analyze performance optimizationsm if they do make sense.

Yeah, but I think there are much lower hanging fruit than this (as you point out below). I am all for making/keeping KUnit super fast, but I also don't want to waste time with premature optimizations and I think having thread safe expectations and non-thread safe expectations hurts usability.

Still, I am on board with making this a mutex instead of a spinlock for now.

Quoted 5 lines

While on the topic of parallization, what about support for running different test cases in parallel? Or at the very least different kunit modules in parallel. Few questions come up based on this prospect:

* Why not support parallelism from the start?

Quoted 7 lines
Quoted 5 lines

Just because it is more work and there isn't much to gain from it right now.

Some numbers:
I currently have a collection of 86 test cases in the branch that this patchset is from.

Impressive, imagine 86 tests and kunit is not even *merged yet*.

Full disclaimer, about half of them are KUnit tests for KUnit - to make sure KUnit works, so I don't know if you consider that cheating.

Quoted 6 lines
Quoted 3 lines

I turned on PRINTK_TIME and looked at the first
KUnit output and the last. On UML, start time was 0.090000, and end time was 0.090000. Looks like sched_clock is not very good on UML.

Since you have a python thing that kicks tests, what if you just run time on it?

That's what I did on the this following paragraph (I just couldn't time the tests by themselves in this case):

Quoted 11 lines
Quoted 11 lines

Still it seems quite likely that all of these tests run around 0.01 seconds or less on UML: I ran KUnit with only 2 test cases enabled three times and got an average runtime of 1.55867 seconds with a standard deviation of 0.0346747. I then ran it another three times with all test cases enabled and got an average runtime of 1.535 seconds with a standard deviation of 0.0150997. The second average is less, but that doesn't really mean anything because it is well within one standard deviation with a very small sample size. Nevertheless, we can conclude that the actual runtime of those 84 test cases is most likely within one standard deviation, so on the order of 0.01 seconds.

Quoted 8 lines
Quoted 3 lines

On x86 running on QEMU, first message from KUnit was printed at 0.194251 and the last KUnit message was printed at 0.340915, meaning that all 86 test cases ran in about 0.146664 seconds.

Pretty impressive numbers. But can you blame me for expressing the desire to possibly being able to do better? I am not saying -- let's definitely have parallelism in place *now*. Just wanted to hear out tangibles of why we *don't* want it now.

I agree, faster is almost always better in these types of things, and certainly is in this case.

In fairness to you, I also short sold the speed of KUnit in the cover letter. I was too lazy to do this complete of an analysis back when I wrote it (even if I did a complete timing like this, I would have to put a bunch of asterisks since it wouldn't include the time to "boot" the kernel or to build it, which vastly outstrip the speed of individual test cases). And given the original numbers, I think speeding things up would probably seem more urgent. So no, I really cannot blame you.

Sorry if it came across that I was frustrated or impatient, but I am actually glad you asked because I now have this public email where I did the full analysis of how fast KUnit really is which I can refer to in the future.

Quoted 3 lines

And.. also, since we are reviewing now, try to target so that the code can later likely get a face lift to support parallelism without requiring much changes.

Also fair.

Quoted 33 lines
Quoted 3 lines

In any case, running KUnit tests in parallel is definitely something I plan on adding it eventually, but it just doesn't really seem worth it right now.

Makes sense!

Quoted 8 lines

I find the incremental build time of the kernel to typically be between 3 and 30 seconds, and a clean build to be between 30 seconds to several minutes, depending on the number of available cores, so I don't think most users would even notice the amount of runtime contributed by the actual unit tests until we start getting into the 1000s of test cases. I don't suspect it will become an issue until we get into the 10,000s of test cases. I think we are a pretty long way off from that.

All makes sense, and agreed based on the numbers you are providing. Thanks for the details!

Quoted 5 lines
Quoted 4 lines

* Are you opposed to eventually having this added? For instance, there is enough code on lib/test_kmod.c for batching tons of kthreads each one running its own thing for testing purposes which could be used as template.

Quoted 9 lines

I am not opposed to adding it eventually at all. I actually plan on doing so, just not in this patchset. There are a lot of additional features, improvements, and sugar that I really want to add, so much so that most of it doesn't belong in this patchset; I just think this is one of those things that belongs in a follow up. I tried to boil down this patchset to as small as I could while still being useful; this is basically an MVP. Maybe after this patchset gets merged I should post a list of things I have ready for review, or would like to work on, and people can comment on what things they want to see next.

Quoted 1 line

Groovy.

Cool, I will do that then!

Quoted 16 lines
Quoted 15 lines
Quoted 2 lines

* If we eventually *did* support it:
- Would logs be skewed?

Probably, before I went with the TAP approach, I was tagging each message with the test case it came from and I could have parsed it and assembled a coherent view of the logs using that; now that I am using TAP conforming output, that won't work. I haven't really thought too hard about how to address it, but there are ways. For the UML users, I am planning on adding a feature to guarantee hermeticity between tests running in different modules by adding a feature that allows a single kernel to be built with all tests included, and then determine which tests get run by passing in command line arguments or something. This way you can get the isolation from running tests in separate environments without increasing the build cost. We could also use this method to achieve parallelism by dispatching multiple kernels at once.

Quoted 3 lines

Indeed. Or... wait for it... containers... There tools for these sorts of things already. And I'm evaluating such prospects now for some other tests I care for.

Containers could definitely be useful in the long run. I have a long term goal to build and run just parts of the kernel as I have mentioned to you, and doing so in a totally hermetic environment could provide a lot of value; in this case I would probably only want a chroot, but if I want to deploy tests to run on different machines containers could be very useful.

Actually, on the topic of containers for running tests, the presubmit system I have set up for KUnit uses containers for deploying KUnit on servers for testing[1]. Actually, I have some experimental patches to make it work with LKML instead of Gerrit, but I am not sure whether it makes more sense to go that route, with one of the many patchworks clones that support presubmit, or something else.

Quoted 8 lines
Quoted 2 lines

That only works for UML, but I imagine you could do something similar for users running tests under qemu.

Or containers.

Quoted 3 lines
Quoted 2 lines

- Could we have a way to query: give me log for only kunit module named "foo"?

Quoted 6 lines
Quoted 4 lines

Yeah, I think that would make sense as part of the hermeticity thing I mentioned above.

Hope that seems reasonable!

All groovy. Thanks for the details!

[1] https://kunit-review.googlesource.com/c/linux/+/1809/2#message-c243e1c9086d9432d2dcabc67a42a977b8a020ff

#10 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

In reply to Brendan Higgins

Quoting Brendan Higgins (2019-06-25 13:28:25)

Quoted 42 lines · Stephen Boyd
Quoted 24 lines

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 22 lines
kunit/test.c new file +16 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
Quoted 8 lines

kunit/test.c line 19

Quoted 3 lines
kunit/test.c new file +3 -0
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

Yes, your understanding is correct. It is possible for a user to write a test such that certain elements may be updated in different threads; this would most likely happen in the case where someone wants to make an assertion or an expectation in a thread created by a piece of code under test. Although this should generally be avoided, it is possible, and there are occasionally good reasons to do so, so it is functionality that we should support.

Quoted 1 line

Do you think I should add a comment to this effect?

No, I think the locking should be removed.

Quoted 7 lines
Quoted 3 lines

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be

As I said above, it is possible that the code under test may spawn a new thread that may make an expectation or an assertion. It is not a super common use case, but it is possible.

Sure, sounds super possible and OK.

Quoted 4 lines
Quoted 3 lines

operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

Quoted 8 lines

There are instances where someone may want to test a driver which has an interrupt handler in it. I actually have (not the greatest) example here. Now in these cases, I expect someone to use a mock irqchip or some other fake mechanism to trigger the interrupt handler and not actual hardware; technically speaking in this case, it is not going to be accessed from a "real" irq context; however, the code under test should think that it is in an irq context; given that, I figured it is best to just treat it as a real irq context. Does that make sense?

Can you please describe the scenario in which grabbing the lock here, updating a single variable, and then releasing the lock right after does anything useful vs. not having the lock? I'm looking for a two CPU scenario like below, but where it is a problem. There could be three CPUs, or even one CPU and three threads if you want to describe the extra thread scenario.

Here's my scenario where it isn't needed:

    CPU0                                      CPU1
    ----                                      ----
    kunit_run_test(&test)
                                              test_case_func()
					        ....
                                              [mock hardirq]
					        kunit_set_success(&test)
					      [hardirq ends]
                                                ...
                                                complete(&test_done)
      wait_for_completion(&test_done)
      kunit_get_success(&test)

We don't need to care about having locking here because success or failure only happens in one place and it's synchronized with the completion.

Quoted 13 lines
Quoted 13 lines
Quoted 13 lines
kunit/test.c new file +12 -0
+
+       return success;
+}
+
+static void kunit_set_success(struct kunit *test, bool success)
+{
+       unsigned long flags;
+
+       spin_lock_irqsave(&test->lock, flags);
+       test->success = success;
+       spin_unlock_irqrestore(&test->lock, flags);
+}
#11 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 71 lines · Stephen Boyd

Quoting Brendan Higgins (2019-06-25 13:28:25)

Quoted 42 lines · Stephen Boyd
Quoted 24 lines

Quoting Brendan Higgins (2019-06-17 01:25:56)

Quoted 22 lines
kunit/test.c new file +16 -0
new file mode 100644
index 0000000000000..d05d254f1521f
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Base unit test (KUnit) API.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#include <linux/sched/debug.h>
+#include <kunit/test.h>
+
+static bool kunit_get_success(struct kunit *test)
+{
+       unsigned long flags;
+       bool success;
+
Quoted 8 lines

kunit/test.c line 19

Quoted 3 lines
kunit/test.c new file +3 -0
+       spin_lock_irqsave(&test->lock, flags);
+       success = test->success;
+       spin_unlock_irqrestore(&test->lock, flags);

I still don't understand the locking scheme in this code. Is the intention to make getter and setter APIs that are "safe" by adding in a spinlock that is held around getting and setting various members in the kunit structure?

Yes, your understanding is correct. It is possible for a user to write a test such that certain elements may be updated in different threads; this would most likely happen in the case where someone wants to make an assertion or an expectation in a thread created by a piece of code under test. Although this should generally be avoided, it is possible, and there are occasionally good reasons to do so, so it is functionality that we should support.

Quoted 1 line

Do you think I should add a comment to this effect?

No, I think the locking should be removed.

Quoted 7 lines
Quoted 3 lines

In what situation is there more than one thread reading or writing the kunit struct? Isn't it only a single process that is going to be

As I said above, it is possible that the code under test may spawn a new thread that may make an expectation or an assertion. It is not a super common use case, but it is possible.

Sure, sounds super possible and OK.

Quoted 4 lines
Quoted 3 lines

operating on this structure? And why do we need to disable irqs? Are we expecting to be modifying the unit tests from irq contexts?

Quoted 8 lines

There are instances where someone may want to test a driver which has an interrupt handler in it. I actually have (not the greatest) example here. Now in these cases, I expect someone to use a mock irqchip or some other fake mechanism to trigger the interrupt handler and not actual hardware; technically speaking in this case, it is not going to be accessed from a "real" irq context; however, the code under test should think that it is in an irq context; given that, I figured it is best to just treat it as a real irq context. Does that make sense?

Quoted 3 lines

Can you please describe the scenario in which grabbing the lock here, updating a single variable, and then releasing the lock right after does anything useful vs. not having the lock? I'm looking for a two CPU

Sure.

Quoted 19 lines

scenario like below, but where it is a problem. There could be three CPUs, or even one CPU and three threads if you want to describe the extra thread scenario.

Here's my scenario where it isn't needed:

    CPU0                                      CPU1
    ----                                      ----
    kunit_run_test(&test)
                                              test_case_func()
                                                ....
                                              [mock hardirq]
                                                kunit_set_success(&test)
                                              [hardirq ends]
                                                ...
                                                complete(&test_done)
      wait_for_completion(&test_done)
      kunit_get_success(&test)
Quoted 3 lines

We don't need to care about having locking here because success or failure only happens in one place and it's synchronized with the completion.

Here is the scenario I am concerned about:

CPU0                      CPU1                       CPU2
----                      ----                       ----

kunit_run_test(&test)
test_case_func()
....
schedule_work(foo_func)
[mock hardirq] foo_func()
... ...
kunit_set_success(false) kunit_set_success(false)
[hardirq ends] ...
...
complete(&test_done)
wait_for_completion(...) kunit_get_success(&test)

In my scenario, since both CPU1 and CPU2 update the success status of the test simultaneously, even though they are setting it to the same value. If my understanding is correct, this could result in a write-tear on some architectures in some circumstances. I suppose we could just make it an atomic boolean, but I figured locking is also fine, and generally preferred.

Also, to be clear, I am onboard with dropping then IRQ stuff for now. I am fine moving to a mutex for the time being.

Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
kunit/test.c new file +12 -0
+
+       return success;
+}
+
+static void kunit_set_success(struct kunit *test, bool success)
+{
+       unsigned long flags;
+
+       spin_lock_irqsave(&test->lock, flags);
+       test->success = success;
+       spin_unlock_irqrestore(&test->lock, flags);
+}
#12 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoting Brendan Higgins (2019-06-26 16:00:40)

Quoted 42 lines · Stephen Boyd
Quoted 20 lines

scenario like below, but where it is a problem. There could be three CPUs, or even one CPU and three threads if you want to describe the extra thread scenario.

Here's my scenario where it isn't needed:

    CPU0                                      CPU1
    ----                                      ----
    kunit_run_test(&test)
                                              test_case_func()
                                                ....
                                              [mock hardirq]
                                                kunit_set_success(&test)
                                              [hardirq ends]
                                                ...
                                                complete(&test_done)
      wait_for_completion(&test_done)
      kunit_get_success(&test)
Quoted 3 lines

We don't need to care about having locking here because success or failure only happens in one place and it's synchronized with the completion.

Here is the scenario I am concerned about:

CPU0                      CPU1                       CPU2
----                      ----                       ----

kunit_run_test(&test)
test_case_func()
....
schedule_work(foo_func)
[mock hardirq] foo_func()
... ...
kunit_set_success(false) kunit_set_success(false)
[hardirq ends] ...
...
complete(&test_done)
wait_for_completion(...) kunit_get_success(&test)

Quoted 6 lines

In my scenario, since both CPU1 and CPU2 update the success status of the test simultaneously, even though they are setting it to the same value. If my understanding is correct, this could result in a write-tear on some architectures in some circumstances. I suppose we could just make it an atomic boolean, but I figured locking is also fine, and generally preferred.

This is what we have WRITE_ONCE() and READ_ONCE() for. Maybe you could just use that in the getter and setters and remove the lock if it isn't used for anything else.

It may also be a good idea to have a kunit_fail_test() API that fails the test passed in with a WRITE_ONCE(false). Otherwise, the test is assumed successful and it isn't even possible for a test to change the state from failure to success due to a logical error because the API isn't available. Then we don't really need to have a generic kunit_set_success() function at all. We could have a kunit_test_failed() function too that replaces the kunit_get_success() function. That would read better in an if condition.

Quoted 4 lines

Also, to be clear, I am onboard with dropping then IRQ stuff for now. I am fine moving to a mutex for the time being.

Ok.

#13 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 55 lines · Stephen Boyd

Quoting Brendan Higgins (2019-06-26 16:00:40)

Quoted 42 lines · Stephen Boyd
Quoted 20 lines

scenario like below, but where it is a problem. There could be three CPUs, or even one CPU and three threads if you want to describe the extra thread scenario.

Here's my scenario where it isn't needed:

    CPU0                                      CPU1
    ----                                      ----
    kunit_run_test(&test)
                                              test_case_func()
                                                ....
                                              [mock hardirq]
                                                kunit_set_success(&test)
                                              [hardirq ends]
                                                ...
                                                complete(&test_done)
      wait_for_completion(&test_done)
      kunit_get_success(&test)
Quoted 3 lines

We don't need to care about having locking here because success or failure only happens in one place and it's synchronized with the completion.

Here is the scenario I am concerned about:

CPU0                      CPU1                       CPU2
----                      ----                       ----

kunit_run_test(&test)
test_case_func()
....
schedule_work(foo_func)
[mock hardirq] foo_func()
... ...
kunit_set_success(false) kunit_set_success(false)
[hardirq ends] ...
...
complete(&test_done)
wait_for_completion(...) kunit_get_success(&test)

Quoted 6 lines

In my scenario, since both CPU1 and CPU2 update the success status of the test simultaneously, even though they are setting it to the same value. If my understanding is correct, this could result in a write-tear on some architectures in some circumstances. I suppose we could just make it an atomic boolean, but I figured locking is also fine, and generally preferred.

This is what we have WRITE_ONCE() and READ_ONCE() for. Maybe you could just use that in the getter and setters and remove the lock if it isn't used for anything else.

Quoted 8 lines

It may also be a good idea to have a kunit_fail_test() API that fails the test passed in with a WRITE_ONCE(false). Otherwise, the test is assumed successful and it isn't even possible for a test to change the state from failure to success due to a logical error because the API isn't available. Then we don't really need to have a generic kunit_set_success() function at all. We could have a kunit_test_failed() function too that replaces the kunit_get_success() function. That would read better in an if condition.

You know what, I think you are right.

Sorry, for not realizing this earlier, I think you mentioned something along these lines a long time ago.

Thanks for your patience!

Quoted 6 lines
Quoted 4 lines

Also, to be clear, I am onboard with dropping then IRQ stuff for now. I am fine moving to a mutex for the time being.

Ok.

Thanks!
_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#14 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

In reply to Brendan Higgins

include/kunit/test.h line 124

Quoted 13 lines · Brendan Higgins
include/kunit/test.h new file +13 -0
+/**
+ * module_test() - used to register a &struct kunit_module with KUnit.
+ * @module: a statically allocated &struct kunit_module.
+ *
+ * Registers @module with the test framework. See &struct kunit_module for more
+ * information.
+ */
+#define module_test(module) \
+		static int module_kunit_init##module(void) \
+		{ \
+			return kunit_run_tests(&module); \
+		} \
+		late_initcall(module_kunit_init##module)

Becuase late_initcall() is used, if these modules are built-in, this would preclude the ability to test things prior to this part of the kernel under UML or whatever architecture runs the tests. So, this limits the scope of testing. Small detail but the scope whould be documented.

kunit/test.c line 62

Quoted 4 lines
kunit/test.c new file +4 -0
+static void kunit_print_tap_version(void)
+{
+	if (!kunit_has_printed_tap_version) {
+		kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");

What is this TAP thing? Why should we care what version it is on? Why are we printing this?

kunit/test.c line 72

Quoted 10 lines
kunit/test.c new file +10 -0
+		kunit_has_printed_tap_version = true;
+	}
+}
+
+static size_t kunit_test_cases_len(struct kunit_case *test_cases)
+{
+	struct kunit_case *test_case;
+	size_t len = 0;
+
+	for (test_case = test_cases; test_case->run_case; test_case++)

If we make the last test case NULL, we'd just check for test_case here, and save ourselves an extra few bytes per test module. Any reason why the last test case cannot be NULL?

Quoted 10 lines
kunit/test.c new file +10 -0
+void kunit_init_test(struct kunit *test, const char *name)
+{
+	spin_lock_init(&test->lock);
+	test->name = name;
+	test->success = true;
+}
+
+/*
+ * Performs all logic to run a test case.
+ */

kunit/test.c line 161

Quoted 10 lines
kunit/test.c new file +10 -0
+static void kunit_run_case(struct kunit_module *module,
+			   struct kunit_case *test_case)
+{
+	struct kunit test;
+	int ret = 0;
+
+	kunit_init_test(&test, test_case->name);
+
+	if (module->init) {
+		ret = module->init(&test);

I believe if we used struct kunit_module *kmodule it would be much clearer who's init this is.

Luis

#15 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 13 lines · Luis Chamberlain
Quoted 11 lines · Brendan Higgins
include/kunit/test.h new file +11 -0
+/**
+ * module_test() - used to register a &struct kunit_module with KUnit.
+ * @module: a statically allocated &struct kunit_module.
+ *
+ * Registers @module with the test framework. See &struct kunit_module for more
+ * information.
+ */
+#define module_test(module) \
+             static int module_kunit_init##module(void) \
+             { \
+                     return kunit_run_tests(&module); \
Quoted 8 lines

include/kunit/test.h line 124

Quoted 2 lines
include/kunit/test.h new file +2 -0
+             } \
+             late_initcall(module_kunit_init##module)

Becuase late_initcall() is used, if these modules are built-in, this would preclude the ability to test things prior to this part of the kernel under UML or whatever architecture runs the tests. So, this limits the scope of testing. Small detail but the scope whould be documented.

You aren't the first person to complain about this (and I am not sure it is the first time you have complained about it). Anyway, I have some follow on patches that will improve the late_initcall thing, and people seemed okay with discussing the follow on patches as part of a subsequent patchset after this gets merged.

I will nevertheless document the restriction until then.

Quoted 7 lines

kunit/test.c line 62

Quoted 4 lines
kunit/test.c new file +4 -0
+static void kunit_print_tap_version(void)
+{
+     if (!kunit_has_printed_tap_version) {
+             kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");

What is this TAP thing? Why should we care what version it is on? Why are we printing this?

It's part of the TAP specification[1]. Greg and Frank asked me to make the intermediate format conform to TAP. Seems like something else I should probable document...

Quoted 6 lines
Quoted 6 lines
kunit/test.c new file +6 -0
+             kunit_has_printed_tap_version = true;
+     }
+}
+
+static size_t kunit_test_cases_len(struct kunit_case *test_cases)
+{
Quoted 8 lines

kunit/test.c line 72

Quoted 4 lines
kunit/test.c new file +4 -0
+     struct kunit_case *test_case;
+     size_t len = 0;
+
+     for (test_case = test_cases; test_case->run_case; test_case++)

If we make the last test case NULL, we'd just check for test_case here, and save ourselves an extra few bytes per test module. Any reason why the last test case cannot be NULL?

Is there anyway to make that work with a statically defined array?

Basically, I want to be able to do something like:

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(example_simple_test),
        KUNIT_CASE(example_mock_test),
        {}
};

FYI,
#define KUNIT_CASE(test_name) { .run_case = test_name, .name = #test_name }

In order to do what you are proposing, I think I need an array of pointers to test cases, which is not ideal.

Quoted 15 lines
Quoted 15 lines
kunit/test.c new file +15 -0
+void kunit_init_test(struct kunit *test, const char *name)
+{
+     spin_lock_init(&test->lock);
+     test->name = name;
+     test->success = true;
+}
+
+/*
+ * Performs all logic to run a test case.
+ */
+static void kunit_run_case(struct kunit_module *module,
+                        struct kunit_case *test_case)
+{
+     struct kunit test;
+     int ret = 0;
Quoted 8 lines

kunit/test.c line 161

Quoted 5 lines
kunit/test.c new file +5 -0
+
+     kunit_init_test(&test, test_case->name);
+
+     if (module->init) {
+             ret = module->init(&test);

I believe if we used struct kunit_module *kmodule it would be much clearer who's init this is.

That's reasonable. I will fix in next revision.

Cheers!

[1] https://github.com/TestAnything/Specification/blob/tap-14-specification/specification.md

#16 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 23 lines · Brendan Higgins
Quoted 13 lines · Luis Chamberlain
Quoted 11 lines · Brendan Higgins
include/kunit/test.h new file +11 -0
+/**
+ * module_test() - used to register a &struct kunit_module with KUnit.
+ * @module: a statically allocated &struct kunit_module.
+ *
+ * Registers @module with the test framework. See &struct kunit_module for more
+ * information.
+ */
+#define module_test(module) \
+             static int module_kunit_init##module(void) \
+             { \
+                     return kunit_run_tests(&module); \
Quoted 8 lines

include/kunit/test.h line 124

Quoted 2 lines
include/kunit/test.h new file +2 -0
+             } \
+             late_initcall(module_kunit_init##module)

Becuase late_initcall() is used, if these modules are built-in, this would preclude the ability to test things prior to this part of the kernel under UML or whatever architecture runs the tests. So, this limits the scope of testing. Small detail but the scope whould be documented.

Quoted 7 lines

You aren't the first person to complain about this (and I am not sure it is the first time you have complained about it). Anyway, I have some follow on patches that will improve the late_initcall thing, and people seemed okay with discussing the follow on patches as part of a subsequent patchset after this gets merged.

I will nevertheless document the restriction until then.

To be clear, I am not complaining about it. I just find it simply critical to document its limitations, so folks don't try to invest time and energy on kunit right away for an early init test, if it cannot support it.

If support for that requires some work, it may be worth mentioning as well.

Quoted 11 lines
Quoted 7 lines

kunit/test.c line 62

Quoted 4 lines
kunit/test.c new file +4 -0
+static void kunit_print_tap_version(void)
+{
+     if (!kunit_has_printed_tap_version) {
+             kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");

What is this TAP thing? Why should we care what version it is on? Why are we printing this?

It's part of the TAP specification[1]. Greg and Frank asked me to make the intermediate format conform to TAP. Seems like something else I should probable document...

Yes thanks!

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
kunit/test.c new file +6 -0
+             kunit_has_printed_tap_version = true;
+     }
+}
+
+static size_t kunit_test_cases_len(struct kunit_case *test_cases)
+{
Quoted 8 lines

kunit/test.c line 72

Quoted 4 lines
kunit/test.c new file +4 -0
+     struct kunit_case *test_case;
+     size_t len = 0;
+
+     for (test_case = test_cases; test_case->run_case; test_case++)

If we make the last test case NULL, we'd just check for test_case here, and save ourselves an extra few bytes per test module. Any reason why the last test case cannot be NULL?

Quoted 1 line

Is there anyway to make that work with a statically defined array?

No you're right.

Quoted 8 lines

Basically, I want to be able to do something like:

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(example_simple_test),
        KUNIT_CASE(example_mock_test),
        {}
};
Quoted 6 lines

FYI,
#define KUNIT_CASE(test_name) { .run_case = test_name, .name = #test_name }

In order to do what you are proposing, I think I need an array of pointers to test cases, which is not ideal.

Yeah, you're right. The only other alternative is to have a:

struct kunit_module {
       const char name[256];
       int (*init)(struct kunit *test);
       void (*exit)(struct kunit *test);
       struct kunit_case *test_cases;

+ unsigned int num_cases;
};

And then something like:

#define KUNIT_MODULE(name, init, exit, cases) { \
	.name = name, \
	.init = init, \
	.exit = exit, \
	.test_cases = cases,
	num_cases = ARRAY_SIZE(cases), \
}

Let's evaluate which is better: one extra test case per all test cases, or an extra unsigned int for each kunit module.

Luis

#17 lore raw

Re: [PATCH v5 01/18] kunit: test: add KUnit test runner core

Quoted 33 lines · Luis Chamberlain
Quoted 23 lines · Brendan Higgins
Quoted 13 lines · Luis Chamberlain
Quoted 11 lines · Brendan Higgins
include/kunit/test.h new file +11 -0
+/**
+ * module_test() - used to register a &struct kunit_module with KUnit.
+ * @module: a statically allocated &struct kunit_module.
+ *
+ * Registers @module with the test framework. See &struct kunit_module for more
+ * information.
+ */
+#define module_test(module) \
+             static int module_kunit_init##module(void) \
+             { \
+                     return kunit_run_tests(&module); \
Quoted 8 lines

include/kunit/test.h line 124

Quoted 2 lines
include/kunit/test.h new file +2 -0
+             } \
+             late_initcall(module_kunit_init##module)

Becuase late_initcall() is used, if these modules are built-in, this would preclude the ability to test things prior to this part of the kernel under UML or whatever architecture runs the tests. So, this limits the scope of testing. Small detail but the scope whould be documented.

Quoted 7 lines

You aren't the first person to complain about this (and I am not sure it is the first time you have complained about it). Anyway, I have some follow on patches that will improve the late_initcall thing, and people seemed okay with discussing the follow on patches as part of a subsequent patchset after this gets merged.

I will nevertheless document the restriction until then.

Quoted 7 lines

To be clear, I am not complaining about it. I just find it simply critical to document its limitations, so folks don't try to invest time and energy on kunit right away for an early init test, if it cannot support it.

If support for that requires some work, it may be worth mentioning as well.

Makes sense. And in anycase, it is something I do want to do, just not right now. I will put a TODO here in the next revision.

Quoted 68 lines
Quoted 11 lines
Quoted 7 lines

kunit/test.c line 62

Quoted 4 lines
kunit/test.c new file +4 -0
+static void kunit_print_tap_version(void)
+{
+     if (!kunit_has_printed_tap_version) {
+             kunit_printk_emit(LOGLEVEL_INFO, "TAP version 14\n");

What is this TAP thing? Why should we care what version it is on? Why are we printing this?

It's part of the TAP specification[1]. Greg and Frank asked me to make the intermediate format conform to TAP. Seems like something else I should probable document...

Yes thanks!

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
kunit/test.c new file +6 -0
+             kunit_has_printed_tap_version = true;
+     }
+}
+
+static size_t kunit_test_cases_len(struct kunit_case *test_cases)
+{
Quoted 8 lines

kunit/test.c line 72

Quoted 4 lines
kunit/test.c new file +4 -0
+     struct kunit_case *test_case;
+     size_t len = 0;
+
+     for (test_case = test_cases; test_case->run_case; test_case++)

If we make the last test case NULL, we'd just check for test_case here, and save ourselves an extra few bytes per test module. Any reason why the last test case cannot be NULL?

Quoted 1 line

Is there anyway to make that work with a statically defined array?

No you're right.

Quoted 8 lines

Basically, I want to be able to do something like:

static struct kunit_case example_test_cases[] = {
        KUNIT_CASE(example_simple_test),
        KUNIT_CASE(example_mock_test),
        {}
};
Quoted 6 lines

FYI,
#define KUNIT_CASE(test_name) { .run_case = test_name, .name = #test_name }

In order to do what you are proposing, I think I need an array of pointers to test cases, which is not ideal.

Yeah, you're right. The only other alternative is to have a:

struct kunit_module {
       const char name[256];
       int (*init)(struct kunit *test);
       void (*exit)(struct kunit *test);
       struct kunit_case *test_cases;

+ unsigned int num_cases;
};

And then something like:

#define KUNIT_MODULE(name, init, exit, cases) { \
        .name = name, \
        .init = init, \
        .exit = exit, \
        .test_cases = cases,
        num_cases = ARRAY_SIZE(cases), \
}
Quoted 2 lines

Let's evaluate which is better: one extra test case per all test cases, or an extra unsigned int for each kunit module.

I am in favor of the current method since init and exit are optional arguments. I could see myself (actually I am planning on) adding more optional things to the kunit_module, so having optional arguments will make my life a lot easier since I won't have to go through big refactorings around the kernel to support new features that tie in here.
_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#18 lore raw

PATCH v5 2/18 kunit: test: add test resource management API

In reply to Brendan Higgins

Create a common API for test managed resources like memory and test objects. A lot of times a test will want to set up infrastructure to be used in test cases; this could be anything from just wanting to allocate some memory to setting up a driver stack; this defines facilities for creating "test resources" which are managed by the test infrastructure and are automatically cleaned up at the conclusion of the test.

---
Changes Since Last Revision:
- Found and fixed bug in resource deallocation logic. Bug was discovered as a result of making a change suggested by Stephen Boyd. This does not substantially change how any of the code works conceptually.

---
 include/kunit/test.h | 110 +++++++++++++++++++++++++++++++++++++++++++
 kunit/test.c         |  95 +++++++++++++++++++++++++++++++++++++
 2 files changed, 205 insertions(+)
include/kunit/test.h +110 -0
index 8476b3d371cb9..27bd95b6b5523 100644
@@ -10,6 +10,70 @@
 #define _KUNIT_TEST_H
 
 #include <linux/types.h>
+#include <linux/slab.h>
+
+struct kunit_resource;
+
+typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
+typedef void (*kunit_resource_free_t)(struct kunit_resource *);
+
+/**
+ * struct kunit_resource - represents a *test managed resource*
+ * @allocation: for the user to store arbitrary data.
+ * @free: a user supplied function to free the resource. Populated by
+ * kunit_alloc_resource().
+ *
+ * Represents a *test managed resource*, a resource which will automatically be
+ * cleaned up at the end of a test case.
+ *
+ * Example:
+ *
+ * .. code-block:: c
+ *
+ *	struct kunit_kmalloc_params {
+ *		size_t size;
+ *		gfp_t gfp;
+ *	};
+ *
+ *	static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
+ *	{
+ *		struct kunit_kmalloc_params *params = context;
+ *		res->allocation = kmalloc(params->size, params->gfp);
+ *
+ *		if (!res->allocation)
+ *			return -ENOMEM;
+ *
+ *		return 0;
+ *	}
+ *
+ *	static void kunit_kmalloc_free(struct kunit_resource *res)
+ *	{
+ *		kfree(res->allocation);
+ *	}
+ *
+ *	void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
+ *	{
+ *		struct kunit_kmalloc_params params;
+ *		struct kunit_resource *res;
+ *
+ *		params.size = size;
+ *		params.gfp = gfp;
+ *
+ *		res = kunit_alloc_resource(test, kunit_kmalloc_init,
+ *			kunit_kmalloc_free, &params);
+ *		if (res)
+ *			return res->allocation;
+ *
+ *		return NULL;
+ *	}
+ */
+struct kunit_resource {
+	void *allocation;
+	kunit_resource_free_t free;
+
+	/* private: internal use only. */
+	struct list_head node;
+};
 
 struct kunit;
 
@@ -103,6 +167,7 @@ struct kunit {
 	const char *name; /* Read only after initialization! */
 	spinlock_t lock; /* Gaurds all mutable test state. */
 	bool success; /* Protected by lock. */
+	struct list_head resources; /* Protected by lock. */
 };
 
 void kunit_init_test(struct kunit *test, const char *name);
@@ -123,6 +188,51 @@ int kunit_run_tests(struct kunit_module *module);
 		} \
 		late_initcall(module_kunit_init##module)
 
+/**
+ * kunit_alloc_resource() - Allocates a *test managed resource*.
+ * @test: The test context object.
+ * @init: a user supplied function to initialize the resource.
+ * @free: a user supplied function to free the resource.
+ * @context: for the user to pass in arbitrary data to the init function.
+ *
+ * Allocates a *test managed resource*, a resource which will automatically be
+ * cleaned up at the end of a test case. See &struct kunit_resource for an
+ * example.
+ */
+struct kunit_resource *kunit_alloc_resource(struct kunit *test,
+					    kunit_resource_init_t init,
+					    kunit_resource_free_t free,
+					    void *context);
+
+void kunit_free_resource(struct kunit *test, struct kunit_resource *res);
+
+/**
+ * kunit_kmalloc() - Like kmalloc() except the allocation is *test managed*.
+ * @test: The test context object.
+ * @size: The size in bytes of the desired memory.
+ * @gfp: flags passed to underlying kmalloc().
+ *
+ * Just like `kmalloc(...)`, except the allocation is managed by the test case
+ * and is automatically cleaned up after the test case concludes. See &struct
+ * kunit_resource for more information.
+ */
+void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp);
+
+/**
+ * kunit_kzalloc() - Just like kunit_kmalloc(), but zeroes the allocation.
+ * @test: The test context object.
+ * @size: The size in bytes of the desired memory.
+ * @gfp: flags passed to underlying kmalloc().
+ *
+ * See kzalloc() and kunit_kmalloc() for more information.
+ */
+static inline void *kunit_kzalloc(struct kunit *test, size_t size, gfp_t gfp)
+{
+	return kunit_kmalloc(test, size, gfp | __GFP_ZERO);
+}
+
+void kunit_cleanup(struct kunit *test);
+
 void __printf(3, 4) kunit_printk(const char *level,
 				 const struct kunit *test,
 				 const char *fmt, ...);
kunit/test.c +95 -0

113 lines not on this page · raw message

Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#19 lore raw

PATCH v5 3/18 kunit: test: add string_stream a std::stream like string builder

In reply to Brendan Higgins

A number of test features need to do pretty complicated string printing where it may not be possible to rely on a single preallocated string with parameters.

So provide a library for constructing the string as you go similar to C++'s std::string.

---
Changes Since Last Revision:
- Renamed new_string_stream() to alloc_string_stream() as suggested by Stephen Boyd.
- Made string-stream a KUnit managed object - based on a suggestion made by Stephen Boyd.
- Made a number of other small changes like renaming parameters as suggested by Stephen Boyd.

---
 include/kunit/string-stream.h |  49 ++++++++++++
 kunit/Makefile                |   3 +-
 kunit/string-stream.c         | 147 ++++++++++++++++++++++++++++++++++
 3 files changed, 198 insertions(+), 1 deletion(-)
 create mode 100644 include/kunit/string-stream.h
 create mode 100644 kunit/string-stream.c
include/kunit/string-stream.h new file +49 -0
new file mode 100644
index 0000000000000..0552a05781afe
@@ -0,0 +1,49 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * C++ stream style string builder used in KUnit for building messages.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#ifndef _KUNIT_STRING_STREAM_H
+#define _KUNIT_STRING_STREAM_H
+
+#include <linux/types.h>
+#include <linux/spinlock.h>
+#include <linux/kref.h>
+#include <stdarg.h>
+
+struct string_stream_fragment {
+	struct list_head node;
+	char *fragment;
+};
+
+struct string_stream {
+	size_t length;
+	struct list_head fragments;
+	/* length and fragments are protected by this lock */
+	spinlock_t lock;
+};
+
+struct kunit;
+
+struct string_stream *alloc_string_stream(struct kunit *test);
+
+void string_stream_get(struct string_stream *stream);
+
+int string_stream_put(struct string_stream *stream);
+
+int string_stream_add(struct string_stream *stream, const char *fmt, ...);
+
+int string_stream_vadd(struct string_stream *stream,
+		       const char *fmt,
+		       va_list args);
+
+char *string_stream_get_string(struct string_stream *stream);
+
+void string_stream_clear(struct string_stream *stream);
+
+bool string_stream_is_empty(struct string_stream *stream);
+
+#endif /* _KUNIT_STRING_STREAM_H */
kunit/Makefile +2 -1
index 5efdc4dea2c08..275b565a0e81f 100644
@@ -1 +1,2 @@
-obj-$(CONFIG_KUNIT) +=			test.o
+obj-$(CONFIG_KUNIT) +=			test.o \
+					string-stream.o
kunit/string-stream.c new file +147 -0

147 lines not on this page · raw message

Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#20 lore raw

PATCH v5 4/18 kunit: test: add kunit_stream a std::stream like logger

In reply to Brendan Higgins

A lot of the expectation and assertion infrastructure prints out fairly complicated test failure messages, so add a C++ style log library for for logging test results.

---
Changes Since Last Revision:
- Renamed kunit_new_stream() to alloc_kunit_stream() as suggested by Stephen Boyd.
- Removed the ability to set log level after allocating a stream, as suggested by Stephen Boyd.
- Removed locking, as it is now unnecessary with the previous change.
- Made a number of other small changes like renaming parameters as suggested by Stephen Boyd.

---
 include/kunit/kunit-stream.h |  81 +++++++++++++++++++++++
 include/kunit/test.h         |   3 +
 kunit/Makefile               |   3 +-
 kunit/kunit-stream.c         | 123 +++++++++++++++++++++++++++++++++++
 kunit/test.c                 |   6 ++
 5 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 include/kunit/kunit-stream.h
 create mode 100644 kunit/kunit-stream.c
include/kunit/kunit-stream.h new file +81 -0
new file mode 100644
index 0000000000000..a7b53eabf6be4
@@ -0,0 +1,81 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * C++ stream style string formatter and printer used in KUnit for outputting
+ * KUnit messages.
+ *
+ * Copyright (C) 2019, Google LLC.
+ * Author: Brendan Higgins <[email protected]>
+ */
+
+#ifndef _KUNIT_KUNIT_STREAM_H
+#define _KUNIT_KUNIT_STREAM_H
+
+#include <linux/types.h>
+#include <kunit/string-stream.h>
+
+struct kunit;
+
+/**
+ * struct kunit_stream - a std::stream style string builder.
+ *
+ * A std::stream style string builder. Allows messages to be built up and
+ * printed all at once.
+ */
+struct kunit_stream {
+	/* private: internal use only. */
+	struct kunit *test;
+	const char *level;
+	struct string_stream *internal_stream;
+};
+
+/**
+ * alloc_kunit_stream() - constructs a new &struct kunit_stream.
+ * @test: The test context object.
+ * @level: The log level at which to print out the message.
+ *
+ * Constructs a new test managed &struct kunit_stream.
+ */
+struct kunit_stream *alloc_kunit_stream(struct kunit *test, const char *level);
+
+/**
+ * kunit_stream_add(): adds the formatted input to the internal buffer.
+ * @kstream: the stream being operated on.
+ * @fmt: printf style format string to append to stream.
+ *
+ * Appends the formatted string, @fmt, to the internal buffer.
+ */
+void __printf(2, 3) kunit_stream_add(struct kunit_stream *kstream,
+				     const char *fmt, ...);
+
+/**
+ * kunit_stream_append(): appends the contents of @other to @kstream.
+ * @kstream: the stream to which @other is appended.
+ * @other: the stream whose contents are appended to @kstream.
+ *
+ * Appends the contents of @other to @kstream.
+ */
+void kunit_stream_append(struct kunit_stream *kstream,
+			 struct kunit_stream *other);
+
+/**
+ * kunit_stream_commit(): prints out the internal buffer to the user.
+ * @kstream: the stream being operated on.
+ *
+ * Outputs the contents of the internal buffer as a kunit_printk formatted
+ * output. KUNIT_STREAM ONLY OUTPUTS ITS BUFFER TO THE USER IF COMMIT IS
+ * CALLED!!! The reason for this is that it allows us to construct a message
+ * before we know whether we want to print it out; this can be extremely handy
+ * if there is information you might need for a failure message that is easiest
+ * to collect in the steps leading up to the actual check.
+ */
+void kunit_stream_commit(struct kunit_stream *kstream);
+
+/**
+ * kunit_stream_clear(): clears the internal buffer.
+ * @kstream: the stream being operated on.
+ *
+ * Clears the contents of the internal buffer.
+ */
+void kunit_stream_clear(struct kunit_stream *kstream);
+
+#endif /* _KUNIT_KUNIT_STREAM_H */
include/kunit/test.h +3 -0
index 27bd95b6b5523..83fb7ace1b320 100644
@@ -11,6 +11,7 @@
 
 #include <linux/types.h>
 #include <linux/slab.h>
+#include <kunit/kunit-stream.h>
 
 struct kunit_resource;
 
@@ -172,6 +173,8 @@ struct kunit {
 
 void kunit_init_test(struct kunit *test, const char *name);
 
+void kunit_fail(struct kunit *test, struct kunit_stream *stream);
+
 int kunit_run_tests(struct kunit_module *module);
 
 /**
kunit/Makefile +2 -1
index 275b565a0e81f..6ddc622ee6b1c 100644
@@ -1,2 +1,3 @@
 obj-$(CONFIG_KUNIT) +=			test.o \
-					string-stream.o
+					string-stream.o \
+					kunit-stream.o
kunit/kunit-stream.c new file +123 -0

123 lines not on this page · raw message

kunit/test.c +6 -0
index 53838f5394303..9404e4d34fa3f 100644
@@ -139,6 +139,12 @@ static void kunit_print_test_case_ok_not_ok(struct kunit_case *test_case,
 			      test_case->name);
 }
 
+void kunit_fail(struct kunit *test, struct kunit_stream *stream)
+{
+	kunit_set_success(test, false);
+	kunit_stream_commit(stream);
+}
+
 void kunit_init_test(struct kunit *test, const char *name)
 {
 	spin_lock_init(&test->lock);
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#21 lore raw

PATCH v5 5/18 kunit: test: add the concept of expectations

In reply to Brendan Higgins

Add support for expectations, which allow properties to be specified and then verified in tests.

---
Changes Since Last Revision:
- Added typechecking to expectations that compare two things of arbitrary types (it just verifies that the two compared types match), as suggested by Stephen Boyd.

---
 include/kunit/test.h | 525 +++++++++++++++++++++++++++++++++++++++++++
 kunit/test.c         |  66 ++++++
 2 files changed, 591 insertions(+)
include/kunit/test.h +525 -0
index 83fb7ace1b320..e4c760ccc8717 100644
@@ -9,6 +9,7 @@
 #ifndef _KUNIT_TEST_H
 #define _KUNIT_TEST_H
 
+#include <linux/kernel.h>
 #include <linux/types.h>
 #include <linux/slab.h>
 #include <kunit/kunit-stream.h>
@@ -271,4 +272,528 @@ void __printf(3, 4) kunit_printk(const char *level,
 #define kunit_err(test, fmt, ...) \
 		kunit_printk(KERN_ERR, test, fmt, ##__VA_ARGS__)
 
+/*
+ * Generates a compile-time warning in case of comparing incompatible types.
+ */
+#define __kunit_typecheck(lhs, rhs) \
+	((void) __typecheck(lhs, rhs))
+
+static inline struct kunit_stream *kunit_expect_start(struct kunit *test,
+						      const char *file,
+						      const char *line)
+{
+	struct kunit_stream *stream = alloc_kunit_stream(test, KERN_ERR);
+
+	kunit_stream_add(stream, "EXPECTATION FAILED at %s:%s\n\t", file, line);
+
+	return stream;
+}
+
+static inline void kunit_expect_end(struct kunit *test,
+				    bool success,
+				    struct kunit_stream *stream)
+{
+	if (!success)
+		kunit_fail(test, stream);
+	else
+		kunit_stream_clear(stream);
+}
+
+#define KUNIT_EXPECT_START(test) \
+		kunit_expect_start(test, __FILE__, __stringify(__LINE__))
+
+#define KUNIT_EXPECT_END(test, success, stream) \
+		kunit_expect_end(test, success, stream)
+
+#define KUNIT_EXPECT_MSG(test, success, message, fmt, ...) do {		       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, message);				       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+	KUNIT_EXPECT_END(test, success, __stream);			       \
+} while (0)
+
+#define KUNIT_EXPECT(test, success, message) do {			       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, message);				       \
+	KUNIT_EXPECT_END(test, success, __stream);			       \
+} while (0)
+
+/**
+ * KUNIT_SUCCEED() - A no-op expectation. Only exists for code clarity.
+ * @test: The test context object.
+ *
+ * The opposite of KUNIT_FAIL(), it is an expectation that cannot fail. In other
+ * words, it does nothing and only exists for code clarity. See
+ * KUNIT_EXPECT_TRUE() for more information.
+ */
+#define KUNIT_SUCCEED(test) do {} while (0)
+
+/**
+ * KUNIT_FAIL() - Always causes a test to fail when evaluated.
+ * @test: The test context object.
+ * @fmt: an informational message to be printed when the assertion is made.
+ * @...: string format arguments.
+ *
+ * The opposite of KUNIT_SUCCEED(), it is an expectation that always fails. In
+ * other words, it always results in a failed expectation, and consequently
+ * always causes the test case to fail when evaluated. See KUNIT_EXPECT_TRUE()
+ * for more information.
+ */
+#define KUNIT_FAIL(test, fmt, ...) do {					       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+	KUNIT_EXPECT_END(test, false, __stream);			       \
+} while (0)
+
+/**
+ * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
+ * @test: The test context object.
+ * @condition: an arbitrary boolean expression. The test fails when this does
+ * not evaluate to true.
+ *
+ * This and expectations of the form `KUNIT_EXPECT_*` will cause the test case
+ * to fail when the specified condition is not met; however, it will not prevent
+ * the test case from continuing to run; this is otherwise known as an
+ * *expectation failure*.
+ */
+#define KUNIT_EXPECT_TRUE(test, condition)				       \
+		KUNIT_EXPECT(test, (condition),				       \
+		       "Expected " #condition " is true, but is false\n")
+
+#define KUNIT_EXPECT_TRUE_MSG(test, condition, fmt, ...)		       \
+		KUNIT_EXPECT_MSG(test, (condition),			       \
+				"Expected " #condition " is true, but is false\n",\
+				fmt, ##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_FALSE() - Makes a test failure when the expression is not false.
+ * @test: The test context object.
+ * @condition: an arbitrary boolean expression. The test fails when this does
+ * not evaluate to false.
+ *
+ * Sets an expectation that @condition evaluates to false. See
+ * KUNIT_EXPECT_TRUE() for more information.
+ */
+#define KUNIT_EXPECT_FALSE(test, condition)				       \
+		KUNIT_EXPECT(test, !(condition),			       \
+		       "Expected " #condition " is false, but is true\n")
+
+#define KUNIT_EXPECT_FALSE_MSG(test, condition, fmt, ...)		       \
+		KUNIT_EXPECT_MSG(test, !(condition),			       \
+				"Expected " #condition " is false, but is true\n",\
+				fmt, ##__VA_ARGS__)
+
+void kunit_expect_binary_msg(struct kunit *test,
+			     long long left, const char *left_name,
+			     long long right, const char *right_name,
+			     bool compare_result,
+			     const char *compare_name,
+			     const char *file,
+			     const char *line,
+			     const char *fmt, ...);
+
+static inline void kunit_expect_binary(struct kunit *test,
+				       long long left, const char *left_name,
+				       long long right, const char *right_name,
+				       bool compare_result,
+				       const char *compare_name,
+				       const char *file,
+				       const char *line)
+{
+	kunit_expect_binary_msg(test,
+				left, left_name,
+				right, right_name,
+				compare_result,
+				compare_name,
+				file,
+				line,
+				NULL);
+}
+
+void kunit_expect_ptr_binary_msg(struct kunit *test,
+				 void *left, const char *left_name,
+				 void *right, const char *right_name,
+				 bool compare_result,
+				 const char *compare_name,
+				 const char *file,
+				 const char *line,
+				 const char *fmt, ...);
+
+static inline void kunit_expect_ptr_binary(struct kunit *test,
+					   void *left, const char *left_name,
+					   void *right, const char *right_name,
+					   bool compare_result,
+					   const char *compare_name,
+					   const char *file,
+					   const char *line)
+{
+	kunit_expect_ptr_binary_msg(test,
+				    left, left_name,
+				    right, right_name,
+				    compare_result,
+				    compare_name,
+				    file,
+				    line,
+				    NULL);
+}
+
+/*
+ * A factory macro for defining the expectations for the basic comparisons
+ * defined for the built in types.
+ *
+ * Unfortunately, there is no common type that all types can be promoted to for
+ * which all the binary operators behave the same way as for the actual types
+ * (for example, there is no type that long long and unsigned long long can
+ * both be cast to where the comparison result is preserved for all values). So
+ * the best we can do is do the comparison in the original types and then coerce
+ * everything to long long for printing; this way, the comparison behaves
+ * correctly and the printed out value usually makes sense without
+ * interpretation, but can always be interpretted to figure out the actual
+ * value.
+ */
+#define KUNIT_EXPECT_BINARY(test, left, condition, right) do {		       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_expect_binary(test,					       \
+			    (long long) __left, #left,			       \
+			    (long long) __right, #right,		       \
+			    __left condition __right, #condition,	       \
+			    __FILE__, __stringify(__LINE__));		       \
+} while (0)
+
+#define KUNIT_EXPECT_BINARY_MSG(test, left, condition, right, fmt, ...) do {   \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_expect_binary_msg(test,					       \
+				(long long) __left, #left,		       \
+				(long long) __right, #right,		       \
+				__left condition __right, #condition,	       \
+				__FILE__, __stringify(__LINE__),	       \
+				fmt, ##__VA_ARGS__);			       \
+} while (0)
+
+/*
+ * Just like KUNIT_EXPECT_BINARY, but for comparing pointer types.
+ */
+#define KUNIT_EXPECT_PTR_BINARY(test, left, condition, right) do {	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_expect_ptr_binary(test,					       \
+			    (void *) __left, #left,			       \
+			    (void *) __right, #right,			       \
+			    __left condition __right, #condition,	       \
+			    __FILE__, __stringify(__LINE__));		       \
+} while (0)
+
+#define KUNIT_EXPECT_PTR_BINARY_MSG(test, left, condition, right, fmt, ...)    \
+do {									       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_expect_ptr_binary_msg(test,				       \
+				    (void *) __left, #left,		       \
+				    (void *) __right, #right,		       \
+				    __left condition __right, #condition,      \
+				    __FILE__, __stringify(__LINE__),	       \
+				    fmt, ##__VA_ARGS__);		       \
+} while (0)
+
+/**
+ * KUNIT_EXPECT_EQ() - Sets an expectation that @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are
+ * equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) == (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_EQ(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, ==, right)
+
+#define KUNIT_EXPECT_EQ_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					==,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_PTR_EQ() - Expects that pointers @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a pointer.
+ * @right: an arbitrary expression that evaluates to a pointer.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are
+ * equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) == (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_PTR_EQ(test, left, right) \
+		KUNIT_EXPECT_PTR_BINARY(test, left, ==, right)
+
+#define KUNIT_EXPECT_PTR_EQ_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_PTR_BINARY_MSG(test,			       \
+					    left,			       \
+					    ==,				       \
+					    right,			       \
+					    fmt,			       \
+					    ##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_NE() - An expectation that @left and @right are not equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are not
+ * equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) != (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_NE(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, !=, right)
+
+#define KUNIT_EXPECT_NE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					!=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_PTR_NE() - Expects that pointers @left and @right are not equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a pointer.
+ * @right: an arbitrary expression that evaluates to a pointer.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are not
+ * equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) != (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_PTR_NE(test, left, right) \
+		KUNIT_EXPECT_PTR_BINARY(test, left, !=, right)
+
+#define KUNIT_EXPECT_PTR_NE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_PTR_BINARY_MSG(test,			       \
+					    left,			       \
+					    !=,				       \
+					    right,			       \
+					    fmt,			       \
+					    ##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_LT() - An expectation that @left is less than @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the value that @left evaluates to is less than the
+ * value that @right evaluates to. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) < (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_LT(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, <, right)
+
+#define KUNIT_EXPECT_LT_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					<,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_LE() - Expects that @left is less than or equal to @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the value that @left evaluates to is less than or
+ * equal to the value that @right evaluates to. Semantically this is equivalent
+ * to KUNIT_EXPECT_TRUE(@test, (@left) <= (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_LE(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, <=, right)
+
+#define KUNIT_EXPECT_LE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					<=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_GT() - An expectation that @left is greater than @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the value that @left evaluates to is greater than
+ * the value that @right evaluates to. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) > (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_GT(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, >, right)
+
+#define KUNIT_EXPECT_GT_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					>,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_GE() - Expects that @left is greater than or equal to @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an expectation that the value that @left evaluates to is greater than
+ * the value that @right evaluates to. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, (@left) >= (@right)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_GE(test, left, right) \
+		KUNIT_EXPECT_BINARY(test, left, >=, right)
+
+#define KUNIT_EXPECT_GE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_EXPECT_BINARY_MSG(test,				       \
+					left,				       \
+					>=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_EXPECT_STREQ() - Expects that strings @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a null terminated string.
+ * @right: an arbitrary expression that evaluates to a null terminated string.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are
+ * equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, !strcmp((@left), (@right))). See KUNIT_EXPECT_TRUE()
+ * for more information.
+ */
+#define KUNIT_EXPECT_STREQ(test, left, right) do {			       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Expected " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+									       \
+	KUNIT_EXPECT_END(test, !strcmp(left, right), __stream);		       \
+} while (0)
+
+#define KUNIT_EXPECT_STREQ_MSG(test, left, right, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Expected " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+									       \
+	KUNIT_EXPECT_END(test, !strcmp(left, right), __stream);		       \
+} while (0)
+
+/**
+ * KUNIT_EXPECT_STRNEQ() - Expects that strings @left and @right are not equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a null terminated string.
+ * @right: an arbitrary expression that evaluates to a null terminated string.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are
+ * not equal. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, strcmp((@left), (@right))). See KUNIT_EXPECT_TRUE()
+ * for more information.
+ */
+#define KUNIT_EXPECT_STRNEQ(test, left, right) do {			       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Expected " #left " != " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+									       \
+	KUNIT_EXPECT_END(test, strcmp(left, right), __stream);		       \
+} while (0)
+
+#define KUNIT_EXPECT_STRNEQ_MSG(test, left, right, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Expected " #left " != " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+									       \
+	KUNIT_EXPECT_END(test, strcmp(left, right), __stream);		       \
+} while (0)
+
+/**
+ * KUNIT_EXPECT_NOT_ERR_OR_NULL() - Expects that @ptr is not null and not err.
+ * @test: The test context object.
+ * @ptr: an arbitrary pointer.
+ *
+ * Sets an expectation that the value that @ptr evaluates to is not null and not
+ * an errno stored in a pointer. This is semantically equivalent to
+ * KUNIT_EXPECT_TRUE(@test, !IS_ERR_OR_NULL(@ptr)). See KUNIT_EXPECT_TRUE() for
+ * more information.
+ */
+#define KUNIT_EXPECT_NOT_ERR_OR_NULL(test, ptr) do {			       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(ptr) __ptr = (ptr);					       \
+									       \
+	if (!__ptr)							       \
+		kunit_stream_add(__stream,				       \
+			      "Expected " #ptr " is not null, but is\n");      \
+	if (IS_ERR(__ptr))						       \
+		kunit_stream_add(__stream,				       \
+			      "Expected " #ptr " is not error, but is: %ld",   \
+			      PTR_ERR(__ptr));				       \
+									       \
+	KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream);	       \
+} while (0)
+
+#define KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, ptr, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_EXPECT_START(test);	       \
+	typeof(ptr) __ptr = (ptr);					       \
+									       \
+	if (!__ptr) {							       \
+		kunit_stream_add(__stream,				       \
+			      "Expected " #ptr " is not null, but is\n");      \
+		kunit_stream_add(__stream, fmt, ##__VA_ARGS__);		       \
+	}								       \
+	if (IS_ERR(__ptr)) {						       \
+		kunit_stream_add(__stream,				       \
+			      "Expected " #ptr " is not error, but is: %ld",   \
+			      PTR_ERR(__ptr));				       \
+									       \
+		kunit_stream_add(__stream, fmt, ##__VA_ARGS__);		       \
+	}								       \
+	KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream);	       \
+} while (0)
+
 #endif /* _KUNIT_TEST_H */
kunit/test.c +66 -0

69 lines not on this page · raw message

Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#22 lore raw

PATCH v5 6/18 kbuild: enable building KUnit

In reply to Brendan Higgins

KUnit is a new unit testing framework for the kernel and when used is built into the kernel as a part of it. Add KUnit to the root Kconfig and Makefile to allow it to be actually built.

---
 Kconfig  | 2 ++
 Makefile | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)
Kconfig +2 -0
index 48a80beab6853..10428501edb78 100644
@@ -30,3 +30,5 @@ source "crypto/Kconfig"
 source "lib/Kconfig"
 
 source "lib/Kconfig.debug"
+
+source "kunit/Kconfig"
Makefile +1 -1
index b81e172612507..4b544a8eebee4 100644
@@ -991,7 +991,7 @@ endif
 PHONY += prepare0
 
 ifeq ($(KBUILD_EXTMOD),)
-core-y		+= kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/
+core-y		+= kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/ kunit/
 
 vmlinux-dirs	:= $(patsubst %/,%,$(filter %/, $(init-y) $(init-m) \
 		     $(core-y) $(core-m) $(drivers-y) $(drivers-m) \
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#23 lore raw

Re: [PATCH v5 06/18] kbuild: enable building KUnit

Kconfig source "crypto/Kconfig" · line 34

Quoted 10 lines · Brendan Higgins
Kconfig +2 -0
index 48a80beab6853..10428501edb78 100644
@@ -30,3 +30,5 @@ source "crypto/Kconfig"
 source "lib/Kconfig"
 
 source "lib/Kconfig.debug"
+
+source "kunit/Kconfig"

This patch would break compilation as kunit/Kconfig is not introduced. This would would also break bisectability on this commit. This change should either be folded in to the next patch, or just be a separate patch after the next one.

Luis

#24 lore raw

Re: [PATCH v5 06/18] kbuild: enable building KUnit

Quoted 9 lines · Luis Chamberlain
Quoted 7 lines · Brendan Higgins
Kconfig +0 -0
index 48a80beab6853..10428501edb78 100644
@@ -30,3 +30,5 @@ source "crypto/Kconfig"
 source "lib/Kconfig"
 
Quoted 8 lines

Kconfig source "crypto/Kconfig" · line 34

Quoted 3 lines
Kconfig +2 -0
 source "lib/Kconfig.debug"
+
+source "kunit/Kconfig"

This patch would break compilation as kunit/Kconfig is not introduced. This would would also break bisectability on this commit. This change should either be folded in to the next patch, or just be a separate patch after the next one.

Maybe my brain isn't working right now, but I am pretty darn sure that I introduce kunit/Kconfig in the very first patch of this series. Quoting from the change summary from the first commit:

Quoted 7 lines
 include/kunit/test.h | 161 +++++++++++++++++++++++++++++++++
 kunit/Kconfig        |  17 ++++
 kunit/Makefile       |   1 +
 kunit/test.c         | 210 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 389 insertions(+)
 create mode 100644 include/kunit/test.h
 create mode 100644 kunit/Kconfig

I am not crazy, right?

Quoted 2 lines
 create mode 100644 kunit/Makefile
 create mode 100644 kunit/test.c
#25 lore raw

Re: [PATCH v5 06/18] kbuild: enable building KUnit

Quoted 19 lines · Brendan Higgins
Quoted 9 lines · Luis Chamberlain
Quoted 7 lines · Brendan Higgins
Kconfig +0 -0
index 48a80beab6853..10428501edb78 100644
@@ -30,3 +30,5 @@ source "crypto/Kconfig"
 source "lib/Kconfig"
 
Quoted 8 lines

Kconfig source "crypto/Kconfig" · line 34

Quoted 3 lines
Kconfig +2 -0
 source "lib/Kconfig.debug"
+
+source "kunit/Kconfig"

This patch would break compilation as kunit/Kconfig is not introduced. This would would also break bisectability on this commit. This change should either be folded in to the next patch, or just be a separate patch after the next one.

Quoted 3 lines

Maybe my brain isn't working right now, but I am pretty darn sure that I introduce kunit/Kconfig in the very first patch of this series. Quoting from the change summary from the first commit:

Indeed, my mistake, thanks!

Luis

#26 lore raw

PATCH v5 7/18 kunit: test: add initial tests

In reply to Brendan Higgins

Add a test for string stream along with a simpler example.

---
 kunit/Kconfig              | 21 +++++++++
 kunit/Makefile             |  4 ++
 kunit/example-test.c       | 88 ++++++++++++++++++++++++++++++++++++++
 kunit/string-stream-test.c | 75 ++++++++++++++++++++++++++++++++
 4 files changed, 188 insertions(+)
 create mode 100644 kunit/example-test.c
 create mode 100644 kunit/string-stream-test.c
kunit/Kconfig +21 -0
index 330ae83527c23..8541ef95b65ad 100644
@@ -14,4 +14,25 @@ config KUNIT
 	  architectures. For more information, please see
 	  Documentation/dev-tools/kunit/.
 
+config KUNIT_TEST
+	bool "KUnit test for KUnit"
+	depends on KUNIT
+	help
+	  Enables the unit tests for the KUnit test framework. These tests test
+	  the KUnit test framework itself; the tests are both written using
+	  KUnit and test KUnit. This option should only be enabled for testing
+	  purposes by developers interested in testing that KUnit works as
+	  expected.
+
+config KUNIT_EXAMPLE_TEST
+	bool "Example test for KUnit"
+	depends on KUNIT
+	help
+	  Enables an example unit test that illustrates some of the basic
+	  features of KUnit. This test only exists to help new users understand
+	  what KUnit is and how it is used. Please refer to the example test
+	  itself, kunit/example-test.c, for more information. This option is
+	  intended for curious hackers who would like to understand how to use
+	  KUnit for kernel development.
+
 endmenu
kunit/Makefile +4 -0
index 6ddc622ee6b1c..60a9ea6cb4697 100644
@@ -1,3 +1,7 @@
 obj-$(CONFIG_KUNIT) +=			test.o \
 					string-stream.o \
 					kunit-stream.o
+
+obj-$(CONFIG_KUNIT_TEST) +=		string-stream-test.o
+
+obj-$(CONFIG_KUNIT_EXAMPLE_TEST) +=	example-test.o
kunit/example-test.c new file +88 -0

88 lines not on this page · raw message

kunit/string-stream-test.c new file +75 -0

75 lines not on this page · raw message

Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#27 lore raw

Re: [PATCH v5 07/18] kunit: test: add initial tests

kunit/example-test.c

Quoted 5 lines · Brendan Higgins
kunit/example-test.c new file +0 -0
new file mode 100644
index 0000000000000..f44b8ece488bb

<-- snip -->

Quoted 4 lines

+/*
+ * This defines a suite or grouping of tests.
+ *
+ * Test cases are defined as belonging to the suite by adding them to

Quoted 8 lines

+ * kunit_cases.
+ *
+ * Often it is desirable to run some function which will set up things which
+ * will be used by every test; this is accomplished with an init function
+ * which runs before each test case is invoked. Similarly, an exit function
+ * may be specified which runs after every test case and can be used to for
+ * cleanup. For clarity, running tests in a test module would behave as follows:
+ *

To be clear this is not the kernel module init, but rather the kunit module init. I think using kmodule would make this clearer to a reader.

Quoted 8 lines

+ * module.init(test);
+ * module.test_case[0](test);
+ * module.exit(test);
+ * module.init(test);
+ * module.test_case[1](test);
+ * module.exit(test);
+ * ...;
+ */

Luis

#28 lore raw

Re: [PATCH v5 07/18] kunit: test: add initial tests

Quoted 23 lines · Luis Chamberlain

kunit/example-test.c

Quoted 5 lines · Brendan Higgins
kunit/example-test.c new file +0 -0
new file mode 100644
index 0000000000000..f44b8ece488bb

<-- snip -->

Quoted 4 lines

+/*
+ * This defines a suite or grouping of tests.
+ *
+ * Test cases are defined as belonging to the suite by adding them to

Quoted 8 lines

+ * kunit_cases.
+ *
+ * Often it is desirable to run some function which will set up things which
+ * will be used by every test; this is accomplished with an init function
+ * which runs before each test case is invoked. Similarly, an exit function
+ * may be specified which runs after every test case and can be used to for
+ * cleanup. For clarity, running tests in a test module would behave as follows:
+ *

Quoted 2 lines

To be clear this is not the kernel module init, but rather the kunit module init. I think using kmodule would make this clearer to a reader.

Seems reasonable. Will fix in next revision.

Quoted 10 lines
Quoted 8 lines

+ * module.init(test);
+ * module.test_case[0](test);
+ * module.exit(test);
+ * module.init(test);
+ * module.test_case[1](test);
+ * module.exit(test);
+ * ...;
+ */

Luis

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#29 lore raw

Re: [PATCH v5 07/18] kunit: test: add initial tests

Quoted 25 lines · Brendan Higgins
Quoted 23 lines · Luis Chamberlain

kunit/example-test.c

Quoted 5 lines · Brendan Higgins
kunit/example-test.c new file +0 -0
new file mode 100644
index 0000000000000..f44b8ece488bb

<-- snip -->

Quoted 12 lines

+/*
+ * This defines a suite or grouping of tests.
+ *
+ * Test cases are defined as belonging to the suite by adding them to
+ * kunit_cases.
+ *
+ * Often it is desirable to run some function which will set up things which
+ * will be used by every test; this is accomplished with an init function
+ * which runs before each test case is invoked. Similarly, an exit function
+ * may be specified which runs after every test case and can be used to for
+ * cleanup. For clarity, running tests in a test module would behave as follows:
+ *

Quoted 13 lines
Quoted 2 lines

To be clear this is not the kernel module init, but rather the kunit module init. I think using kmodule would make this clearer to a reader.

Seems reasonable. Will fix in next revision.

Quoted 8 lines
Quoted 8 lines

+ * module.init(test);
+ * module.test_case[0](test);
+ * module.exit(test);
+ * module.init(test);
+ * module.test_case[1](test);
+ * module.exit(test);
+ * ...;
+ */

Do you think it might be clearer yet to rename struct kunit_module *module; to struct kunit_suite *suite;?

#30 lore raw

Re: [PATCH v5 07/18] kunit: test: add initial tests

Quoted 41 lines · Brendan Higgins
Quoted 25 lines · Brendan Higgins
Quoted 23 lines · Luis Chamberlain

kunit/example-test.c

Quoted 5 lines · Brendan Higgins
kunit/example-test.c new file +0 -0
new file mode 100644
index 0000000000000..f44b8ece488bb

<-- snip -->

Quoted 12 lines

+/*
+ * This defines a suite or grouping of tests.
+ *
+ * Test cases are defined as belonging to the suite by adding them to
+ * kunit_cases.
+ *
+ * Often it is desirable to run some function which will set up things which
+ * will be used by every test; this is accomplished with an init function
+ * which runs before each test case is invoked. Similarly, an exit function
+ * may be specified which runs after every test case and can be used to for
+ * cleanup. For clarity, running tests in a test module would behave as follows:
+ *

Quoted 13 lines
Quoted 2 lines

To be clear this is not the kernel module init, but rather the kunit module init. I think using kmodule would make this clearer to a reader.

Seems reasonable. Will fix in next revision.

Quoted 8 lines
Quoted 8 lines

+ * module.init(test);
+ * module.test_case[0](test);
+ * module.exit(test);
+ * module.init(test);
+ * module.test_case[1](test);
+ * module.exit(test);
+ * ...;
+ */

Quoted 2 lines

Do you think it might be clearer yet to rename struct kunit_module *module; to struct kunit_suite *suite;?

Yes. Definitely. Or struct kunit_test. Up to you.

Luis

#31 lore raw

PATCH v5 8/18 objtool: add kunit_try_catch_throw to the noreturn list

In reply to Brendan Higgins

Fix the following warning seen on GCC 7.3:
kunit/test-test.o: warning: objtool: kunit_test_unsuccessful_try() falls through to next function kunit_test_catch()

kunit_try_catch_throw is a function added in the following patch in this series; it allows KUnit, a unit testing framework for the kernel, to bail out of a broken test. As a consequence, it is a new __noreturn function that objtool thinks is broken (as seen above). So fix this warning by adding kunit_try_catch_throw to objtool's noreturn list.

---
 tools/objtool/check.c | 1 +
 1 file changed, 1 insertion(+)
tools/objtool/check.c +1 -0
index 172f991957269..98db5fe85c797 100644
@@ -134,6 +134,7 @@ static int __dead_end_function(struct objtool_file *file, struct symbol *func,
 		"usercopy_abort",
 		"machine_real_restart",
 		"rewind_stack_do_exit",
+		"kunit_try_catch_throw",
 	};
 
 	if (func->bind == STB_WEAK)
Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#32 lore raw

PATCH v5 9/18 kunit: test: add support for test abort

In reply to Brendan Higgins

Add support for aborting/bailing out of test cases, which is needed for implementing assertions.

An assertion is like an expectation, but bails out of the test case early if the assertion is not met. The idea with assertions is that you use them to state all the preconditions for your test. Logically speaking, these are the premises of the test case, so if a premise isn't true, there is no point in continuing the test case because there are no conclusions that can be drawn without the premises. Whereas, the expectation is the thing you are trying to prove.

---
 include/kunit/test.h      |  14 +++
 include/kunit/try-catch.h |  69 +++++++++++++++
 kunit/Makefile            |   3 +-
 kunit/test.c              | 177 ++++++++++++++++++++++++++++++++++----
 kunit/try-catch.c         |  95 ++++++++++++++++++++
 5 files changed, 342 insertions(+), 16 deletions(-)
 create mode 100644 include/kunit/try-catch.h
 create mode 100644 kunit/try-catch.c
include/kunit/test.h +14 -0
index e4c760ccc8717..194c85afc69a8 100644
@@ -13,6 +13,7 @@
 #include <linux/types.h>
 #include <linux/slab.h>
 #include <kunit/kunit-stream.h>
+#include <kunit/try-catch.h>
 
 struct kunit_resource;
 
@@ -167,15 +168,28 @@ struct kunit {
 
 	/* private: internal use only. */
 	const char *name; /* Read only after initialization! */
+	struct kunit_try_catch try_catch;
 	spinlock_t lock; /* Gaurds all mutable test state. */
 	bool success; /* Protected by lock. */
+	bool death_test; /* Protected by lock. */
 	struct list_head resources; /* Protected by lock. */
 };
 
+static inline void kunit_set_death_test(struct kunit *test, bool death_test)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&test->lock, flags);
+	test->death_test = death_test;
+	spin_unlock_irqrestore(&test->lock, flags);
+}
+
 void kunit_init_test(struct kunit *test, const char *name);
 
 void kunit_fail(struct kunit *test, struct kunit_stream *stream);
 
+void kunit_abort(struct kunit *test);
+
 int kunit_run_tests(struct kunit_module *module);
 
 /**
include/kunit/try-catch.h new file +69 -0

69 lines not on this page · raw message

kunit/Makefile +2 -1
index 60a9ea6cb4697..1f7680cfa11ad 100644
@@ -1,6 +1,7 @@
 obj-$(CONFIG_KUNIT) +=			test.o \
 					string-stream.o \
-					kunit-stream.o
+					kunit-stream.o \
+					try-catch.o
 
 obj-$(CONFIG_KUNIT_TEST) +=		string-stream-test.o
 
kunit/test.c +162 -15

222 lines not on this page · raw message

kunit/try-catch.c new file +95 -0

95 lines not on this page · raw message

Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#33 lore raw

PATCH v5 10/18 kunit: test: add tests for kunit test abort

In reply to Brendan Higgins

Add KUnit tests for the KUnit test abort mechanism (see preceding commit). Add tests both for general try catch mechanism as well as non-architecture specific mechanism.

---
 kunit/Makefile    |   3 +-
 kunit/test-test.c | 101 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 103 insertions(+), 1 deletion(-)
 create mode 100644 kunit/test-test.c
kunit/Makefile +2 -1
index 1f7680cfa11ad..533355867abd2 100644
@@ -3,6 +3,7 @@ obj-$(CONFIG_KUNIT) +=			test.o \
 					kunit-stream.o \
 					try-catch.o
 
-obj-$(CONFIG_KUNIT_TEST) +=		string-stream-test.o
+obj-$(CONFIG_KUNIT_TEST) +=		test-test.o \
+					string-stream-test.o
 
 obj-$(CONFIG_KUNIT_EXAMPLE_TEST) +=	example-test.o
kunit/test-test.c new file +101 -0

101 lines not on this page · raw message

Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#34 lore raw

PATCH v5 11/18 kunit: test: add the concept of assertions

In reply to Brendan Higgins

Add support for assertions which are like expectations except the test terminates if the assertion is not satisfied.

The idea with assertions is that you use them to state all the preconditions for your test. Logically speaking, these are the premises of the test case, so if a premise isn't true, there is no point in continuing the test case because there are no conclusions that can be drawn without the premises. Whereas, the expectation is the thing you are trying to prove. It is not used universally in x-unit style test frameworks, but I really like it as a convention. You could still express the idea of a premise using the above idiom, but I think KUNIT_ASSERT_* states the intended idea perfectly.

---
 include/kunit/test.h       | 499 ++++++++++++++++++++++++++++++++++++-
 kunit/string-stream-test.c |  12 +-
 kunit/test-test.c          |   2 +
 kunit/test.c               |  66 +++++
 4 files changed, 570 insertions(+), 9 deletions(-)
include/kunit/test.h +496 -3
index 194c85afc69a8..92ddad36ab9b8 100644
@@ -86,9 +86,10 @@ struct kunit;
  * @name: the name of the test case.
  *
  * A test case is a function with the signature, ``void (*)(struct kunit *)``
- * that makes expectations (see KUNIT_EXPECT_TRUE()) about code under test. Each
- * test case is associated with a &struct kunit_module and will be run after the
- * module's init function and followed by the module's exit function.
+ * that makes expectations and assertions (see KUNIT_EXPECT_TRUE() and
+ * KUNIT_ASSERT_TRUE()) about code under test. Each test case is associated with
+ * a &struct kunit_module and will be run after the module's init function and
+ * followed by the module's exit function.
  *
  * A test case should be static and should only be created with the KUNIT_CASE()
  * macro; additionally, every array of test cases should be terminated with an
@@ -810,4 +811,496 @@ do {									       \
 	KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream);	       \
 } while (0)
 
+static inline struct kunit_stream *kunit_assert_start(struct kunit *test,
+						      const char *file,
+						      const char *line)
+{
+	struct kunit_stream *stream = alloc_kunit_stream(test, KERN_ERR);
+
+	kunit_stream_add(stream, "ASSERTION FAILED at %s:%s\n\t", file, line);
+
+	return stream;
+}
+
+static inline void kunit_assert_end(struct kunit *test,
+				    bool success,
+				    struct kunit_stream *stream)
+{
+	if (!success) {
+		kunit_fail(test, stream);
+		kunit_abort(test);
+	} else {
+		kunit_stream_clear(stream);
+	}
+}
+
+#define KUNIT_ASSERT_START(test) \
+		kunit_assert_start(test, __FILE__, __stringify(__LINE__))
+
+#define KUNIT_ASSERT_END(test, success, stream) \
+		kunit_assert_end(test, success, stream)
+
+#define KUNIT_ASSERT(test, success, message) do {			       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, message);				       \
+	KUNIT_ASSERT_END(test, success, __stream);			       \
+} while (0)
+
+#define KUNIT_ASSERT_MSG(test, success, message, fmt, ...) do {		       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, message);				       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+	KUNIT_ASSERT_END(test, success, __stream);			       \
+} while (0)
+
+#define KUNIT_ASSERT_FAILURE(test, fmt, ...) do {			       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+									       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+	KUNIT_ASSERT_END(test, false, __stream);			       \
+} while (0)
+
+/**
+ * KUNIT_ASSERT_TRUE() - Sets an assertion that @condition is true.
+ * @test: The test context object.
+ * @condition: an arbitrary boolean expression. The test fails and aborts when
+ * this does not evaluate to true.
+ *
+ * This and assertions of the form `KUNIT_ASSERT_*` will cause the test case to
+ * fail *and immediately abort* when the specified condition is not met. Unlike
+ * an expectation failure, it will prevent the test case from continuing to run;
+ * this is otherwise known as an *assertion failure*.
+ */
+#define KUNIT_ASSERT_TRUE(test, condition)				       \
+		KUNIT_ASSERT(test, (condition),				       \
+			     "Asserted " #condition " is true, but is false\n")
+
+#define KUNIT_ASSERT_TRUE_MSG(test, condition, fmt, ...)		       \
+		KUNIT_ASSERT_MSG(test, (condition),			       \
+				 "Asserted " #condition " is true, but is false\n",\
+				 fmt, ##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_FALSE() - Sets an assertion that @condition is false.
+ * @test: The test context object.
+ * @condition: an arbitrary boolean expression.
+ *
+ * Sets an assertion that the value that @condition evaluates to is false. This
+ * is the same as KUNIT_EXPECT_FALSE(), except it causes an assertion failure
+ * (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_FALSE(test, condition)				       \
+		KUNIT_ASSERT(test, !(condition),			       \
+			     "Asserted " #condition " is false, but is true\n")
+
+#define KUNIT_ASSERT_FALSE_MSG(test, condition, fmt, ...)		       \
+		KUNIT_ASSERT_MSG(test, !(condition),			       \
+				 "Asserted " #condition " is false, but is true\n",\
+				 fmt, ##__VA_ARGS__)
+
+void kunit_assert_binary_msg(struct kunit *test,
+			     long long left, const char *left_name,
+			     long long right, const char *right_name,
+			     bool compare_result,
+			     const char *compare_name,
+			     const char *file,
+			     const char *line,
+			     const char *fmt, ...);
+
+static inline void kunit_assert_binary(struct kunit *test,
+				       long long left, const char *left_name,
+				       long long right, const char *right_name,
+				       bool compare_result,
+				       const char *compare_name,
+				       const char *file,
+				       const char *line)
+{
+	kunit_assert_binary_msg(test,
+				left, left_name,
+				right, right_name,
+				compare_result,
+				compare_name,
+				file,
+				line,
+				NULL);
+}
+
+void kunit_assert_ptr_binary_msg(struct kunit *test,
+				 void *left, const char *left_name,
+				 void *right, const char *right_name,
+				 bool compare_result,
+				 const char *compare_name,
+				 const char *file,
+				 const char *line,
+				 const char *fmt, ...);
+
+static inline void kunit_assert_ptr_binary(struct kunit *test,
+					   void *left, const char *left_name,
+					   void *right, const char *right_name,
+					   bool compare_result,
+					   const char *compare_name,
+					   const char *file,
+					   const char *line)
+{
+	kunit_assert_ptr_binary_msg(test,
+				    left, left_name,
+				    right, right_name,
+				    compare_result,
+				    compare_name,
+				    file,
+				    line,
+				    NULL);
+}
+
+/*
+ * A factory macro for defining the expectations for the basic comparisons
+ * defined for the built in types.
+ *
+ * Unfortunately, there is no common type that all types can be promoted to for
+ * which all the binary operators behave the same way as for the actual types
+ * (for example, there is no type that long long and unsigned long long can
+ * both be cast to where the comparison result is preserved for all values). So
+ * the best we can do is do the comparison in the original types and then coerce
+ * everything to long long for printing; this way, the comparison behaves
+ * correctly and the printed out value usually makes sense without
+ * interpretation, but can always be interpretted to figure out the actual
+ * value.
+ */
+#define KUNIT_ASSERT_BINARY(test, left, condition, right) do {		       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_assert_binary(test,					       \
+			    (long long) __left, #left,			       \
+			    (long long) __right, #right,		       \
+			    __left condition __right, #condition,	       \
+			    __FILE__, __stringify(__LINE__));		       \
+} while (0)
+
+#define KUNIT_ASSERT_BINARY_MSG(test, left, condition, right, fmt, ...) do {   \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_assert_binary_msg(test,					       \
+				(long long) __left, #left,		       \
+				(long long) __right, #right,		       \
+				__left condition __right, #condition,	       \
+				__FILE__, __stringify(__LINE__),	       \
+				fmt, ##__VA_ARGS__);			       \
+} while (0)
+
+/*
+ * Just like KUNIT_EXPECT_BINARY, but for comparing pointer types.
+ */
+#define KUNIT_ASSERT_PTR_BINARY(test, left, condition, right) do {	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_assert_ptr_binary(test,					       \
+				(void *) __left, #left,			       \
+				(void *) __right, #right,		       \
+				__left condition __right, #condition,	       \
+				__FILE__, __stringify(__LINE__));	       \
+} while (0)
+
+#define KUNIT_ASSERT_PTR_BINARY_MSG(test, left, condition, right, fmt, ...)    \
+do {									       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+	__kunit_typecheck(__left, __right);				       \
+	kunit_assert_ptr_binary_msg(test,				       \
+				    (void *) __left, #left,		       \
+				    (void *) __right, #right,		       \
+				    __left condition __right, #condition,      \
+				    __FILE__, __stringify(__LINE__),	       \
+				    fmt, ##__VA_ARGS__);		       \
+} while (0)
+
+/**
+ * KUNIT_ASSERT_EQ() - Sets an assertion that @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the values that @left and @right evaluate to are
+ * equal. This is the same as KUNIT_EXPECT_EQ(), except it causes an assertion
+ * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_EQ(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, ==, right)
+
+#define KUNIT_ASSERT_EQ_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					==,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_PTR_EQ() - Asserts that pointers @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a pointer.
+ * @right: an arbitrary expression that evaluates to a pointer.
+ *
+ * Sets an assertion that the values that @left and @right evaluate to are
+ * equal. This is the same as KUNIT_EXPECT_EQ(), except it causes an assertion
+ * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_PTR_EQ(test, left, right) \
+		KUNIT_ASSERT_PTR_BINARY(test, left, ==, right)
+
+#define KUNIT_ASSERT_PTR_EQ_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_PTR_BINARY_MSG(test,			       \
+					    left,			       \
+					    ==,				       \
+					    right,			       \
+					    fmt,			       \
+					    ##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_NE() - An assertion that @left and @right are not equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the values that @left and @right evaluate to are not
+ * equal. This is the same as KUNIT_EXPECT_NE(), except it causes an assertion
+ * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_NE(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, !=, right)
+
+#define KUNIT_ASSERT_NE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					!=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_PTR_NE() - Asserts that pointers @left and @right are not equal.
+ * KUNIT_ASSERT_PTR_EQ() - Asserts that pointers @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a pointer.
+ * @right: an arbitrary expression that evaluates to a pointer.
+ *
+ * Sets an assertion that the values that @left and @right evaluate to are not
+ * equal. This is the same as KUNIT_EXPECT_NE(), except it causes an assertion
+ * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_PTR_NE(test, left, right) \
+		KUNIT_ASSERT_PTR_BINARY(test, left, !=, right)
+
+#define KUNIT_ASSERT_PTR_NE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_PTR_BINARY_MSG(test,			       \
+					    left,			       \
+					    !=,				       \
+					    right,			       \
+					    fmt,			       \
+					    ##__VA_ARGS__)
+/**
+ * KUNIT_ASSERT_LT() - An assertion that @left is less than @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the value that @left evaluates to is less than the
+ * value that @right evaluates to. This is the same as KUNIT_EXPECT_LT(), except
+ * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion
+ * is not met.
+ */
+#define KUNIT_ASSERT_LT(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, <, right)
+
+#define KUNIT_ASSERT_LT_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					<,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+/**
+ * KUNIT_ASSERT_LE() - An assertion that @left is less than or equal to @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the value that @left evaluates to is less than or
+ * equal to the value that @right evaluates to. This is the same as
+ * KUNIT_EXPECT_LE(), except it causes an assertion failure (see
+ * KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_LE(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, <=, right)
+
+#define KUNIT_ASSERT_LE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					<=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+/**
+ * KUNIT_ASSERT_GT() - An assertion that @left is greater than @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the value that @left evaluates to is greater than the
+ * value that @right evaluates to. This is the same as KUNIT_EXPECT_GT(), except
+ * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion
+ * is not met.
+ */
+#define KUNIT_ASSERT_GT(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, >, right)
+
+#define KUNIT_ASSERT_GT_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					>,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_GE() - Assertion that @left is greater than or equal to @right.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a primitive C type.
+ * @right: an arbitrary expression that evaluates to a primitive C type.
+ *
+ * Sets an assertion that the value that @left evaluates to is greater than the
+ * value that @right evaluates to. This is the same as KUNIT_EXPECT_GE(), except
+ * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion
+ * is not met.
+ */
+#define KUNIT_ASSERT_GE(test, left, right) \
+		KUNIT_ASSERT_BINARY(test, left, >=, right)
+
+#define KUNIT_ASSERT_GE_MSG(test, left, right, fmt, ...)		       \
+		KUNIT_ASSERT_BINARY_MSG(test,				       \
+					left,				       \
+					>=,				       \
+					right,				       \
+					fmt,				       \
+					##__VA_ARGS__)
+
+/**
+ * KUNIT_ASSERT_STREQ() - An assertion that strings @left and @right are equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a null terminated string.
+ * @right: an arbitrary expression that evaluates to a null terminated string.
+ *
+ * Sets an assertion that the values that @left and @right evaluate to are
+ * equal. This is the same as KUNIT_EXPECT_STREQ(), except it causes an
+ * assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_STREQ(test, left, right) do {			       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Asserted " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+									       \
+	KUNIT_ASSERT_END(test, !strcmp(left, right), __stream);		       \
+} while (0)
+
+#define KUNIT_ASSERT_STREQ_MSG(test, left, right, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Asserted " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+									       \
+	KUNIT_ASSERT_END(test, !strcmp(left, right), __stream);		       \
+} while (0)
+
+/**
+ * KUNIT_ASSERT_STRNEQ() - Expects that strings @left and @right are not equal.
+ * @test: The test context object.
+ * @left: an arbitrary expression that evaluates to a null terminated string.
+ * @right: an arbitrary expression that evaluates to a null terminated string.
+ *
+ * Sets an expectation that the values that @left and @right evaluate to are
+ * not equal. This is semantically equivalent to
+ * KUNIT_ASSERT_TRUE(@test, strcmp((@left), (@right))). See KUNIT_ASSERT_TRUE()
+ * for more information.
+ */
+#define KUNIT_ASSERT_STRNEQ(test, left, right) do {			       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Asserted " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+									       \
+	KUNIT_ASSERT_END(test, strcmp(left, right), __stream);		       \
+} while (0)
+
+#define KUNIT_ASSERT_STRNEQ_MSG(test, left, right, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(left) __left = (left);					       \
+	typeof(right) __right = (right);				       \
+									       \
+	kunit_stream_add(__stream, "Asserted " #left " == " #right ", but\n"); \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #left, __left);	       \
+	kunit_stream_add(__stream, "\t\t%s == %s\n", #right, __right);	       \
+	kunit_stream_add(__stream, fmt, ##__VA_ARGS__);			       \
+									       \
+	KUNIT_ASSERT_END(test, strcmp(left, right), __stream);		       \
+} while (0)
+
+/**
+ * KUNIT_ASSERT_NOT_ERR_OR_NULL() - Assertion that @ptr is not null and not err.
+ * @test: The test context object.
+ * @ptr: an arbitrary pointer.
+ *
+ * Sets an assertion that the value that @ptr evaluates to is not null and not
+ * an errno stored in a pointer. This is the same as
+ * KUNIT_EXPECT_NOT_ERR_OR_NULL(), except it causes an assertion failure (see
+ * KUNIT_ASSERT_TRUE()) when the assertion is not met.
+ */
+#define KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr) do {			       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(ptr) __ptr = (ptr);					       \
+									       \
+	if (!__ptr)							       \
+		kunit_stream_add(__stream,				       \
+				 "Asserted " #ptr " is not null, but is\n");  \
+	if (IS_ERR(__ptr))						       \
+		kunit_stream_add(__stream,				       \
+				 "Asserted " #ptr " is not error, but is: %ld\n",\
+				 PTR_ERR(__ptr));			       \
+									       \
+	KUNIT_ASSERT_END(test, !IS_ERR_OR_NULL(__ptr), __stream);	       \
+} while (0)
+
+#define KUNIT_ASSERT_NOT_ERR_OR_NULL_MSG(test, ptr, fmt, ...) do {	       \
+	struct kunit_stream *__stream = KUNIT_ASSERT_START(test);	       \
+	typeof(ptr) __ptr = (ptr);					       \
+									       \
+	if (!__ptr) {							       \
+		kunit_stream_add(__stream,				       \
+				 "Asserted " #ptr " is not null, but is\n");  \
+		kunit_stream_add(__stream, fmt, ##__VA_ARGS__);		       \
+	}								       \
+	if (IS_ERR(__ptr)) {						       \
+		kunit_stream_add(__stream,				       \
+				 "Asserted " #ptr " is not error, but is: %ld\n",\
+				 PTR_ERR(__ptr));			       \
+									       \
+		kunit_stream_add(__stream, fmt, ##__VA_ARGS__);		       \
+	}								       \
+	KUNIT_ASSERT_END(test, !IS_ERR_OR_NULL(__ptr), __stream);	       \
+} while (0)
+
 #endif /* _KUNIT_TEST_H */
kunit/string-stream-test.c +6 -6
index 36f0b5769a5a4..a88ecef799a6b 100644
@@ -34,7 +34,7 @@ static void string_stream_test_get_string(struct kunit *test)
 	string_stream_add(stream, " %s", "bar");
 
 	output = string_stream_get_string(stream);
-	KUNIT_EXPECT_STREQ(test, output, "Foo bar");
+	KUNIT_ASSERT_STREQ(test, output, "Foo bar");
 	kfree(output);
 }
 
@@ -48,16 +48,16 @@ static void string_stream_test_add_and_clear(struct kunit *test)
 		string_stream_add(stream, "A");
 
 	output = string_stream_get_string(stream);
-	KUNIT_EXPECT_STREQ(test, output, "AAAAAAAAAA");
-	KUNIT_EXPECT_EQ(test, stream->length, (size_t)10);
-	KUNIT_EXPECT_FALSE(test, string_stream_is_empty(stream));
+	KUNIT_ASSERT_STREQ(test, output, "AAAAAAAAAA");
+	KUNIT_ASSERT_EQ(test, stream->length, (size_t)10);
+	KUNIT_ASSERT_FALSE(test, string_stream_is_empty(stream));
 	kfree(output);
 
 	string_stream_clear(stream);
 
 	output = string_stream_get_string(stream);
-	KUNIT_EXPECT_STREQ(test, output, "");
-	KUNIT_EXPECT_TRUE(test, string_stream_is_empty(stream));
+	KUNIT_ASSERT_STREQ(test, output, "");
+	KUNIT_ASSERT_TRUE(test, string_stream_is_empty(stream));
 }
 
 static struct kunit_case string_stream_test_cases[] = {
kunit/test-test.c +2 -0
index 5d14e1ae35ed5..43d1bedcf4592 100644
@@ -78,11 +78,13 @@ static int kunit_try_catch_test_init(struct kunit *test)
 	struct kunit_try_catch_test_context *ctx;
 
 	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);
 	test->priv = ctx;
 
 	ctx->try_catch = kunit_kmalloc(test,
 				       sizeof(*ctx->try_catch),
 				       GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->try_catch);
 
 	return 0;
 }
kunit/test.c +66 -0

69 lines not on this page · raw message

Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#35 lore raw

PATCH v5 12/18 kunit: test: add tests for KUnit managed resources

In reply to Brendan Higgins

From: Avinash Kondareddy <[email protected]>

Add unit tests for KUnit managed resources. KUnit managed resources (struct kunit_resource) are resources that are automatically cleaned up at the end of a KUnit test, similar to the concept of devm_* managed resources.

---
 kunit/test-test.c | 219 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 219 insertions(+)
kunit/test-test.c +219 -0
index 43d1bedcf4592..60ef508cda1c6 100644
@@ -101,3 +101,222 @@ static struct kunit_module kunit_try_catch_test_module = {
 	.test_cases = kunit_try_catch_test_cases,
 };
 module_test(kunit_try_catch_test_module);
+
+/*
+ * Context for testing test managed resources
+ * is_resource_initialized is used to test arbitrary resources
+ */
+struct kunit_test_resource_context {
+	struct kunit test;
+	bool is_resource_initialized;
+	int allocate_order[2];
+	int free_order[2];
+};
+
+static int fake_resource_init(struct kunit_resource *res, void *context)
+{
+	struct kunit_test_resource_context *ctx = context;
+
+	res->allocation = &ctx->is_resource_initialized;
+	ctx->is_resource_initialized = true;
+	return 0;
+}
+
+static void fake_resource_free(struct kunit_resource *res)
+{
+	bool *is_resource_initialized = res->allocation;
+
+	*is_resource_initialized = false;
+}
+
+static void kunit_resource_test_init_resources(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx = test->priv;
+
+	kunit_init_test(&ctx->test, "testing_test_init_test");
+
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources));
+}
+
+static void kunit_resource_test_alloc_resource(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx = test->priv;
+	struct kunit_resource *res;
+	kunit_resource_free_t free = fake_resource_free;
+
+	res = kunit_alloc_resource(&ctx->test,
+				   fake_resource_init,
+				   fake_resource_free,
+				   ctx);
+
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, res);
+	KUNIT_EXPECT_PTR_EQ(test,
+			    &ctx->is_resource_initialized,
+			    (bool *) res->allocation);
+	KUNIT_EXPECT_TRUE(test, list_is_last(&res->node, &ctx->test.resources));
+	KUNIT_EXPECT_PTR_EQ(test, free, res->free);
+}
+
+static void kunit_resource_test_free_resource(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx = test->priv;
+	struct kunit_resource *res = kunit_alloc_resource(&ctx->test,
+							  fake_resource_init,
+							  fake_resource_free,
+							  ctx);
+
+	kunit_free_resource(&ctx->test, res);
+
+	KUNIT_EXPECT_FALSE(test, ctx->is_resource_initialized);
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources));
+}
+
+static void kunit_resource_test_cleanup_resources(struct kunit *test)
+{
+	int i;
+	struct kunit_test_resource_context *ctx = test->priv;
+	struct kunit_resource *resources[5];
+
+	for (i = 0; i < ARRAY_SIZE(resources); i++) {
+		resources[i] = kunit_alloc_resource(&ctx->test,
+						    fake_resource_init,
+						    fake_resource_free,
+						    ctx);
+	}
+
+	kunit_cleanup(&ctx->test);
+
+	KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources));
+}
+
+static void kunit_resource_test_mark_order(int order_array[],
+					   size_t order_size,
+					   int key)
+{
+	int i;
+
+	for (i = 0; i < order_size && order_array[i]; i++)
+		;
+
+	order_array[i] = key;
+}
+
+#define KUNIT_RESOURCE_TEST_MARK_ORDER(ctx, order_field, key)		       \
+		kunit_resource_test_mark_order(ctx->order_field,	       \
+					       ARRAY_SIZE(ctx->order_field),   \
+					       key)
+
+static int fake_resource_2_init(struct kunit_resource *res, void *context)
+{
+	struct kunit_test_resource_context *ctx = context;
+
+	KUNIT_RESOURCE_TEST_MARK_ORDER(ctx, allocate_order, 2);
+
+	res->allocation = ctx;
+
+	return 0;
+}
+
+static void fake_resource_2_free(struct kunit_resource *res)
+{
+	struct kunit_test_resource_context *ctx = res->allocation;
+
+	KUNIT_RESOURCE_TEST_MARK_ORDER(ctx, free_order, 2);
+}
+
+static int fake_resource_1_init(struct kunit_resource *res, void *context)
+{
+	struct kunit_test_resource_context *ctx = context;
+
+	kunit_alloc_resource(&ctx->test,
+			     fake_resource_2_init,
+			     fake_resource_2_free,
+			     ctx);
+
+	KUNIT_RESOURCE_TEST_MARK_ORDER(ctx, allocate_order, 1);
+
+	res->allocation = ctx;
+
+	return 0;
+}
+
+static void fake_resource_1_free(struct kunit_resource *res)
+{
+	struct kunit_test_resource_context *ctx = res->allocation;
+
+	KUNIT_RESOURCE_TEST_MARK_ORDER(ctx, free_order, 1);
+}
+
+/*
+ * TODO([email protected]): replace the arrays that keep track of the
+ * order of allocation and freeing with strict mocks using the IN_SEQUENCE macro
+ * to assert allocation and freeing order when the feature becomes available.
+ */
+static void kunit_resource_test_proper_free_ordering(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx = test->priv;
+
+	/* fake_resource_1 allocates a fake_resource_2 in its init. */
+	kunit_alloc_resource(&ctx->test,
+			     fake_resource_1_init,
+			     fake_resource_1_free,
+			     ctx);
+
+	/*
+	 * Since fake_resource_2_init calls KUNIT_RESOURCE_TEST_MARK_ORDER
+	 * before returning to fake_resource_1_init, it should be the first to
+	 * put its key in the allocate_order array.
+	 */
+	KUNIT_EXPECT_EQ(test, ctx->allocate_order[0], 2);
+	KUNIT_EXPECT_EQ(test, ctx->allocate_order[1], 1);
+
+	kunit_cleanup(&ctx->test);
+
+	/*
+	 * Because fake_resource_2 finishes allocation before fake_resource_1,
+	 * fake_resource_1 should be freed first since it could depend on
+	 * fake_resource_2.
+	 */
+	KUNIT_EXPECT_EQ(test, ctx->free_order[0], 1);
+	KUNIT_EXPECT_EQ(test, ctx->free_order[1], 2);
+}
+
+static int kunit_resource_test_init(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx =
+			kzalloc(sizeof(*ctx), GFP_KERNEL);
+
+	if (!ctx)
+		return -ENOMEM;
+
+	test->priv = ctx;
+
+	kunit_init_test(&ctx->test, "test_test_context");
+
+	return 0;
+}
+
+static void kunit_resource_test_exit(struct kunit *test)
+{
+	struct kunit_test_resource_context *ctx = test->priv;
+
+	kunit_cleanup(&ctx->test);
+	kfree(ctx);
+}
+
+static struct kunit_case kunit_resource_test_cases[] = {
+	KUNIT_CASE(kunit_resource_test_init_resources),
+	KUNIT_CASE(kunit_resource_test_alloc_resource),
+	KUNIT_CASE(kunit_resource_test_free_resource),
+	KUNIT_CASE(kunit_resource_test_cleanup_resources),
+	KUNIT_CASE(kunit_resource_test_proper_free_ordering),
+	{}
+};
+
+static struct kunit_module kunit_resource_test_module = {
+	.name = "kunit-resource-test",
+	.init = kunit_resource_test_init,
+	.exit = kunit_resource_test_exit,
+	.test_cases = kunit_resource_test_cases,
+};
+module_test(kunit_resource_test_module);
Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#36 lore raw

PATCH v5 13/18 kunit: tool: add Python wrappers for running KUnit tests

In reply to Brendan Higgins

From: Felix Guo <[email protected]>

The ultimate goal is to create minimal isolated test binaries; in the meantime we are using UML to provide the infrastructure to run tests, so define an abstract way to configure and run tests that allow us to change the context in which tests are built without affecting the user. This also makes pretty and dynamic error reporting, and a lot of other nice features easier.

kunit_config.py:
- parse .config and Kconfig files.

kunit_kernel.py: provides helper functions to:
- configure the kernel using kunitconfig.
- build the kernel with the appropriate configuration.
- provide function to invoke the kernel and stream the output back.

---
 tools/testing/kunit/.gitignore                |   3 +
 tools/testing/kunit/kunit.py                  | 116 +++++++
 tools/testing/kunit/kunit_config.py           |  66 ++++
 tools/testing/kunit/kunit_kernel.py           | 148 +++++++++
 tools/testing/kunit/kunit_parser.py           | 290 ++++++++++++++++++
 tools/testing/kunit/kunit_tool_test.py        | 206 +++++++++++++
 .../test_is_test_passed-all_passed.log        |  32 ++
 .../test_data/test_is_test_passed-crash.log   |  69 +++++
 .../test_data/test_is_test_passed-failure.log |  36 +++
 .../test_is_test_passed-no_tests_run.log      |  75 +++++
 .../test_output_isolated_correctly.log        | 106 +++++++
 .../test_data/test_read_from_file.kconfig     |  17 +
 12 files changed, 1164 insertions(+)
 create mode 100644 tools/testing/kunit/.gitignore
 create mode 100755 tools/testing/kunit/kunit.py
 create mode 100644 tools/testing/kunit/kunit_config.py
 create mode 100644 tools/testing/kunit/kunit_kernel.py
 create mode 100644 tools/testing/kunit/kunit_parser.py
 create mode 100755 tools/testing/kunit/kunit_tool_test.py
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-all_passed.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-crash.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-failure.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log
 create mode 100644 tools/testing/kunit/test_data/test_output_isolated_correctly.log
 create mode 100644 tools/testing/kunit/test_data/test_read_from_file.kconfig
tools/testing/kunit/.gitignore new file +3 -0
new file mode 100644
index 0000000000000..c791ff59a37a9
@@ -0,0 +1,3 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
\ No newline at end of file
tools/testing/kunit/kunit.py new file +116 -0

116 lines not on this page · raw message

tools/testing/kunit/kunit_config.py new file +66 -0

66 lines not on this page · raw message

tools/testing/kunit/kunit_kernel.py new file +148 -0

148 lines not on this page · raw message

tools/testing/kunit/kunit_parser.py new file +290 -0

290 lines not on this page · raw message

tools/testing/kunit/kunit_tool_test.py new file +206 -0

206 lines not on this page · raw message

tools/testing/kunit/test_data/test_is_test_passed-all_passed.log new file +32 -0
new file mode 100644
index 0000000000000..8b5aa2f0cb498
@@ -0,0 +1,32 @@
+TAP version 14
+	# Subtest: sysctl_test
+	1..8
+	# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
+	ok 1 - sysctl_test_dointvec_null_tbl_data
+	# sysctl_test_dointvec_table_maxlen_unset: sysctl_test_dointvec_table_maxlen_unset passed
+	ok 2 - sysctl_test_dointvec_table_maxlen_unset
+	# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
+	ok 3 - sysctl_test_dointvec_table_len_is_zero
+	# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
+	ok 4 - sysctl_test_dointvec_table_read_but_position_set
+	# sysctl_test_dointvec_happy_single_positive: sysctl_test_dointvec_happy_single_positive passed
+	ok 5 - sysctl_test_dointvec_happy_single_positive
+	# sysctl_test_dointvec_happy_single_negative: sysctl_test_dointvec_happy_single_negative passed
+	ok 6 - sysctl_test_dointvec_happy_single_negative
+	# sysctl_test_dointvec_single_less_int_min: sysctl_test_dointvec_single_less_int_min passed
+	ok 7 - sysctl_test_dointvec_single_less_int_min
+	# sysctl_test_dointvec_single_greater_int_max: sysctl_test_dointvec_single_greater_int_max passed
+	ok 8 - sysctl_test_dointvec_single_greater_int_max
+kunit sysctl_test: all tests passed
+ok 1 - sysctl_test
+	# Subtest: example
+	1..2
+init_module
+	# example_simple_test: initializing
+	# example_simple_test: example_simple_test passed
+	ok 1 - example_simple_test
+	# example_mock_test: initializing
+	# example_mock_test: example_mock_test passed
+	ok 2 - example_mock_test
+kunit example: all tests passed
+ok 2 - example
tools/testing/kunit/test_data/test_is_test_passed-crash.log new file +69 -0

69 lines not on this page · raw message

tools/testing/kunit/test_data/test_is_test_passed-failure.log new file +36 -0
new file mode 100644
index 0000000000000..73ed8730b76b2
@@ -0,0 +1,36 @@
+TAP version 14
+	# Subtest: sysctl_test
+	1..8
+	# sysctl_test_dointvec_null_tbl_data: sysctl_test_dointvec_null_tbl_data passed
+	ok 1 - sysctl_test_dointvec_null_tbl_data
+	# sysctl_test_dointvec_table_maxlen_unset: sysctl_test_dointvec_table_maxlen_unset passed
+	ok 2 - sysctl_test_dointvec_table_maxlen_unset
+	# sysctl_test_dointvec_table_len_is_zero: sysctl_test_dointvec_table_len_is_zero passed
+	ok 3 - sysctl_test_dointvec_table_len_is_zero
+	# sysctl_test_dointvec_table_read_but_position_set: sysctl_test_dointvec_table_read_but_position_set passed
+	ok 4 - sysctl_test_dointvec_table_read_but_position_set
+	# sysctl_test_dointvec_happy_single_positive: sysctl_test_dointvec_happy_single_positive passed
+	ok 5 - sysctl_test_dointvec_happy_single_positive
+	# sysctl_test_dointvec_happy_single_negative: sysctl_test_dointvec_happy_single_negative passed
+	ok 6 - sysctl_test_dointvec_happy_single_negative
+	# sysctl_test_dointvec_single_less_int_min: sysctl_test_dointvec_single_less_int_min passed
+	ok 7 - sysctl_test_dointvec_single_less_int_min
+	# sysctl_test_dointvec_single_greater_int_max: sysctl_test_dointvec_single_greater_int_max passed
+	ok 8 - sysctl_test_dointvec_single_greater_int_max
+kunit sysctl_test: all tests passed
+ok 1 - sysctl_test
+	# Subtest: example
+	1..2
+init_module
+	# example_simple_test: initializing
+	# example_simple_test: EXPECTATION FAILED at kunit/example-test.c:30
+	Expected 1 + 1 == 3, but
+		1 + 1 == 2
+		3 == 3
+	# example_simple_test: example_simple_test failed
+	not ok 1 - example_simple_test
+	# example_mock_test: initializing
+	# example_mock_test: example_mock_test passed
+	ok 2 - example_mock_test
+kunit example: one or more tests failed
+not ok 2 - example
tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log new file +75 -0

75 lines not on this page · raw message

tools/testing/kunit/test_data/test_output_isolated_correctly.log new file +106 -0

106 lines not on this page · raw message

tools/testing/kunit/test_data/test_read_from_file.kconfig new file +17 -0
new file mode 100644
index 0000000000000..d2a4928ac773b
@@ -0,0 +1,17 @@
+#
+# Automatically generated file; DO NOT EDIT.
+# User Mode Linux/x86 4.12.0-rc3 Kernel Configuration
+#
+CONFIG_UML=y
+CONFIG_MMU=y
+
+#
+# UML-specific options
+#
+
+#
+# Host processor type and features
+#
+# CONFIG_MK8 is not set
+CONFIG_TEST=y
+CONFIG_EXAMPLE_TEST=y
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#37 lore raw

Re: [PATCH v5 13/18] kunit: tool: add Python wrappers for running KUnit tests

Quoted 6 lines · Brendan Higgins
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-all_passed.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-crash.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-failure.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log
 create mode 100644 tools/testing/kunit/test_data/test_output_isolated_correctly.log
 create mode 100644 tools/testing/kunit/test_data/test_read_from_file.kconfig

Why are these being added upstream? The commit log does not explain this.

Luis

#38 lore raw

Re: [PATCH v5 13/18] kunit: tool: add Python wrappers for running KUnit tests

Quoted 11 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-all_passed.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-crash.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-failure.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log
 create mode 100644 tools/testing/kunit/test_data/test_output_isolated_correctly.log
 create mode 100644 tools/testing/kunit/test_data/test_read_from_file.kconfig

Why are these being added upstream? The commit log does not explain this.

Oh sorry, those are for testing purposes. I thought that was clear from being in the test_data directory. I will reference it in the commit log in the next revision.

#39 lore raw

Re: [PATCH v5 13/18] kunit: tool: add Python wrappers for running KUnit tests

Quoted 10 lines · Brendan Higgins
Quoted 9 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-all_passed.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-crash.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-failure.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log
 create mode 100644 tools/testing/kunit/test_data/test_output_isolated_correctly.log
 create mode 100644 tools/testing/kunit/test_data/test_read_from_file.kconfig
Quoted 6 lines
Quoted 2 lines

Why are these being added upstream? The commit log does not explain this.

Oh sorry, those are for testing purposes. I thought that was clear from being in the test_data directory. I will reference it in the commit log in the next revision.

Still, I don't get it. They seem to be results from a prior run. Why do we need them for testing purposes?

Luis

#40 lore raw

Re: [PATCH v5 13/18] kunit: tool: add Python wrappers for running KUnit tests

Quoted 15 lines · Luis Chamberlain
Quoted 13 lines · Brendan Higgins
Quoted 11 lines · Luis Chamberlain
Quoted 6 lines · Brendan Higgins
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-all_passed.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-crash.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-failure.log
 create mode 100644 tools/testing/kunit/test_data/test_is_test_passed-no_tests_run.log
 create mode 100644 tools/testing/kunit/test_data/test_output_isolated_correctly.log
 create mode 100644 tools/testing/kunit/test_data/test_read_from_file.kconfig

Why are these being added upstream? The commit log does not explain this.

Quoted 6 lines
Quoted 3 lines

Oh sorry, those are for testing purposes. I thought that was clear from being in the test_data directory. I will reference it in the commit log in the next revision.

Still, I don't get it. They seem to be results from a prior run. Why do we need them for testing purposes?

Those logs are the raw output from UML with KUnit installed. They are for testing kunit_tool, the Python scripts added in this commit. One of the things that kunit_tool does is parses the results output by UML, extracts the KUnit data, and presents it in a user friendly manner.

I added these logs so I could test that kunit_tool parses certain kinds of output correctly. For example, I want to know that it parses a test failure correctly and includes the appropriate context. So I have a log from a unit test that failed, and I have a test (a Python test that is also in this commit) that tests whether kunit_tool can parse the log correctly.

Does that make sense?

#41 lore raw

PATCH v5 14/18 kunit: defconfig: add defconfigs for building KUnit tests

In reply to Brendan Higgins

Add defconfig for UML and a fragment that can be used to configure other architectures for building KUnit tests. Add option to kunit_tool to use a defconfig to create the kunitconfig.

---
 arch/um/configs/kunit_defconfig              |  8 ++++++++
 tools/testing/kunit/configs/all_tests.config |  8 ++++++++
 tools/testing/kunit/kunit.py                 | 18 ++++++++++++++++--
 tools/testing/kunit/kunit_kernel.py          |  3 ++-
 4 files changed, 34 insertions(+), 3 deletions(-)
 create mode 100644 arch/um/configs/kunit_defconfig
 create mode 100644 tools/testing/kunit/configs/all_tests.config
arch/um/configs/kunit_defconfig new file +8 -0
new file mode 100644
index 0000000000000..bfe49689038f1
@@ -0,0 +1,8 @@
+CONFIG_OF=y
+CONFIG_OF_UNITTEST=y
+CONFIG_OF_OVERLAY=y
+CONFIG_I2C=y
+CONFIG_I2C_MUX=y
+CONFIG_KUNIT=y
+CONFIG_KUNIT_TEST=y
+CONFIG_KUNIT_EXAMPLE_TEST=y
tools/testing/kunit/configs/all_tests.config new file +8 -0
new file mode 100644
index 0000000000000..bfe49689038f1
@@ -0,0 +1,8 @@
+CONFIG_OF=y
+CONFIG_OF_UNITTEST=y
+CONFIG_OF_OVERLAY=y
+CONFIG_I2C=y
+CONFIG_I2C_MUX=y
+CONFIG_KUNIT=y
+CONFIG_KUNIT_TEST=y
+CONFIG_KUNIT_EXAMPLE_TEST=y
tools/testing/kunit/kunit.py +16 -2
index da11bd62a4b82..3e51dc4febfdc 100755
@@ -11,6 +11,7 @@ import argparse
 import sys
 import os
 import time
+import shutil
 
 from collections import namedtuple
 from enum import Enum, auto
@@ -21,7 +22,7 @@ import kunit_parser
 
 KunitResult = namedtuple('KunitResult', ['status','result'])
 
-KunitRequest = namedtuple('KunitRequest', ['raw_output','timeout', 'jobs', 'build_dir'])
+KunitRequest = namedtuple('KunitRequest', ['raw_output','timeout', 'jobs', 'build_dir', 'defconfig'])
 
 class KunitStatus(Enum):
 	SUCCESS = auto()
@@ -29,8 +30,16 @@ class KunitStatus(Enum):
 	BUILD_FAILURE = auto()
 	TEST_FAILURE = auto()
 
+def create_default_kunitconfig():
+	if not os.path.exists(kunit_kernel.KUNITCONFIG_PATH):
+		shutil.copyfile('arch/um/configs/kunit_defconfig',
+				kunit_kernel.KUNITCONFIG_PATH)
+
 def run_tests(linux: kunit_kernel.LinuxSourceTree,
 	      request: KunitRequest) -> KunitResult:
+	if request.defconfig:
+		create_default_kunitconfig()
+
 	config_start = time.time()
 	success = linux.build_reconfig(request.build_dir)
 	config_end = time.time()
@@ -99,13 +108,18 @@ def main(argv, linux):
 				'directory.',
 				type=str, default=None, metavar='build_dir')
 
+	run_parser.add_argument('--defconfig',
+				help='Uses a default kunitconfig.',
+				action='store_true')
+
 	cli_args = parser.parse_args(argv)
 
 	if cli_args.subcommand == 'run':
 		request = KunitRequest(cli_args.raw_output,
 				       cli_args.timeout,
 				       cli_args.jobs,
-				       cli_args.build_dir)
+				       cli_args.build_dir,
+				       cli_args.defconfig)
 		result = run_tests(linux, request)
 		if result.status != KunitStatus.SUCCESS:
 			sys.exit(1)
tools/testing/kunit/kunit_kernel.py +2 -1
index 07c0abf2f47df..bf38768353313 100644
@@ -14,6 +14,7 @@ import os
 import kunit_config
 
 KCONFIG_PATH = '.config'
+KUNITCONFIG_PATH = 'kunitconfig'
 
 class ConfigError(Exception):
 	"""Represents an error trying to configure the Linux kernel."""
@@ -81,7 +82,7 @@ class LinuxSourceTree(object):
 
 	def __init__(self):
 		self._kconfig = kunit_config.Kconfig()
-		self._kconfig.read_from_file('kunitconfig')
+		self._kconfig.read_from_file(KUNITCONFIG_PATH)
 		self._ops = LinuxSourceTreeOperations()
 
 	def clean(self):
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#42 lore raw

PATCH v5 15/18 Documentation: kunit: add documentation for KUnit

In reply to Brendan Higgins

Add documentation for KUnit, the Linux kernel unit testing framework.
- Add intro and usage guide for KUnit
- Add API reference

---
 Documentation/dev-tools/index.rst           |   1 +
 Documentation/dev-tools/kunit/api/index.rst |  16 +
 Documentation/dev-tools/kunit/api/test.rst  |  14 +
 Documentation/dev-tools/kunit/faq.rst       |  62 +++
 Documentation/dev-tools/kunit/index.rst     |  79 +++
 Documentation/dev-tools/kunit/start.rst     | 180 ++++++
 Documentation/dev-tools/kunit/usage.rst     | 575 ++++++++++++++++++++
 7 files changed, 927 insertions(+)
 create mode 100644 Documentation/dev-tools/kunit/api/index.rst
 create mode 100644 Documentation/dev-tools/kunit/api/test.rst
 create mode 100644 Documentation/dev-tools/kunit/faq.rst
 create mode 100644 Documentation/dev-tools/kunit/index.rst
 create mode 100644 Documentation/dev-tools/kunit/start.rst
 create mode 100644 Documentation/dev-tools/kunit/usage.rst
Documentation/dev-tools/index.rst +1 -0
index b0522a4dd1073..09dee10d25928 100644
@@ -24,6 +24,7 @@ whole; patches welcome!
    gdb-kernel-debugging
    kgdb
    kselftest
+   kunit/index
 
 
 .. only::  subproject and html
Documentation/dev-tools/kunit/api/index.rst new file +16 -0
new file mode 100644
index 0000000000000..9b9bffe5d41a0
@@ -0,0 +1,16 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============
+API Reference
+=============
+.. toctree::
+
+	test
+
+This section documents the KUnit kernel testing API. It is divided into the
+following sections:
+
+================================= ==============================================
+:doc:`test`                       documents all of the standard testing API
+                                  excluding mocking or mocking related features.
+================================= ==============================================
Documentation/dev-tools/kunit/api/test.rst new file +14 -0
new file mode 100644
index 0000000000000..d0ce19b1e1185
@@ -0,0 +1,14 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+========
+Test API
+========
+
+This file documents all of the standard testing API excluding mocking or mocking
+related features.
+
+.. kernel-doc:: include/kunit/test.h
+   :internal:
+
+.. kernel-doc:: include/kunit/kunit-stream.h
+   :internal:
Documentation/dev-tools/kunit/faq.rst new file +62 -0

62 lines not on this page · raw message

Documentation/dev-tools/kunit/index.rst new file +79 -0

79 lines not on this page · raw message

Documentation/dev-tools/kunit/start.rst new file +180 -0

180 lines not on this page · raw message

Documentation/dev-tools/kunit/usage.rst new file +575 -0

575 lines not on this page · raw message

Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#43 lore raw

PATCH v5 16/18 MAINTAINERS: add entry for KUnit the unit testing framework

In reply to Brendan Higgins

Add myself as maintainer of KUnit, the Linux kernel's unit testing framework.

---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)
MAINTAINERS +11 -0
index 57f496cff9997..f3fb3fc30853e 100644
@@ -8590,6 +8590,17 @@ S:	Maintained
 F:	tools/testing/selftests/
 F:	Documentation/dev-tools/kselftest*
 
+KERNEL UNIT TESTING FRAMEWORK (KUnit)
+M:	Brendan Higgins <[email protected]>
+L:	[email protected]
+L:	[email protected]
+W:	https://google.github.io/kunit-docs/third_party/kernel/docs/
+S:	Maintained
+F:	Documentation/dev-tools/kunit/
+F:	include/kunit/
+F:	kunit/
+F:	tools/testing/kunit/
+
 KERNEL USERMODE HELPER
 M:	Luis Chamberlain <[email protected]>
 L:	[email protected]
Signature · 6 lines
2.22.0.410.gd8fdbe21b5-goog

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel
#44 lore raw

PATCH v5 17/18 kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

In reply to Brendan Higgins

From: Iurii Zaikin <[email protected]>

KUnit tests for initialized data behavior of proc_dointvec that is explicitly checked in the code. Includes basic parsing tests including int min/max overflow.

---
Changes Since Last Revision:
- Iurii did some clean up (thanks Iurii!) as suggested by Stephen Boyd.

---
 kernel/Makefile      |   2 +
 kernel/sysctl-test.c | 242 +++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig.debug    |  10 ++
 3 files changed, 254 insertions(+)
 create mode 100644 kernel/sysctl-test.c
kernel/Makefile +2 -0
index a8d923b5481ba..50fd511cd0ee0 100644
@@ -114,6 +114,8 @@ obj-$(CONFIG_HAS_IOMEM) += iomem.o
 obj-$(CONFIG_ZONE_DEVICE) += memremap.o
 obj-$(CONFIG_RSEQ) += rseq.o
 
+obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o
+
 obj-$(CONFIG_GCC_PLUGIN_STACKLEAK) += stackleak.o
 KASAN_SANITIZE_stackleak.o := n
 KCOV_INSTRUMENT_stackleak.o := n
kernel/sysctl-test.c new file +242 -0

242 lines not on this page · raw message

lib/Kconfig.debug +10 -0
index cbdfae3798965..389b8986f5b77 100644
@@ -1939,6 +1939,16 @@ config TEST_SYSCTL
 
 	  If unsure, say N.
 
+config SYSCTL_KUNIT_TEST
+	bool "KUnit test for sysctl"
+	depends on KUNIT
+	help
+	  This builds the proc sysctl unit test, which runs on boot. For more
+	  information on KUnit and unit tests in general please refer to the
+	  KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  If unsure, say N.
+
 config TEST_UDELAY
 	tristate "udelay test driver"
 	help
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#45 lore raw

Re: [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

Quoted 5 lines · Brendan Higgins

From: Iurii Zaikin <[email protected]>

KUnit tests for initialized data behavior of proc_dointvec that is explicitly checked in the code. Includes basic parsing tests including int min/max overflow.

First, thanks for this work! My review below.

Quoted 20 lines

---
Changes Since Last Revision:
- Iurii did some clean up (thanks Iurii!) as suggested by Stephen Boyd.

---
 kernel/Makefile      |   2 +
 kernel/sysctl-test.c | 242 +++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig.debug    |  10 ++
 3 files changed, 254 insertions(+)
 create mode 100644 kernel/sysctl-test.c
kernel/Makefile +0 -0
index a8d923b5481ba..50fd511cd0ee0 100644

kernel/Makefile obj-$(CONFIG_HAS_IOMEM) += iomem.o · line 117

Quoted 4 lines
kernel/Makefile +1 -0
@@ -114,6 +114,8 @@ obj-$(CONFIG_HAS_IOMEM) += iomem.o
 obj-$(CONFIG_ZONE_DEVICE) += memremap.o
 obj-$(CONFIG_RSEQ) += rseq.o
 
+obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o

And we have lib/test_sysctl.c of selftests.

I'm fine with this going in as-is to its current place, but if we have to learn from selftests I'd say we try to stick to a convention so folks know what framework a test is for, and to ensure folks can easily tell if its test code or not.

Perhaps simply a directory for kunit tests would suffice alone.

Quoted 53 lines
kernel/Makefile +1 -0
+
 obj-$(CONFIG_GCC_PLUGIN_STACKLEAK) += stackleak.o
 KASAN_SANITIZE_stackleak.o := n
 KCOV_INSTRUMENT_stackleak.o := n
kernel/sysctl-test.c new file +43 -0
new file mode 100644
index 0000000000000..cb61ad3c7db63
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * KUnit test of proc sysctl.
+ */
+
+#include <kunit/test.h>
+#include <linux/sysctl.h>
+
+static int i_zero;
+static int i_one_hundred = 100;
+
+struct test_sysctl_data {
+	int int_0001;
+	int int_0002;
+	int int_0003[4];
+
+	unsigned int uint_0001;
+
+	char string_0001[65];
+};
+
+static struct test_sysctl_data test_data = {
+	.int_0001 = 60,
+	.int_0002 = 1,
+
+	.int_0003[0] = 0,
+	.int_0003[1] = 1,
+	.int_0003[2] = 2,
+	.int_0003[3] = 3,
+
+	.uint_0001 = 314,
+
+	.string_0001 = "(none)",
+};
+
+static void sysctl_test_dointvec_null_tbl_data(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= NULL,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,

kernel/sysctl-test.c line 53

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};
+	void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	size_t len;
+	loff_t pos;
+
+	len = 1234;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);

It is a bit odd, but it does happen, for a developer to be calling proc_dointvec() directly, instead typically folks just register a table and let it do its thing. That said, someone not too familiar with proc code would see this and really have no clue exactly what is being tested.

Even as a maintainer, I had to read the code for proc_dointvec() a bit to understand that the above is a *read* attempt to the .data field being allocated. Because its a write, the len set to a bogus does not matter as we are expecting the proc_dointvec() to update len for us.

If a test fails, it would be good to for anyone to easily grasp what is being tested. So... a few words documenting each test case would be nice.

kernel/sysctl-test.c line 56

Quoted 3 lines
kernel/sysctl-test.c new file +3 -0
+	len = 1234;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);

And this is a write...

A nice tests given the data on the table allocated is not assigned.

I don't see any other areas in the kernel where we open code a proc_dointvec() call where the second argument is a digit, it always is with a variable. As such there would be no need for us to expose helpers to make it clear if one is a read or write. But for *this* case, I think it would be useful to add two wrappers inside this kunit test module which sprinkles the 0 or 1, this way a reader can easily know what mode is being tested.

kunit_proc_dointvec_read()
kunit_proc_dointvec_write()

Or just use #define KUNIT_PROC_READ 0, #define KUNIT_PROC_WRITE 1. Whatever makes this code more legible.

Quoted 14 lines
kernel/sysctl-test.c new file +14 -0
+}
+
+static void sysctl_test_dointvec_table_maxlen_unset(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= 0,
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};
+	void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);

kernel/sysctl-test.c line 80

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+	size_t len;
+	loff_t pos;
+
+	len = 1234;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);
+	len = 1234;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

In a way this is also testing for general kernel API changes. This is and the last one were good examples. So this is not just testing functionality here. There is no wrong or write answer if 0 or -EINVAL was returned other than the fact that we have been doing this for years.

Its a perhaps small but important difference for some of these tests. I *do* think its worth clarifying through documentation which ones are testing for API consistency Vs proper correctness.

Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+
+static void sysctl_test_dointvec_table_len_is_zero(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};

kernel/sysctl-test.c line 102

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+	void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	size_t len;
+	loff_t pos;
+
+	len = 0;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

Likewise an API change test.

Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+
+static void sysctl_test_dointvec_table_read_but_position_set(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,

kernel/sysctl-test.c line 123

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+	};
+	void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	size_t len;
+	loff_t pos;
+
+	len = 1234;
+	pos = 1;
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+	KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

Likewise an API test.

All the above kunit test cases are currently testing this call on __do_proc_dointvec():

        if (!tbl_data || !table->maxlen || !*lenp || (*ppos && !write))
	{
		*lenp = 0;
		return 0;
	}

Just an API test.

Perhaps use an api prefix or postfix for these to help distinguish which are api tests Vs correctness. We want someone who runs into a failure to *easily* determine *what* went wrong.

Right now this kunit test leaves no leashes around to help the reader.

Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+
+static void sysctl_test_dointvec_happy_single_positive(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};

kernel/sysctl-test.c line 145

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+	char input[] = "9";
+	size_t len = sizeof(input) - 1;
+	loff_t pos = 0;
+
+	table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, input, &len, &pos));
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, (size_t)pos);
+	KUNIT_EXPECT_EQ(test, 9, ((int *)table.data)[0]);
+}

Yeap, running these kunit test cases will surely be faster than stupid shell :) nice!

Quoted 40 lines
kernel/sysctl-test.c new file +40 -0
+static void sysctl_test_dointvec_happy_single_negative(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};
+	char input[] = "-9";
+	size_t len = sizeof(input) - 1;
+	loff_t pos = 0;
+
+	table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, input, &len, &pos));
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, (size_t)pos);
+	KUNIT_EXPECT_EQ(test, -9, ((int *)table.data)[0]);
+}
+
+static void sysctl_test_dointvec_single_less_int_min(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};
+	char input[32];
+	size_t len = sizeof(input) - 1;
+	loff_t pos = 0;
+	unsigned long abs_of_less_than_min = (unsigned long)INT_MAX
+					     - (INT_MAX + INT_MIN) + 1;
+
+	KUNIT_EXPECT_LT(test,

kernel/sysctl-test.c line 196

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+			(size_t)snprintf(input, sizeof(input), "-%lu",
+					 abs_of_less_than_min),
+			sizeof(input));
+
+	table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+			proc_dointvec(&table, 1, input, &len, &pos));
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+	KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}

API test.

Quoted 17 lines
kernel/sysctl-test.c new file +17 -0
+static void sysctl_test_dointvec_single_greater_int_max(struct kunit *test)
+{
+	struct ctl_table table = {
+		.procname = "foo",
+		.data		= &test_data.int_0001,
+		.maxlen		= sizeof(int),
+		.mode		= 0644,
+		.proc_handler	= proc_dointvec,
+		.extra1		= &i_zero,
+		.extra2         = &i_one_hundred,
+	};
+	char input[32];
+	size_t len = sizeof(input) - 1;
+	loff_t pos = 0;
+	unsigned long greater_than_max = (unsigned long)INT_MAX + 1;
+
+	KUNIT_EXPECT_GT(test, greater_than_max, (unsigned long)INT_MAX);

kernel/sysctl-test.c line 224

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+	KUNIT_EXPECT_LT(test, (size_t)snprintf(input, sizeof(input), "%lu",
+					       greater_than_max),
+			sizeof(input));
+	table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+			proc_dointvec(&table, 1, input, &len, &pos));
+	KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+	KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}
+

API test.

kernel/sysctl-test.c line 235

Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+static struct kunit_case sysctl_test_cases[] = {
+	KUNIT_CASE(sysctl_test_dointvec_null_tbl_data),
+	KUNIT_CASE(sysctl_test_dointvec_table_maxlen_unset),
+	KUNIT_CASE(sysctl_test_dointvec_table_len_is_zero),
+	KUNIT_CASE(sysctl_test_dointvec_table_read_but_position_set),
+	KUNIT_CASE(sysctl_test_dointvec_happy_single_positive),
+	KUNIT_CASE(sysctl_test_dointvec_happy_single_negative),
+	KUNIT_CASE(sysctl_test_dointvec_single_less_int_min),
+	KUNIT_CASE(sysctl_test_dointvec_single_greater_int_max),
+	{}
+};

Oh all are API tests.. perhaps then just rename then sysctl_test_cases to sysctl_api_test_cases.

Would be good to add at least *two* other tests cases for this example, one which does a valid read and one which does a valid write.

If that is done either we add another kunit test module for correctness or just extend the above and use prefix / postfixes on the functions to distinguish between API / correctness somehow.

Quoted 12 lines
kernel/sysctl-test.c new file +7 -0
+
+static struct kunit_module sysctl_test_module = {
+	.name = "sysctl_test",
+	.test_cases = sysctl_test_cases,
+};
+
+module_test(sysctl_test_module);
lib/Kconfig.debug +0 -0
index cbdfae3798965..389b8986f5b77 100644

lib/Kconfig.debug config TEST_SYSCTL · line 1948

Quoted 10 lines
lib/Kconfig.debug +7 -0
@@ -1939,6 +1939,16 @@ config TEST_SYSCTL
 
 	  If unsure, say N.
 
+config SYSCTL_KUNIT_TEST
+	bool "KUnit test for sysctl"
+	depends on KUNIT
+	help
+	  This builds the proc sysctl unit test, which runs on boot. For more
+	  information on KUnit and unit tests in general please refer to the
+	  KUnit documentation in Documentation/dev-tools/kunit/.

A little more description here would help. It is testing for API and hopefully also correctness (if extended with those two examples I mentioned).

Quoted 9 lines
lib/Kconfig.debug +3 -0
+
+	  If unsure, say N.
+
 config TEST_UDELAY
 	tristate "udelay test driver"
 	help
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog

Thanks for the work, it is very much appreciated and gives a clearer appreciation of value of kunit and what can be done and not. Another random test idea that comes up, would be to use different memory types for the table data. In case the kernel API users does something odd, we should be ensuring we do something proper.

Luis

#46 lore raw

Re: [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

Quoted 137 lines · Luis Chamberlain
Quoted 5 lines · Brendan Higgins

From: Iurii Zaikin <[email protected]>

KUnit tests for initialized data behavior of proc_dointvec that is explicitly checked in the code. Includes basic parsing tests including int min/max overflow.

First, thanks for this work! My review below.

Quoted 20 lines

---
Changes Since Last Revision:
- Iurii did some clean up (thanks Iurii!) as suggested by Stephen Boyd.

---
 kernel/Makefile      |   2 +
 kernel/sysctl-test.c | 242 +++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig.debug    |  10 ++
 3 files changed, 254 insertions(+)
 create mode 100644 kernel/sysctl-test.c
kernel/Makefile +0 -0
index a8d923b5481ba..50fd511cd0ee0 100644

kernel/Makefile obj-$(CONFIG_HAS_IOMEM) += iomem.o · line 117

Quoted 4 lines
kernel/Makefile +1 -0
@@ -114,6 +114,8 @@ obj-$(CONFIG_HAS_IOMEM) += iomem.o
 obj-$(CONFIG_ZONE_DEVICE) += memremap.o
 obj-$(CONFIG_RSEQ) += rseq.o
 
+obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o

And we have lib/test_sysctl.c of selftests.

I'm fine with this going in as-is to its current place, but if we have to learn from selftests I'd say we try to stick to a convention so folks know what framework a test is for, and to ensure folks can easily tell if its test code or not.

Perhaps simply a directory for kunit tests would suffice alone.

Quoted 53 lines
kernel/Makefile +1 -0
+
 obj-$(CONFIG_GCC_PLUGIN_STACKLEAK) += stackleak.o
 KASAN_SANITIZE_stackleak.o := n
 KCOV_INSTRUMENT_stackleak.o := n
kernel/sysctl-test.c new file +43 -0
new file mode 100644
index 0000000000000..cb61ad3c7db63
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * KUnit test of proc sysctl.
+ */
+
+#include <kunit/test.h>
+#include <linux/sysctl.h>
+
+static int i_zero;
+static int i_one_hundred = 100;
+
+struct test_sysctl_data {
+     int int_0001;
+     int int_0002;
+     int int_0003[4];
+
+     unsigned int uint_0001;
+
+     char string_0001[65];
+};
+
+static struct test_sysctl_data test_data = {
+     .int_0001 = 60,
+     .int_0002 = 1,
+
+     .int_0003[0] = 0,
+     .int_0003[1] = 1,
+     .int_0003[2] = 2,
+     .int_0003[3] = 3,
+
+     .uint_0001 = 314,
+
+     .string_0001 = "(none)",
+};
+
+static void sysctl_test_dointvec_null_tbl_data(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = NULL,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,

kernel/sysctl-test.c line 53

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);

It is a bit odd, but it does happen, for a developer to be calling proc_dointvec() directly, instead typically folks just register a table and let it do its thing. That said, someone not too familiar with proc code would see this and really have no clue exactly what is being tested.

Even as a maintainer, I had to read the code for proc_dointvec() a bit to understand that the above is a *read* attempt to the .data field being allocated. Because its a write, the len set to a bogus does not matter as we are expecting the proc_dointvec() to update len for us.

If a test fails, it would be good to for anyone to easily grasp what is being tested. So... a few words documenting each test case would be nice.

kernel/sysctl-test.c line 56

Quoted 3 lines
kernel/sysctl-test.c new file +3 -0
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);

And this is a write...

A nice tests given the data on the table allocated is not assigned.

I don't see any other areas in the kernel where we open code a proc_dointvec() call where the second argument is a digit, it always is with a variable. As such there would be no need for us to expose helpers to make it clear if one is a read or write. But for *this* case, I think it would be useful to add two wrappers inside this kunit test module which sprinkles the 0 or 1, this way a reader can easily know what mode is being tested.

Quoted 5 lines

kunit_proc_dointvec_read()
kunit_proc_dointvec_write()

Or just use #define KUNIT_PROC_READ 0, #define KUNIT_PROC_WRITE 1. Whatever makes this code more legible.

Went with the #define * suggestion above to keep it clear what function is being tested.

Quoted 30 lines
Quoted 14 lines
kernel/sysctl-test.c new file +14 -0
+}
+
+static void sysctl_test_dointvec_table_maxlen_unset(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = 0,
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);

kernel/sysctl-test.c line 80

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

In a way this is also testing for general kernel API changes. This is and the last one were good examples. So this is not just testing functionality here. There is no wrong or write answer if 0 or -EINVAL was returned other than the fact that we have been doing this for years.

Quoted 4 lines

Its a perhaps small but important difference for some of these tests. I *do* think its worth clarifying through documentation which ones are testing for API consistency Vs proper correctness.

You make a good point that the test codifies the existing behavior of the function
in lieu of formal documentation.
However, the test cases were derived from examining the source code of the function under test and attempting to cover all branches. The assertions were added
only for the values that appeared to be set deliberately in the implementation. And it makes
sense to me to test that the code does exactly what the implementation author intended.

Quoted 16 lines
Quoted 16 lines
kernel/sysctl-test.c new file +16 -0
+
+static void sysctl_test_dointvec_table_len_is_zero(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     size_t len;
+     loff_t pos;
+
Quoted 9 lines

kernel/sysctl-test.c line 102

Quoted 6 lines
kernel/sysctl-test.c new file +6 -0
+     len = 0;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

Likewise an API change test.

Same as the above, if the implementation author meant the function to behave deterministically
with the given input, it makes sense to test the behavior. Otherwise, why not just remove the branch in
the function under test and say that the given input results in
undefined behavior?

Quoted 111 lines
Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+
+static void sysctl_test_dointvec_table_read_but_position_set(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,

kernel/sysctl-test.c line 123

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     pos = 1;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

Likewise an API test.

All the above kunit test cases are currently testing this call on __do_proc_dointvec():

        if (!tbl_data || !table->maxlen || !*lenp || (*ppos && !write))
        {
                *lenp = 0;
                return 0;
        }

Just an API test.

Perhaps use an api prefix or postfix for these to help distinguish which are api tests Vs correctness. We want someone who runs into a failure to *easily* determine *what* went wrong.

Right now this kunit test leaves no leashes around to help the reader.

Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+
+static void sysctl_test_dointvec_happy_single_positive(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };

kernel/sysctl-test.c line 145

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     char input[] = "9";
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, (size_t)pos);
+     KUNIT_EXPECT_EQ(test, 9, ((int *)table.data)[0]);
+}

Yeap, running these kunit test cases will surely be faster than stupid shell :) nice!

Quoted 44 lines
kernel/sysctl-test.c new file +44 -0
+static void sysctl_test_dointvec_happy_single_negative(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[] = "-9";
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, (size_t)pos);
+     KUNIT_EXPECT_EQ(test, -9, ((int *)table.data)[0]);
+}
+
+static void sysctl_test_dointvec_single_less_int_min(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long abs_of_less_than_min = (unsigned long)INT_MAX
+                                          - (INT_MAX + INT_MIN) + 1;
+
+     KUNIT_EXPECT_LT(test,
+                     (size_t)snprintf(input, sizeof(input), "-%lu",
+                                      abs_of_less_than_min),
+                     sizeof(input));
+
Quoted 9 lines

kernel/sysctl-test.c line 196

Quoted 6 lines
kernel/sysctl-test.c new file +6 -0
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}

API test.

Not sure why. I believe there has been a real bug with int overflow in proc_dointvec.
Covering it with test seems like a good idea.

Quoted 45 lines
Quoted 17 lines
kernel/sysctl-test.c new file +17 -0
+static void sysctl_test_dointvec_single_greater_int_max(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long greater_than_max = (unsigned long)INT_MAX + 1;
+
+     KUNIT_EXPECT_GT(test, greater_than_max, (unsigned long)INT_MAX);

kernel/sysctl-test.c line 224

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     KUNIT_EXPECT_LT(test, (size_t)snprintf(input, sizeof(input), "%lu",
+                                            greater_than_max),
+                     sizeof(input));
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}
+

API test.

kernel/sysctl-test.c line 235

Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+static struct kunit_case sysctl_test_cases[] = {
+     KUNIT_CASE(sysctl_test_dointvec_null_tbl_data),
+     KUNIT_CASE(sysctl_test_dointvec_table_maxlen_unset),
+     KUNIT_CASE(sysctl_test_dointvec_table_len_is_zero),
+     KUNIT_CASE(sysctl_test_dointvec_table_read_but_position_set),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_positive),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_negative),
+     KUNIT_CASE(sysctl_test_dointvec_single_less_int_min),
+     KUNIT_CASE(sysctl_test_dointvec_single_greater_int_max),
+     {}
+};

Oh all are API tests.. perhaps then just rename then sysctl_test_cases to sysctl_api_test_cases.

Quoted 2 lines

Would be good to add at least *two* other tests cases for this example, one which does a valid read and one which does a valid write.

Added valid reads. There already are 2 valid writes.

Quoted 19 lines

If that is done either we add another kunit test module for correctness or just extend the above and use prefix / postfixes on the functions to distinguish between API / correctness somehow.

Quoted 15 lines
kernel/sysctl-test.c new file +7 -0
+
+static struct kunit_module sysctl_test_module = {
+     .name = "sysctl_test",
+     .test_cases = sysctl_test_cases,
+};
+
+module_test(sysctl_test_module);
lib/Kconfig.debug +0 -0
index cbdfae3798965..389b8986f5b77 100644
@@ -1939,6 +1939,16 @@ config TEST_SYSCTL
 
        If unsure, say N.
 
Quoted 12 lines

lib/Kconfig.debug config TEST_SYSCTL · line 1948

Quoted 7 lines
lib/Kconfig.debug +7 -0
+config SYSCTL_KUNIT_TEST
+     bool "KUnit test for sysctl"
+     depends on KUNIT
+     help
+       This builds the proc sysctl unit test, which runs on boot. For more
+       information on KUnit and unit tests in general please refer to the
+       KUnit documentation in Documentation/dev-tools/kunit/.

A little more description here would help. It is testing for API and hopefully also correctness (if extended with those two examples I mentioned).

Added "Tests the API contract and implementation correctness of sysctl."

Quoted 17 lines
Quoted 9 lines
lib/Kconfig.debug +3 -1
+
+       If unsure, say N.
+
 config TEST_UDELAY
      tristate "udelay test driver"
      help
--

2.22.0.410.gd8fdbe21b5-goog

Thanks for the work, it is very much appreciated and gives a clearer appreciation of value of kunit and what can be done and not. Another random test idea that comes up, would be to use different memory types for the table data. In case the kernel API users does something odd, we should be ensuring we do something proper.

Luis

#47 lore raw

Re: [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

Quoted 33 lines · Iurii Zaikin
Quoted 28 lines · Luis Chamberlain
Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+static void sysctl_test_dointvec_table_maxlen_unset(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = 0,
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);

kernel/sysctl-test.c line 80

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

In a way this is also testing for general kernel API changes. This is and the last one were good examples. So this is not just testing functionality here. There is no wrong or write answer if 0 or -EINVAL was returned other than the fact that we have been doing this for years.

Quoted 3 lines

Its a perhaps small but important difference for some of these tests. I *do* think its worth clarifying through documentation which ones are testing for API consistency Vs proper correctness.

Quoted 7 lines

You make a good point that the test codifies the existing behavior of the function in lieu of formal documentation. However, the test cases were derived from examining the source code of the function under test and attempting to cover all branches. The assertions were added only for the values that appeared to be set deliberately in the implementation. And it makes sense to me to test that the code does exactly what the implementation author intended.

I'm not arguing against adding them. I'm suggesting that it is different to test for API than for correctness of intended functionality, and it would be wise to make it clear which test cases are for API and which for correctness.

This will come up later for other kunit tests and it would be great to set precendent so that other kunit tests can follow similar practices to ensure its clear what is API realted Vs correctness of intended functionality.

In fact, I'm not yet sure if its possible to test public kernel API to userspace with kunit, but if it is possible... well, that could make linux-api folks happy as they could enable us to codify interpreation of what is expected into kunit test cases, and we'd ensure that the codified interpretation is not only documented in man pages but also through formal kunit test cases.

A regression in linux-api then could be formalized through a proper kunit tests case. And if an API evolves, it would force developers to update the respective kunit which codifies that contract.

Quoted 31 lines
Quoted 22 lines
Quoted 22 lines
kernel/sysctl-test.c new file +22 -0
+static void sysctl_test_dointvec_single_less_int_min(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long abs_of_less_than_min = (unsigned long)INT_MAX
+                                          - (INT_MAX + INT_MIN) + 1;
+
+     KUNIT_EXPECT_LT(test,
+                     (size_t)snprintf(input, sizeof(input), "-%lu",
+                                      abs_of_less_than_min),
+                     sizeof(input));
+
Quoted 9 lines

kernel/sysctl-test.c line 196

Quoted 6 lines
kernel/sysctl-test.c new file +6 -0
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}

API test.

Quoted 1 line

Not sure why.

Because you are codifying that we *definitely* return -EINVAL on overlow. Some parts of the kernel return -ERANGE for overflows for instance.

It would be a generic test for overflow if it would just test for any error.

It is a fine and good test to keep. All these tests are good to keep.

Quoted 3 lines

I believe there has been a real bug with int overflow in proc_dointvec.
Covering it with test seems like a good idea.

Oh definitely.

Quoted 45 lines
Quoted 45 lines
Quoted 17 lines
kernel/sysctl-test.c new file +17 -0
+static void sysctl_test_dointvec_single_greater_int_max(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long greater_than_max = (unsigned long)INT_MAX + 1;
+
+     KUNIT_EXPECT_GT(test, greater_than_max, (unsigned long)INT_MAX);

kernel/sysctl-test.c line 224

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     KUNIT_EXPECT_LT(test, (size_t)snprintf(input, sizeof(input), "%lu",
+                                            greater_than_max),
+                     sizeof(input));
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}
+

API test.

kernel/sysctl-test.c line 235

Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+static struct kunit_case sysctl_test_cases[] = {
+     KUNIT_CASE(sysctl_test_dointvec_null_tbl_data),
+     KUNIT_CASE(sysctl_test_dointvec_table_maxlen_unset),
+     KUNIT_CASE(sysctl_test_dointvec_table_len_is_zero),
+     KUNIT_CASE(sysctl_test_dointvec_table_read_but_position_set),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_positive),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_negative),
+     KUNIT_CASE(sysctl_test_dointvec_single_less_int_min),
+     KUNIT_CASE(sysctl_test_dointvec_single_greater_int_max),
+     {}
+};

Oh all are API tests.. perhaps then just rename then sysctl_test_cases to sysctl_api_test_cases.

Quoted 3 lines
Quoted 2 lines

Would be good to add at least *two* other tests cases for this example, one which does a valid read and one which does a valid write.

Added valid reads. There already are 2 valid writes.

Thanks.

Quoted 31 lines
Quoted 19 lines

If that is done either we add another kunit test module for correctness or just extend the above and use prefix / postfixes on the functions to distinguish between API / correctness somehow.

Quoted 15 lines
kernel/sysctl-test.c new file +7 -0
+
+static struct kunit_module sysctl_test_module = {
+     .name = "sysctl_test",
+     .test_cases = sysctl_test_cases,
+};
+
+module_test(sysctl_test_module);
lib/Kconfig.debug +0 -0
index cbdfae3798965..389b8986f5b77 100644
@@ -1939,6 +1939,16 @@ config TEST_SYSCTL
 
        If unsure, say N.
 
Quoted 12 lines

lib/Kconfig.debug config TEST_SYSCTL · line 1948

Quoted 7 lines
lib/Kconfig.debug +7 -0
+config SYSCTL_KUNIT_TEST
+     bool "KUnit test for sysctl"
+     depends on KUNIT
+     help
+       This builds the proc sysctl unit test, which runs on boot. For more
+       information on KUnit and unit tests in general please refer to the
+       KUnit documentation in Documentation/dev-tools/kunit/.

A little more description here would help. It is testing for API and hopefully also correctness (if extended with those two examples I mentioned).

Quoted 1 line

Added "Tests the API contract and implementation correctness of sysctl."

Yes, much clearer, thanks!

Luis

#48 lore raw

Re: [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

Quoted 43 lines · Luis Chamberlain
Quoted 33 lines · Iurii Zaikin
Quoted 28 lines · Luis Chamberlain
Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+static void sysctl_test_dointvec_table_maxlen_unset(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = 0,
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);

kernel/sysctl-test.c line 80

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

In a way this is also testing for general kernel API changes. This is and the last one were good examples. So this is not just testing functionality here. There is no wrong or write answer if 0 or -EINVAL was returned other than the fact that we have been doing this for years.

Quoted 3 lines

Its a perhaps small but important difference for some of these tests. I *do* think its worth clarifying through documentation which ones are testing for API consistency Vs proper correctness.

Quoted 7 lines

You make a good point that the test codifies the existing behavior of the function in lieu of formal documentation. However, the test cases were derived from examining the source code of the function under test and attempting to cover all branches. The assertions were added only for the values that appeared to be set deliberately in the implementation. And it makes sense to me to test that the code does exactly what the implementation author intended.

Quoted 4 lines

I'm not arguing against adding them. I'm suggesting that it is different to test for API than for correctness of intended functionality, and it would be wise to make it clear which test cases are for API and which for correctness.

I see later on that some of the API stuff you are talking about is public APIs from the standpoint of user (outside of LInux) visible. To be clear, is that what you mean by public APIs throughout, or would you distinguish between correctness tests, internal API tests, and external API tests?

Quoted 12 lines

This will come up later for other kunit tests and it would be great to set precendent so that other kunit tests can follow similar practices to ensure its clear what is API realted Vs correctness of intended functionality.

In fact, I'm not yet sure if its possible to test public kernel API to userspace with kunit, but if it is possible... well, that could make linux-api folks happy as they could enable us to codify interpreation of what is expected into kunit test cases, and we'd ensure that the codified interpretation is not only documented in man pages but also through formal kunit test cases.

Quoted 3 lines

A regression in linux-api then could be formalized through a proper kunit tests case. And if an API evolves, it would force developers to update the respective kunit which codifies that contract.

Yep, I think that is long term hope. Some of the file system interface stuff that requires a filesystem to be mounted somewhere might get a little weird/difficult, but I suspect we should be able to do it eventually. I mean it's all just C code right? Should mostly boil down to someone figuring out how to do it the first time.

Quoted 130 lines
Quoted 31 lines
Quoted 22 lines
Quoted 22 lines
kernel/sysctl-test.c new file +22 -0
+static void sysctl_test_dointvec_single_less_int_min(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long abs_of_less_than_min = (unsigned long)INT_MAX
+                                          - (INT_MAX + INT_MIN) + 1;
+
+     KUNIT_EXPECT_LT(test,
+                     (size_t)snprintf(input, sizeof(input), "-%lu",
+                                      abs_of_less_than_min),
+                     sizeof(input));
+
Quoted 9 lines

kernel/sysctl-test.c line 196

Quoted 6 lines
kernel/sysctl-test.c new file +6 -0
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}

API test.

Quoted 1 line

Not sure why.

Because you are codifying that we *definitely* return -EINVAL on overlow. Some parts of the kernel return -ERANGE for overflows for instance.

It would be a generic test for overflow if it would just test for any error.

It is a fine and good test to keep. All these tests are good to keep.

Quoted 3 lines

I believe there has been a real bug with int overflow in proc_dointvec.
Covering it with test seems like a good idea.

Oh definitely.

Quoted 45 lines
Quoted 45 lines
Quoted 17 lines
kernel/sysctl-test.c new file +17 -0
+static void sysctl_test_dointvec_single_greater_int_max(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = sizeof(int),
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     char input[32];
+     size_t len = sizeof(input) - 1;
+     loff_t pos = 0;
+     unsigned long greater_than_max = (unsigned long)INT_MAX + 1;
+
+     KUNIT_EXPECT_GT(test, greater_than_max, (unsigned long)INT_MAX);

kernel/sysctl-test.c line 224

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     KUNIT_EXPECT_LT(test, (size_t)snprintf(input, sizeof(input), "%lu",
+                                            greater_than_max),
+                     sizeof(input));
+     table.data = kunit_kzalloc(test, sizeof(int), GFP_USER);
+     KUNIT_EXPECT_EQ(test, -EINVAL,
+                     proc_dointvec(&table, 1, input, &len, &pos));
+     KUNIT_EXPECT_EQ(test, sizeof(input) - 1, len);
+     KUNIT_EXPECT_EQ(test, 0, ((int *)table.data)[0]);
+}
+

API test.

kernel/sysctl-test.c line 235

Quoted 11 lines
kernel/sysctl-test.c new file +11 -0
+static struct kunit_case sysctl_test_cases[] = {
+     KUNIT_CASE(sysctl_test_dointvec_null_tbl_data),
+     KUNIT_CASE(sysctl_test_dointvec_table_maxlen_unset),
+     KUNIT_CASE(sysctl_test_dointvec_table_len_is_zero),
+     KUNIT_CASE(sysctl_test_dointvec_table_read_but_position_set),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_positive),
+     KUNIT_CASE(sysctl_test_dointvec_happy_single_negative),
+     KUNIT_CASE(sysctl_test_dointvec_single_less_int_min),
+     KUNIT_CASE(sysctl_test_dointvec_single_greater_int_max),
+     {}
+};

Oh all are API tests.. perhaps then just rename then sysctl_test_cases to sysctl_api_test_cases.

Quoted 3 lines
Quoted 2 lines

Would be good to add at least *two* other tests cases for this example, one which does a valid read and one which does a valid write.

Added valid reads. There already are 2 valid writes.

Thanks.

Quoted 31 lines
Quoted 31 lines

If that is done either we add another kunit test module for correctness or just extend the above and use prefix / postfixes on the functions to distinguish between API / correctness somehow.

Quoted 12 lines
kernel/sysctl-test.c new file +7 -0
+
+static struct kunit_module sysctl_test_module = {
+     .name = "sysctl_test",
+     .test_cases = sysctl_test_cases,
+};
+
+module_test(sysctl_test_module);
lib/Kconfig.debug +0 -0
index cbdfae3798965..389b8986f5b77 100644

lib/Kconfig.debug config TEST_SYSCTL · line 1948

Quoted 10 lines
lib/Kconfig.debug +7 -0
@@ -1939,6 +1939,16 @@ config TEST_SYSCTL
 
        If unsure, say N.
 
+config SYSCTL_KUNIT_TEST
+     bool "KUnit test for sysctl"
+     depends on KUNIT
+     help
+       This builds the proc sysctl unit test, which runs on boot. For more
+       information on KUnit and unit tests in general please refer to the
+       KUnit documentation in Documentation/dev-tools/kunit/.

A little more description here would help. It is testing for API and hopefully also correctness (if extended with those two examples I mentioned).

Quoted 3 lines
Quoted 1 line

Added "Tests the API contract and implementation correctness of sysctl."

Yes, much clearer, thanks!

Cheers!

#49 lore raw

Re: [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()

Quoted 44 lines · Brendan Higgins
Quoted 43 lines · Luis Chamberlain
Quoted 40 lines · Iurii Zaikin
Quoted 28 lines · Luis Chamberlain
Quoted 12 lines
kernel/sysctl-test.c new file +12 -0
+static void sysctl_test_dointvec_table_maxlen_unset(struct kunit *test)
+{
+     struct ctl_table table = {
+             .procname = "foo",
+             .data           = &test_data.int_0001,
+             .maxlen         = 0,
+             .mode           = 0644,
+             .proc_handler   = proc_dointvec,
+             .extra1         = &i_zero,
+             .extra2         = &i_one_hundred,
+     };
+     void  *buffer = kunit_kzalloc(test, sizeof(int), GFP_USER);

kernel/sysctl-test.c line 80

Quoted 10 lines
kernel/sysctl-test.c new file +10 -0
+     size_t len;
+     loff_t pos;
+
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 0, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+     len = 1234;
+     KUNIT_EXPECT_EQ(test, 0, proc_dointvec(&table, 1, buffer, &len, &pos));
+     KUNIT_EXPECT_EQ(test, (size_t)0, len);
+}

In a way this is also testing for general kernel API changes. This is and the last one were good examples. So this is not just testing functionality here. There is no wrong or write answer if 0 or -EINVAL was returned other than the fact that we have been doing this for years.

Quoted 3 lines

Its a perhaps small but important difference for some of these tests. I *do* think its worth clarifying through documentation which ones are testing for API consistency Vs proper correctness.

You make a good point that the test codifies the existing behavior of the function in lieu of formal documentation. However, the test cases were derived from examining the source code of the function under test and attempting to cover all branches. The assertions were added only for the values that appeared to be set deliberately in the implementation. And it makes sense to me to test that the code does exactly what the implementation author intended.

Quoted 7 lines
Quoted 4 lines

I'm not arguing against adding them. I'm suggesting that it is different to test for API than for correctness of intended functionality, and it would be wise to make it clear which test cases are for API and which for correctness.

I see later on that some of the API stuff you are talking about is public APIs from the standpoint of user (outside of LInux) visible.

Right, UAPI.

Quoted 4 lines

To
be clear, is that what you mean by public APIs throughout, or would you distinguish between correctness tests, internal API tests, and external API tests?

I would definitely recommend distingishing between all of these. Kernel API (or just call it API), UAPI, and correctness.

Quoted 16 lines
Quoted 12 lines

This will come up later for other kunit tests and it would be great to set precendent so that other kunit tests can follow similar practices to ensure its clear what is API realted Vs correctness of intended functionality.

In fact, I'm not yet sure if its possible to test public kernel API to userspace with kunit, but if it is possible... well, that could make linux-api folks happy as they could enable us to codify interpreation of what is expected into kunit test cases, and we'd ensure that the codified interpretation is not only documented in man pages but also through formal kunit test cases.

Quoted 3 lines

A regression in linux-api then could be formalized through a proper kunit tests case. And if an API evolves, it would force developers to update the respective kunit which codifies that contract.

Quoted 5 lines

Yep, I think that is long term hope. Some of the file system interface stuff that requires a filesystem to be mounted somewhere might get a little weird/difficult, but I suspect we should be able to do it eventually. I mean it's all just C code right? Should mostly boil down to someone figuring out how to do it the first time.

There used to be hacks in the kernel the call syscalls in a few places. This was cleaned up and addressed via Dominik Brodowski's series last year in March:

http://lkml.kernel.org/r/20180325162527.GA17492-SGhQLRGLuNwb6pqDj42GsMgv3T4z79SOrE5yTffgRl4@public.gmane.org

An example commit: d300b610812f3 ("kernel: use kernel_wait4() instead of sys_wait4()").

So it would seem the work is done, and you'd just have to use the respective exposed kernel_syscallname() calls, or add some if you want to test a specific syscall in kernel space.

Luis

#50 lore raw

PATCH v5 18/18 MAINTAINERS: add proc sysctl KUnit test to PROC SYSCTL section

In reply to Brendan Higgins

Add entry for the new proc sysctl KUnit test to the PROC SYSCTL section.

---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index f3fb3fc30853e..05cd8ffd33c8f 100644
@@ -12718,6 +12718,7 @@ S:	Maintained
 F:	fs/proc/proc_sysctl.c
 F:	include/linux/sysctl.h
 F:	kernel/sysctl.c
+F:	kernel/sysctl-test.c
 F:	tools/testing/selftests/sysctl/
 
 PS3 NETWORK SUPPORT
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
#52 lore raw
In reply to Brendan Higgins

Hi Brendan,

I am only responding to this because you asked me to in the v4 thread.

Thank you for evaluating my comments in the v4 thread and asking me to comment on v5

Quoted 45 lines · Brendan Higgins

## TL;DR

A not so quick follow-up to Stephen's suggestions on PATCH v4. Nothing that really changes any functionality or usage with the minor exception of a couple public functions that Stephen asked me to rename. Nevertheless, a good deal of clean up and fixes. See changes below.

As for our current status, right now we got Reviewed-bys on all patches except:

- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list

However, it would probably be good to get reviews/acks from the subsystem maintainers on:

- [PATCH v5 06/18] kbuild: enable building KUnit
- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list
- [PATCH v5 15/18] Documentation: kunit: add documentation for KUnit
- [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()
- [PATCH v5 18/18] MAINTAINERS: add proc sysctl KUnit test to PROC SYSCTL section

Other than that, I think we should be good to go.

One last thing, I updated the background to include my thoughts on KUnit vs. in kernel testing with kselftest in the background sections as suggested by Frank in the discussion on PATCH v2.

## Background

This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.

Unlike Autotest and kselftest, KUnit is a true unit testing framework; it does not require installing the kernel on a test machine or in a VM (however, KUnit still allows you to run tests on test machines or in VMs if you want[1]) and does not require tests to be written in userspace running on a host kernel. Additionally, KUnit is fast: From invocation to completion KUnit can run several dozen tests in under a second. Currently, the entire KUnit test suite for KUnit runs in under a second from the initial invocation (build time excluded).

Quoted 5 lines

KUnit is heavily inspired by JUnit, Python's unittest.mock, and Googletest/Googlemock for C++. KUnit provides facilities for defining unit test cases, grouping related test cases into test suites, providing common infrastructure for running tests, mocking, spying, and much more.

I looked only at this section, as was specifically requested:

Quoted 15 lines

### But wait! Doesn't kselftest support in kernel testing?!

In a previous version of this patchset Frank pointed out that kselftest already supports writing a test that resides in the kernel using the test module feature[2]. LWN did a really great summary on this discussion here[3].

Kselftest has a feature that allows a test module to be loaded into a kernel using the kselftest framework; this does allow someone to write tests against kernel code not directly exposed to userland; however, it does not provide much of a framework around how to structure the tests. The kselftest test module feature just provides a header which has a standardized way of reporting test failures,

Quoted 3 lines

and then provides
infrastructure to load and run the tests using the kselftest test harness.

The in-kernel tests can also be invoked at boot time if they are configured (Kconfig) as in-kernel instead of as modules. I did not check how many of the tests have tri-state configuration to allow this, but the few that I looked at did.

Quoted 8 lines

The kselftest test module does not seem to be opinionated at all in regards to how tests are structured, how they check for failures, how tests are organized. Even in the method it provides for reporting failures is pretty simple; it doesn't have any more advanced failure reporting or logging features. Given what's there, I think it is fair to say that it is not actually a framework, but a feature that makes it possible for someone to do some checks in kernel space.

I would call that description a little dismissive. The set of in-kernel tests that I looked like followed a common pattern and reported results in a uniform manner.

Quoted 8 lines

Furthermore, kselftest test module has very few users. I checked for all the tests that use it using the following grep command:

grep -Hrn -e 'kselftest_module\.h'

and only got three results: lib/test_strscpy.c, lib/test_printf.c, and lib/test_bitmap.c.

You missed many tests. I listed much more than that in the v4 thread, and someone else also listed more in the v4 thread.

Quoted 8 lines

So despite kselftest test module's existence, there really is no feature overlap between kselftest and KUnit, save one: that you can use either to write an in-kernel test, but this is a very small feature in comparison to everything that KUnit allows you to do. KUnit is a full x-unit style unit testing framework, whereas kselftest looks a lot more like an end-to-end/functional testing framework, with a feature that makes it possible to write in-kernel tests.

The description does not give enough credit to what is in kselftest.

It does not matter whether KUnit provides additional things, relative to kselftest. The point I was making is that there appears to be _some_ overlap between kselftest and KUnit, and if there is overlap then it is worth considering whether the overlap can be unified instead of duplicated.

I don't have a dog in this fight and the discussion in the v4 thread went way off track. Thus I am not going to get sucked back into a pointless debate in this thread.

Thanks for adding this section to address the issue.

-Frank

Quoted 62 lines

### What's so special about unit testing?

A unit test is supposed to test a single unit of code in isolation, hence the name. There should be no dependencies outside the control of the test; this means no external dependencies, which makes tests orders of magnitudes faster. Likewise, since there are no external dependencies, there are no hoops to jump through to run the tests. Additionally, this makes unit tests deterministic: a failing unit test always indicates a problem. Finally, because unit tests necessarily have finer granularity, they are able to test all code paths easily solving the classic problem of difficulty in exercising error handling code.

### Is KUnit trying to replace other testing frameworks for the kernel?

No. Most existing tests for the Linux kernel are end-to-end tests, which have their place. A well tested system has lots of unit tests, a reasonable number of integration tests, and some end-to-end tests. KUnit is just trying to address the unit test space which is currently not being addressed.

### More information on KUnit

There is a bunch of documentation near the end of this patch set that describes how to use KUnit and best practices for writing unit tests. For convenience I am hosting the compiled docs here[4].

Additionally for convenience, I have applied these patches to a branch[5]. The repo may be cloned with:
git clone https://kunit.googlesource.com/linux
This patchset is on the kunit/rfc/v5.2-rc4/v5 branch.

## Changes Since Last Version

Aside from a couple public function renames, there isn't really anything in here that changes any functionality.

- Went through and fixed a couple of anti-patterns suggested by Stephen Boyd. Things like:
- Dropping an else clause at the end of a function.
- Dropping the comma on the closing sentinel, {}, of a list.
- Inlines a bunch of functions in the test case running logic in patch 01/18 to make it more readable as suggested by Stephen Boyd
- Found and fixed bug in resource deallocation logic in patch 02/18. Bug was discovered as a result of making a change suggested by Stephen Boyd. This does not substantially change how any of the code works conceptually.
- Renamed new_string_stream() to alloc_string_stream() as suggested by Stephen Boyd.
- Made string-stream a KUnit managed object - based on a suggestion made by Stephen Boyd.
- Renamed kunit_new_stream() to alloc_kunit_stream() as suggested by Stephen Boyd.
- Removed the ability to set log level after allocating a kunit_stream, as suggested by Stephen Boyd.

[1] https://google.github.io/kunit-docs/third_party/kernel/docs/usage.html#kunit-on-non-uml-architectures
[2] https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html#test-module
[3] https://lwn.net/Articles/790235/
[4] https://google.github.io/kunit-docs/third_party/kernel/docs/
[5] https://kunit.googlesource.com/linux/+/kunit/rfc/v5.2-rc4/v5

maintainer
#53 lore raw

Hi Brendan,

Quoted 94 lines · Frank Rowand

Hi Brendan,

I am only responding to this because you asked me to in the v4 thread.

Thank you for evaluating my comments in the v4 thread and asking me to comment on v5

Quoted 45 lines · Brendan Higgins

## TL;DR

A not so quick follow-up to Stephen's suggestions on PATCH v4. Nothing that really changes any functionality or usage with the minor exception of a couple public functions that Stephen asked me to rename. Nevertheless, a good deal of clean up and fixes. See changes below.

As for our current status, right now we got Reviewed-bys on all patches except:

- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list

However, it would probably be good to get reviews/acks from the subsystem maintainers on:

- [PATCH v5 06/18] kbuild: enable building KUnit
- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list
- [PATCH v5 15/18] Documentation: kunit: add documentation for KUnit
- [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()
- [PATCH v5 18/18] MAINTAINERS: add proc sysctl KUnit test to PROC SYSCTL section

Other than that, I think we should be good to go.

One last thing, I updated the background to include my thoughts on KUnit vs. in kernel testing with kselftest in the background sections as suggested by Frank in the discussion on PATCH v2.

## Background

This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.

Unlike Autotest and kselftest, KUnit is a true unit testing framework; it does not require installing the kernel on a test machine or in a VM (however, KUnit still allows you to run tests on test machines or in VMs if you want[1]) and does not require tests to be written in userspace running on a host kernel. Additionally, KUnit is fast: From invocation to completion KUnit can run several dozen tests in under a second. Currently, the entire KUnit test suite for KUnit runs in under a second from the initial invocation (build time excluded).

Quoted 5 lines

KUnit is heavily inspired by JUnit, Python's unittest.mock, and Googletest/Googlemock for C++. KUnit provides facilities for defining unit test cases, grouping related test cases into test suites, providing common infrastructure for running tests, mocking, spying, and much more.

I looked only at this section, as was specifically requested:

Quoted 15 lines

### But wait! Doesn't kselftest support in kernel testing?!

In a previous version of this patchset Frank pointed out that kselftest already supports writing a test that resides in the kernel using the test module feature[2]. LWN did a really great summary on this discussion here[3].

Kselftest has a feature that allows a test module to be loaded into a kernel using the kselftest framework; this does allow someone to write tests against kernel code not directly exposed to userland; however, it does not provide much of a framework around how to structure the tests. The kselftest test module feature just provides a header which has a standardized way of reporting test failures,

Quoted 3 lines

and then provides
infrastructure to load and run the tests using the kselftest test harness.

The in-kernel tests can also be invoked at boot time if they are configured (Kconfig) as in-kernel instead of as modules. I did not check how many of the tests have tri-state configuration to allow this, but the few that I looked at did.

Quoted 8 lines

The kselftest test module does not seem to be opinionated at all in regards to how tests are structured, how they check for failures, how tests are organized. Even in the method it provides for reporting failures is pretty simple; it doesn't have any more advanced failure reporting or logging features. Given what's there, I think it is fair to say that it is not actually a framework, but a feature that makes it possible for someone to do some checks in kernel space.

Quoted 5 lines

I would call that description a little dismissive. The set of in-kernel tests that I looked like followed a common pattern and reported results in a uniform manner.

Quoted 1 line

I think I commented on this before. I agree with the statement that there is no overlap between Kselftest and KUnit. I would like see this removed. Kselftest module support supports use-cases KUnit won't be able to. I can build an kernel with Kselftest test modules and use it in the filed to load and run tests if I need to debug a problem and get data from a system. I can't do that with KUnit.

In my mind, I am not viewing this as which is better. Kselftest and KUnit both have their place in the kernel development process. It isn't productive and/or necessary to comparing Kselftest and KUnit without a good understanding of the problem spaces for each of these.

I would strongly recommend not making reference to Kselftest and talk about what KUnit offers.

Quoted 8 lines
Quoted 7 lines

Furthermore, kselftest test module has very few users. I checked for all the tests that use it using the following grep command:

grep -Hrn -e 'kselftest_module\.h'

and only got three results: lib/test_strscpy.c, lib/test_printf.c, and lib/test_bitmap.c.

Again, unnecessary. KUnit can't replace Kselftest module in the way Kselftest module support can be used for debugging and gathering information on system that might be in active use and not dedicated to test and development alone. I wouldn't hesitate loading a Kselftest test module on my laptop and running tests, but I wouldn't use KUnit the same way.

Again, this is not a competition between which is better. Kselftest and KUnit serve different needs and problem spaces.

Please redo this documentation to reflect that.

thanks,
-- Shuah

_______________________________________________
dri-devel mailing list
[email protected]
https://lists.freedesktop.org/mailman/listinfo/dri-devel

#54 lore raw
Quoted 11 lines · shuah
Quoted 3 lines
Quoted 3 lines

### But wait! Doesn't kselftest support in kernel testing?!

....

I think I commented on this before. I agree with the statement that there is no overlap between Kselftest and KUnit. I would like see this removed. Kselftest module support supports use-cases KUnit won't be able to. I can build an kernel with Kselftest test modules and use it in the filed to load and run tests if I need to debug a problem and get data from a system. I can't do that with KUnit.

Quoted 7 lines

In my mind, I am not viewing this as which is better. Kselftest and KUnit both have their place in the kernel development process. It isn't productive and/or necessary to comparing Kselftest and KUnit without a good understanding of the problem spaces for each of these.

I would strongly recommend not making reference to Kselftest and talk about what KUnit offers.

Shuah,

Just to recall the history, this section of the FAQ was added to rebut the ***very*** strong statements that Frank made that there was overlap between Kselftest and Kunit, and that having too many ways for kernel developers to do the identical thing was harmful (he said it was too much of a burden on a kernel developer) --- and this was an argument for not including Kunit in the upstream kernel.

If we're past that objection, then perhaps this section can be dropped, but there's a very good reason why it was there. I wouldn't Brendan to be accused of ignoring feedback from those who reviewed his
patches. :-)

- Ted

maintainer
#55 lore raw
Quoted 29 lines · Theodore Ts'o
Quoted 11 lines · shuah
Quoted 3 lines
Quoted 3 lines

### But wait! Doesn't kselftest support in kernel testing?!

....

I think I commented on this before. I agree with the statement that there is no overlap between Kselftest and KUnit. I would like see this removed. Kselftest module support supports use-cases KUnit won't be able to. I can build an kernel with Kselftest test modules and use it in the filed to load and run tests if I need to debug a problem and get data from a system. I can't do that with KUnit.

Quoted 7 lines

In my mind, I am not viewing this as which is better. Kselftest and KUnit both have their place in the kernel development process. It isn't productive and/or necessary to comparing Kselftest and KUnit without a good understanding of the problem spaces for each of these.

I would strongly recommend not making reference to Kselftest and talk about what KUnit offers.

Shuah,

Just to recall the history, this section of the FAQ was added to rebut the ***very*** strong statements that Frank made that there was overlap between Kselftest and Kunit, and that having too many ways for kernel developers to do the identical thing was harmful (he said it was too much of a burden on a kernel developer) --- and this was an argument for not including Kunit in the upstream kernel.

Quoted 5 lines

If we're past that objection, then perhaps this section can be dropped, but there's a very good reason why it was there. I wouldn't Brendan to be accused of ignoring feedback from those who reviewed his
patches. :-)

Agreed. I understand that this FAQ probably was needed at one time and Brendan added it to address the concerns.

I think at some point we do need to have a document that outlines when to KUnit and when to use Kselftest modules. I think one concern people have is that if KUnit is perceived as a replacement for Ksefltest module, Kselftest module will be ignored leaving users without the ability to build and run with Kselftest modules and load them on a need basis to gather data on a systems that aren't dedicated strictly for testing.

I am trying to move the conversation forward from KUnit vs. Kselftest modules discussion to which problem areas each one addresses keeping in mind that it is not about which is better. Kselftest and KUnit both have their place in the kernel development process. We just have to be clear on usage as we write tests for each.

thanks,
-- Shuah

#56 lore raw
Quoted 5 lines · shuah
Quoted 3 lines · Theodore Ts'o
Quoted 2 lines · shuah
Quoted 2 lines
Quoted 2 lines

### But wait! Doesn't kselftest support in kernel testing?!

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 1 line
Quoted 1 line

....

I think I commented on this before. I agree with the statement that there is no overlap between Kselftest and KUnit. I would like see this removed. Kselftest module support supports use-cases KUnit won't be able to. I can build an kernel with Kselftest test modules and use it in the filed to load and run tests if I need to debug a problem and get data from a system. I can't do that with KUnit.

Sure, I think this point has been brought up a number of times before. Maybe I didn't write this section well because, like Frank said, it comes across as being critical of the Kselftest module support; that wasn't my intention. I was speaking from the perspective that Kselftest module support is just a feature of Kselftest, and not a full framework like KUnit is (obviously Kselftest itself *is* a framework, but a very small part of it is not).

It was obvious to me what Kselftest module support was intended for, and it is not intended to cover the use case that KUnit is targeting.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

In my mind, I am not viewing this as which is better. Kselftest and KUnit both have their place in the kernel development process. It isn't productive and/or necessary to comparing Kselftest and KUnit without a good understanding of the problem spaces for each of these.

Again, I didn't mean to draw a comparison of which is better than the other. I was just trying to point out that Kselftest module support doesn't make sense as a stand alone unit testing framework, or really a framework of any kind, despite how it might actually be used.

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I would strongly recommend not making reference to Kselftest and talk about what KUnit offers.

I can see your point. It seems that both you and Frank seem to think that I drew a comparison between Kselftest and KUnit, which was unintended. I probably should have spent more time editing this section, but I can see the point of drawing the comparison itself might invite this confusion.

Quoted 8 lines
Quoted 8 lines

Shuah,

Just to recall the history, this section of the FAQ was added to rebut the ***very*** strong statements that Frank made that there was overlap between Kselftest and Kunit, and that having too many ways for kernel developers to do the identical thing was harmful (he said it was too much of a burden on a kernel developer) --- and this was an argument for not including Kunit in the upstream kernel.

I don't think he was actually advocating that we don't include KUnit, maybe playing devil's advocate; nevertheless, at the end, Frank seemed to agree that there were valuable things that KUnit offered. I thought he just wanted to make the point that I hadn't made the distinction sufficiently clear in the cover letter, and other reviewers might get confused in the future as well.

Additionally, it does look like people were trying to use Kselftest module support to cover some things which really were trying to be unit tests. I know this isn't really intended - everything looks like a nail when you only have a hammer, which I think Frank was pointing out furthers the above confusion.

In anycase, it sounds like I have, if anything, only made the discussion even more confusing by adding this section; sorry about that.

Quoted 8 lines
Quoted 5 lines

If we're past that objection, then perhaps this section can be dropped, but there's a very good reason why it was there. I wouldn't Brendan to be accused of ignoring feedback from those who reviewed his
patches. :-)

Agreed. I understand that this FAQ probably was needed at one time and Brendan added it to address the concerns.

I don't want to speak for Frank, but I don't think it was an objection to KUnit itself, but rather an objection to not sufficiently addressing the point about how they differ.

Quoted 7 lines

I think at some point we do need to have a document that outlines when to KUnit and when to use Kselftest modules. I think one concern people have is that if KUnit is perceived as a replacement for Ksefltest module, Kselftest module will be ignored leaving users without the ability to build and run with Kselftest modules and load them on a need basis to gather data on a systems that aren't dedicated strictly for testing.

I absolutely agree! I posed a suggestion here[1], which after I just now searched for a link, I realize for some reason it didn't seem like it reached a number of the mailing lists that I sent it to, so I should probably resend it.

Anyway, a summary of what I suggested: We should start off by better organizing Documentation/dev-tools/ and create a landing page that groups the dev-tools by function according to what person is likely to use them and for what. Eventually and specifically for Kselftest and KUnit, I would like to have a testing guide for the kernel that explains what testing procedure should look like and what to use and when.

Quoted 5 lines

I am trying to move the conversation forward from KUnit vs. Kselftest modules discussion to which problem areas each one addresses keeping in mind that it is not about which is better. Kselftest and KUnit both have their place in the kernel development process. We just have to be clear on usage as we write tests for each.

I think that is the right long term approach. I think a good place to start, like I suggested above, is cleaning up Documentation/dev-tools/, but I think that belongs in a (probably several) follow-up patchset.

Frank, I believe your objection was mostly related to how KUnit is presented specifically in the cover letter, and doesn't necessarily deal with the intended use case. So I don't think that doing this, especially doing this later, really addresses your concern. I don't want to belabor the issue, but I would also rather not put words in your mouth, what are your thoughts on the above?

I think my main concern moving forward on this point is that I am not sure that I can address the debate that this section covers in a way that is both sufficiently concise for a cover letter, but also doesn't invite more potential confusion. My inclination at this point is to drop it since I think the set of reviewers for this patchset has at this point become fixed, and it seems that it will likely cause more confusion rather than reduce it; also, I don't really think this will be an issue for end users, especially once we have proper documentation in place. Alternatively, I guess I could maybe address the point elsewhere and refer to it in the cover letter? Or maybe just put it at the end of the cover letter?

[1] https://www.mail-archive.com/[email protected]/msg05059.html

#57 lore raw
Quoted 124 lines · Brendan Higgins
Quoted 5 lines · shuah
Quoted 3 lines · Theodore Ts'o
Quoted 2 lines · shuah
Quoted 2 lines
Quoted 2 lines

### But wait! Doesn't kselftest support in kernel testing?!

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 1 line
Quoted 1 line

....

I think I commented on this before. I agree with the statement that there is no overlap between Kselftest and KUnit. I would like see this removed. Kselftest module support supports use-cases KUnit won't be able to. I can build an kernel with Kselftest test modules and use it in the filed to load and run tests if I need to debug a problem and get data from a system. I can't do that with KUnit.

Sure, I think this point has been brought up a number of times before. Maybe I didn't write this section well because, like Frank said, it comes across as being critical of the Kselftest module support; that wasn't my intention. I was speaking from the perspective that Kselftest module support is just a feature of Kselftest, and not a full framework like KUnit is (obviously Kselftest itself *is* a framework, but a very small part of it is not).

It was obvious to me what Kselftest module support was intended for, and it is not intended to cover the use case that KUnit is targeting.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

In my mind, I am not viewing this as which is better. Kselftest and KUnit both have their place in the kernel development process. It isn't productive and/or necessary to comparing Kselftest and KUnit without a good understanding of the problem spaces for each of these.

Again, I didn't mean to draw a comparison of which is better than the other. I was just trying to point out that Kselftest module support doesn't make sense as a stand alone unit testing framework, or really a framework of any kind, despite how it might actually be used.

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

I would strongly recommend not making reference to Kselftest and talk about what KUnit offers.

I can see your point. It seems that both you and Frank seem to think that I drew a comparison between Kselftest and KUnit, which was unintended. I probably should have spent more time editing this section, but I can see the point of drawing the comparison itself might invite this confusion.

Quoted 8 lines
Quoted 8 lines

Shuah,

Just to recall the history, this section of the FAQ was added to rebut the ***very*** strong statements that Frank made that there was overlap between Kselftest and Kunit, and that having too many ways for kernel developers to do the identical thing was harmful (he said it was too much of a burden on a kernel developer) --- and this was an argument for not including Kunit in the upstream kernel.

I don't think he was actually advocating that we don't include KUnit, maybe playing devil's advocate; nevertheless, at the end, Frank seemed to agree that there were valuable things that KUnit offered. I thought he just wanted to make the point that I hadn't made the distinction sufficiently clear in the cover letter, and other reviewers might get confused in the future as well.

Additionally, it does look like people were trying to use Kselftest module support to cover some things which really were trying to be unit tests. I know this isn't really intended - everything looks like a nail when you only have a hammer, which I think Frank was pointing out furthers the above confusion.

In anycase, it sounds like I have, if anything, only made the discussion even more confusing by adding this section; sorry about that.

Quoted 8 lines
Quoted 5 lines

If we're past that objection, then perhaps this section can be dropped, but there's a very good reason why it was there. I wouldn't Brendan to be accused of ignoring feedback from those who reviewed his
patches. :-)

Agreed. I understand that this FAQ probably was needed at one time and Brendan added it to address the concerns.

I don't want to speak for Frank, but I don't think it was an objection to KUnit itself, but rather an objection to not sufficiently addressing the point about how they differ.

Quoted 7 lines

I think at some point we do need to have a document that outlines when to KUnit and when to use Kselftest modules. I think one concern people have is that if KUnit is perceived as a replacement for Ksefltest module, Kselftest module will be ignored leaving users without the ability to build and run with Kselftest modules and load them on a need basis to gather data on a systems that aren't dedicated strictly for testing.

I absolutely agree! I posed a suggestion here[1], which after I just now searched for a link, I realize for some reason it didn't seem like it reached a number of the mailing lists that I sent it to, so I should probably resend it.

Anyway, a summary of what I suggested: We should start off by better organizing Documentation/dev-tools/ and create a landing page that groups the dev-tools by function according to what person is likely to use them and for what. Eventually and specifically for Kselftest and KUnit, I would like to have a testing guide for the kernel that explains what testing procedure should look like and what to use and when.

Quoted 5 lines

I am trying to move the conversation forward from KUnit vs. Kselftest modules discussion to which problem areas each one addresses keeping in mind that it is not about which is better. Kselftest and KUnit both have their place in the kernel development process. We just have to be clear on usage as we write tests for each.

I think that is the right long term approach. I think a good place to start, like I suggested above, is cleaning up Documentation/dev-tools/, but I think that belongs in a (probably several) follow-up patchset.

Frank, I believe your objection was mostly related to how KUnit is presented specifically in the cover letter, and doesn't necessarily deal with the intended use case. So I don't think that doing this, especially doing this later, really addresses your concern. I don't want to belabor the issue, but I would also rather not put words in your mouth, what are your thoughts on the above?

Quoted 7 lines

I think my main concern moving forward on this point is that I am not sure that I can address the debate that this section covers in a way that is both sufficiently concise for a cover letter, but also doesn't invite more potential confusion. My inclination at this point is to drop it since I think the set of reviewers for this patchset has at this point become fixed, and it seems that it will likely cause more confusion rather than reduce it; also, I don't really think this will

Since no one has objected to dropping the "### But wait! Doesn't kselftest support in kernel testing?!" section in the past almost two weeks, I am just going to continue on without it.

Cheers

Quoted 6 lines

be an issue for end users, especially once we have proper documentation in place. Alternatively, I guess I could maybe address the point elsewhere and refer to it in the cover letter? Or maybe just put it at the end of the cover letter?

[1] https://www.mail-archive.com/[email protected]/msg05059.html

#58 lore raw
In reply to Frank Rowand
Quoted 4 lines · Frank Rowand

Hi Brendan,

I am only responding to this because you asked me to in the v4 thread.

Yes, I did! Thank you, I appreciate it!

Quoted 2 lines

Thank you for evaluating my comments in the v4 thread and asking me to comment on v5

Of course, I feel as though I ought to address any and all valid comments.

Quoted 87 lines · Brendan Higgins
Quoted 45 lines

## TL;DR

A not so quick follow-up to Stephen's suggestions on PATCH v4. Nothing that really changes any functionality or usage with the minor exception of a couple public functions that Stephen asked me to rename. Nevertheless, a good deal of clean up and fixes. See changes below.

As for our current status, right now we got Reviewed-bys on all patches except:

- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list

However, it would probably be good to get reviews/acks from the subsystem maintainers on:

- [PATCH v5 06/18] kbuild: enable building KUnit
- [PATCH v5 08/18] objtool: add kunit_try_catch_throw to the noreturn list
- [PATCH v5 15/18] Documentation: kunit: add documentation for KUnit
- [PATCH v5 17/18] kernel/sysctl-test: Add null pointer test for sysctl.c:proc_dointvec()
- [PATCH v5 18/18] MAINTAINERS: add proc sysctl KUnit test to PROC SYSCTL section

Other than that, I think we should be good to go.

One last thing, I updated the background to include my thoughts on KUnit vs. in kernel testing with kselftest in the background sections as suggested by Frank in the discussion on PATCH v2.

## Background

This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.

Unlike Autotest and kselftest, KUnit is a true unit testing framework; it does not require installing the kernel on a test machine or in a VM (however, KUnit still allows you to run tests on test machines or in VMs if you want[1]) and does not require tests to be written in userspace running on a host kernel. Additionally, KUnit is fast: From invocation to completion KUnit can run several dozen tests in under a second. Currently, the entire KUnit test suite for KUnit runs in under a second from the initial invocation (build time excluded).

Quoted 5 lines

KUnit is heavily inspired by JUnit, Python's unittest.mock, and Googletest/Googlemock for C++. KUnit provides facilities for defining unit test cases, grouping related test cases into test suites, providing common infrastructure for running tests, mocking, spying, and much more.

I looked only at this section, as was specifically requested:

Quoted 15 lines

### But wait! Doesn't kselftest support in kernel testing?!

In a previous version of this patchset Frank pointed out that kselftest already supports writing a test that resides in the kernel using the test module feature[2]. LWN did a really great summary on this discussion here[3].

Kselftest has a feature that allows a test module to be loaded into a kernel using the kselftest framework; this does allow someone to write tests against kernel code not directly exposed to userland; however, it does not provide much of a framework around how to structure the tests. The kselftest test module feature just provides a header which has a standardized way of reporting test failures,

Quoted 3 lines

and then provides
infrastructure to load and run the tests using the kselftest test harness.

The in-kernel tests can also be invoked at boot time if they are configured (Kconfig) as in-kernel instead of as modules. I did not check how many of the tests have tri-state configuration to allow this, but the few that I looked at did.

Quoted 8 lines

The kselftest test module does not seem to be opinionated at all in regards to how tests are structured, how they check for failures, how tests are organized. Even in the method it provides for reporting failures is pretty simple; it doesn't have any more advanced failure reporting or logging features. Given what's there, I think it is fair to say that it is not actually a framework, but a feature that makes it possible for someone to do some checks in kernel space.

Quoted 3 lines

I would call that description a little dismissive. The set of in-kernel tests that I looked like followed a common pattern and reported results in a uniform manner.

I didn't mean to sound dismissive. I was only referring to what was present in the actual header itself. There really isn't much there; it provides a function which takes an expression, evaluates it, increments a counter of all tests, and if false, prints out a warning; also, it provides a module init which runs the user defined test function called selftest(), and then prints the number of tests that passed and the number of tests that failed; that's it. I was just trying to make the point that it is pretty bare bones, and isn't really much of a framework.

Quoted 11 lines
Quoted 8 lines

Furthermore, kselftest test module has very few users. I checked for all the tests that use it using the following grep command:

grep -Hrn -e 'kselftest_module\.h'

and only got three results: lib/test_strscpy.c, lib/test_printf.c, and lib/test_bitmap.c.

You missed many tests. I listed much more than that in the v4 thread, and someone else also listed more in the v4 thread.

Oh, sorry, I forgot that more were listed in the thread.

Quoted 10 lines
Quoted 8 lines

So despite kselftest test module's existence, there really is no feature overlap between kselftest and KUnit, save one: that you can use either to write an in-kernel test, but this is a very small feature in comparison to everything that KUnit allows you to do. KUnit is a full x-unit style unit testing framework, whereas kselftest looks a lot more like an end-to-end/functional testing framework, with a feature that makes it possible to write in-kernel tests.

The description does not give enough credit to what is in kselftest.

You are right about me missing a number of the tests, but there really is not much infrastructure in kselftest for this at all. It really doesn't impose any structure of any kind other than that there must be exactly one static function named selftest() that takes no arguments; and then you use KSTM_CHECK_ZERO() to do some checks; that's it. It doesn't have anything else in the actual kselftest module stuff.

Quoted 6 lines

It does not matter whether KUnit provides additional things, relative to kselftest. The point I was making is that there appears to be _some_ overlap between kselftest and KUnit, and if there is overlap then it is worth considering whether the overlap can be unified instead of duplicated.

I think I understand what you are saying, but the point I was trying to make here is that it is so simplistic, it doesn't really conceptually overlap since it is so limited in what structure and features it provides. It's kind of like what Ted said previously about how you have C so you can technically do whatever you want, but there is nothing inherent to the kselftest test module that does any of those things (other than what I mentioned above).

Quoted 3 lines

I don't have a dog in this fight and the discussion in the v4 thread went way off track. Thus I am not going to get sucked back into a pointless debate in this thread.

Sure, I don't want to debate the point further either (I had a hard time understanding what the point was at the end myself).

Nevertheless, I do want to make sure that I addressed this because I think you did indeed have a point that was worth addressing, and I don't want to waste anyone's time in the future by not addressing it.

Nevertheless, like I said, I don't want to get too detailed on the topic otherwise like Shuah suggests later, it might end up just leading people to draw a comparison that doesn't need to be made, but I also don't want to misrepresent anything. In anycase, I will follow up on this point directly with Shuah.

Quoted 1 line

Thanks for adding this section to address the issue.

No need to thank me; that is what I felt is the correct thing to do. I didn't address the point before and it caused you and other to spend a lot of time debating the point.

Also, it looks like Shuah is asking me to drop the section. I will discuss this point further there.

Thanks!

Quoted 66 lines

-Frank

Quoted 62 lines

### What's so special about unit testing?

A unit test is supposed to test a single unit of code in isolation, hence the name. There should be no dependencies outside the control of the test; this means no external dependencies, which makes tests orders of magnitudes faster. Likewise, since there are no external dependencies, there are no hoops to jump through to run the tests. Additionally, this makes unit tests deterministic: a failing unit test always indicates a problem. Finally, because unit tests necessarily have finer granularity, they are able to test all code paths easily solving the classic problem of difficulty in exercising error handling code.

### Is KUnit trying to replace other testing frameworks for the kernel?

No. Most existing tests for the Linux kernel are end-to-end tests, which have their place. A well tested system has lots of unit tests, a reasonable number of integration tests, and some end-to-end tests. KUnit is just trying to address the unit test space which is currently not being addressed.

### More information on KUnit

There is a bunch of documentation near the end of this patch set that describes how to use KUnit and best practices for writing unit tests. For convenience I am hosting the compiled docs here[4].

Additionally for convenience, I have applied these patches to a branch[5]. The repo may be cloned with:
git clone https://kunit.googlesource.com/linux
This patchset is on the kunit/rfc/v5.2-rc4/v5 branch.

## Changes Since Last Version

Aside from a couple public function renames, there isn't really anything in here that changes any functionality.

- Went through and fixed a couple of anti-patterns suggested by Stephen Boyd. Things like:
- Dropping an else clause at the end of a function.
- Dropping the comma on the closing sentinel, {}, of a list.
- Inlines a bunch of functions in the test case running logic in patch 01/18 to make it more readable as suggested by Stephen Boyd
- Found and fixed bug in resource deallocation logic in patch 02/18. Bug was discovered as a result of making a change suggested by Stephen Boyd. This does not substantially change how any of the code works conceptually.
- Renamed new_string_stream() to alloc_string_stream() as suggested by Stephen Boyd.
- Made string-stream a KUnit managed object - based on a suggestion made by Stephen Boyd.
- Renamed kunit_new_stream() to alloc_kunit_stream() as suggested by Stephen Boyd.
- Removed the ability to set log level after allocating a kunit_stream, as suggested by Stephen Boyd.

[1] https://google.github.io/kunit-docs/third_party/kernel/docs/usage.html#kunit-on-non-uml-architectures
[2] https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html#test-module
[3] https://lwn.net/Articles/790235/
[4] https://google.github.io/kunit-docs/third_party/kernel/docs/
[5] https://kunit.googlesource.com/linux/+/kunit/rfc/v5.2-rc4/v5

#59 lore raw
In reply to Frank Rowand
Quoted 7 lines · Frank Rowand

It does not matter whether KUnit provides additional things, relative to kselftest. The point I was making is that there appears to be _some_ overlap between kselftest and KUnit, and if there is overlap then it is worth considering whether the overlap can be unified instead of duplicated.

From my experience as an author of several kselftests drivers, one

faily complex, and after reviewing the sysctl kunit test module, I disagree with this.

Even if there were an overlap, I'd say let the best test harness win. Just as we have different LSMs that do something similar.

But this is not about that though. Although both are testing code, they do so in *very* different ways.

The design philosophy and architecture are fundamentally different. The *only* thing I can think of where there is overlap is that both can test similar code paths. Beyond that, the layout of how one itemizes tests could be borrowed, but that would be up to each kselftest author to decide, in fact some ksefltests do exist which follow similar pattern of itemizing test cases and running them. Kunit just provides a proper framework to do this easily but also with a focus on UML. This last aspect makes kselftests fundamentally orthogonal from an architecture / design perspective.

After careful review, I cannot personally identify what could be shared at this point. Can you? If you did identify one part, how do you recommend to share it?

Luis