kunit: Introducing KUnit, the Linux kernel unit testing framework
Subsystems (8)
cover kunit: Introducing KUnit, the Linux kernel unit testing framework
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 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.
## 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:
https://google.github.io/kunit-docs/third_party/kernel/docs/
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 1/31 kunit: test: added string_stream a std::stream like string builder
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.
This provides a library for constructing the string as you go similar to C++'s std::string.
--- include/kunit/string-stream.h | 44 ++++++++++ kunit/Kconfig | 16 ++++ kunit/Makefile | 1 + kunit/string-stream.c | 149 ++++++++++++++++++++++++++++++++++ 4 files changed, 210 insertions(+) create mode 100644 include/kunit/string-stream.h create mode 100644 kunit/Kconfig create mode 100644 kunit/Makefile create mode 100644 kunit/string-stream.c
include/kunit/string-stream.h new file +44 -0
@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* C++ stream style string builder used in KUnit for building messages. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#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 kref refcount; +int (*add)(struct string_stream *this,const char *fmt, ...); +int (*vadd)(struct string_stream *this,const char *fmt,va_list args); +char *(*get_string)(struct string_stream *this); +void (*clear)(struct string_stream *this); +bool (*is_empty)(struct string_stream *this); +}; + +struct string_stream *new_string_stream (void ); + +void destroy_string_stream (struct string_stream *stream); + +void string_stream_get (struct string_stream *stream); + +int string_stream_put (struct string_stream *stream); + +#endif /* _KUNIT_STRING_STREAM_H */
kunit/Kconfig new file +16 -0
@@ -0,0 +1,16 @@ +# +# 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. For more information, please see + Documentation/kunit/ + +endmenu
kunit/Makefile new file +1 -0
@@ -0,0 +1 @@ +obj-$(CONFIG_KUNIT) += string-stream.o
kunit/string-stream.c new file +149 -0
149 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 2/31 kunit: test: adds KUnit test runner core
In reply to Brendan HigginsAdds the KUnit core, which allows test cases to be defined and associated with common initialization and cleanup logic.
--- include/kunit/test.h | 165 ++++++++++++++++++++++++++++++++++++++++++ kunit/Makefile | 2 +- kunit/test.c | 168 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 334 insertions(+), 1 deletion(-) create mode 100644 include/kunit/test.h create mode 100644 kunit/test.c
include/kunit/test.h new file +165 -0
@@ -0,0 +1,165 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Base unit test (KUnit) API. + * + * Copyright (C) 2018, Google LLC. + * Author: Brendan Higgins <brendanhiggins at google.com> + */ + +#ifndef _KUNIT_TEST_H +#define _KUNIT_TEST_H + +#include <linux/types.h> +#include <linux/slab.h> + +struct test; + +/** + * struct test_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 test *)`` + * that makes expectations (see TEST_EXPECT_TRUE()) about code under test. Each + * test case is associated with a &struct test_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 TEST_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 test *test) + * { + * TEST_EXPECT_EQ(test, 1, add(1, 0)); + * TEST_EXPECT_EQ(test, 2, add(1, 1)); + * TEST_EXPECT_EQ(test, 0, add(-1, 1)); + * TEST_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); + * TEST_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); + * } + * + * static struct test_case example_test_cases[] = { + * TEST_CASE(add_test_basic), + * {}, + * }; + * + */ +struct test_case { + void (*run_case)(struct test *test); + const char name[256]; + + /* private: internal use only. */ + bool success; +}; + +/** + * TEST_CASE - A helper for creating a &struct test_case + * @test_name: a reference to a test case function. + * + * Takes a symbol for a function representing a test case and creates a &struct + * test_case object from it. See the documentation for &struct test_case for an + * example on how to use it. + */ +#define TEST_CASE(test_name) { .run_case = test_name, .name = #test_name } + +/** + * struct test_module - describes a related collection of &struct test_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 test_module is a collection of related &struct test_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 test_case must be associated with a test_module for KUnit to + * run it. + */ +struct test_module { + const char name[256]; + int (*init)(struct test *test); + void (*exit)(struct test *test); + struct test_case *test_cases; +}; + +/** + * struct test - 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 test_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 test { + 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 (*vprintk)(const struct test *test, + const char *level, + struct va_format *vaf); +}; + +int test_init_test(struct test *test, const char *name); + +int test_run_tests(struct test_module *module); + +/** + * module_test() - used to register a &struct test_module with KUnit. + * @module: a statically allocated &struct test_module. + * + * Registers @module with the test framework. See &struct test_module for more + * information. + */ +#define module_test(module) \ + static int module_test_init##module(void) \ + { \ + return test_run_tests(&module); \ + } \ + late_initcall(module_test_init##module) + +void __printf(3, 4) test_printk(const char *level, + const struct test *test, + const char *fmt, ...); + +/** + * test_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 test_info(test, fmt, ...) \ + test_printk(KERN_INFO, test, fmt, ##__VA_ARGS__) + +/** + * test_warn() - Prints a WARN level message associated with the current test. + * @test: The test context object. + * @fmt: A printk() style format string. + * + * See test_info(). + */ +#define test_warn(test, fmt, ...) \ + test_printk(KERN_WARNING, test, fmt, ##__VA_ARGS__) + +/** + * test_err() - Prints an ERROR level message associated with the current test. + * @test: The test context object. + * @fmt: A printk() style format string. + * + * See test_info(). + */ +#define test_err(test, fmt, ...) \ + test_printk(KERN_ERR, test, fmt, ##__VA_ARGS__) + +#endif /* _KUNIT_TEST_H */
kunit/Makefile +1 -1
@@ -1 +1 @@ -obj-$(CONFIG_KUNIT) += string-stream.o +obj-$(CONFIG_KUNIT) += test.o string-stream.o
kunit/test.c new file +168 -0
168 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 3/31 kunit: test: added test resource management API
In reply to Brendan HigginsThis creates a common API for test managed resources like memory and test objects.
--- include/kunit/test.h | 109 +++++++++++++++++++++++++++++++++++++++++++ kunit/test.c | 95 +++++++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+)
include/kunit/test.h +109 -0
@@ -12,6 +12,69 @@#include <linux/types.h> #include <linux/slab.h> +struct test_resource ; + +typedef int (*test_resource_init_t )(struct test_resource *,void *); +typedef void (*test_resource_free_t )(struct test_resource *); + +/** +* struct test_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 +* test_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 test_kmalloc_params { +* size_t size; +* gfp_t gfp; +* }; +* +* static int test_kmalloc_init(struct test_resource *res, void *context) +* { +* struct test_kmalloc_params *params = context; +* res->allocation = kmalloc(params->size, params->gfp); +* +* if (!res->allocation) +* return -ENOMEM; +* +* return 0; +* } +* +* static void test_kmalloc_free(struct test_resource *res) +* { +* kfree(res->allocation); +* } +* +* void *test_kmalloc(struct test *test, size_t size, gfp_t gfp) +* { +* struct test_kmalloc_params params; +* struct test_resource *res; +* +* params.size = size; +* params.gfp = gfp; +* +* res = test_alloc_resource(test, test_kmalloc_init, +* test_kmalloc_free, ¶ms); +* if (res) +* return res->allocation; +* else +* return NULL; +* } +*/ +struct test_resource { +void *allocation; +test_resource_free_t free; + +/* private: internal use only. */ +struct list_head node; +}; +struct test ;/**
@@ -104,6 +167,7 @@ struct test {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 (*vprintk)(const struct test *test,const char *level,struct va_format *vaf);
@@ -127,6 +191,51 @@ int test_run_tests(struct test_module *module); } \ late_initcall(module_test_init##module) +/** +* test_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. +* +* Allocates a *test managed resource*, a resource which will automatically be +* cleaned up at the end of a test case. See &struct test_resource for an +* example. +*/ +struct test_resource *test_alloc_resource (struct test *test, +test_resource_init_t init, +test_resource_free_t free, +void *context); + +void test_free_resource (struct test *test,struct test_resource *res); + +/** +* test_kmalloc() - Just 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 +* test_resource for more information. +*/ +void *test_kmalloc (struct test *test,size_t size,gfp_t gfp); + +/** +* test_kzalloc() - Just like test_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 test_kmalloc() for more information. +*/ +static inline void *test_kzalloc (struct test *test,size_t size,gfp_t gfp) +{ +return test_kmalloc (test, size, gfp | __GFP_ZERO); +} + +void test_cleanup (struct test *test); + void __printf(3, 4) test_printk(const char *level, const struct test *test, const char *fmt, ...);
kunit/test.c +95 -0
119 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 4/31 kunit: test: added test_stream a std::stream like logger
In reply to Brendan HigginsAdds a C++ style log library for for logging test results.
--- include/kunit/test-stream.h | 49 ++++++++++++ include/kunit/test.h | 2 + kunit/Makefile | 2 +- kunit/test-stream.c | 153 ++++++++++++++++++++++++++++++++++++ kunit/test.c | 8 ++ 5 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 include/kunit/test-stream.h create mode 100644 kunit/test-stream.c
include/kunit/test-stream.h new file +49 -0
@@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* C++ stream style string formatter and printer used in KUnit for outputting +* KUnit messages. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#ifndef _KUNIT_TEST_STREAM_H +#define _KUNIT_TEST_STREAM_H + +#include <linux/types.h> +#include <kunit/string-stream.h> + +struct test ; + +/** +* struct test_stream - a std::stream style string builder. +* @set_level: sets the level that this string should be printed at. +* @add: adds the formatted input to the internal buffer. +* @commit: prints out the internal buffer to the user. +* @clear: clears the internal buffer. +* +* A std::stream style string builder. Allows messages to be built up and +* printed all at once. +*/ +struct test_stream { +void (*set_level)(struct test_stream *this,const char *level); +void (*add)(struct test_stream *this,const char *fmt, ...); +void (*append)(struct test_stream *this,struct test_stream *other); +void (*commit)(struct test_stream *this); +void (*clear)(struct test_stream *this); +/* private: internal use only. */ +struct test *test; +spinlock_t lock;/* Guards level. */ +const char *level; +struct string_stream *internal_stream; +}; + +/** +* test_new_stream() - constructs a new &struct test_stream. +* @test: The test context object. +* +* Constructs a new test managed &struct test_stream. +*/ +struct test_stream *test_new_stream (struct test *test); + +#endif /* _KUNIT_TEST_STREAM_H */
include/kunit/test.h +2 -0
@@ -11,6 +11,7 @@#include <linux/types.h> #include <linux/slab.h> +#include <kunit/test-stream.h> struct test_resource ;
@@ -171,6 +172,7 @@ struct test {void (*vprintk)(const struct test *test,const char *level,struct va_format *vaf); +void (*fail)(struct test *test,struct test_stream *stream); };int test_init_test (struct test *test,const char *name);
kunit/Makefile +1 -1
@@ -1 +1 @@ -obj-$(CONFIG_KUNIT) += test.o string-stream.o +obj-$(CONFIG_KUNIT) += test.o string-stream.o test-stream.o
kunit/test-stream.c new file +153 -0
153 lines not on this page · raw message
kunit/test.c +8 -0
@@ -63,12 +63,20 @@ static void test_vprintk(const struct test *test, "kunit %s: %pV", test->name, vaf); } +static void test_fail (struct test *test,struct test_stream *stream) +{ +test_set_success (test, false); + stream->set_level (stream,KERN_ERR ); + stream->commit (stream); +} +int test_init_test (struct test *test,const char *name) {spin_lock_init (&test->lock);INIT_LIST_HEAD (&test->resources); test->name = name; test->vprintk = test_vprintk; + test->fail = test_fail;return 0 ; }
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 5/31 kunit: test: added the concept of expectations
In reply to Brendan HigginsAdded support for expectations, which allow properties to be specified and then verified in tests.
--- include/kunit/test.h | 259 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+)
include/kunit/test.h +259 -0
@@ -273,4 +273,263 @@ void __printf(3, 4) test_printk(const char *level,#define test_err (test, fmt, ...) \ test_printk(KERN_ERR, test, fmt, ##__VA_ARGS__) +static inline struct test_stream *test_expect_start (struct test *test, +const char *file, +const char *line) +{ +struct test_stream *stream =test_new_stream (test); + + stream->add (stream,"EXPECTATION FAILED at %s:%s\n\t" , file, line); + +return stream; +} + +static inline void test_expect_end (struct test *test, +bool success, +struct test_stream *stream) +{ +if (!success) + test->fail (test, stream); +else + stream->clear (stream); +} + +#define TEST_EXPECT_START (test) \ + test_expect_start(test, __FILE__, __stringify(__LINE__)) + +#define TEST_EXPECT_END (test, success, stream) \ + test_expect_end(test, success, stream) + +#define TEST_EXPECT (test, success, message) do { \ + struct test_stream *__stream = TEST_EXPECT_START(test); \ + \ + __stream->add(__stream, message); \ + TEST_EXPECT_END(test, success, __stream); \ +} while (0) + +/** +* TEST_SUCCEED() - A no-op expectation. Only exists for code clarity. +* @test: The test context object. +* +* The opposite of TEST_FAIL(), it is an expectation that cannot fail. In other +* words, it does nothing and only exists for code clarity. See +* TEST_EXPECT_TRUE() for more information. +*/ +#define TEST_SUCCEED (test) do {} while (0) + +/** +* TEST_FAIL() - Always causes a test to fail when evaluated. +* @test: The test context object. +* @message: an informational message to be printed when the assertion is made. +* +* The opposite of TEST_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 TEST_EXPECT_TRUE() +* for more information. +*/ +#define TEST_FAIL (test, message) TEST_EXPECT(test, false, message) + +/** +* TEST_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 `TEST_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 TEST_EXPECT_TRUE (test, condition) \ + TEST_EXPECT(test, (condition), \ + "Expected " #condition " is true, but is false.") + +/** +* TEST_EXPECT_FALSE() - Causes 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 +* TEST_EXPECT_TRUE() for more information. +*/ +#define TEST_EXPECT_FALSE (test, condition) \ + TEST_EXPECT(test, !(condition), \ + "Expected " #condition " is false, but is true.") + +static inline void test_expect_binary (struct test *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) +{ +struct test_stream *stream =test_expect_start (test, file, line); + + stream->add (stream, +"Expected %s %s %s, but\n" , + left_name, compare_name, right_name); + stream->add (stream,"\t\t%s == %lld\n" , left_name, left); + stream->add (stream,"\t\t%s == %lld" , right_name, right); + +test_expect_end (test, compare_result, stream); +} + +/* +* 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 TEST_EXPECT_BINARY (test, left, condition, right) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + test_expect_binary(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__)); \ +} while (0) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, (@left) == (@right)). See TEST_EXPECT_TRUE() for more +* information. +*/ +#define TEST_EXPECT_EQ (test, left, right) \ + TEST_EXPECT_BINARY(test, left, ==, right) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, (@left) != (@right)). See TEST_EXPECT_TRUE() for more +* information. +*/ +#define TEST_EXPECT_NE (test, left, right) \ + TEST_EXPECT_BINARY(test, left, !=, right) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, (@left) < (@right)). See TEST_EXPECT_TRUE() for more +* information. +*/ +#define TEST_EXPECT_LT (test, left, right) \ + TEST_EXPECT_BINARY(test, left, <, right) + +/** +* TEST_EXPECT_LE() - An expectation 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 TEST_EXPECT_TRUE(@test, (@left) <= (@right)). See TEST_EXPECT_TRUE() for +* more information. +*/ +#define TEST_EXPECT_LE (test, left, right) \ + TEST_EXPECT_BINARY(test, left, <=, right) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, (@left) > (@right)). See TEST_EXPECT_TRUE() for more +* information. +*/ +#define TEST_EXPECT_GT (test, left, right) \ + TEST_EXPECT_BINARY(test, left, >, right) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, (@left) >= (@right)). See TEST_EXPECT_TRUE() for more +* information. +*/ +#define TEST_EXPECT_GE (test, left, right) \ + TEST_EXPECT_BINARY(test, left, >=, right) + +/** +* TEST_EXPECT_STREQ() - An expectation 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 +* TEST_EXPECT_TRUE(@test, !strcmp((@left), (@right))). See TEST_EXPECT_TRUE() +* for more information. +*/ +#define TEST_EXPECT_STREQ (test, left, right) do { \ + struct test_stream *__stream = TEST_EXPECT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __stream->add(__stream, "Expected " #left " == " #right ", but\n"); \ + __stream->add(__stream, "\t\t%s == %s\n", #left, __left); \ + __stream->add(__stream, "\t\t%s == %s\n", #right, __right); \ + \ + TEST_EXPECT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +/** +* TEST_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 +* TEST_EXPECT_TRUE(@test, !IS_ERR_OR_NULL(@ptr)). See TEST_EXPECT_TRUE() for +* more information. +*/ +#define TEST_EXPECT_NOT_ERR_OR_NULL (test, ptr) do { \ + struct test_stream *__stream = TEST_EXPECT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) \ + __stream->add(__stream, \ + "Expected " #ptr " is not null, but is."); \ + if (IS_ERR(__ptr)) \ + __stream->add(__stream, \ + "Expected " #ptr " is not error, but is: %ld", \ + PTR_ERR(__ptr)); \ + \ + TEST_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) +#endif /* _KUNIT_TEST_H */
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 6/31 arch: um: enabled running kunit from User Mode Linux
In reply to Brendan HigginsMakes minimum number of changes outside of the KUnit directories for KUnit to build and run using UML.
--- Makefile | 2 +- arch/um/Kconfig.rest | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-)
Makefile +1 -1
@@ -944,7 +944,7 @@ endif 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) \
arch/um/Kconfig.rest +3 -0
@@ -1,4 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 + +source "kunit/Kconfig" + source "init/Kconfig" source "kernel/Kconfig.freezer"
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 7/31 kunit: test: added initial tests
In reply to Brendan HigginsAdded a test for string stream along with a more simple example.
--- kunit/Kconfig | 12 ++++++ kunit/Makefile | 2 + kunit/example-test.c | 88 ++++++++++++++++++++++++++++++++++++++ kunit/string-stream-test.c | 61 ++++++++++++++++++++++++++ 4 files changed, 163 insertions(+) create mode 100644 kunit/example-test.c create mode 100644 kunit/string-stream-test.c
kunit/Kconfig +12 -0
@@ -13,4 +13,16 @@ config KUNIT special hardware. For more information, please see Documentation/kunit/ +config KUNIT_TEST + bool "KUnit test for KUnit" + depends on KUNIT + help + Enables KUnit test to test KUnit. + +config KUNIT_EXAMPLE_TEST + bool "Example test for KUnit" + depends on KUNIT + help + Enables example KUnit test to demo features of KUnit. + endmenu
kunit/Makefile +2 -0
@@ -1 +1,3 @@ obj-$(CONFIG_KUNIT) += test.o string-stream.o test-stream.o +obj-$(CONFIG_KUNIT_TEST) += string-stream-test.o +obj-$(CONFIG_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 +61 -0
61 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 8/31 arch: um: added shim to trap to allow installing a fault catcher for tests
In reply to Brendan HigginsAdded context to current thread that allows a test to specify that it wants to skip the normal checks to run an installed fault catcher.
--- arch/um/include/asm/processor-generic.h | 4 +++- arch/um/kernel/trap.c | 15 +++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-)
arch/um/include/asm/processor-generic.h +3 -1
@@ -27,6 +27,7 @@ struct thread_struct {struct task_struct *prev_sched;struct arch_thread arch;jmp_buf switch_buf; +bool is_running_test; struct { int op; union {
@@ -51,7 +52,8 @@ struct thread_struct { .fault_addr = NULL, \ .prev_sched = NULL, \ .arch = INIT_ARCH_THREAD, \ - .request = { 0 } \ + .request = { 0 }, \ + .is_running_test = false, \ }static inline void release_thread (struct task_struct *task)
arch/um/kernel/trap.c +11 -4
@@ -201,6 +201,12 @@ void segv_handler(int sig, struct siginfo *unused_si, struct uml_pt_regs *regs)segv (*fi,UPT_IP (regs),UPT_IS_USER (regs), regs); } +static void segv_run_catcher (jmp_buf *catcher,void *fault_addr) +{ + current->thread.fault_addr = fault_addr; +UML_LONGJMP (catcher,1 ); +} +/* * We give a *copy* of the faultinfo in the regs to segv. * This must be done, since nesting SEGVs could overwrite
@@ -219,7 +225,10 @@ unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user,if (!is_user && regs) current->thread.segv_regs = container_of(regs, struct pt_regs, regs); -if (!is_user && (address >= start_vm) && (address < end_vm)) { + catcher = current->thread.fault_catcher; +if (catcher && current->thread.is_running_test) +segv_run_catcher (catcher, (void *) address); +else if (!is_user && (address >= start_vm) && (address < end_vm)) {flush_tlb_kernel_vm (); goto out; }
@@ -246,12 +255,10 @@ unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user, address =0 ; } - catcher = current->thread.fault_catcher;if (!err) goto out;else if (catcher !=NULL ) { - current->thread.fault_addr = (void *) address; -UML_LONGJMP (catcher,1 ); +segv_run_catcher (catcher, (void *) address); }else if (current->thread.fault_addr !=NULL )panic ("fault_addr set but no fault catcher" );
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 9/31 kunit: test: added the concept of assertions
In reply to Brendan HigginsAdded support for assertions which are like expectations except the test terminates if the assertion is not satisfied.
--- include/kunit/test.h | 272 ++++++++++++++++++++++++++++++++++++- kunit/Makefile | 2 +- kunit/string-stream-test.c | 12 +- kunit/test-test.c | 37 +++++ kunit/test.c | 131 ++++++++++++++++-- 5 files changed, 436 insertions(+), 18 deletions(-) create mode 100644 kunit/test-test.c
include/kunit/test.h +269 -3
@@ -84,9 +84,10 @@ struct test;* @name: the name of the test case. * * A test case is a function with the signature, ``void (*)(struct test *)`` -* that makes expectations (see TEST_EXPECT_TRUE()) about code under test. Each -* test case is associated with a &struct test_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 TEST_EXPECT_TRUE() and +* TEST_ASSERT_TRUE()) about code under test. Each test case is associated with +* a &struct test_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 TEST_CASE() * macro; additionally, every array of test cases should be terminated with an
@@ -168,11 +169,14 @@ struct test {const char *name;/* Read only after initialization! */ 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. */ +void (*set_death_test)(struct test *test,bool death_test);void (*vprintk)(const struct test *test,const char *level,struct va_format *vaf);void (*fail)(struct test *test,struct test_stream *stream); +void (*abort)(struct test *test); };int test_init_test (struct test *test,const char *name);
@@ -532,4 +536,266 @@ static inline void test_expect_binary(struct test *test,TEST_EXPECT_END (test, !IS_ERR_OR_NULL (__ptr), __stream); \ } while (0) +static inline struct test_stream *test_assert_start(struct test *test, +const char *file, +const char *line) +{ +struct test_stream *stream =test_new_stream (test); + + stream->add (stream,"ASSERTION FAILED at %s:%s\n\t" , file, line); + +return stream; +} + +static inline void test_assert_end (struct test *test, +bool success, +struct test_stream *stream) +{ +if (!success) { + test->fail (test, stream); + test->abort (test); + }else { + stream->clear (stream); + } +} + +#define TEST_ASSERT_START (test) \ + test_assert_start(test, __FILE__, __stringify(__LINE__)) + +#define TEST_ASSERT_END (test, success, stream) \ + test_assert_end(test, success, stream) + +#define TEST_ASSERT (test, success, message) do { \ + struct test_stream *__stream = TEST_ASSERT_START(test); \ + \ + __stream->add(__stream, message); \ + TEST_ASSERT_END(test, success, __stream); \ +} while (0) + +#define TEST_ASSERT_FAILURE (test, message) TEST_ASSERT(test, false, message) + +/** +* TEST_ASSERT_TRUE() - Causes an assertion failure when expression is not 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 `TEST_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 TEST_ASSERT_TRUE (test, condition) \ + TEST_ASSERT(test, (condition), \ + "Asserted " #condition " is true, but is false.") + +/** +* TEST_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 TEST_EXPECT_FALSE(), except it causes an assertion failure +* (see TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_FALSE (test, condition) \ + TEST_ASSERT(test, !(condition), \ + "Asserted " #condition " is false, but is true.") + +static inline void test_assert_binary (struct test *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) +{ +struct test_stream *stream =test_assert_start (test, file, line); + + stream->add (stream, +"Asserted %s %s %s, but\n" , + left_name, compare_name, right_name); + stream->add (stream,"\t\t%s == %lld\n" , left_name, left); + stream->add (stream,"\t\t%s == %lld" , right_name, right); + +test_assert_end (test, compare_result, stream); +} + +/* +* 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 TEST_ASSERT_BINARY (test, left, condition, right) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + test_assert_binary(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__)); \ +} while (0) + +/** +* TEST_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 TEST_EXPECT_EQ(), except it causes an assertion +* failure (see TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_EQ (test, left, right) \ + TEST_ASSERT_BINARY(test, left, ==, right) + +/** +* TEST_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 TEST_EXPECT_NE(), except it causes an assertion +* failure (see TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_NE (test, left, right) \ + TEST_ASSERT_BINARY(test, left, !=, right) + +/** +* TEST_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 TEST_EXPECT_LT(), except +* it causes an assertion failure (see TEST_ASSERT_TRUE()) when the assertion is +* not met. +*/ +#define TEST_ASSERT_LT (test, left, right) \ + TEST_ASSERT_BINARY(test, left, <, right) + +/** +* TEST_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 +* TEST_EXPECT_LE(), except it causes an assertion failure (see +* TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_LE (test, left, right) \ + TEST_ASSERT_BINARY(test, left, <=, right) + +/** +* TEST_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 TEST_EXPECT_GT(), except +* it causes an assertion failure (see TEST_ASSERT_TRUE()) when the assertion is +* not met. +*/ +#define TEST_ASSERT_GT (test, left, right) \ + TEST_ASSERT_BINARY(test, left, >, right) + +/** +* TEST_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 TEST_EXPECT_GE(), except +* it causes an assertion failure (see TEST_ASSERT_TRUE()) when the assertion is +* not met. +*/ +#define TEST_ASSERT_GE (test, left, right) \ + TEST_ASSERT_BINARY(test, left, >=, right) + +/** +* TEST_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 TEST_EXPECT_STREQ(), except it causes an +* assertion failure (see TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_STREQ (test, left, right) do { \ + struct test_stream *__stream = TEST_ASSERT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __stream->add(__stream, "Asserted " #left " == " #right ", but\n"); \ + __stream->add(__stream, "\t\t%s == %s\n", #left, __left); \ + __stream->add(__stream, "\t\t%s == %s\n", #right, __right); \ + \ + TEST_ASSERT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +/** +* TEST_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 +* TEST_EXPECT_NOT_ERR_OR_NULL(), except it causes an assertion failure (see +* TEST_ASSERT_TRUE()) when the assertion is not met. +*/ +#define TEST_ASSERT_NOT_ERR_OR_NULL (test, ptr) do { \ + struct test_stream *__stream = TEST_ASSERT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) \ + __stream->add(__stream, \ + "Asserted " #ptr " is not null, but is."); \ + if (IS_ERR(__ptr)) \ + __stream->add(__stream, \ + "Asserted " #ptr " is not error, but is: %ld", \ + PTR_ERR(__ptr)); \ + \ + TEST_ASSERT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) + +/** +* TEST_ASSERT_SIGSEGV() - An assertion that @expr will cause a segfault. +* @test: The test context object. +* @expr: an arbitrary block of code. +* +* Sets an assertion that @expr, when evaluated, will cause a segfault. +* Currently this assertion is only really useful for testing the KUnit +* framework, as a segmentation fault in normal kernel code is always incorrect. +* However, the plan is to replace this assertion with an arbitrary death +* assertion similar to +* https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests +* which will probably be massaged to make sense in the context of the kernel +* (maybe assert that a panic occurred, or that BUG() was called). +* +* NOTE: no code after this assertion will ever be executed. +*/ +#define TEST_ASSERT_SIGSEGV (test, expr) do { \ + test->set_death_test(test, true); \ + expr; \ + test->set_death_test(test, false); \ + TEST_ASSERT_FAILURE(test, \ + "Asserted that " #expr " would cause death, but did not.");\ +} while (0) +#endif /* _KUNIT_TEST_H */
kunit/Makefile +1 -1
@@ -1,3 +1,3 @@ obj-$(CONFIG_KUNIT) += test.o string-stream.o test-stream.o -obj-$(CONFIG_KUNIT_TEST) += string-stream-test.o +obj-$(CONFIG_KUNIT_TEST) += test-test.o string-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/string-stream-test.c +6 -6
@@ -19,7 +19,7 @@ static void string_stream_test_get_string(struct test *test) stream->add (stream," %s" ,"bar" ); output = stream->get_string (stream); -TEST_EXPECT_STREQ (test, output,"Foo bar" ); +TEST_ASSERT_STREQ (test, output,"Foo bar" );kfree (output);destroy_string_stream (stream); }
@@ -34,16 +34,16 @@ static void string_stream_test_add_and_clear(struct test *test) stream->add (stream,"A" ); output = stream->get_string (stream); -TEST_EXPECT_STREQ (test, output,"AAAAAAAAAA" ); -TEST_EXPECT_EQ (test, stream->length,10 ); -TEST_EXPECT_FALSE (test, stream->is_empty (stream)); +TEST_ASSERT_STREQ (test, output,"AAAAAAAAAA" ); +TEST_ASSERT_EQ (test, stream->length,10 ); +TEST_ASSERT_FALSE (test, stream->is_empty (stream));kfree (output); stream->clear (stream); output = stream->get_string (stream); -TEST_EXPECT_STREQ (test, output,"" ); -TEST_EXPECT_TRUE (test, stream->is_empty (stream)); +TEST_ASSERT_STREQ (test, output,"" ); +TEST_ASSERT_TRUE (test, stream->is_empty (stream));destroy_string_stream (stream); }
kunit/test-test.c new file +37 -0
@@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* KUnit test for core test infrastructure. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ +#include <kunit/test.h> + +static void test_test_catches_segfault (struct test *test) +{ +void (*invalid_func)(void ) = (void (*)(void ))SIZE_MAX ; + +TEST_ASSERT_SIGSEGV (test,invalid_func ()); +} + +static int test_test_init (struct test *test) +{ +return 0 ; +} + +static void test_test_exit (struct test *test) +{ +} + +static struct test_case test_test_cases[] = { +TEST_CASE (test_test_catches_segfault), + {}, +}; + +static struct test_module test_test_module = { + .name ="test-test" , + .init = test_test_init, + .exit = test_test_exit, + .test_cases = test_test_cases, +}; +module_test (test_test_module);
kunit/test.c +123 -8
165 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 10/31 kunit: test: added concept of initcalls
In reply to Brendan HigginsAdded a way to add plugins that require a test module to be loaded during initialization.
--- include/kunit/test.h | 19 +++++++++++++++++++ kunit/test.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+)
include/kunit/test.h +19 -0
@@ -152,6 +152,12 @@ struct test_module {struct test_case *test_cases; }; +struct test_initcall { +struct list_head node; +int (*init)(struct test_initcall *this,struct test *test); +void (*exit)(struct test_initcall *this); +}; +/** * struct test - represents a running instance of a test. * @priv: for user to store arbitrary data. Commonly used to pass data created
@@ -183,6 +189,19 @@ int test_init_test(struct test *test, const char *name);int test_run_tests (struct test_module *module); +void test_install_initcall (struct test_initcall *initcall); + +#define test_pure_initcall (fn) postcore_initcall(fn) + +#define test_register_initcall (initcall) \ + static int register_test_initcall_##initcall(void) \ + { \ + test_install_initcall(&initcall); \ + \ + return 0; \ + } \ + test_pure_initcall(register_test_initcall_##initcall) +/** * module_test() - used to register a &struct test_module with KUnit. * @module: a statically allocated &struct test_module.
kunit/test.c +29 -0
@@ -53,6 +53,19 @@ static void test_set_death_test(struct test *test, bool death_test)spin_unlock_irqrestore (&test->lock, flags); } +struct test_global_context { +struct list_head initcalls; +}; + +static struct test_global_context test_global_context = { + .initcalls =LIST_HEAD_INIT (test_global_context.initcalls), +}; + +void test_install_initcall (struct test_initcall *initcall) +{ +list_add_tail (&initcall->node, &test_global_context.initcalls); +} + static int test_vprintk_emit(const struct test *test, int level, const char *fmt,
@@ -130,8 +143,18 @@ static void test_run_case_internal(struct test *test,struct test_module *module, struct test_case *test_case) { + struct test_initcall *initcall;int ret; +list_for_each_entry (initcall, &test_global_context.initcalls, node) { + ret = initcall->init (initcall, test); +if (ret) { +test_err (test,"failed to initialize: %d" , ret); + test->success = false; +return ; + } + } +if (module->init) { ret = module->init (test);if (ret) {
@@ -146,6 +169,12 @@ static void test_run_case_internal(struct test *test,static void test_case_internal_cleanup (struct test *test) { +struct test_initcall *initcall; + +list_for_each_entry (initcall, &test_global_context.initcalls, node) { + initcall->exit (initcall); + } +test_cleanup (test); }
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 11/31 kunit: test: added concept of post conditions
In reply to Brendan HigginsAdds a way to specify that certain conditions must be met at the end of a test case.
--- include/kunit/test.h | 6 ++++++ kunit/test.c | 13 ++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-)
include/kunit/test.h +6 -0
@@ -158,6 +158,11 @@ struct test_initcall {void (*exit)(struct test_initcall *this); }; +struct test_post_condition { +struct list_head node; +void (*validate)(struct test_post_condition *condition); +}; +/** * struct test - represents a running instance of a test. * @priv: for user to store arbitrary data. Commonly used to pass data created
@@ -177,6 +182,7 @@ struct test {bool success;/* Protected by lock. */ bool death_test;/* Protected by lock. */ struct list_head resources;/* Protected by lock. */ +struct list_head post_conditions;void (*set_death_test)(struct test *test,bool death_test); void (*vprintk)(const struct test *test, const char *level,
kunit/test.c +12 -1
@@ -125,8 +125,9 @@ static void __noreturn test_abort(struct test *test)int test_init_test (struct test *test,const char *name) { -spin_lock_init (&test->lock);INIT_LIST_HEAD (&test->resources); +INIT_LIST_HEAD (&test->post_conditions); +spin_lock_init (&test->lock); test->name = name; test->set_death_test = test_set_death_test; test->vprintk = test_vprintk;
@@ -186,6 +187,16 @@ static void test_run_case_cleanup(struct test *test,struct test_module *module, struct test_case *test_case) { + struct test_post_condition *condition, *condition_safe; + +list_for_each_entry_safe (condition, + condition_safe, + &test->post_conditions, + node) { + condition->validate (condition); +list_del (&condition->node); + } +if (module->exit) module->exit (test);
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 12/31 checkpatch: added support for struct MOCK(foo) syntax
In reply to Brendan HigginsThis adds struct MOCK(foo) as a NonptrType so that it is recognized correctly in declarations.
--- scripts/checkpatch.pl | 4 ++++ 1 file changed, 4 insertions(+)
scripts/checkpatch.pl +4 -0
@@ -745,6 +745,10 @@ sub build_types { (?: (?:typeof|__typeof__)\s*\([^\)]*\)| (?:$typeTypedefs\b)| + # Matching a \b breaks struct MOCK(foo) syntax, + # so we need to have it not lumped in with the + # types in @typeList. + (?:struct\s+MOCK\($Ident\))| (?:${all}\b) ) (?:\s+$Modifier|\s+const)*
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 13/31 kunit: mock: added parameter list minipulation macros
In reply to Brendan HigginsAdds macros for parsing and manipulating parameter lists needed for generating mocks.
--- include/kunit/params.h | 305 ++++++++++++++++++++++++++++++++++++++++ kunit/Makefile | 2 +- kunit/mock-macro-test.c | 149 ++++++++++++++++++++ 3 files changed, 455 insertions(+), 1 deletion(-) create mode 100644 include/kunit/params.h create mode 100644 kunit/mock-macro-test.c
include/kunit/params.h new file +305 -0
@@ -0,0 +1,305 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Macros for parsing and manipulating parameter lists needed for generating +* mocks. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#ifndef _KUNIT_PARAMS_H +#define _KUNIT_PARAMS_H + +#define NUM_VA_ARGS_IMPL (__dummy, \ + __1, \ + __2, \ + __3, \ + __4, \ + __5, \ + __6, \ + __7, \ + __8, \ + __9, \ + __10, \ + __11, \ + __12, \ + __13, \ + __14, \ + __15, \ + __16, \ + __nargs, args...) __nargs + +#define NUM_VA_ARGS(args...) NUM_VA_ARGS_IMPL(__dummy, ##args, \ + 16, \ + 15, \ + 14, \ + 13, \ + 12, \ + 11, \ + 10, \ + 9, \ + 8, \ + 7, \ + 6, \ + 5, \ + 4, \ + 3, \ + 2, \ + 1, \ + 0) + +#define CONCAT_INTERNAL (left, right) left##right +#define CONCAT (left, right) CONCAT_INTERNAL(left, right) + +#define EMPTY () + +/* +* Takes the name of a function style macro such as FOO() and prevents it from +* being evaluated on the current pass. +* +* This is useful when you need to write a "recursive" macro since a macro name +* becomes painted after it is pasted. If a different macro is pasted, this +* different macro won't be pasted; if we then defer the evaluation of the this +* "indirection macro", we can prevent the original definition from getting +* painted. +* +* Example: +* #define EXAMPLE EXPAND(FOO()) // FOO() is evaluated on 1st pass. +* #define EXAMPLE EXPAND(DEFER(FOO)()) // FOO() is evaluated on the second +* // pass. +*/ +#define DEFER (macro_id) macro_id EMPTY() + +/* +* Takes the name of a function style macro such as FOO() and prevents it from +* being evaluated on the current or following pass. +* +* This is useful when you need to DEFER inside an operation which causes an +* extra pass, like IF. +* +* Example: +* #define EXAMPLE EXPAND(FOO()) // FOO() is evaluated on 1st pass. +* #define EXAMPLE EXPAND(DEFER(FOO)()) // FOO() is evaluated on the second +* // pass. +* #define EXAMPLE EXPAND(OBSTRUCT(FOO)()) // FOO() is evaluated on the third +* // pass. +*/ +#define OBSTRUCT (macro_id) macro_id DEFER(EMPTY)() + +#define EXPAND_1(args...) args +#define EXPAND_2(args...) EXPAND_1(EXPAND_1(args)) +#define EXPAND_4(args...) EXPAND_2(EXPAND_2(args)) +#define EXPAND_8(args...) EXPAND_4(EXPAND_4(args)) +#define EXPAND_16(args...) EXPAND_8(EXPAND_8(args)) + +/* +* Causes multiple evaluation passes of a macro. +* +* CPP is implemented as a push down automaton. It consumes a stream of tokens +* and as it comes across macros, it either evaluates them and pastes the +* result, or if the macro is a function macro, it pushes the macro to a stack, +* it evaluates the input to the function macro, pops the state from the stack +* and continues. +* +* This macro serves the function of making the cursor return to the beginging +* of a macro that requires mulitple passes to evaluate. It is most useful when +* used with DEFER(...) and OBSTRUCT(...). +*/ +#define EXPAND(args...) EXPAND_16(args) + +#define INC (id) INC_##id +#define INC_0 1 +#define INC_1 2 +#define INC_2 3 +#define INC_3 4 +#define INC_4 5 +#define INC_5 6 +#define INC_6 7 +#define INC_7 8 +#define INC_8 9 +#define INC_9 10 +#define INC_10 11 +#define INC_11 12 +#define INC_12 13 +#define INC_13 14 +#define INC_14 15 +#define INC_15 16 +#define INC_16 17 + +#define DEC (id) DEC_##id +#define DEC_1 0 +#define DEC_2 1 +#define DEC_3 2 +#define DEC_4 3 +#define DEC_5 4 +#define DEC_6 5 +#define DEC_7 6 +#define DEC_8 7 +#define DEC_9 8 +#define DEC_10 9 +#define DEC_11 10 +#define DEC_12 11 +#define DEC_13 12 +#define DEC_14 13 +#define DEC_15 14 +#define DEC_16 15 + +#define DROP_FIRST_ARG_INTERNAL(dropped, x, args...) x +#define DROP_FIRST_ARG(args...) DROP_FIRST_ARG_INTERNAL(args) + +#define EQUAL (left, right) EQUAL_##left##_##right +#define EQUAL_0_0 dropped, 1 +#define EQUAL_1_1 dropped, 1 +#define EQUAL_2_2 dropped, 1 +#define EQUAL_3_3 dropped, 1 +#define EQUAL_4_4 dropped, 1 +#define EQUAL_5_5 dropped, 1 +#define EQUAL_6_6 dropped, 1 +#define EQUAL_7_7 dropped, 1 +#define EQUAL_8_8 dropped, 1 +#define EQUAL_9_9 dropped, 1 +#define EQUAL_10_10 dropped, 1 +#define EQUAL_11_11 dropped, 1 +#define EQUAL_12_12 dropped, 1 +#define EQUAL_13_13 dropped, 1 +#define EQUAL_14_14 dropped, 1 +#define EQUAL_15_15 dropped, 1 +#define EQUAL_16_16 dropped, 1 + +#define IS_EQUAL (left, right) DROP_FIRST_ARG(EQUAL(left, right), 0) + +#define NOT_INTERNAL (condition) NOT_##condition +#define NOT (condition) NOT_INTERNAL(condition) +#define NOT_0 1 +#define NOT_1 0 + +#define IS_NOT_EQUAL (left, right) NOT(IS_EQUAL(left, right)) + +#define EMPTY_IMPL (tokens) CONCAT(EMPTY_, tokens) +#define IS_EMPTY (tokens) + +#define OR_INTERNAL (left, right) OR_##left##_##right +#define OR (left, right) OR_INTERNAL(left, right) +#define OR_0_0 0 +#define OR_0_1 1 +#define OR_1_0 1 +#define OR_1_1 1 + +#define IF (condition) CONCAT(IF_, condition) +#define IF_0 (body) +#define IF_1 (body) body + +#define COMMA () , + +#define APPLY_TOKENS_INTERNAL (tokens, yield_token, seen_token) \ + IF(yield_token)(IF(seen_token)(COMMA()) tokens) +#define APPLY_TOKENS (tokens, yield_token, seen_token) \ + APPLY_TOKENS_INTERNAL(tokens, yield_token, seen_token) + +/* +* Provides the indirection to keep the PARAM_LIST_RECURSE_INTERNAL from getting +* pasted, only useful if used with DEFER(...) or OBSTRUCT(...). +*/ +#define PARAM_LIST_RECURSE_INDIRECT () PARAM_LIST_RECURSE_INTERNAL + +/* +* Given a starting index, a number of args, a MACRO to apply, and a list of +* types (with at least one element) this will call MACRO with the first type in +* the list and index; it will then call itself again on all remaining types, if +* any, while incrementing index, and decrementing nargs. +* +* Assumes nargs is the number of types in the list. +*/ +#define PARAM_LIST_RECURSE_INTERNAL (index, \ + nargs, \ +MACRO , \ +FILTER , \ + context, \ + seen_token, \ + type, \ + args...) \ + APPLY_TOKENS(MACRO(context, type, index), \ + FILTER(context, type, index), \ + seen_token) \ + IF(IS_NOT_EQUAL(nargs, 1)) \ + (OBSTRUCT(PARAM_LIST_RECURSE_INDIRECT)() \ + (INC(index), DEC(nargs), \ + MACRO, FILTER, context, \ + OR(seen_token, FILTER(context, type, index)), \ + args)) + +#define PARAM_LIST_RECURSE(index, nargs, MACRO, FILTER, context, args...) \ + IF(IS_NOT_EQUAL(nargs, 0)) \ + (OBSTRUCT(PARAM_LIST_RECURSE_INTERNAL)(index, \ + nargs, \ + MACRO, \ + FILTER, \ + context, \ + 0, \ + args)) + +#define FILTER_NONE (context, type, index) 1 + +#define FILTER_INDEX_INTERNAL (index_to_drop, type, index) \ + IS_NOT_EQUAL(index, index_to_drop) +#define FILTER_INDEX (index_to_drop, type, index) \ + FILTER_INDEX_INTERNAL(index_to_drop, type, index) + +/* +* Applies a MACRO which takes a type and the index of the type and outputs a +* sequence of tokens to a list of types. +*/ +#define FOR_EACH_PARAM(MACRO, FILTER, context, args...) \ + EXPAND(PARAM_LIST_RECURSE(0,\ + NUM_VA_ARGS(args),\ + MACRO,\ + FILTER,\ + context,\ + args)) + +#define PRODUCE_TYPE_AND_ARG (context, type, index) type arg##index +#define PARAM_LIST_FROM_TYPES(args...) \ + FOR_EACH_PARAM(PRODUCE_TYPE_AND_ARG, \ + FILTER_NONE, \ + not_used, \ + args) + +#define PRODUCE_TYPE_NAME (context, type, index) #type +#define TYPE_NAMES_FROM_TYPES(handle_index, args...) \ + FOR_EACH_PARAM(PRODUCE_TYPE_NAME, \ + FILTER_INDEX, \ + handle_index, \ + args) + +#define PRODUCE_PTR_TO_ARG (context, type, index) &arg##index +#define PTR_TO_ARG_FROM_TYPES(handle_index, args...) \ + FOR_EACH_PARAM(PRODUCE_PTR_TO_ARG, \ + FILTER_INDEX, \ + handle_index, \ + args) + +#define PRODUCE_MATCHER_AND_ARG (ctrl_index, type, index) \ + IF(IS_EQUAL(index, ctrl_index))(struct mock *arg##ctrl_index) \ + IF(IS_NOT_EQUAL(index, ctrl_index))( \ + struct mock_param_matcher *arg##index) +#define MATCHER_PARAM_LIST_FROM_TYPES(ctrl_index, args...) \ + FOR_EACH_PARAM(PRODUCE_MATCHER_AND_ARG, \ + FILTER_NONE, \ + ctrl_index, \ + args) + +#define PRODUCE_ARG (context, type, index) arg##index +#define ARG_NAMES_FROM_TYPES(ctrl_index, args...) \ + FOR_EACH_PARAM(PRODUCE_ARG, \ + FILTER_INDEX, \ + ctrl_index, \ + args) + +#define PRODUCE_ARRAY_ACCESSOR (context, type, index) *((type *) params[index]) +#define ARRAY_ACCESSORS_FROM_TYPES(args...) \ + FOR_EACH_PARAM(PRODUCE_ARRAY_ACCESSOR, \ + FILTER_NONE, \ + not_used, \ + args) + +#endif /* _KUNIT_PARAMS_H */
kunit/Makefile +1 -1
@@ -1,3 +1,3 @@ obj-$(CONFIG_KUNIT) += test.o string-stream.o test-stream.o -obj-$(CONFIG_KUNIT_TEST) += test-test.o string-stream-test.o +obj-$(CONFIG_KUNIT_TEST) += test-test.o mock-macro-test.o string-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/mock-macro-test.c new file +149 -0
149 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 14/31 kunit: mock: added internal mock infrastructure
In reply to Brendan HigginsAdds the core internal mechanisms that mocks are implemented with; in particular, this adds the mechanisms by which expectation on mocks are validated and by which actions may be supplied and then executed when mocks are called.
--- include/kunit/mock.h | 125 +++++++++++++++ kunit/Makefile | 5 +- kunit/mock.c | 359 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 487 insertions(+), 2 deletions(-) create mode 100644 include/kunit/mock.h create mode 100644 kunit/mock.c
include/kunit/mock.h new file +125 -0
@@ -0,0 +1,125 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Mocking API for KUnit. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#ifndef _KUNIT_MOCK_H +#define _KUNIT_MOCK_H + +#include <linux/types.h> +#include <linux/tracepoint.h> /* For PARAMS(...) */ +#include <kunit/test.h> +#include <kunit/test-stream.h> +#include <kunit/params.h> + +/** +* struct mock_param_matcher - represents a matcher used in a *call expectation* +* @match: the function that performs the matching +* +* The matching function takes a couple of parameters: +* +* - ``this``: refers to the parent struct +* - ``stream``: a &test_stream to which a detailed message should be added as +* to why the parameter matches or not +* - ``param``: a pointer to the parameter to check for a match +* +* The matching function should return whether or not the passed parameter +* matches. +*/ +struct mock_param_matcher { +bool (*match)(struct mock_param_matcher *this, +struct test_stream *stream, +const void *param); +}; + +#define MOCK_MAX_PARAMS 255 + +struct mock_matcher { +struct mock_param_matcher *matchers[MOCK_MAX_PARAMS ]; +int num; +}; + +/** +* struct mock_action - Represents an action that a mock performs when +* expectation is matched +* @do_action: the action to perform +* +* The action function is given some parameters: +* +* - ``this``: refers to the parent struct +* - ``params``: an array of pointers to the params passed into the mocked +* method or function. **The class argument is excluded for a mocked class +* method.** +* - ``len``: size of ``params`` +* +* The action function returns a pointer to the value that the mocked method +* or function should be returning. +*/ +struct mock_action { +void *(*do_action)(struct mock_action *this, +const void **params, +int len); +}; + +/** +* struct mock_expectation - represents a *call expectation* on a function. +* @action: A &struct mock_action to perform when the function is called. +* @max_calls_expected: maximum number of times an expectation may be called. +* @min_calls_expected: minimum number of times an expectation may be called. +* @retire_on_saturation: no longer match once ``max_calls_expected`` is +* reached. +* +* Represents a *call expectation* on a function created with EXPECT_CALL(). +*/ +struct mock_expectation { +struct mock_action *action; +int max_calls_expected; +int min_calls_expected; +bool retire_on_saturation; +/* private: internal use only. */ +const char *expectation_name; +struct list_head node; +struct mock_matcher *matcher; +int times_called; +}; + +struct mock_method { +struct list_head node; +const char *method_name; +const void *method_ptr; +struct mock_action *default_action; +struct list_head expectations; +}; + +struct mock { +struct test_post_condition parent; +struct test *test; +struct list_head methods; +/* TODO(brendanhiggins at google.com): add locking to do_expect. */ +const void *(*do_expect)(struct mock *mock, +const char *method_name, +const void *method_ptr, +const char *const *param_types, +const void **params, +int len); +}; + +void mock_init_ctrl (struct test *test,struct mock *mock); + +void mock_validate_expectations (struct mock *mock); + +int mock_set_default_action (struct mock *mock, +const char *method_name, +const void *method_ptr, +struct mock_action *action); + +struct mock_expectation *mock_add_matcher (struct mock *mock, +const char *method_name, +const void *method_ptr, +struct mock_param_matcher *matchers[], +int len); + +#endif /* _KUNIT_MOCK_H */
kunit/Makefile +3 -2
@@ -1,3 +1,4 @@ -obj-$(CONFIG_KUNIT) += test.o string-stream.o test-stream.o -obj-$(CONFIG_KUNIT_TEST) += test-test.o mock-macro-test.o string-stream-test.o +obj-$(CONFIG_KUNIT) += test.o mock.o string-stream.o test-stream.o +obj-$(CONFIG_KUNIT_TEST) += \ + test-test.o mock-macro-test.o string-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/mock.c new file +359 -0
359 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 15/31 kunit: mock: added basic matchers and actions
In reply to Brendan HigginsAdded basic matchers and actions needed for any kind of mocking to be useful; these matchers and actions are how expectations for mocks are
described: what calls the mocks are expected to receive, and what the mock should do under those circumstances.
--- include/kunit/mock.h | 222 +++++++++++++++++++++++++++++++++++ kunit/Makefile | 3 +- kunit/common-mocks.c | 272 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 496 insertions(+), 1 deletion(-) create mode 100644 kunit/common-mocks.c
include/kunit/mock.h +222 -0
@@ -122,4 +122,226 @@ struct mock_expectation *mock_add_matcher(struct mock *mock,struct mock_param_matcher *matchers[], int len); +#define CONVERT_TO_ACTUAL_TYPE (type, ptr) (*((type *) ptr)) + +/** +* DOC: Built In Matchers +* +* These are the matchers that can be used when matching arguments in +* :c:func:`EXPECT_CALL` (more can be defined manually). +* +* For example, there's a matcher that matches any arguments: +* +* .. code-block:: c +* +* struct mock_param_matcher *any(struct test *test); +* +* There are matchers for integers based on the binary condition: +* +* * eq: equals to +* * ne: not equal to +* * lt: less than +* * le: less than or equal to +* * gt: greater than +* * ge: greater than or equal to +* +* .. code-block:: c +* +* struct mock_param_matcher *test_int_eq(struct test *test, int expected); +* struct mock_param_matcher *test_int_ne(struct test *test, int expected); +* struct mock_param_matcher *test_int_lt(struct test *test, int expected); +* struct mock_param_matcher *test_int_le(struct test *test, int expected); +* struct mock_param_matcher *test_int_gt(struct test *test, int expected); +* struct mock_param_matcher *test_int_ge(struct test *test, int expected); +* +* For a detailed list, please see +* ``include/linux/mock.h``. +*/ + +/* Matches any argument */ +struct mock_param_matcher *test_any (struct test *test); + +/* +* Matches different types of integers, the argument is compared to the +* `expected` field, based on the comparison defined. +*/ +struct mock_param_matcher *test_u8_eq (struct test *test,u8 expected); +struct mock_param_matcher *test_u8_ne (struct test *test,u8 expected); +struct mock_param_matcher *test_u8_le (struct test *test,u8 expected); +struct mock_param_matcher *test_u8_lt (struct test *test,u8 expected); +struct mock_param_matcher *test_u8_ge (struct test *test,u8 expected); +struct mock_param_matcher *test_u8_gt (struct test *test,u8 expected); + +struct mock_param_matcher *test_u16_eq (struct test *test,u16 expected); +struct mock_param_matcher *test_u16_ne (struct test *test,u16 expected); +struct mock_param_matcher *test_u16_le (struct test *test,u16 expected); +struct mock_param_matcher *test_u16_lt (struct test *test,u16 expected); +struct mock_param_matcher *test_u16_ge (struct test *test,u16 expected); +struct mock_param_matcher *test_u16_gt (struct test *test,u16 expected); + +struct mock_param_matcher *test_u32_eq (struct test *test,u32 expected); +struct mock_param_matcher *test_u32_ne (struct test *test,u32 expected); +struct mock_param_matcher *test_u32_le (struct test *test,u32 expected); +struct mock_param_matcher *test_u32_lt (struct test *test,u32 expected); +struct mock_param_matcher *test_u32_ge (struct test *test,u32 expected); +struct mock_param_matcher *test_u32_gt (struct test *test,u32 expected); + +struct mock_param_matcher *test_u64_eq (struct test *test,u64 expected); +struct mock_param_matcher *test_u64_ne (struct test *test,u64 expected); +struct mock_param_matcher *test_u64_le (struct test *test,u64 expected); +struct mock_param_matcher *test_u64_lt (struct test *test,u64 expected); +struct mock_param_matcher *test_u64_ge (struct test *test,u64 expected); +struct mock_param_matcher *test_u64_gt (struct test *test,u64 expected); + +struct mock_param_matcher *test_char_eq (struct test *test,char expected); +struct mock_param_matcher *test_char_ne (struct test *test,char expected); +struct mock_param_matcher *test_char_le (struct test *test,char expected); +struct mock_param_matcher *test_char_lt (struct test *test,char expected); +struct mock_param_matcher *test_char_ge (struct test *test,char expected); +struct mock_param_matcher *test_char_gt (struct test *test,char expected); + +struct mock_param_matcher *test_uchar_eq (struct test *test, +unsigned char expected); +struct mock_param_matcher *test_uchar_ne (struct test *test, +unsigned char expected); +struct mock_param_matcher *test_uchar_le (struct test *test, +unsigned char expected); +struct mock_param_matcher *test_uchar_lt (struct test *test, +unsigned char expected); +struct mock_param_matcher *test_uchar_ge (struct test *test, +unsigned char expected); +struct mock_param_matcher *test_uchar_gt (struct test *test, +unsigned char expected); + +struct mock_param_matcher *test_schar_eq (struct test *test, +signed char expected); +struct mock_param_matcher *test_schar_ne (struct test *test, +signed char expected); +struct mock_param_matcher *test_schar_le (struct test *test, +signed char expected); +struct mock_param_matcher *test_schar_lt (struct test *test, +signed char expected); +struct mock_param_matcher *test_schar_ge (struct test *test, +signed char expected); +struct mock_param_matcher *test_schar_gt (struct test *test, +signed char expected); + +struct mock_param_matcher *test_short_eq (struct test *test,short expected); +struct mock_param_matcher *test_short_ne (struct test *test,short expected); +struct mock_param_matcher *test_short_le (struct test *test,short expected); +struct mock_param_matcher *test_short_lt (struct test *test,short expected); +struct mock_param_matcher *test_short_ge (struct test *test,short expected); +struct mock_param_matcher *test_short_gt (struct test *test,short expected); + +struct mock_param_matcher *test_ushort_eq (struct test *test, +unsigned short expected); +struct mock_param_matcher *test_ushort_ne (struct test *test, +unsigned short expected); +struct mock_param_matcher *test_ushort_le (struct test *test, +unsigned short expected); +struct mock_param_matcher *test_ushort_lt (struct test *test, +unsigned short expected); +struct mock_param_matcher *test_ushort_ge (struct test *test, +unsigned short expected); +struct mock_param_matcher *test_ushort_gt (struct test *test, +unsigned short expected); + +struct mock_param_matcher *test_int_eq (struct test *test,int expected); +struct mock_param_matcher *test_int_ne (struct test *test,int expected); +struct mock_param_matcher *test_int_lt (struct test *test,int expected); +struct mock_param_matcher *test_int_le (struct test *test,int expected); +struct mock_param_matcher *test_int_gt (struct test *test,int expected); +struct mock_param_matcher *test_int_ge (struct test *test,int expected); + +struct mock_param_matcher *test_uint_eq (struct test *test, +unsigned int expected); +struct mock_param_matcher *test_uint_ne (struct test *test, +unsigned int expected); +struct mock_param_matcher *test_uint_lt (struct test *test, +unsigned int expected); +struct mock_param_matcher *test_uint_le (struct test *test, +unsigned int expected); +struct mock_param_matcher *test_uint_gt (struct test *test, +unsigned int expected); +struct mock_param_matcher *test_uint_ge (struct test *test, +unsigned int expected); + +struct mock_param_matcher *test_long_eq (struct test *test,long expected); +struct mock_param_matcher *test_long_ne (struct test *test,long expected); +struct mock_param_matcher *test_long_le (struct test *test,long expected); +struct mock_param_matcher *test_long_lt (struct test *test,long expected); +struct mock_param_matcher *test_long_ge (struct test *test,long expected); +struct mock_param_matcher *test_long_gt (struct test *test,long expected); + +struct mock_param_matcher *test_ulong_eq (struct test *test, +unsigned long expected); +struct mock_param_matcher *test_ulong_ne (struct test *test, +unsigned long expected); +struct mock_param_matcher *test_ulong_le (struct test *test, +unsigned long expected); +struct mock_param_matcher *test_ulong_lt (struct test *test, +unsigned long expected); +struct mock_param_matcher *test_ulong_ge (struct test *test, +unsigned long expected); +struct mock_param_matcher *test_ulong_gt (struct test *test, +unsigned long expected); + +struct mock_param_matcher *test_longlong_eq (struct test *test, +long long expected); +struct mock_param_matcher *test_longlong_ne (struct test *test, +long long expected); +struct mock_param_matcher *test_longlong_le (struct test *test, +long long expected); +struct mock_param_matcher *test_longlong_lt (struct test *test, +long long expected); +struct mock_param_matcher *test_longlong_ge (struct test *test, +long long expected); +struct mock_param_matcher *test_longlong_gt (struct test *test, +long long expected); + +struct mock_param_matcher *test_ulonglong_eq (struct test *test, +unsigned long long expected); +struct mock_param_matcher *test_ulonglong_ne (struct test *test, +unsigned long long expected); +struct mock_param_matcher *test_ulonglong_le (struct test *test, +unsigned long long expected); +struct mock_param_matcher *test_ulonglong_lt (struct test *test, +unsigned long long expected); +struct mock_param_matcher *test_ulonglong_ge (struct test *test, +unsigned long long expected); +struct mock_param_matcher *test_ulonglong_gt (struct test *test, +unsigned long long expected); + +/* Matches pointers. */ +struct mock_param_matcher *test_ptr_eq (struct test *test,void *expected); +struct mock_param_matcher *test_ptr_ne (struct test *test,void *expected); +struct mock_param_matcher *test_ptr_lt (struct test *test,void *expected); +struct mock_param_matcher *test_ptr_le (struct test *test,void *expected); +struct mock_param_matcher *test_ptr_gt (struct test *test,void *expected); +struct mock_param_matcher *test_ptr_ge (struct test *test,void *expected); + +/* Matches memory sections and strings. */ +struct mock_param_matcher *test_memeq (struct test *test, +const void *buf, +size_t size); +struct mock_param_matcher *test_streq (struct test *test,const char *str); + +struct mock_action *test_u8_return (struct test *test,u8 ret); +struct mock_action *test_u16_return (struct test *test,u16 ret); +struct mock_action *test_u32_return (struct test *test,u32 ret); +struct mock_action *test_u64_return (struct test *test,u64 ret); +struct mock_action *test_char_return (struct test *test,char ret); +struct mock_action *test_uchar_return (struct test *test,unsigned char ret); +struct mock_action *test_schar_return (struct test *test,signed char ret); +struct mock_action *test_short_return (struct test *test,short ret); +struct mock_action *test_ushort_return (struct test *test,unsigned short ret); +struct mock_action *test_int_return (struct test *test,int ret); +struct mock_action *test_uint_return (struct test *test,unsigned int ret); +struct mock_action *test_long_return (struct test *test,long ret); +struct mock_action *test_ulong_return (struct test *test,unsigned long ret); +struct mock_action *test_longlong_return (struct test *test,long long ret); +struct mock_action *test_ulonglong_return (struct test *test, +unsigned long long ret); +struct mock_action *test_ptr_return (struct test *test,void *ret); +#endif /* _KUNIT_MOCK_H */
kunit/Makefile +2 -1
@@ -1,4 +1,5 @@ -obj-$(CONFIG_KUNIT) += test.o mock.o string-stream.o test-stream.o +obj-$(CONFIG_KUNIT) += test.o mock.o common-mocks.o string-stream.o \ + test-stream.o obj-$(CONFIG_KUNIT_TEST) += \ test-test.o mock-macro-test.o string-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/common-mocks.c new file +272 -0
272 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 16/31 kunit: mock: added class mocking support
In reply to Brendan HigginsIntroduces basic class mocking, the ability to automatically generate a Linux C-style class implementation whose behavior is controlled by test cases, which can also set expectations on when and how mocks are called.
--- include/kunit/mock.h | 438 +++++++++++++++++++++++++++++++++++++++- kunit/Makefile | 2 +- kunit/example-test.c | 90 +++++++++ kunit/mock-macro-test.c | 82 ++++++++ kunit/mock-test.c | 276 +++++++++++++++++++++++++ kunit/test-mock.c | 39 ++++ kunit/test-mock.h | 23 +++ 7 files changed, 947 insertions(+), 3 deletions(-) create mode 100644 kunit/mock-test.c create mode 100644 kunit/test-mock.c create mode 100644 kunit/test-mock.h
include/kunit/mock.h +436 -2
@@ -72,7 +72,8 @@ struct mock_action {* @retire_on_saturation: no longer match once ``max_calls_expected`` is * reached. * -* Represents a *call expectation* on a function created with EXPECT_CALL(). +* Represents a *call expectation* on a function created with +* TEST_EXPECT_CALL(). */ struct mock_expectation {struct mock_action *action;
@@ -122,13 +123,446 @@ struct mock_expectation *mock_add_matcher(struct mock *mock,struct mock_param_matcher *matchers[], int len); +#define MOCK (name) name##_mock + +/** +* TEST_EXPECT_CALL() - Declares a *call expectation* on a mock function. +* @expectation_call: a mocked method or function with parameters replaced with +* matchers. +* +* Example: +* +* .. code-block:: c +* +* // Class to mock. +* struct example { +* int (*foo)(struct example *, int); +* }; +* +* // Define the mock. +* DECLARE_STRUCT_CLASS_MOCK_PREREQS(example); +* +* DEFINE_STRUCT_CLASS_MOCK(METHOD(foo), CLASS(example), +* RETURNS(int), +* PARAMS(struct example *, int)); +* +* static int example_init(struct MOCK(example) *mock_example) +* { +* struct example *example = mock_get_trgt(mock_example); +* +* example->foo = foo; +* return 0; +* } +* +* DEFINE_STRUCT_CLASS_MOCK_INIT(example, example_init); +* +* static void foo_example_test_success(struct test *test) +* { +* struct MOCK(example) *mock_example; +* struct example *example = mock_get_trgt(mock_example); +* struct mock_expectation *handle; +* +* mock_example = CONSTRUCT_MOCK(example, test); +* +* handle = TEST_EXPECT_CALL(foo(mock_get_ctrl(mock_example), +* test_int_eq(test, 5))); +* handle->action = int_return(test, 2); +* +* EXPECT_EQ(test, 2, example_bar(example, 5)); +* } +* +* Return: +* A &struct mock_expectation representing the call expectation. +* allowing additional conditions and actions to be specified. +*/ +#define TEST_EXPECT_CALL (expectation_call) mock_master_##expectation_call + +#define mock_get_ctrl_internal (mock_object) (&(mock_object)->ctrl) +#define mock_get_ctrl (mock_object) mock_get_ctrl_internal(mock_object) + +#define mock_get_trgt_internal (mock_object) (&(mock_object)->trgt) +#define mock_get_trgt (mock_object) mock_get_trgt_internal(mock_object) + +#define mock_get_test (mock_object) (mock_get_ctrl(mock_object)->test) + +#define CLASS (struct_name) struct_name +#define HANDLE_INDEX (index) index +#define METHOD (method_name) method_name +#define RETURNS (return_type) return_type +/* #define PARAMS(...) __VA_ARGS__ included by linux/tracepoint.h */ + +#define MOCK_INIT_ID (struct_name) struct_name##mock_init +#define REAL_ID (func_name) __real__##func_name +#define INVOKE_ID (func_name) __invoke__##func_name + +#define DECLARE_MOCK_CLIENT(name, return_type, param_types...) \ + return_type name(PARAM_LIST_FROM_TYPES(param_types)) + +#define DECLARE_MOCK_MASTER(name, ctrl_index, param_types...) \ + struct mock_expectation *mock_master_##name( \ + MATCHER_PARAM_LIST_FROM_TYPES(ctrl_index, \ + param_types)); + +#define DECLARE_MOCK_COMMON(name, handle_index, return_type, param_types...) \ + DECLARE_MOCK_CLIENT(name, return_type, param_types); \ + DECLARE_MOCK_MASTER(name, handle_index, param_types) + +#define DECLARE_STRUCT_CLASS_MOCK_STRUCT (struct_name) \ + struct MOCK(struct_name) { \ + struct mock ctrl; \ + struct struct_name trgt; \ + } + +#define DECLARE_STRUCT_CLASS_MOCK_CONVERTER (struct_name) \ + static inline struct mock *from_##struct_name##_to_mock( \ + const struct struct_name *trgt) \ + { \ + return mock_get_ctrl( \ + container_of(trgt, \ + struct MOCK(struct_name), \ + trgt)); \ + } + +/** +* DECLARE_STRUCT_CLASS_MOCK_PREREQS() - Create a mock child class +* @struct_name: name of the class/struct to be mocked +* +* Creates a mock child class of ``struct_name`` named +* ``struct MOCK(struct_name)`` along with supporting internally used methods. +* +* See TEST_EXPECT_CALL() for example usages. +*/ +#define DECLARE_STRUCT_CLASS_MOCK_PREREQS (struct_name) \ + DECLARE_STRUCT_CLASS_MOCK_STRUCT(struct_name); \ + DECLARE_STRUCT_CLASS_MOCK_CONVERTER(struct_name) + +#define DECLARE_STRUCT_CLASS_MOCK_HANDLE_INDEX_INTERNAL (name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types...) \ + DECLARE_MOCK_COMMON(name, \ + handle_index, \ + return_type, \ + param_types) + +#define DECLARE_STRUCT_CLASS_MOCK_HANDLE_INDEX (name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types...) \ + DECLARE_STRUCT_CLASS_MOCK_HANDLE_INDEX_INTERNAL(name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types) + +/** +* DECLARE_STRUCT_CLASS_MOCK() +* @name: method name +* @struct_name: name of the class/struct +* @return_type: return type of the method +* @param_types: parameters of the method +* +* Same as DEFINE_STRUCT_CLASS_MOCK(), but only makes header compatible +* declarations. +*/ +#define DECLARE_STRUCT_CLASS_MOCK (name, \ + struct_name, \ + return_type, \ + param_types...) \ + DECLARE_STRUCT_CLASS_MOCK_HANDLE_INDEX(name, \ + struct_name, \ + 0, \ + return_type, \ + param_types) + +/** +* DECLARE_STRUCT_CLASS_MOCK_VOID_RETURN() +* @name: method name +* @struct_name: name of the class/struct +* @param_types: parameters of the method +* +* Same as DEFINE_STRUCT_CLASS_MOCK_VOID_RETURN(), but only makes header +* compatible declarations. +*/ +#define DECLARE_STRUCT_CLASS_MOCK_VOID_RETURN (name, \ + struct_name, \ + param_types...) \ + DECLARE_STRUCT_CLASS_MOCK_HANDLE_INDEX(name, \ + struct_name, \ + 0, \ + void, \ + param_types) + +/** +* DECLARE_STRUCT_CLASS_MOCK_INIT() +* @struct_name: name of the class/struct +* +* Same as DEFINE_STRUCT_CLASS_MOCK_INIT(), but only makes header compatible +* declarations. +*/ +#define DECLARE_STRUCT_CLASS_MOCK_INIT (struct_name) \ + struct MOCK(struct_name) *MOCK_INIT_ID(struct_name)( \ + struct test *test) + +/** +* CONSTRUCT_MOCK() +* @struct_name: name of the class +* @test: associated test +* +* Constructs and allocates a test managed ``struct MOCK(struct_name)`` given +* the name of the class for which the mock is defined and a test object. +* +* See TEST_EXPECT_CALL() for example usage. +*/ +#define CONSTRUCT_MOCK (struct_name, test) MOCK_INIT_ID(struct_name)(test) + +#define DEFINE_MOCK_CLIENT_COMMON (name, \ + handle_index, \ +MOCK_SOURCE , \ + mock_source_ctx, \ + return_type, \ +RETURN , \ + param_types...) \ + return_type name(PARAM_LIST_FROM_TYPES(param_types)) \ + { \ + struct mock *mock = MOCK_SOURCE(mock_source_ctx, \ + handle_index); \ + static const char * const param_type_names[] = { \ + TYPE_NAMES_FROM_TYPES(handle_index, \ + param_types) \ + }; \ + const void *params[] = { \ + PTR_TO_ARG_FROM_TYPES(handle_index, \ + param_types) \ + }; \ + const void *retval; \ + \ + retval = mock->do_expect(mock, \ + #name, \ + name, \ + param_type_names, \ + params, \ + ARRAY_SIZE(params)); \ + TEST_ASSERT_NOT_ERR_OR_NULL(mock->test, retval); \ + if (!retval) { \ + test_info(mock->test, \ + "no action installed for "#name); \ + BUG(); \ + } \ + RETURN(return_type, retval); \ + } + +#define CLASS_MOCK_CLIENT_SOURCE (ctx, handle_index) ctx(arg##handle_index) +#define DEFINE_MOCK_METHOD_CLIENT_COMMON (name, \ + handle_index, \ + mock_converter, \ + return_type, \ +RETURN , \ + param_types...) \ + DEFINE_MOCK_CLIENT_COMMON(name, \ + handle_index, \ + CLASS_MOCK_CLIENT_SOURCE, \ + mock_converter, \ + return_type, \ + RETURN, \ + param_types) + +#define CAST_AND_RETURN (return_type, retval) return *((return_type *) retval) +#define NO_RETURN (return_type, retval) + +#define DEFINE_MOCK_METHOD_CLIENT (name, \ + handle_index, \ + mock_converter, \ + return_type, \ + param_types...) \ + DEFINE_MOCK_METHOD_CLIENT_COMMON(name, \ + handle_index, \ + mock_converter, \ + return_type, \ + CAST_AND_RETURN, \ + param_types) + +#define DEFINE_MOCK_METHOD_CLIENT_VOID_RETURN (name, \ + handle_index, \ + mock_converter, \ + param_types...) \ + DEFINE_MOCK_METHOD_CLIENT_COMMON(name, \ + handle_index, \ + mock_converter, \ + void, \ + NO_RETURN, \ + param_types) + +#define DEFINE_MOCK_MASTER_COMMON_INTERNAL (name, \ + ctrl_index, \ +MOCK_SOURCE , \ + param_types...) \ + struct mock_expectation *mock_master_##name( \ + MATCHER_PARAM_LIST_FROM_TYPES(ctrl_index, \ + param_types)) \ + { \ + struct mock_param_matcher *matchers[] = { \ + ARG_NAMES_FROM_TYPES(ctrl_index, param_types) \ + }; \ + \ + return mock_add_matcher(MOCK_SOURCE(ctrl_index), \ + #name, \ + (const void *) name, \ + matchers, \ + ARRAY_SIZE(matchers)); \ + } +#define DEFINE_MOCK_MASTER_COMMON (name, \ + ctrl_index, \ +MOCK_SOURCE , \ + param_types...) \ + DEFINE_MOCK_MASTER_COMMON_INTERNAL(name, \ + ctrl_index, \ + MOCK_SOURCE, \ + param_types) + +#define CLASS_MOCK_MASTER_SOURCE (ctrl_index) arg##ctrl_index +#define DEFINE_MOCK_METHOD_MASTER(name, ctrl_index, param_types...) \ + DEFINE_MOCK_MASTER_COMMON(name, \ + ctrl_index, \ + CLASS_MOCK_MASTER_SOURCE, \ + param_types) + +#define DEFINE_MOCK_COMMON (name, \ + handle_index, \ + mock_converter, \ + return_type, \ + param_types...) \ + DEFINE_MOCK_METHOD_CLIENT(name, \ + handle_index, \ + mock_converter, \ + return_type, \ + param_types); \ + DEFINE_MOCK_METHOD_MASTER(name, handle_index, param_types) + +#define DEFINE_MOCK_COMMON_VOID_RETURN (name, \ + handle_index, \ + mock_converter, \ + param_types...) \ + DEFINE_MOCK_METHOD_CLIENT_VOID_RETURN(name, \ + handle_index, \ + mock_converter, \ + param_types); \ + DEFINE_MOCK_METHOD_MASTER(name, handle_index, param_types) + +#define DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_INTERNAL (name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types...) \ + DEFINE_MOCK_COMMON(name, \ + handle_index, \ + from_##struct_name##_to_mock, \ + return_type, param_types) +#define DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX (name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types...) \ + DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_INTERNAL(name, \ + struct_name, \ + handle_index, \ + return_type, \ + param_types) + +#define DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_VOID_RETURN_INTERNAL ( \ + name, \ + struct_name, \ + handle_index, \ + param_types...) \ + DEFINE_MOCK_COMMON_VOID_RETURN(name, \ + handle_index, \ + from_##struct_name##_to_mock, \ + param_types) +#define DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_VOID_RETURN (name, \ + struct_name, \ + handle_index, \ + param_types...) \ + DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_VOID_RETURN_INTERNAL( \ + name, \ + struct_name, \ + handle_index, \ + param_types) + +/** +* DEFINE_STRUCT_CLASS_MOCK() +* @name: name of the method +* @struct_name: name of the class of which the method belongs +* @return_type: return type of the method to be created. **Must not be void.** +* @param_types: parameters to method to be created. +* +* See TEST_EXPECT_CALL() for example usage. +*/ +#define DEFINE_STRUCT_CLASS_MOCK (name, \ + struct_name, \ + return_type, \ + param_types...) \ + DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX(name, \ + struct_name, \ + 0, \ + return_type, \ + param_types) + +/** +* DEFINE_STRUCT_CLASS_MOCK_VOID_RETURN() +* @name: name of the method +* @struct_name: name of the class of which the method belongs +* @param_types: parameters to method to be created. +* +* Same as DEFINE_STRUCT_CLASS_MOCK() except the method has a ``void`` return +* type. +*/ +#define DEFINE_STRUCT_CLASS_MOCK_VOID_RETURN(name, struct_name, param_types...)\ + DEFINE_STRUCT_CLASS_MOCK_HANDLE_INDEX_VOID_RETURN(name, \ + struct_name, \ + 0, \ + param_types) + +/** +* DEFINE_STRUCT_CLASS_MOCK_INIT() +* @struct_name: name of the class +* @init_func: a function of type ``int (*)(struct MOCK(struct_name) *)``. This +* function is passed a pointer to an allocated, *but not +* initialized*, ``struct MOCK(struct_name)``. The job of this user +* provided function is to perform remaining initialization. Usually +* this entails assigning mock methods to the function pointers in +* the parent struct. +* +* See TEST_EXPECT_CALL() for example usage. +*/ +#define DEFINE_STRUCT_CLASS_MOCK_INIT (struct_name, init_func) \ + struct MOCK(struct_name) *MOCK_INIT_ID(struct_name)( \ + struct test *test) \ + { \ + struct MOCK(struct_name) *mock_obj; \ + \ + mock_obj = test_kzalloc(test, \ + sizeof(*mock_obj), \ + GFP_KERNEL); \ + if (!mock_obj) \ + return NULL; \ + \ + mock_init_ctrl(test, mock_get_ctrl(mock_obj)); \ + \ + if (init_func(mock_obj)) \ + return NULL; \ + \ + return mock_obj; \ + } +#define CONVERT_TO_ACTUAL_TYPE (type, ptr) (*((type *) ptr))/** * DOC: Built In Matchers * * These are the matchers that can be used when matching arguments in -* :c:func:`EXPECT_CALL` (more can be defined manually). +* :c:func:`TEST_EXPECT_CALL` (more can be defined manually). * * For example, there's a matcher that matches any arguments: *
kunit/Makefile +1 -1
@@ -1,5 +1,5 @@ obj-$(CONFIG_KUNIT) += test.o mock.o common-mocks.o string-stream.o \ test-stream.o obj-$(CONFIG_KUNIT_TEST) += \ - test-test.o mock-macro-test.o string-stream-test.o + test-test.o test-mock.o mock-macro-test.o mock-test.o string-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/example-test.c +90 -0
114 lines not on this page · raw message
kunit/mock-macro-test.c +82 -0
105 lines not on this page · raw message
kunit/mock-test.c new file +276 -0
276 lines not on this page · raw message
kunit/test-mock.c new file +39 -0
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* KUnit mock for struct test. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#include "test-mock.h" + +DEFINE_STRUCT_CLASS_MOCK_VOID_RETURN (METHOD (fail),CLASS (test), + PARAMS(struct test *, + struct test_stream *)); + +DEFINE_STRUCT_CLASS_MOCK_VOID_RETURN (METHOD (mock_vprintk),CLASS (test), + PARAMS(const struct test *, + const char *, + struct va_format *)); + +static int test_init(struct MOCK(test) *mock_test) +{ +struct test *trgt =mock_get_trgt (mock_test); +int ret; + + ret =test_init_test (trgt,"MOCK(test)" ); + trgt->fail = fail; +mock_set_default_action (mock_get_ctrl (mock_test), +"fail" , + fail, +test_int_return (mock_get_test (mock_test),0 )); + trgt->vprintk = mock_vprintk; +mock_set_default_action (mock_get_ctrl (mock_test), +"mock_vprintk" , + mock_vprintk, +test_int_return (mock_get_test (mock_test),0 )); +return ret; +} + +DEFINE_STRUCT_CLASS_MOCK_INIT (test, test_init);
kunit/test-mock.h new file +23 -0
@@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* KUnit mock for struct test. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#include <kunit/test.h> +#include <kunit/mock.h> + +DECLARE_STRUCT_CLASS_MOCK_PREREQS (test); + +DECLARE_STRUCT_CLASS_MOCK_VOID_RETURN (METHOD (fail),CLASS (test), + PARAMS(struct test *, + struct test_stream *)); + +DECLARE_STRUCT_CLASS_MOCK_VOID_RETURN (METHOD (mock_vprintk),CLASS (test), + PARAMS(const struct test *, + const char *, + struct va_format *)); + +DECLARE_STRUCT_CLASS_MOCK_INIT (test);
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 17/31 kunit: mock: added struct param matcher
In reply to Brendan HigginsAdded parameter matcher builder for matching struct values.
--- include/kunit/mock.h | 56 +++++++++++++++ kunit/Makefile | 5 +- kunit/common-mocks.c | 116 ++++++++++++++++++++++++++++++ kunit/mock-test.c | 43 +++++++++++ kunit/test-stream-test.c | 150 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 368 insertions(+), 2 deletions(-) create mode 100644 kunit/test-stream-test.c
include/kunit/mock.h +56 -0
@@ -760,6 +760,14 @@ struct mock_param_matcher *test_memeq(struct test *test, size_t size);struct mock_param_matcher *test_streq (struct test *test,const char *str); +struct mock_param_matcher *test_str_contains (struct test *test, +const char *needle); + +/* Matches var-arg arguments. */ +struct mock_param_matcher *test_va_format_cmp (struct test *test, +struct mock_param_matcher *fmt_matcher, +struct mock_param_matcher *va_matcher); +struct mock_action *test_u8_return (struct test *test,u8 ret);struct mock_action *test_u16_return (struct test *test,u16 ret);struct mock_action *test_u32_return (struct test *test,u32 ret);
@@ -778,4 +786,52 @@ struct mock_action *test_ulonglong_return(struct test *test, unsigned long long ret);struct mock_action *test_ptr_return (struct test *test,void *ret); +/** +* struct mock_struct_matcher_entry - composed with other &struct +* mock_struct_matcher_entry to make a +* &struct struct_matcher +* @member_offset: offset of this member +* @matcher: matcher for this particular member +* +* This is used for struct_cmp() matchers. +*/ +struct mock_struct_matcher_entry { +size_t member_offset; +struct mock_param_matcher *matcher; +}; + +static inline void init_mock_struct_matcher_entry_internal ( +struct mock_struct_matcher_entry *entry, +size_t offset, +struct mock_param_matcher *matcher) +{ + entry->member_offset = offset; + entry->matcher = matcher; +} + +/** +* INIT_MOCK_STRUCT_MATCHER_ENTRY() +* @entry: the &struct mock_struct_matcher_entry to initialize +* @type: the struct being matched +* @member: the member of the struct being matched, used to calculate the offset +* @matcher: matcher to match that member +* +* Initializes ``entry`` to match ``type->member`` with ``matcher``. +*/ +#define INIT_MOCK_STRUCT_MATCHER_ENTRY (entry, type, member, matcher) \ + init_mock_struct_matcher_entry_internal(entry, \ + offsetof(type, member),\ + matcher) + +static inline void INIT_MOCK_STRUCT_MATCHER_ENTRY_LAST ( +struct mock_struct_matcher_entry *entry) +{ + entry->matcher =NULL ; +} + +struct mock_param_matcher *test_struct_cmp ( +struct test *test, +const char *struct_name, +struct mock_struct_matcher_entry *entries); +#endif /* _KUNIT_MOCK_H */
kunit/Makefile +3 -2
@@ -1,5 +1,6 @@ obj-$(CONFIG_KUNIT) += test.o mock.o common-mocks.o string-stream.o \ test-stream.o -obj-$(CONFIG_KUNIT_TEST) += \ - test-test.o test-mock.o mock-macro-test.o mock-test.o string-stream-test.o +obj-$(CONFIG_KUNIT_TEST) += \ + test-test.o test-mock.o mock-macro-test.o mock-test.o string-stream-test.o \ + test-stream-test.o obj-$(CONFIG_EXAMPLE_TEST) += example-test.o
kunit/common-mocks.c +116 -0
122 lines not on this page · raw message
kunit/mock-test.c +43 -0
55 lines not on this page · raw message
kunit/test-stream-test.c new file +150 -0
150 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 18/31 kunit: mock: added parameter formatters
In reply to Brendan HigginsAdded parameter formatters which provide string formatting for parameters that have no matchers to be matched against.
--- include/kunit/mock.h | 49 +++++++++++++++ kunit/common-mocks.c | 132 +++++++++++++++++++++++++++++++++++++++ kunit/mock.c | 48 ++++++++++++-- kunit/test-stream-test.c | 28 +++++++++ 4 files changed, 252 insertions(+), 5 deletions(-)
include/kunit/mock.h +49 -0
@@ -123,6 +123,18 @@ struct mock_expectation *mock_add_matcher(struct mock *mock,struct mock_param_matcher *matchers[], int len); +struct mock_param_formatter { +struct list_head node; +const char *type_name; +void (*format)(struct mock_param_formatter *formatter, +struct test_stream *stream, +const void *param); +}; + +void mock_register_formatter (struct mock_param_formatter *formatter); + +void mock_unregister_formatter (struct mock_param_formatter *formatter); +#define MOCK (name) name##_mock/**
@@ -834,4 +846,41 @@ struct mock_param_matcher *test_struct_cmp(const char *struct_name, struct mock_struct_matcher_entry *entries); +struct mock_struct_formatter_entry { +size_t member_offset; +struct mock_param_formatter *formatter; +}; + +static inline void init_mock_struct_formatter_entry_internal ( +struct mock_struct_formatter_entry *entry, +size_t offset, +struct mock_param_formatter *formatter) +{ + entry->member_offset = offset; + entry->formatter = formatter; +} + +#define INIT_MOCK_STRUCT_FORMATTER_ENTRY (entry, type, member, formatter) \ + init_mock_struct_formatter_entry_internal(entry, \ + offsetof(type, \ + member), \ + formatter) + +static inline void INIT_MOCK_STRUCT_FORMATTER_ENTRY_LAST ( +struct mock_struct_formatter_entry *entry) +{ + entry->formatter =NULL ; +} + +struct mock_param_formatter *mock_struct_formatter ( +struct test *test, +const char *struct_name, +struct mock_struct_formatter_entry *entries); + +struct mock_param_formatter *mock_find_formatter (const char *type_name); + +#define FORMATTER_FROM_TYPE (type) mock_find_formatter(#type) + +extern struct mock_param_formatter unknown_formatter[]; +#endif /* _KUNIT_MOCK_H */
kunit/common-mocks.c +132 -0
135 lines not on this page · raw message
kunit/mock.c +43 -5
58 lines not on this page · raw message
kunit/test-stream-test.c +28 -0
@@ -116,6 +116,7 @@ static void test_stream_test_commits_any_uncommitted_when_cleanup(static int test_stream_test_init (struct test *test) { +struct mock_struct_formatter_entry *entries;struct test_stream_test_context *ctx; ctx =test_kzalloc (test,sizeof (*ctx),GFP_KERNEL );
@@ -131,9 +132,35 @@ static int test_stream_test_init(struct test *test)if (!ctx->stream)return -ENOMEM ; + entries =test_kzalloc (test,sizeof (*entries) *3 ,GFP_KERNEL ); +if (!entries) { +test_warn (test, +"Could not allocate arg formatter for struct va_format" ); +return 0 ; + } + +INIT_MOCK_STRUCT_FORMATTER_ENTRY (&entries[0 ], + struct va_format, + fmt, + FORMATTER_FROM_TYPE(const char *)); +INIT_MOCK_STRUCT_FORMATTER_ENTRY (&entries[1 ], + struct va_format, + va, + unknown_formatter); +INIT_MOCK_STRUCT_FORMATTER_ENTRY_LAST (&entries[2 ]); + +mock_register_formatter (mock_struct_formatter (test, +"struct va_format *" , + entries)); +return 0 ; } +static void test_stream_test_exit (struct test *test) +{ +mock_unregister_formatter (mock_find_formatter ("struct va_format *" )); +} +static struct test_case test_stream_test_cases[] = {TEST_CASE (test_stream_test_add),TEST_CASE (test_stream_test_append),
@@ -145,6 +172,7 @@ static struct test_case test_stream_test_cases[] = {static struct test_module test_stream_test_module = { .name ="test-stream-test" , .init = test_stream_test_init, + .exit = test_stream_test_exit, .test_cases = test_stream_test_cases, };module_test (test_stream_test_module);
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 19/31 kunit: mock: implemented nice, strict and naggy mock distinctions
In reply to Brendan HigginsNice mocks only fail when there is an expectation on a method, but none match a given call. Strict mocks only pass when there is a matching expectation for every call. Naggy mocks have the same pass/fail behavior as nice, but report a warning in any case a strict mock would fail.
--- include/kunit/mock.h | 63 +++++++++++++ kunit/mock-test.c | 192 ++++++++++++++++++++++++++++++++++++++- kunit/mock.c | 10 +- kunit/test-stream-test.c | 6 +- 4 files changed, 265 insertions(+), 6 deletions(-)
include/kunit/mock.h +63 -0
@@ -95,10 +95,17 @@ struct mock_method {struct list_head expectations; }; +enum mock_type { +MOCK_TYPE_NICE , +MOCK_TYPE_NAGGY , +MOCK_TYPE_STRICT +}; +struct mock {struct test_post_condition parent;struct test *test;struct list_head methods; +enum mock_type type;/* TODO(brendanhiggins at google.com): add locking to do_expect. */ const void *(*do_expect)(struct mock *mock, const char *method_name,
@@ -108,6 +115,8 @@ struct mock { int len); }; +#define DEFAULT_MOCK_TYPE MOCK_TYPE_NAGGY +void mock_init_ctrl (struct test *test,struct mock *mock);void mock_validate_expectations (struct mock *mock);
@@ -137,6 +146,60 @@ void mock_unregister_formatter(struct mock_param_formatter *formatter);#define MOCK (name) name##_mock +/** +* STRICT_MOCK() - sets the mock to be strict and returns the mock +* @mock: the mock +* +* For an example, see ``The Nice, the Strict, and the Naggy`` under +* ``Using KUnit``. +*/ +#define STRICT_MOCK (mock) \ +({ \ + mock_get_ctrl(mock)->type = MOCK_TYPE_STRICT; \ + mock; \ +}) + +static inline bool is_strict_mock (struct mock *mock) +{ +return mock->type ==MOCK_TYPE_STRICT ; +} + +/** +* NICE_MOCK() - sets the mock to be nice and returns the mock +* @mock: the mock +* +* For an example, see ``The Nice, the Strict, and the Naggy`` under +* ``Using KUnit``. +*/ +#define NICE_MOCK (mock) \ +({ \ + mock_get_ctrl(mock)->type = MOCK_TYPE_NICE; \ + mock; \ +}) + +static inline bool is_nice_mock (struct mock *mock) +{ +return mock->type ==MOCK_TYPE_NICE ; +} + +/** +* NAGGY_MOCK() - sets the mock to be naggy and returns the mock +* @mock: the mock +* +* For an example, see ``The Nice, the Strict, and the Naggy`` under +* ``Using KUnit``. +*/ +#define NAGGY_MOCK (mock) \ +({ \ + mock_get_ctrl(mock)->type = MOCK_TYPE_NAGGY; \ + mock; \ +}) + +static inline bool is_naggy_mock (struct mock *mock) +{ +return mock->type ==MOCK_TYPE_NAGGY ; +} +/** * TEST_EXPECT_CALL() - Declares a *call expectation* on a mock function. * @expectation_call: a mocked method or function with parameters replaced with
kunit/mock-test.c +191 -1
229 lines not on this page · raw message
kunit/mock.c +8 -2
@@ -79,6 +79,7 @@ void mock_init_ctrl(struct test *test, struct mock *mock) mock->test = test;INIT_LIST_HEAD (&mock->methods); mock->do_expect = mock_do_expect; + mock->type =DEFAULT_MOCK_TYPE ; mock->parent.validate = mock_validate_wrapper;list_add_tail (&mock->parent.node, &test->post_conditions); }
@@ -316,7 +317,12 @@ static struct mock_expectation *mock_apply_expectations(mock_add_method_expectation_error (test, stream,"Method was called with no expectations declared: " , mock, method, type_names, params, len); - stream->commit (stream); +if (is_strict_mock (mock)) + test->fail (test, stream); +else if (is_naggy_mock (mock)) + stream->commit (stream); +else + stream->clear (stream);return NULL ; }
@@ -346,7 +352,7 @@ static struct mock_expectation *mock_apply_expectations( } } -if (expectations_all_saturated) { +if (expectations_all_saturated && !is_nice_mock (mock)) {mock_add_method_expectation_error (test, stream,"Method was called with fully saturated expectations: " , mock, method, type_names, params, len);
kunit/test-stream-test.c +3 -3
@@ -20,7 +20,7 @@ struct test_stream_test_context {static void test_stream_test_add (struct test *test) {struct test_stream_test_context *ctx = test->priv; - struct MOCK(test) *mock_test = ctx->mock_test; + struct MOCK(test) *mock_test = NICE_MOCK(ctx->mock_test);struct test_stream *stream = ctx->stream; stream->add (stream,"Foo" );
@@ -40,7 +40,7 @@ static void test_stream_test_add(struct test *test)static void test_stream_test_append (struct test *test) {struct test_stream_test_context *ctx = test->priv; - struct MOCK(test) *mock_test = ctx->mock_test; + struct MOCK(test) *mock_test = NICE_MOCK(ctx->mock_test);struct test_stream *stream = ctx->stream;struct test_stream *other_stream;
@@ -63,7 +63,7 @@ static void test_stream_test_append(struct test *test)static void test_stream_error_message_when_no_level_set (struct test *test) {struct test_stream_test_context *ctx = test->priv; - struct MOCK(test) *mock_test = ctx->mock_test; + struct MOCK(test) *mock_test = NICE_MOCK(ctx->mock_test);struct test_stream *stream = ctx->stream;struct test_stream *other_stream;
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 20/31 kunit: mock: add ability to mock functions with void context
In reply to Brendan HigginsAdds ability to mock functions with a void* context object.
--- include/kunit/mock.h | 53 +++++++++++++++++++++++++++++++++++++++++ kunit/mock-macro-test.c | 30 +++++++++++++++++++++++ kunit/mock.c | 9 +++++++ 3 files changed, 92 insertions(+)
include/kunit/mock.h +53 -0
@@ -381,6 +381,24 @@ static inline bool is_naggy_mock(struct mock *mock) struct MOCK(struct_name) *MOCK_INIT_ID(struct_name)( \struct test *test) +#define DECLARE_VOID_CLASS_MOCK_HANDLE_INDEX_INTERNAL(name, \ + handle_index, \ + return_type, \ + param_types...) \ +DECLARE_MOCK_COMMON (name, \ + handle_index, \ + return_type, \ + param_types) + +#define DECLARE_VOID_CLASS_MOCK_HANDLE_INDEX(name, \ + handle_index, \ + return_type, \ + param_types...) \ +DECLARE_VOID_CLASS_MOCK_HANDLE_INDEX_INTERNAL (name, \ + handle_index, \ + return_type, \ + param_types) +/** * CONSTRUCT_MOCK() * @struct_name: name of the class
@@ -631,6 +649,41 @@ static inline bool is_naggy_mock(struct mock *mock)return mock_obj; \ } +struct MOCK (void) { +struct mock ctrl; +void *trgt; +}; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" +static inline struct mock *from_void_ptr_to_mock (const void *ptr) +{ + struct MOCK(void) *mock_void_ptr = ptr; + +return mock_get_ctrl (mock_void_ptr); +} +#pragma GCC diagnostic pop + +#define DEFINE_VOID_CLASS_MOCK_HANDLE_INDEX_INTERNAL (name, \ + handle_index, \ + return_type, \ + param_types...) \ + DEFINE_MOCK_COMMON(name, \ + handle_index, \ + from_void_ptr_to_mock, \ + return_type, \ + param_types) +#define DEFINE_VOID_CLASS_MOCK_HANDLE_INDEX (name, \ + handle_index, \ + return_type, \ + param_types...) \ + DEFINE_VOID_CLASS_MOCK_HANDLE_INDEX_INTERNAL(name, \ + handle_index, \ + return_type, \ + param_types) + +DECLARE_STRUCT_CLASS_MOCK_INIT (void); +#define CONVERT_TO_ACTUAL_TYPE (type, ptr) (*((type *) ptr))/**
kunit/mock-macro-test.c +30 -0
@@ -48,8 +48,19 @@ static int test_struct_init(struct MOCK(test_struct) *mock_test_struct)DEFINE_STRUCT_CLASS_MOCK_INIT (test_struct, test_struct_init); +DECLARE_VOID_CLASS_MOCK_HANDLE_INDEX (METHOD (test_void_ptr_func), +HANDLE_INDEX (0 ), +RETURNS (int), + PARAMS(void*, int)); + +DEFINE_VOID_CLASS_MOCK_HANDLE_INDEX (METHOD (test_void_ptr_func), +HANDLE_INDEX (0 ), +RETURNS (int), + PARAMS(void*, int)); +struct mock_macro_context { struct MOCK(test_struct) *mock_test_struct; + struct MOCK(void) *mock_void_ptr; };#define TO_STR_INTERNAL (...) #__VA_ARGS__
@@ -195,6 +206,20 @@ static void mock_macro_test_generated_method_code_works(struct test *test) test_struct->non_first_slot_param (5 , test_struct); } +static void mock_macro_test_generated_method_void_code_works (struct test *test) +{ +struct mock_macro_context *ctx = test->priv; + struct MOCK(void) *mock_void_ptr = ctx->mock_void_ptr; +struct mock_expectation *handle; + + handle =TEST_EXPECT_CALL (test_void_ptr_func ( +mock_get_ctrl (mock_void_ptr), +test_int_eq (test,3 ))); + handle->action =test_int_return (test,0 ); + +test_void_ptr_func (mock_void_ptr,3 ); +} +static int mock_macro_test_init (struct test *test) {struct mock_macro_context *ctx;
@@ -208,6 +233,10 @@ static int mock_macro_test_init(struct test *test)if (!ctx->mock_test_struct)return -EINVAL ; + ctx->mock_void_ptr =CONSTRUCT_MOCK (void, test); +if (!ctx->mock_void_ptr) +return -EINVAL ; +return 0 ; }
@@ -220,6 +249,7 @@ static struct test_case mock_macro_test_cases[] = {TEST_CASE (mock_macro_param_list_from_types_basic),TEST_CASE (mock_macro_arg_names_from_types),TEST_CASE (mock_macro_test_generated_method_code_works), + TEST_CASE(mock_macro_test_generated_method_void_code_works), {}, };
kunit/mock.c +9 -0
@@ -8,6 +8,15 @@#include <kunit/mock.h> +static int mock_void_ptr_init(struct MOCK(void) *mock_void_ptr) +{ + mock_void_ptr->trgt = mock_void_ptr; + +return 0 ; +} + +DEFINE_STRUCT_CLASS_MOCK_INIT (void, mock_void_ptr_init); + static bool mock_match_params(struct mock_matcher *matcher, struct test_stream *stream, const void **params,
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 21/31 kunit: mock: added support for arbitrary function mocking
In reply to Brendan HigginsUp to this point KUnit only supported method style function mocking where there was some type of class or context object and the function was only accessed via a pointer.
This adds support for mocking any function via the __mockable attribute.
--- include/kunit/mock.h | 107 ++++++++++++++++++++++++++++++++++++++++ kunit/mock-macro-test.c | 14 ++++++ kunit/mock.c | 41 +++++++++++++++ 3 files changed, 162 insertions(+)
include/kunit/mock.h +107 -0
@@ -144,6 +144,8 @@ void mock_register_formatter(struct mock_param_formatter *formatter);void mock_unregister_formatter (struct mock_param_formatter *formatter); +struct mock *mock_get_global_mock (void ); +#define MOCK (name) name##_mock/**
@@ -282,6 +284,12 @@ static inline bool is_naggy_mock(struct mock *mock)DECLARE_MOCK_CLIENT (name, return_type, param_types); \ DECLARE_MOCK_MASTER(name, handle_index, param_types) +#define DECLARE_MOCK_FUNC_CLIENT(name, return_type, param_types...) \ + DECLARE_MOCK_CLIENT(name, return_type, param_types) + +#define DECLARE_MOCK_FUNC_MASTER(name, param_types...) \ + DECLARE_MOCK_MASTER(name, MOCK_MAX_PARAMS, param_types) +#define DECLARE_STRUCT_CLASS_MOCK_STRUCT (struct_name) \ struct MOCK(struct_name) { \ struct mock ctrl; \
@@ -411,6 +419,16 @@ static inline bool is_naggy_mock(struct mock *mock)*/ #define CONSTRUCT_MOCK (struct_name, test) MOCK_INIT_ID(struct_name)(test) +#define DECLARE_FUNCTION_MOCK_INTERNAL(name, return_type, param_types...) \ + DECLARE_MOCK_FUNC_CLIENT(name, return_type, param_types); \ + DECLARE_MOCK_FUNC_MASTER(name, param_types); + +#define DECLARE_FUNCTION_MOCK(name, return_type, param_types...) \ + DECLARE_FUNCTION_MOCK_INTERNAL(name, return_type, param_types) + +#define DECLARE_FUNCTION_MOCK_VOID_RETURN(name, param_types...) \ + DECLARE_FUNCTION_MOCK(name, void, param_types) + #define DEFINE_MOCK_CLIENT_COMMON(name, \ handle_index, \ MOCK_SOURCE, \
@@ -488,6 +506,31 @@ static inline bool is_naggy_mock(struct mock *mock) NO_RETURN, \ param_types) +#define FUNC_MOCK_SOURCE (ctx, handle_index) mock_get_global_mock() +#define DEFINE_MOCK_FUNC_CLIENT_COMMON (name, \ + return_type, \ +RETURN , \ + param_types...) \ + DEFINE_MOCK_CLIENT_COMMON(name, \ + MOCK_MAX_PARAMS, \ + FUNC_MOCK_SOURCE, \ + name, \ + return_type, \ + RETURN, \ + param_types) + +#define DEFINE_MOCK_FUNC_CLIENT(name, return_type, param_types...) \ + DEFINE_MOCK_FUNC_CLIENT_COMMON(name, \ + return_type, \ + CAST_AND_RETURN, \ + param_types) + +#define DEFINE_MOCK_FUNC_CLIENT_VOID_RETURN(name, param_types...) \ + DEFINE_MOCK_FUNC_CLIENT_COMMON(name, \ + void, \ + NO_RETURN, \ + param_types) + #define DEFINE_MOCK_MASTER_COMMON_INTERNAL(name, \ ctrl_index, \ MOCK_SOURCE, \
@@ -522,6 +565,13 @@ static inline bool is_naggy_mock(struct mock *mock) CLASS_MOCK_MASTER_SOURCE, \ param_types) +#define FUNC_MOCK_CLIENT_SOURCE (ctrl_index) mock_get_global_mock() +#define DEFINE_MOCK_FUNC_MASTER(name, param_types...) \ + DEFINE_MOCK_MASTER_COMMON(name, \ + MOCK_MAX_PARAMS, \ + FUNC_MOCK_CLIENT_SOURCE, \ + param_types) + #define DEFINE_MOCK_COMMON(name, \ handle_index, \ mock_converter, \
@@ -684,6 +734,63 @@ static inline struct mock *from_void_ptr_to_mock(const void *ptr)DECLARE_STRUCT_CLASS_MOCK_INIT (void); +#define DEFINE_FUNCTION_MOCK_INTERNAL(name, return_type, param_types...) \ + DEFINE_MOCK_FUNC_CLIENT(name, return_type, param_types); \ + DEFINE_MOCK_FUNC_MASTER(name, param_types) + +/** +* DEFINE_FUNCTION_MOCK() +* @name: name of the function +* @return_type: return type of the function +* @...: parameter types of the function +* +* Same as DEFINE_STRUCT_CLASS_MOCK() except can be used to mock any function +* declared %__mockable or DEFINE_REDIRECT_MOCKABLE() +*/ +#define DEFINE_FUNCTION_MOCK(name, return_type, param_types...) \ + DEFINE_FUNCTION_MOCK_INTERNAL(name, return_type, param_types) + +#define DEFINE_FUNCTION_MOCK_VOID_RETURN_INTERNAL(name, param_types...) \ + DEFINE_MOCK_FUNC_CLIENT_VOID_RETURN(name, param_types); \ + DEFINE_MOCK_FUNC_MASTER(name, param_types) + +/** +* DEFINE_FUNCTION_MOCK_VOID_RETURN() +* @name: name of the function +* @...: parameter types of the function +* +* Same as DEFINE_FUNCTION_MOCK() except the method has a ``void`` return +* type. +*/ +#define DEFINE_FUNCTION_MOCK_VOID_RETURN(name, param_types...) \ + DEFINE_FUNCTION_MOCK_VOID_RETURN_INTERNAL(name, param_types) + +#if IS_ENABLED (CONFIG_KUNIT ) + +/** +* __mockable - A function decorator that allows the function to be mocked. +* +* Example: +* +* .. code-block:: c +* +* int __mockable example(int arg) { ... } +*/ +#define __mockable __weak + +/** +* __visible_for_testing - Makes a static function visible when testing. +* +* A macro that replaces the `static` specifier on functions and global +* variables that is static when compiled normally and visible when compiled for +* tests. +*/ +#define __visible_for_testing +#else +#define __mockable +#define __visible_for_testing static +#endif +#define CONVERT_TO_ACTUAL_TYPE (type, ptr) (*((type *) ptr))/**
kunit/mock-macro-test.c +14 -0
@@ -58,6 +58,8 @@ DEFINE_VOID_CLASS_MOCK_HANDLE_INDEX(METHOD(test_void_ptr_func),RETURNS (int), PARAMS(void*, int)); +DEFINE_FUNCTION_MOCK (add,RETURNS (int),PARAMS (int, int)); +struct mock_macro_context { struct MOCK(test_struct) *mock_test_struct; struct MOCK(void) *mock_void_ptr;
@@ -220,6 +222,17 @@ static void mock_macro_test_generated_method_void_code_works(struct test *test)test_void_ptr_func (mock_void_ptr,3 ); } +static void mock_macro_test_generated_function_code_works (struct test *test) +{ +struct mock_expectation *handle; + + handle =TEST_EXPECT_CALL (add (test_int_eq (test,4 ), +test_int_eq (test,3 ))); + handle->action =test_int_return (test,7 ); + +TEST_EXPECT_EQ (test,7 ,add (4 ,3 )); +} +static int mock_macro_test_init (struct test *test) {struct mock_macro_context *ctx;
@@ -250,6 +263,7 @@ static struct test_case mock_macro_test_cases[] = {TEST_CASE (mock_macro_arg_names_from_types),TEST_CASE (mock_macro_test_generated_method_code_works),TEST_CASE (mock_macro_test_generated_method_void_code_works), + TEST_CASE(mock_macro_test_generated_function_code_works), {}, };
kunit/mock.c +41 -0
47 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 22/31 kunit: mock: add the concept of spyable functions
In reply to Brendan HigginsAdds the concept of spying like in Mockito
(http://static.javadoc.io/org.mockito/mockito-core/2.20.0/org/mockito/Mockito.html#spy-T-).
This allows a function declaration to be labled as spyable which allows the function to be mocked *and* to allow the mock to invoke the original function definition.
--- include/kunit/mock.h | 123 ++++++++++++++++++++++++++++++++++++++++++- kunit/common-mocks.c | 36 +++++++++++++ 2 files changed, 158 insertions(+), 1 deletion(-)
include/kunit/mock.h +122 -1
@@ -284,6 +284,13 @@ static inline bool is_naggy_mock(struct mock *mock)DECLARE_MOCK_CLIENT (name, return_type, param_types); \ DECLARE_MOCK_MASTER(name, handle_index, param_types) +#define DECLARE_SPYABLE(name, return_type, param_types...) \ + return_type REAL_ID(name)(param_types); \ + return_type name(param_types); \ + void *INVOKE_ID(name)(struct test *test, \ + const void *params[], \ + int len) + #define DECLARE_MOCK_FUNC_CLIENT(name, return_type, param_types...) \ DECLARE_MOCK_CLIENT(name, return_type, param_types)
@@ -465,6 +472,100 @@ static inline bool is_naggy_mock(struct mock *mock)RETURN (return_type, retval); \ } +#if IS_ENABLED (CONFIG_KUNIT ) +#define DEFINE_INVOKABLE(name, return_type, RETURN_ASSIGN, param_types...) \ + void *INVOKE_ID(name)(struct test *test, \ + const void *params[], \ + int len) { \ + return_type *retval; \ + \ + TEST_ASSERT_EQ(test, NUM_VA_ARGS(param_types), len); \ + retval = test_kzalloc(test, \ + sizeof(*retval), \ + GFP_KERNEL); \ + TEST_ASSERT_NOT_ERR_OR_NULL(test, retval); \ + RETURN_ASSIGN() REAL_ID(name)( \ + ARRAY_ACCESSORS_FROM_TYPES( \ + param_types)); \ + return retval; \ + } +#else +#define DEFINE_INVOKABLE(name, return_type, RETURN_ASSIGN, param_types...) +#endif + +#define DEFINE_SPYABLE_COMMON (name, \ + return_type, \ +RETURN_ASSIGN , \ + param_types...) \ + return_type REAL_ID(name)(param_types); \ + return_type name(param_types) __mockable_alias(REAL_ID(name)); \ + DEFINE_INVOKABLE(name, return_type, RETURN_ASSIGN, param_types); + +#define ASSIGN () *retval = + +/** +* DEFINE_SPYABLE() +* @name: name of the function +* @return_type: return type of the function +* @param_types: parameter types of the function +* +* Used to define a function which is *redirect-mockable*, which allows the +* function to be mocked and refer to the original definition via +* INVOKE_REAL(). +* +* Example: +* +* .. code-block:: c +* +* DEFINE_SPYABLE(i2c_add_adapter, +* RETURNS(int), PARAMS(struct i2c_adapter *)); +* int REAL_ID(i2c_add_adapter)(struct i2c_adapter *adapter) +* { +* ... +* } +* +* static int aspeed_i2c_test_init(struct test *test) +* { +* struct mock_param_capturer *adap_capturer; +* struct mock_expectation *handle; +* struct aspeed_i2c_test *ctx; +* int ret; +* +* ctx = test_kzalloc(test, sizeof(*ctx), GFP_KERNEL); +* if (!ctx) +* return -ENOMEM; +* test->priv = ctx; +* +* handle = TEST_EXPECT_CALL( +* i2c_add_adapter(capturer_to_matcher( +* adap_capturer))); +* handle->action = INVOKE_REAL(test, i2c_add_adapter); +* ret = of_fake_probe_platform_by_name(test, +* "aspeed-i2c-bus", +* "test-i2c-bus"); +* if (ret < 0) +* return ret; +* +* TEST_ASSERT_PARAM_CAPTURED(test, adap_capturer); +* ctx->adap = mock_capturer_get(adap_capturer, +* struct i2c_adapter *); +* +* return 0; +* } +*/ +#define DEFINE_SPYABLE(name, return_type, param_types...) \ + DEFINE_SPYABLE_COMMON(name, \ + return_type, \ + ASSIGN, \ + param_types) + +#define NO_ASSIGN () +#define DEFINE_SPYABLE_VOID_RETURN (name, param_types) \ + DEFINE_SPYABLE_COMMON(name, \ + void, \ + NO_ASSIGN, \ + param_types) +#define CLASS_MOCK_CLIENT_SOURCE (ctx, handle_index) ctx(arg##handle_index) #define DEFINE_MOCK_METHOD_CLIENT_COMMON(name, \ handle_index, \
@@ -745,7 +846,7 @@ DECLARE_STRUCT_CLASS_MOCK_INIT(void);* @...: parameter types of the function * * Same as DEFINE_STRUCT_CLASS_MOCK() except can be used to mock any function -* declared %__mockable or DEFINE_REDIRECT_MOCKABLE() +* declared %__mockable or DEFINE_SPYABLE() */ #define DEFINE_FUNCTION_MOCK(name, return_type, param_types...) \ DEFINE_FUNCTION_MOCK_INTERNAL(name, return_type, param_types)
@@ -777,6 +878,7 @@ DECLARE_STRUCT_CLASS_MOCK_INIT(void);* int __mockable example(int arg) { ... } */ #define __mockable __weak +#define __mockable_alias (id) __weak __alias(id)/** * __visible_for_testing - Makes a static function visible when testing.
@@ -788,6 +890,7 @@ DECLARE_STRUCT_CLASS_MOCK_INIT(void);#define __visible_for_testing#else #define __mockable +#define __mockable_alias (id) __alias(id)#define __visible_for_testing static#endif
@@ -1069,6 +1172,24 @@ struct mock_param_matcher *test_struct_cmp(const char *struct_name, struct mock_struct_matcher_entry *entries); +struct mock_action *invoke (struct test *test, +void *(*invokable)(struct test *, +const void *params[], +int len)); + +/** +* INVOKE_REAL() +* @test: associated test +* @func_name: name of the function +* +* See DEFINE_SPYABLE() for an example. +* +* Return: &struct mock_action that makes the associated mock method or function +* call the original function definition of a redirect-mockable +* function. +*/ +#define INVOKE_REAL (test, func_name) invoke(test, INVOKE_ID(func_name)) +struct mock_struct_formatter_entry {size_t member_offset;struct mock_param_formatter *formatter;
kunit/common-mocks.c +36 -0
@@ -386,6 +386,42 @@ DEFINE_RETURN_ACTION_WITH_TYPENAME(longlong, long long); DEFINE_RETURN_ACTION_WITH_TYPENAME(ulonglong, unsigned long long); DEFINE_RETURN_ACTION_WITH_TYPENAME(ptr, void *); +struct mock_invoke_action { +struct mock_action action; +struct test *test; +void *(*invokable)(struct test *test,const void *params[],int len); +}; + +static void *do_invoke (struct mock_action *paction, +const void *params[], +int len) +{ +struct mock_invoke_action *action = +container_of (paction, + struct mock_invoke_action, + action); + +return action->invokable (action->test, params, len); +} + +struct mock_action *invoke (struct test *test, +void *(*invokable)(struct test *, +const void *params[], +int len)) +{ +struct mock_invoke_action *action; + + action =test_kmalloc (test,sizeof (*action),GFP_KERNEL ); +if (!action) +return NULL ; + + action->action.do_action = do_invoke; + action->test = test; + action->invokable = invokable; + +return &action->action; +} +struct mock_param_integer_formatter {struct mock_param_formatter formatter;const char *fmt_str;
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 23/31 kunit: mock: add parameter capturers
In reply to Brendan HigginsAdds the concept of an argument capturer which, when used with a matcher in an EXPECT_CALL(...), will capture the value of the matching argument.
--- include/kunit/mock.h | 83 ++++++++++++++++++++++++++++++++++++++++++++ kunit/common-mocks.c | 78 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 161 insertions(+)
include/kunit/mock.h +83 -0
@@ -1172,6 +1172,89 @@ struct mock_param_matcher *test_struct_cmp(const char *struct_name, struct mock_struct_matcher_entry *entries); +/** +* struct mock_param_capturer - used to capture parameter when matching +* +* Use the associated helper macros to access relevant fields. +* Example: +* +* .. code-block::c +* +* static int some_test(struct test *test) +* { +* // imagine a mocked function: int add(int a, int b) +* struct mock_param_capturer *capturer = +* mock_int_capturer_create(test, any(test)); +* TEST_EXPECT_CALL(add(any(test), capturer_to_matcher(capturer))); +* TEST_ASSERT_PARAM_CAPTURED(test, capturer); +* +* int captured_value = mock_capturer_get(capturer, int); +* } +*/ +struct mock_param_capturer { +/* private: internal use only. */ +struct mock_param_matcher matcher; +struct mock_param_matcher *child_matcher; +void *(*capture_param)(struct test *test,const void *param); +void *captured_param; +}; + +struct mock_param_capturer *mock_param_capturer_create ( +struct test *test, +struct mock_param_matcher *child_matcher, +void *(*capture_param)(struct test *,const void *)); + +/** +* mock_int_capturer_create() - creates a int parameter capturer +* @test: associated test +* @child_matcher: matcher used to match the integer +* +* The capturer will capture the value if the matcher is satisfied. +*/ +struct mock_param_capturer *mock_int_capturer_create ( +struct test *test,struct mock_param_matcher *child_matcher); + +/** +* mock_int_capturer_create() - creates a generic pointer parameter capturer +* @test: associated test +* @child_matcher: matcher used to match the pointer +* +* The capturer will capture the value if the matcher is satisfied +*/ +struct mock_param_capturer *mock_ptr_capturer_create ( +struct test *test,struct mock_param_matcher *child_matcher); + +/** +* capturer_to_matcher() +* @capturer: the param capturer +* +* Use this function when passing a capturer into an EXPECT_CALL() where a +* matcher would be expected. See the example for &struct mock_param_capturer. +*/ +#define capturer_to_matcher (capturer) (&(capturer)->matcher) + +/** +* TEST_ASSERT_PARAM_CAPTURED(): Asserts that a parameter has been captured. +* @test: the associated test +* @capturer: the param capturer +* +* See &struct mock_param_capturer for an example. +*/ +#define TEST_ASSERT_PARAM_CAPTURED (test, capturer) \ + TEST_ASSERT(test, \ + !IS_ERR_OR_NULL((capturer)->captured_param), \ + "Asserted " #capturer " captured param, but did not.") + +/** +* mock_capturer_get(): Returns the value captured by ``capturer`` +* @capturer: the param capturer +* @type: the type of the value +* +* See &struct mock_param_capturer for an example. +*/ +#define mock_capturer_get (capturer, type) \ + CONVERT_TO_ACTUAL_TYPE(type, (capturer)->captured_param) + struct mock_action *invoke(struct test *test, void *(*invokable)(struct test *, const void *params[],
kunit/common-mocks.c +78 -0
84 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 24/31 kunit: improved sigsegv stack trace printing
In reply to Brendan HigginsSacrificed the control of printing stack trace within the crash handler in the test runner for getting a better stack trace; this is still not ideal, but much better than before.
--- arch/um/kernel/trap.c | 11 ++++++++++- kunit/test.c | 13 +++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-)
arch/um/kernel/trap.c +10 -1
@@ -226,8 +226,17 @@ unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user, current->thread.segv_regs = container_of(regs, struct pt_regs, regs); catcher = current->thread.fault_catcher; -if (catcher && current->thread.is_running_test) +if (catcher && current->thread.is_running_test) { +/* +* TODO(b/77223210): Right now we don't have a way to store a +* copy of the stack, or a copy of information from the stack, +* so we need to print it now; otherwise, the stack will be +* destroyed by segv_run_catcher which works by popping off +* stack frames. +*/ +show_stack (NULL ,NULL );segv_run_catcher (catcher, (void *) address); + }else if (!is_user && (address >= start_vm) && (address < end_vm)) {flush_tlb_kernel_vm (); goto out;
kunit/test.c +9 -4
@@ -210,12 +210,17 @@ static void test_handle_test_crash(struct test *test, struct test_module *module, struct test_case *test_case) { - test_err(test, "%s crashed", test_case->name);/* -* TODO(brendanhiggins at google.com): This prints the stack trace up -* through this frame, not up to the frame that caused the crash. +* TODO(brendanhiggins at google.com): Right now we don't have a way to +* store a copy of the stack, or a copy of information from the stack, +* so we need to print it in the "trap" handler; otherwise, the stack +* will be destroyed when it returns to us by popping off the +* appropriate stack frames (see longjmp). +* +* Ideally we would print the stack trace here, but we do not have the +* ability to do so with meaningful information at this time. */ -show_stack (NULL ,NULL ); +test_err (test,"%s crashed" , test_case->name);test_case_internal_cleanup (test); }
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 25/31 kunit: added concept of platform mocking
In reply to Brendan HigginsPlatform mocking is the mocking of all platform specific functions that interact directly with hardware. In effect, this provides the ability to mock any hardware behavior.
--- drivers/base/Makefile | 1 + drivers/base/platform-mock.c | 65 ++++++++++++++++++++++++++++ include/linux/platform_device_mock.h | 64 +++++++++++++++++++++++++++ 3 files changed, 130 insertions(+) create mode 100644 drivers/base/platform-mock.c create mode 100644 include/linux/platform_device_mock.h
drivers/base/Makefile +1 -0
@@ -23,6 +23,7 @@ obj-$(CONFIG_PINCTRL) += pinctrl.o obj-$(CONFIG_DEV_COREDUMP) += devcoredump.o obj-$(CONFIG_GENERIC_MSI_IRQ_DOMAIN) += platform-msi.o obj-$(CONFIG_GENERIC_ARCH_TOPOLOGY) += arch_topology.o +obj-$(CONFIG_PLATFORM_MOCK) += platform-mock.o obj-y += test/
drivers/base/platform-mock.c new file +65 -0
65 lines not on this page · raw message
include/linux/platform_device_mock.h new file +64 -0
64 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 26/31 arch: um: added stubs for mock iomem for KUnit
In reply to Brendan HigginsThis mocks out some iomem functions (functions like readl and writel), for mocking hardware interfaces.
--- arch/um/Kconfig.common | 8 +++++- arch/um/Kconfig.um | 5 ++++ arch/um/include/asm/Kbuild | 1 - arch/um/include/asm/io-mock-shared.h | 33 +++++++++++++++++++++ arch/um/include/asm/io-mock.h | 43 ++++++++++++++++++++++++++++ arch/um/include/asm/io.h | 8 ++++++ arch/um/kernel/Makefile | 1 + arch/um/kernel/io-mock.c | 40 ++++++++++++++++++++++++++ kunit/Kconfig | 1 + 9 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 arch/um/include/asm/io-mock-shared.h create mode 100644 arch/um/include/asm/io-mock.h create mode 100644 arch/um/kernel/io-mock.c
arch/um/Kconfig.common +7 -1
@@ -19,7 +19,13 @@ config MMU default y config NO_IOMEM - def_bool y + bool + default y if !KUNIT + +config HAS_IOMEM + bool "Turns on fake IOMEM support for KUnit" + depends on KUNIT + select MOCK_IOMEM config ISA bool
arch/um/Kconfig.um +5 -0
@@ -122,3 +122,8 @@ config SECCOMP defined by each seccomp mode. If unsure, say Y. + +config PLATFORM_MOCK + bool "Enable a mock architecture used for unit testing." + depends on KUNIT && OF + default n
arch/um/include/asm/Kbuild +0 -1
@@ -12,7 +12,6 @@ generic-y += ftrace.h generic-y += futex.h generic-y += hardirq.h generic-y += hw_irq.h -generic-y += io.h generic-y += irq_regs.h generic-y += irq_work.h generic-y += kdebug.h
arch/um/include/asm/io-mock-shared.h new file +33 -0
@@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_UM_IO_MOCK_SHARED_H +#define _ASM_UM_IO_MOCK_SHARED_H + +#define readb readb +u8 readb (const volatile void __iomem *); + +#define readw readw +u16 readw (const volatile void __iomem *); + +#define readl readl +u32 readl (const volatile void __iomem *); + +#ifdef CONFIG_64BIT +#define readq readq +u64 readq (const volatile void __iomem *); +#endif /* CONFIG_64BIT */ + +#define writeb writeb +void writeb (u8 ,const volatile void __iomem *); + +#define writew writew +void writew (u16 ,const volatile void __iomem *); + +#define writel writel +void writel (u32 ,const volatile void __iomem *); + +#ifdef CONFIG_64BIT +#define writeq writeq +void writeq (u64 ,const volatile void __iomem *); +#endif /* CONFIG_64BIT */ + +#endif /* _ASM_UM_IO_MOCK_SHARED_H */
arch/um/include/asm/io-mock.h new file +43 -0
43 lines not on this page · raw message
arch/um/include/asm/io.h +8 -0
@@ -2,11 +2,19 @@#ifndef _ASM_UM_IO_H#define _ASM_UM_IO_H +#include <linux/types.h> +#include <asm/byteorder.h> + +#if IS_ENABLED (CONFIG_PLATFORM_MOCK ) +#include <asm/io-mock-shared.h> +#endif +#define ioremap ioremapstatic inline void __iomem *ioremap (phys_addr_t offset,size_t size) {return (void __iomem *)(unsigned long )offset; } +#define ioremap_nocache ioremap#define iounmap iounmapstatic inline void iounmap (void __iomem *addr)
arch/um/kernel/Makefile +1 -0
@@ -25,6 +25,7 @@ obj-$(CONFIG_GPROF) += gprof_syms.o obj-$(CONFIG_GCOV) += gmon_syms.o obj-$(CONFIG_EARLY_PRINTK) += early_printk.o obj-$(CONFIG_STACKTRACE) += stacktrace.o +obj-$(CONFIG_PLATFORM_MOCK) += io-mock.o USER_OBJS := config.o
arch/um/kernel/io-mock.c new file +40 -0
@@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Mock IO functions. +* +* Copyright (C) 2018, Google LLC. +* Author: Brendan Higgins <brendanhiggins at google.com> +*/ + +#include <linux/mm.h> +#include <linux/io.h> +#include <linux/kernel.h> +#include <kunit/mock.h> + +DEFINE_FUNCTION_MOCK (readb, + RETURNS(u8), PARAMS(const volatile void __iomem *)); + +DEFINE_FUNCTION_MOCK (readw, + RETURNS(u16), PARAMS(const volatile void __iomem *)); + +DEFINE_FUNCTION_MOCK (readl, + RETURNS(u32), PARAMS(const volatile void __iomem *)); + +#ifdef CONFIG_64BIT +DEFINE_FUNCTION_MOCK (readq, + RETURNS(u64), PARAMS(const volatile void __iomem *)); +#endif /* CONFIG_64BIT */ + +DEFINE_FUNCTION_MOCK_VOID_RETURN (writeb, + PARAMS(u8, const volatile void __iomem *)); + +DEFINE_FUNCTION_MOCK_VOID_RETURN (writew, + PARAMS(u16, const volatile void __iomem *)); + +DEFINE_FUNCTION_MOCK_VOID_RETURN (writel, + PARAMS(u32, const volatile void __iomem *)); + +#ifdef CONFIG_64BIT +DEFINE_FUNCTION_MOCK_VOID_RETURN (writeq, + PARAMS(u64, const volatile void __iomem *)); +#endif /* CONFIG_64BIT */
kunit/Kconfig +1 -0
@@ -6,6 +6,7 @@ menu "KUnit support" config KUNIT bool "Enable support for unit tests (KUnit)" + select HAS_IOMEM help Enables support for kernel unit tests (KUnit), a lightweight unit testing and mocking framework for the Linux kernel. These tests are
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 27/31 Documentation: kunit: adds complete documentation for KUnit
In reply to Brendan Higgins- Added intro and usage guide for KUnit
- Added API reference
--- Documentation/index.rst | 1 + .../kunit/api/class-and-function-mocking.rst | 68 ++ Documentation/kunit/api/index.rst | 21 + Documentation/kunit/api/platform-mocking.rst | 36 + Documentation/kunit/api/test.rst | 15 + Documentation/kunit/faq.rst | 46 + Documentation/kunit/index.rst | 84 ++ Documentation/kunit/start.rst | 185 ++++ Documentation/kunit/usage.rst | 876 ++++++++++++++++++ 9 files changed, 1332 insertions(+) create mode 100644 Documentation/kunit/api/class-and-function-mocking.rst create mode 100644 Documentation/kunit/api/index.rst create mode 100644 Documentation/kunit/api/platform-mocking.rst create mode 100644 Documentation/kunit/api/test.rst create mode 100644 Documentation/kunit/faq.rst create mode 100644 Documentation/kunit/index.rst create mode 100644 Documentation/kunit/start.rst create mode 100644 Documentation/kunit/usage.rst
Documentation/index.rst +1 -0
@@ -66,6 +66,7 @@ merged much easier. kernel-hacking/index trace/index maintainer/index + kunit/index Kernel API documentation ------------------------
Documentation/kunit/api/class-and-function-mocking.rst new file +68 -0
68 lines not on this page · raw message
Documentation/kunit/api/index.rst new file +21 -0
@@ -0,0 +1,21 @@ +.. SPDX-License-Identifier: GPL-2.0 + +============= +API Reference +============= +.. toctree:: + + test + class-and-function-mocking + platform-mocking + +This section documents the KUnit kernel testing API. It is divided into 3 +sections: + +================================= ============================================== +:doc:`test` documents all of the standard testing API + excluding mocking or mocking related features. +:doc:`class-and-function-mocking` documents class and function mocking features. +:doc:`platform-mocking` documents mocking libraries that mock out + platform specific features. +================================= ==============================================
Documentation/kunit/api/platform-mocking.rst new file +36 -0
@@ -0,0 +1,36 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================ +Platform Mocking +================ + +This file documents *platform mocking*, mocking libraries that mock out platform +specific features and aid in writing mocks for platform drivers and other low +level kernel code. + +Enable Platform Mocking +----------------------- +``CONFIG_PLATFORM_MOCK`` needs to be added to the .config (or kunitconfig) to +enable platform mocking. + +Mocked IO Functions +------------------- +The following functions have been mocked for convenience. + +.. code-block:: c + + u8 readb(const volatile void __iomem *); + u16 readw(const volatile void __iomem *); + u32 readl(const volatile void __iomem *); + u64 readq(const volatile void __iomem *); + void writeb(u8, const volatile void __iomem *); + void writew(u16, const volatile void __iomem *); + void writel(u32, const volatile void __iomem *); + void writeq(u64, const volatile void __iomem *); + +.. note:: These functions do not have any non-mocked behaviour in UML. + +API +--- +.. kernel-doc:: include/linux/platform_device_mock.h + :internal:
Documentation/kunit/api/test.rst new file +15 -0
@@ -0,0 +1,15 @@ +.. 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/test-stream.h + :internal: +
Documentation/kunit/faq.rst new file +46 -0
46 lines not on this page · raw message
Documentation/kunit/index.rst new file +84 -0
84 lines not on this page · raw message
Documentation/kunit/start.rst new file +185 -0
185 lines not on this page · raw message
Documentation/kunit/usage.rst new file +876 -0
876 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 28/31 kunit: added Python libraries for handing KUnit config and kernel
In reply to Brendan Higginskunit_config.py:
- parses .config and Kconfig files
kunit_kernel.py: provides helper functions to:
- configure the kernel using kunitconfig
- builds the kernel with the correct architecture
- provides function to invoke the kernel and stream the output back
The kernel invocation is wrapped in a subprocess call within the module because regular invocation of the kernel (./linux) may modify TTY settings.
--- tools/testing/kunit/.gitignore | 3 + tools/testing/kunit/kunit_config.py | 60 ++++++++++++++ tools/testing/kunit/kunit_kernel.py | 123 ++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+) create mode 100644 tools/testing/kunit/.gitignore create mode 100644 tools/testing/kunit/kunit_config.py create mode 100644 tools/testing/kunit/kunit_kernel.py
tools/testing/kunit/.gitignore new file +3 -0
@@ -0,0 +1,3 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod]
tools/testing/kunit/kunit_config.py new file +60 -0
60 lines not on this page · raw message
tools/testing/kunit/kunit_kernel.py new file +123 -0
123 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 29/31 kunit: added KUnit wrapper script and simple output parser
In reply to Brendan HigginsThe KUnit wrapper script interfaces with the two modules (kunit_config.py and kunit_kernel.py) and provides a command line interface for running KUnit tests. This interface allows the caller to specify options like test timeouts. The script handles configuring, building and running the kernel and tests.
The output parser (kunit_parser.py) simply strips out all the output from the kernel that is outputted as part of it's initialization sequence. This ensures that only the output from KUnit is displayed on the screen.
A full version of the output is written to test.log, or can be seen by passing --raw_output to the wrapper script.
--- tools/testing/kunit/kunit.py | 40 +++++++++++++++++++++++++++++ tools/testing/kunit/kunit_kernel.py | 3 +-- tools/testing/kunit/kunit_parser.py | 24 +++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) create mode 100755 tools/testing/kunit/kunit.py create mode 100644 tools/testing/kunit/kunit_parser.py
tools/testing/kunit/kunit.py new file +40 -0
@@ -0,0 +1,40 @@ +#!/usr/bin/python3 +# SPDX-License-Identifier: GPL-2.0 + +# A thin wrapper on top of the KUnit Kernel + +import argparse +import sys +import os + +import kunit_config +import kunit_kernel +import kunit_parser + +parser = argparse.ArgumentParser(description='Runs KUnit tests.') + +parser.add_argument('--raw_output', help='don\'t format output from kernel', + action='store_true') + +parser.add_argument('--timeout', help='maximum number of seconds to allow for ' + 'all tests to run. This does not include time taken to ' + 'build the tests.', type=int, default=300, + metavar='timeout') + +cli_args = parser.parse_args() +linux = kunit_kernel.LinuxSourceTree() + +success = linux.build_reconfig() +if not success: + quit() + +print('Building KUnit Kernel ...') +success = linux.build_um_kernel() +if not success: + quit() + +print('Starting KUnit Kernel ...') +if cli_args.raw_output: + kunit_parser.raw_output(linux.run_kernel(timeout=cli_args.timeout)) +else: + kunit_parser.parse_run_tests(linux.run_kernel(timeout=cli_args.timeout))
tools/testing/kunit/kunit_kernel.py +1 -2
@@ -113,8 +113,7 @@ class LinuxSourceTree(object): return False return True - def run_kernel(self, args=[]): - timeout = None + def run_kernel(self, args=[], timeout=None): args.extend(['mem=256M']) process = self._ops.linux_bin(args, timeout) with open('test.log', 'w') as f:
tools/testing/kunit/kunit_parser.py new file +24 -0
@@ -0,0 +1,24 @@ +# SPDX-License-Identifier: GPL-2.0 + +import re + +kunit_start_re = re.compile('console .* enabled') +kunit_end_re = re.compile('List of all partitions:') + +def isolate_kunit_output(kernel_output): + started = False + for line in kernel_output: + if kunit_start_re.match(line): + started = True + elif kunit_end_re.match(line): + break + elif started: + yield line + +def raw_output(kernel_output): + for line in kernel_output: + print(line) + +def parse_run_tests(kernel_output): + for output in isolate_kunit_output(kernel_output): + print(output)
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 30/31 kunit.py: improved output from python wrapper
In reply to Brendan Higgins- added colors to displayed output
- added timing and summary
--- tools/testing/kunit/kunit.py | 20 ++++++- tools/testing/kunit/kunit_parser.py | 93 ++++++++++++++++++++++++++++- 2 files changed, 109 insertions(+), 4 deletions(-)
tools/testing/kunit/kunit.py +18 -2
@@ -6,6 +6,7 @@ import argparse import sys import os +import time import kunit_config import kunit_kernel
@@ -24,17 +25,32 @@ parser.add_argument('--timeout', help='maximum number of seconds to allow for ' cli_args = parser.parse_args() linux = kunit_kernel.LinuxSourceTree() +config_start = time.time() success = linux.build_reconfig() +config_end = time.time() if not success: quit() -print('Building KUnit Kernel ...') +kunit_parser.print_with_timestamp('Building KUnit Kernel ...') + +build_start = time.time() success = linux.build_um_kernel() +build_end = time.time() if not success: quit() -print('Starting KUnit Kernel ...') +kunit_parser.print_with_timestamp('Starting KUnit Kernel ...') +test_start = time.time() + if cli_args.raw_output: kunit_parser.raw_output(linux.run_kernel(timeout=cli_args.timeout)) else: kunit_parser.parse_run_tests(linux.run_kernel(timeout=cli_args.timeout)) + +test_end = time.time() + +kunit_parser.print_with_timestamp(( + "Elapsed time: %.3fs total, %.3fs configuring, %.3fs " + + "building, %.3fs running.\n") % (test_end - config_start, + config_end - config_start, build_end - build_start, + test_end - test_start))
tools/testing/kunit/kunit_parser.py +91 -2
103 lines not on this page · raw message
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
RFC 31/31 MAINTAINERS: add entry for KUnit the unit testing framework
In reply to Brendan HigginsAdded myself as maintainer of KUnit, the Linux kernel's unit testing framework.
--- MAINTAINERS | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
MAINTAINERS +15 -0
@@ -7801,6 +7801,21 @@ S: Maintained F: tools/testing/selftests/ F: Documentation/dev-tools/kselftest* +KERNEL UNIT TESTING FRAMEWORK (KUnit) +M: Brendan Higgins <brendanhiggins at google.com> +L: kunit-dev at googlegroups.com +W: https://google.github.io/kunit-docs/third_party/kernel/docs/ +S: Maintained +F: Documentation/kunit/ +F: arch/um/include/asm/io-mock-shared.h +F: arch/um/include/asm/io-mock.h +F: arch/um/kernel/io-mock.c +F: drivers/base/platform-mock.c +F: include/linux/platform_device_mock.h +F: include/kunit/ +F: kunit/ +F: tools/testing/kunit/ + KERNEL USERMODE HELPER M: "Luis R. Rodriguez" <mcgrof at kernel.org> L: linux-kernel at vger.kernel.org
Signature · 1 line
2.19.1.331.ge82ca0e54c-goog
Joe Perches
maintainerRe: [RFC v1 12/31] checkpatch: added support for struct MOCK(foo) syntax
In reply to Brendan HigginsQuoted 2 lines · Brendan Higgins
This adds struct MOCK(foo) as a NonptrType so that it is recognized correctly in declarations.
I think this commit message is lacking context.
Quoted 20 lines
Signed-off-by Brendan Higgins <brendanhiggins at google.com>--- scripts/checkpatch.pl | 4 ++++ 1 file changed, 4 insertions(+)scripts/checkpatch.pl +4
-0@@ -745,6 +745,10 @@ sub build_types { (?: (?:typeof|__typeof__)\s*\([^\)]*\)| (?:$typeTypedefs\b)| + # Matching a \b breaks struct MOCK(foo) syntax, + # so we need to have it not lumped in with the + # types in @typeList. + (?:struct\s+MOCK\($Ident\))| (?:${all}\b) ) (?:\s+$Modifier|\s+const)*
Re: [RFC v1 12/31] checkpatch: added support for struct MOCK(foo) syntax
Quoted 6 lines · Joe Perches
Quoted 2 lines · Brendan Higgins
This adds struct MOCK(foo) as a NonptrType so that it is recognized correctly in declarations.
I think this commit message is lacking context.
Oh sorry, you are right. We added macros for generating mocks from types, so we decided to name the generated mock types struct MOCK(foo) (where the base type is struct foo); this commit makes checkpatch not complain at this new syntax.
Quoted 36 lines · Brendan Higgins
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 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.
## 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.
Quoted 6 lines
## 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:
https://google.github.io/kunit-docs/third_party/kernel/docs/
We've started our own unit test framework (very early, and not any real infrastructure yet) under drivers/gpu/drm/selftests. They're all meant to test functions and small pieces of functionality of our libraries in isolation, without any need for a real (or virtual) gpu driver. It kinda integrates both with kselftests and with our graphics test suite, but directly running tests using UML as part of the build process sounds much, much better. Having proper and standardized infrastructure for kernel unit tests sounds terrific.
In other words: I want.
Please keep [email protected] in the loop on future versions.
Cheers, Daniel
Signature · 7 lines
Daniel Vetter Software Engineer, Intel Corporation http://blog.ffwll.ch _______________________________________________ dri-devel mailing list [email protected] https://lists.freedesktop.org/mailman/listinfo/dri-devel
Re: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
In reply to Brendan HigginsHi Brendan,
I very excitedly jumped on these patches to try them out, as this is essentially something I was trying to do a few weeks back.
Quoted 7 lines · Brendan Higgins
Makes minimum number of changes outside of the KUnit directories for KUnit to build and run using UML.
Signed-off-by Brendan Higgins <brendanhiggins at google.com>--- Makefile | 2 +- arch/um/Kconfig.rest | 3 +++
But this file isn't present on v4.19-rc8
It looks like the file is removed at f163977d21a2 ("um: cleanup Kconfig files")
What version have you currently based these patches on? Do you expect to keep a branch somewhere that's easy to pull in?
Please add me to the CC list as an interested party on later versions :-)
It might be of interest to the automated testing mailing list too ? (Tim?)
--
regards
Kieran
Quoted 28 lines
2 files changed, 4 insertions(+), 1 deletion(-)Makefile +1
-1@@ -944,7 +944,7 @@ endif 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) \arch/um/Kconfig.rest +3
-0@@ -1,4 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 + +source "kunit/Kconfig" + source "init/Kconfig" source "kernel/Kconfig.freezer"
Re: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
Quoted 15 lines · Kieran Bingham
Hi Brendan,
I very excitedly jumped on these patches to try them out, as this is essentially something I was trying to do a few weeks back.
Quoted 7 lines · Brendan Higgins
Makes minimum number of changes outside of the KUnit directories for KUnit to build and run using UML.
Signed-off-by Brendan Higgins <brendanhiggins at google.com>--- Makefile | 2 +- arch/um/Kconfig.rest | 3 +++
Quoted 4 lines
But this file isn't present on v4.19-rc8
It looks like the file is removed at
f163977d21a2("um: cleanupKconfigfiles")
Whoops.
Quoted 2 lines
What version have you currently based these patches on?
This patch set is based on 4.18, but I have versions for 4.4, 4.9, 4.14, 4.16, and 4.17.
I will rebase this patch set to 4.19-rc8 and send it out shortly.
Quoted 1 line
Do you expect to keep a branch somewhere that's easy to pull in?
I have one here: https://kunit-review.googlesource.com/c/linux/+/1030
(you can check it out with git fetch
https://kunit.googlesource.com/linux refs/changes/30/1030/4 && git checkout FETCH_HEAD)
Quoted 2 lines
Please add me to the CC list as an interested party on later versions :-)
Will do.
Quoted 5 lines
-----Original Message-----
From: Brendan HigginsThis patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.
I'm interested in this, and think the kernel might benefit from this, but I have lots of questions.
Quoted 4 lines
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 and does not require tests to be written in userspace running on a host kernel.
This is stated here and a few places in the documentation. Just to clarify, KUnit works by compiling the unit under test, along with the test code itself, and then runs it on the machine where the compilation took place? Is this right? How does cross-compiling enter into the equation? If not what I described, then what exactly is happening?
Sorry - I haven't had time to look through the patches in detail.
Another issue is, what requirements does this place on the tested code? Is extra instrumentation required? I didn't see any, but I didn't look exhaustively at the code.
Are all unit tests stored separately from the unit-under-test, or are they expected to be in the same directory? Who is expected to maintain the unit tests? How often are they expected to change? (Would it be every time the unit-under-test changed?)
Does the test code require the same level of expertise to write and maintain as the unit-under-test code? That is, could this be a new opportunity for additional developers (especially relative newcomers) to add value to the kernel by writing and maintaining test code, or does this add to the already large burden of code maintenance for our existing maintainers.
Thanks,
-- Tim
...
RE: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
In reply to Kieran BinghamQuoted 24 lines
-----Original Message-----
From: Kieran BinghamHi Brendan,
I very excitedly jumped on these patches to try them out, as this is essentially something I was trying to do a few weeks back.
Quoted 7 lines · Brendan Higgins
Makes minimum number of changes outside of the KUnit directories for KUnit to build and run using UML.
Signed-off-by Brendan Higgins <brendanhiggins at google.com>--- Makefile | 2 +- arch/um/Kconfig.rest | 3 +++But this file isn't present on v4.19-rc8
It looks like the file is removed at
f163977d21a2("um: cleanupKconfigfiles")
Quoted 6 lines
What version have you currently based these patches on? Do you expect to keep a branch somewhere that's easy to pull in?
Please add me to the CC list as an interested party on later versions :-)
It might be of interest to the automated testing mailing list too ? (Tim?)
I think this is interesting to groups doing automated testing of the kernel
(including myself) as another set of tests to run. Right now I don't see it as having any special attributes related to automation. But I could be wrong.
-- Tim
Quoted 12 lines · Brendan Higgins
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 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 4 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 very much like this. The DT code too has unit tests with our own, simple infrastructure. They too can run under UML (and every other arch).
Rob
Re: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
In reply to [email protected]Quoted 6 lines · On Wed, Oct 17, 2018 at 10:52 AM <Tim.Bird at sony.com> wrote:
Quoted 2 lines
It might be of interest to the automated testing mailing list too ? (Tim?)
I think this is interesting to groups doing automated testing of the kernel
(including myself) as another set of tests to run. Right now I don't see it as having any special attributes related to automation. But I could be wrong.
Pardon my ignorance, but by automated testing you mean a CI server with presubmits, nightlys, and things of the sort?
If that's the case, KUnit could be helpful because of the low resource cost in running them and the speed at which they run. There are some other features we would like to add which would help with that goal as well like test isolation. We actually have a presubmit server internally for running KUnit tests that can usually respond to patches with test results within a couple minutes. Would something like that be interesting?
RE: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
Quoted 9 lines
-----Original Message-----
From: Brendan HigginsQuoted 3 lines · On Wed, Oct 17, 2018@10:52 AM <[email protected]> wrote:
Quoted 2 lines
It might be of interest to the automated testing mailing list too ? (Tim?)
Quoted 7 lines
Quoted 3 lines
I think this is interesting to groups doing automated testing of the kernel
(including myself) as another set of tests to run. Right now I don't see it as having any special attributes related to automation. But I could bewrong.
Pardon my ignorance, but by automated testing you mean a CI server with presubmits, nightlys, and things of the sort?
Yes.
Quoted 3 lines
If that's the case, KUnit could be helpful because of the low resource cost in running them and the speed at which they run.
True.
Quoted 6 lines
There are some
other features we would like to add which would help with that goal as well like test isolation. We actually have a presubmit server internally for running KUnit tests that can usually respond to patches with test results within a couple minutes. Would something like that be interesting?
I think the code and architecture of the software that handles presubmit, mail-list scanning, notifications, etc. would be of interest. But KUnit features themselves (macro definitions, mocking vs. faking, etc.) would not.
I only say that in the context of CC-ing the automated testing list on the patch set. Of course the KUnit features are interesting by themselves for testers doing unit testing.
-- Tim
Quoted 10 lines · On Wed, Oct 17, 2018@10:49 AM <[email protected]> wrote:
Quoted 6 lines
-----Original Message-----
From: Brendan HigginsThis patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.
I'm interested in this, and think the kernel might benefit from this, but I have lots of questions.
Awesome!
Quoted 6 lines
Quoted 4 lines
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 and does not require tests to be written in userspace running on a host kernel.
Quoted 6 lines
This is stated here and a few places in the documentation. Just to clarify, KUnit works by compiling the unit under test, along with the test code itself, and then runs it on the machine where the compilation took place? Is this right? How does cross-compiling enter into the equation? If not what I described, then what exactly is happening?
Yep, that's exactly right!
The test and the code under test are linked together in the same binary and are compiled under Kbuild. Right now I am linking everything into a UML kernel, but I would ultimately like to make tests compile into completely independent test binaries. So each test file would get compiled into its own test binary and would link against only the code needed to run the test, but we are a bit of a ways off from that.
For now, tests compile as part of a UML kernel and a test script boots the UML kernel, tests run as part of the boot process, and the script extracts test results and reports them.
I intentionally made it so the KUnit test libraries could be relatively easily ported to other architectures, but in the long term, tests that depend on being built into a real kernel that boots on real hardware would be a lot more difficult to maintain and we would never be able to provide the kind of resources and infrastructure as we could for tests that run as normal user space binaries.
Does that answer your question?
Quoted 6 lines
Sorry - I haven't had time to look through the patches in detail.
Another issue is, what requirements does this place on the tested code? Is extra instrumentation required? I didn't see any, but I didn't look exhaustively at the code.
Nope, no special instrumentation. As long as the code under tests can be compiled under COMPILE_TEST for the host architecture, you should be able to use KUnit.
Quoted 5 lines
Are all unit tests stored separately from the unit-under-test, or are they expected to be in the same directory? Who is expected to maintain the unit tests? How often are they expected to change? (Would it be every time the unit-under-test changed?)
Tests are in the same directory as the code under test. For example, if I have a driver drivers/i2c/busses/i2c-aspeed.c, I would write a test drivers/i2c/busses/i2c-aspeed-test.c (that's my opinion anyway).
Unit tests should be the responsibility of the person who is responsible for the code. So one way to do this would be that unit tests should be the responsibility of the maintainer who would in turn require that new tests are written for any new code added, and that all tests should pass for every patch sent for review.
A well written unit test tests public interfaces (by public I just mean functions exported outside of a .c file, so non-static functions and functions which are shared as a member of a struct) so a unit test should change at a slower rate than the code under test, but you would likely have to change the test anytime the public interface changes (intended behavior changes, function signature changes, new public feature added, etc). More succinctly, if the contract that your code provide changes your test should probably change, if the contract doesn't change, your test probably shouldn't change. Does that make sense?
Quoted 6 lines
Does the test code require the same level of expertise to write and maintain as the unit-under-test code? That is, could this be a new opportunity for additional developers (especially relative newcomers) to add value to the kernel by writing and maintaining test code, or does this add to the already large burden of code maintenance for our existing maintainers.
So a couple things, in order to write a unit test, the person who writes the test must understand what the code they are testing is supposed to do. To some extent that will probably require someone with some expertise to ensure that the test makes sense, and indeed a change that breaks a test should be accompanied by a update to the test.
On the other hand, I think understanding what pre-existing code does and is supposed to do is much easier than writing new code from scratch, and probably doesn't require too much expertise. I actually did a bit of an experiment internally on this: I had some people with no prior knowledge of the kernel write some tests for existing kernel code and they were able to do it with only minimal guidance. I was so happy with the result that I was already thinking that it might have some potential for onboarding newcomers.
Now, how much burden does this add to maintainers? As someone who pretty regularly reviews code that come in with unit tests and code that comes in without unit tests. I find it much easier to review code that comes in with unit tests. I would actually say that from the standpoint of being an owner of a code base, unit tests actually reduce the amount of work I have to do overall. Code with unit tests is usually cleaner, the tests tell me exactly what the code is supposed to do, and I can run the tests (or ideally have an automated service run the tests) that tell me that the code actually does what the tests say it should. Even when it comes to writing code I find that writing code with unit tests ends up saving me time overall.
Re: [RFC v1 26/31] arch: um: added stubs for mock iomem for KUnit
In reply to Brendan HigginsQuoted 25 lines · Brendan Higgins
This mocks out some iomem functions (functions like readl and writel), for mocking hardware interfaces.
Signed-off-by Brendan Higgins <brendanhiggins at google.com>--- arch/um/Kconfig.common | 8 +++++- arch/um/Kconfig.um | 5 ++++ arch/um/include/asm/Kbuild | 1 - arch/um/include/asm/io-mock-shared.h | 33 +++++++++++++++++++++ arch/um/include/asm/io-mock.h | 43 ++++++++++++++++++++++++++++ arch/um/include/asm/io.h | 8 ++++++ arch/um/kernel/Makefile | 1 + arch/um/kernel/io-mock.c | 40 ++++++++++++++++++++++++++ kunit/Kconfig | 1 + 9 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 arch/um/include/asm/io-mock-shared.h create mode 100644 arch/um/include/asm/io-mock.h create mode 100644 arch/um/kernel/io-mock.carch/um/Kconfig.common +0
-0
arch/um/Kconfig.common config MMU · line 25
Quoted 8 lines
arch/um/Kconfig.common +4
-1@@ -19,7 +19,13 @@ config MMU default y config NO_IOMEM - def_bool y + bool + default y if !KUNIT + +config HAS_IOMEM
HAS_IOMEM is essentially a disable flag for lots of drivers on UML. Ignoring drivers, it doesn't really control a significant amount of code (albeit small amount of code you need for this series). As a driver disable, it does a poor job as lots of drivers aren't MMIO and aren't disabled. I think we should decouple these 2 things. Perhaps get rid of the driver disable part altogether. We already do 'depends on ARCH_FOO || COMPILE_TEST' for lots of drivers.
Also, I wouldn't be surprised if turning on HAS_IOMEM causes UML randconfig failures. Arnd does lots of randconfig testing and might be willing to help check.
Quoted 37 lines
arch/um/Kconfig.common +3
-0+ bool "Turns on fake IOMEM support for KUnit" + depends on KUNIT + select MOCK_IOMEM config ISA boolarch/um/Kconfig.um +5
-0@@ -122,3 +122,8 @@ config SECCOMP defined by each seccomp mode. If unsure, say Y. + +config PLATFORM_MOCK + bool "Enable a mock architecture used for unit testing." + depends on KUNIT && OF + default narch/um/include/asm/Kbuild +0
-1@@ -12,7 +12,6 @@ generic-y += ftrace.h generic-y += futex.h generic-y += hardirq.h generic-y += hw_irq.h -generic-y += io.h generic-y += irq_regs.h generic-y += irq_work.h generic-y += kdebug.harch/um/include/asm/io-mock-shared.h new file +0
-0
arch/um/include/asm/io-mock-shared.h line 6
Quoted 6 lines
arch/um/include/asm/io-mock-shared.h new file +6
-0@@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_UM_IO_MOCK_SHARED_H +#define _ASM_UM_IO_MOCK_SHARED_H + +#define readb readb +u8 readb (const volatile void __iomem *);
What about all the other flavors of MMIO accessors like __raw_readb, readb_relaxed, etc.? readX/writeX is intended for PCI based drivers which doesn't seem to be what you are targeting in this series.
I think it would be good if this capability was not just on UML. I could also imagine wanting to run tests on real h/w. Perhaps you just want to log and/or check i/o accesses. Or you need some dependencies in place rather than trying to fake everything (clocks, gpios, pinmux, irq, etc.). That being said, I'm not trying to add a bunch of things for you to do. Though maybe it makes sense to split this series some. How many of the patches are needed to convert the DT unittests for example?
Rob
Re: [RFC v1 06/31] arch: um: enabled running kunit from User Mode Linux
In reply to [email protected]On Wed, Oct 17, 2018 at 2:18 PM <Tim.Bird at sony.com> wrote:
<snip>
Quoted 6 lines
Quoted 6 lines
There are some
other features we would like to add which would help with that goal as well like test isolation. We actually have a presubmit server internally for running KUnit tests that can usually respond to patches with test results within a couple minutes. Would something like that be interesting?
Quoted 6 lines
I think the code and architecture of the software that handles presubmit, mail-list scanning, notifications, etc. would be of interest. But KUnit features themselves (macro definitions, mocking vs. faking, etc.) would not.
I only say that in the context of CC-ing the automated testing list on the patch set. Of course the KUnit features are interesting by themselves for testers doing unit testing.
Fair enough. Well, we will share what we have in that regard, but that belongs on a separate thread.
BTW, what mailing list is that? I am also guessing your code isn't in the kernel repo; where is it?
Re: [RFC v1 22/31] kunit: mock: add the concept of spyable functions
In reply to Brendan HigginsQuoted 6 lines · Brendan Higgins
Adds the concept of spying like in Mockito
(http://static.javadoc.io/org.mockito/mockito-core/2.20.0/org/mockito/Mockito.html#spy-T-).
This allows a function declaration to be labled as spyable which allows the function to be mocked *and* to allow the mock to invoke the original function definition.
We can already hook into arbitrary functions ftrace. Wouldn't utilizing that simplify features like this and avoid having to touch existing code for testing? Not sure what it would take to enable ftrace on UML. It is at least partially compiler dependent.
Rob
Randy Dunlap
reviewerQuoted 2 lines · Brendan Higgins
This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.
Hi,
Just a general comment:
Documentation/process/submitting-patches.rst says:
<<Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behaviour.>>
That also means saying things like:
... test: add
instead of ... test: added
and "enable" instead of "enabled"
and "improve" instead of "improved"
and "implement" instead of "implemented".
thanks.
Signature · 1 line
~Randy
Re: [RFC v1 26/31] arch: um: added stubs for mock iomem for KUnit
In reply to Rob HerringOn Wed, Oct 17, 2018@3:28 PM Rob Herring <[email protected]> wrote:
<snip>
Quoted 7 lines
Quoted 7 lines
arch/um/Kconfig.common +0
-0@@ -19,7 +19,13 @@ config MMU default y
Quoted 15 lines
arch/um/Kconfig.common config MMU · line 25
Quoted 6 lines
arch/um/Kconfig.common +4
-1config NO_IOMEM - def_bool y + bool + default y if !KUNIT + +config HAS_IOMEM
HAS_IOMEMis essentially a disable flag for lots of drivers on UML. Ignoring drivers, it doesn't really control a significant amount of code (albeit small amount of code you need for this series). As a driver disable, it does a poor job as lots of drivers aren't MMIO and aren't disabled. I think we should decouple these 2 things. Perhaps get rid of the driver disable part altogether. We already do 'depends onARCH_FOO||COMPILE_TEST' for lots of drivers.
I think that makes sense. Any code that can build should be able to build under KUnit, but we probably want to turn that on on a per driver basis as we write tests for them.
Quoted 4 lines
Also, I wouldn't be surprised if turning on
HAS_IOMEMcauses UML randconfig failures. Arnd does lots of randconfig testing and might be willing to help check.
It almost certainly would fail randconfig. As you point out below, I don't implement everything that's required, just enough to show off KUnit in a couple examples.
Quoted 39 lines
Quoted 39 lines
arch/um/Kconfig.common +3
-0+ bool "Turns on fake IOMEM support for KUnit" + depends on KUNIT + select MOCK_IOMEM config ISA boolarch/um/Kconfig.um +5
-0@@ -122,3 +122,8 @@ config SECCOMP defined by each seccomp mode. If unsure, say Y. + +config PLATFORM_MOCK + bool "Enable a mock architecture used for unit testing." + depends on KUNIT && OF + default narch/um/include/asm/Kbuild +0
-1@@ -12,7 +12,6 @@ generic-y += ftrace.h generic-y += futex.h generic-y += hardirq.h generic-y += hw_irq.h -generic-y += io.h generic-y += irq_regs.h generic-y += irq_work.h generic-y += kdebug.harch/um/include/asm/io-mock-shared.h new file +2
-0@@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_UM_IO_MOCK_SHARED_H
Quoted 9 lines
arch/um/include/asm/io-mock-shared.h line 6
Quoted 4 lines
arch/um/include/asm/io-mock-shared.h new file +4
-0+#define _ASM_UM_IO_MOCK_SHARED_H + +#define readb readb +u8 readb (const volatile void __iomem *);What about all the other flavors of MMIO accessors like
__raw_readb,readb_relaxed, etc.? readX/writeX is intended for PCI based drivers which doesn't seem to be what you are targeting in this series.
Those need to be done too. I just mostly wanted to illustrate that it can be done, and what is needed to support mocking MMIO. I wasn't sure how controversial my approach would be, so I didn't want to put any more work than was necessary for illustration without getting some feedback.
Quoted 2 lines
I think it would be good if this capability was not just on UML. I could also imagine wanting to run tests on real h/w. Perhaps you just
I think that's reasonable.
Quoted 4 lines
want to log and/or check i/o accesses. Or you need some dependencies in place rather than trying to fake everything (clocks, gpios, pinmux, irq, etc.). That being said, I'm not trying to add a bunch of things for you to do. Though maybe it makes sense to split this series some.
Almost definitely. I figured this patchset, as is, is a good illustration of what I am trying to do, what is possible, and the kind of work that is necessary to get there. If people like what I am doing and want more of this type of thing, I think focussing on getting base support in and then working on features separately is the way to go.
Quoted 2 lines
How many of the patches are needed to convert the DT unittests for example?
At first glance, just you probably only need the stuff in the first 9 patches for that. You don't appear to be doing any IO of any sort, so you don't need this stuff. You appear to depend only on some fake data; everything else seems pretty self contained, so you don't need any of the mocking support for that. So if I understand correctly you just need the base support needed for bare bones unit tests, all that stuff is in the first 9 patches.
Cheers
Re: [RFC v1 22/31] kunit: mock: add the concept of spyable functions
In reply to Rob HerringQuoted 10 lines · Rob Herring
Quoted 6 lines · Brendan Higgins
Adds the concept of spying like in Mockito
(http://static.javadoc.io/org.mockito/mockito-core/2.20.0/org/mockito/Mockito.html#spy-T-).
This allows a function declaration to be labled as spyable which allows the function to be mocked *and* to allow the mock to invoke the original function definition.
Quoted 4 lines
We can already hook into arbitrary functions ftrace. Wouldn't utilizing that simplify features like this and avoid having to touch existing code for testing? Not sure what it would take to enable ftrace on UML. It is at least partially compiler dependent.
Regardless of what we end up doing, this definitely needs more work.
After looking at include/linux/ftrace.h, it does look feasible to use ftrace for spying. I totally agree that we don't want to reinvent this wheel if we can avoid it, but I have no idea what getting it working on UML would look like. Dependence on compiler features could be an
issue: pretty much anyone who can build the kernel should be able to run our tests.
Quoted 7 lines · Randy Dunlap
Quoted 2 lines · Brendan Higgins
This patch set proposes KUnit, a lightweight unit testing and mocking framework for the Linux kernel.
Hi,
Quoted 8 lines
Just a general comment:
Documentation/process/submitting-patches.rstsays:
<<Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behaviour.>>
Thanks! I will fix this in the next revision.
Quoted 37 lines · Brendan Higgins
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 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.
## 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.
Quoted 6 lines
## 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:
https://google.github.io/kunit-docs/third_party/kernel/docs/
Nice! I've been using mocking techniques in kernel code for the libnvdimm test infrastructure in tools/testing/nvdimm/. It's part unit test infrastructure, part emulation, and I've always had the feeling it's all a bit too adhoc. I'm going to take a look and see what can be converted to kunit. Please include linux-nvdimm at lists.01.org on future postings.
I'll shamelessly plug my lwn article about unit testing
https://lwn.net/Articles/654071/ because it's always good to find fellow co-travelers to compare notes and advocate for more test oriented kernel development.
On Wed, Oct 17, 2018@8:55 PM Dan Williams <[email protected]> wrote:
<snip>
Quoted 7 lines
Quoted 6 lines
## 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:
https://google.github.io/kunit-docs/third_party/kernel/docs/
Quoted 6 lines
Nice! I've been using mocking techniques in kernel code for the libnvdimm test infrastructure in
tools/testing/nvdimm/. It's part unit test infrastructure, part emulation, and I've always had the feeling it's all a bit too adhoc. I'm going to take a look and see what can be converted to kunit. Please include linux-nvdimm at lists.01.org on future postings.
Great to hear!
Interesting, is this kind of like the nfsim stuff?
Quoted 5 lines
I'll shamelessly plug my lwn article about unit testing
https://lwn.net/Articles/654071/ because it's always good to find fellow co-travelers to compare notes and advocate for more test oriented kernel development.
Most definitely! I will take a look, and be in touch.
Cheers!