From patchwork Thu Feb 14 21:37:13 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813853 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 01A5A6C2 for ; Thu, 14 Feb 2019 21:38:32 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id E213D2E955 for ; Thu, 14 Feb 2019 21:38:31 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id D57632EB15; Thu, 14 Feb 2019 21:38:31 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 207932E955 for ; Thu, 14 Feb 2019 21:38:31 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 07016208AE2AE; Thu, 14 Feb 2019 13:38:31 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::64a; helo=mail-pl1-x64a.google.com; envelope-from=31n9lxa4kdbuwcz8yv8231138d19916z.x97638fi-8gy37763ded.lm.9c1@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-pl1-x64a.google.com (mail-pl1-x64a.google.com [IPv6:2607:f8b0:4864:20::64a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id D12DE208AE2A5 for ; Thu, 14 Feb 2019 13:38:29 -0800 (PST) Received: by mail-pl1-x64a.google.com with SMTP id w17so5223583plp.23 for ; Thu, 14 Feb 2019 13:38:29 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=SoRE8+uYlb20xlX661s+vuA7DD7As2RVdTcIlioYiq8=; b=rgeDg8zsoW5bbKgyPerCGY+hb3Hw/7MfO37JyT/Z3P5n9oEfPf6Xhp3pTSm2R5DF8/ 0jLEn1oIz7pVEOHPtRdRsZexmyBIwhtktaQScQ2sPAA1nXGSLt3/wXjzeJyI445PVGZW /e78RjS5NAkgwxRMhhIrFEMWjxSlTDbB8/ZJEk1HN1d9RxTuH1lJHD9vPvDU+l7ZSzJo PgP+YtiFv4y46xb1zO5NQpjNnfTB/dp46YP24QEdq/kFzDRaOhG6P1ztFuW7Nc2rnbTL ixDeLcJ3Dw2mWfTBAKzAg8VZ+U9lQMOyZPWv5KcU1xYlLRqz1Wzf996QIau92i8bpxyE rLkg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=SoRE8+uYlb20xlX661s+vuA7DD7As2RVdTcIlioYiq8=; b=b8iJndQlSWViy8MdxZgmJpWWDJAqucK0pFvxCLhxz8NvBivva+Hx+g87d/SYD8REa/ 4Oodm8GgUj/sTEbR/p2Xbl2Xc7w6isPXIn9KU+Nn3sLHiye68uboOvMb9yHHMDGHRhD1 b5XHzz5mG10sTpOsjhc/LLd8Cw8z1XOEjeQPdKtwq/zm6A0R3M4WNFEHG3rr/hQg3RZ0 QaG3d8vf4xQ9MKVVn4xonr8M11UgMnaXWLOnSB3h7+HuSVt/zxk7ktSrgyolnKGPIPpa 9DdZ4A4zKDp/DIxzUlNBephGM1yRBcda/1TIEOn+mK0n6d0TTv8IgZegbTngTUX/JztF GQQw== X-Gm-Message-State: AHQUAuZ1+7RJ8kzCRUkUpL65JDnQKmIDi3bGsVmk0E5sXrcvgjPOv/8E Mc0sSCiFIecN9Uc8iM6PygyI2Fc5tGPxufwPNTF7dg== X-Google-Smtp-Source: AHgI3IYSs+euiTVdtb/Mp7wRiQZbwvIYIP86+kJ1rymlHJOgBolXQmUc+LHgsgTk2Nd+5WnZHVOTjfM73jYEgtGChRqTYw== X-Received: by 2002:a63:6b84:: with SMTP id g126mr2379919pgc.19.1550180308941; Thu, 14 Feb 2019 13:38:28 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:13 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-2-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 01/17] kunit: test: add KUnit test runner core From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add core facilities for defining unit tests; this provides a common way to define test cases, functions that execute code which is under test and determine whether the code under test behaves as expected; this also provides a way to group together related test cases in test suites (here we call them test_modules). Just define test cases and how to execute them for now; setting expectations on code will be defined later. Signed-off-by: Brendan Higgins --- include/kunit/test.h | 165 ++++++++++++++++++++++++++++++++++++++++++ kunit/Kconfig | 16 +++++ kunit/Makefile | 1 + kunit/test.c | 168 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 350 insertions(+) create mode 100644 include/kunit/test.h create mode 100644 kunit/Kconfig create mode 100644 kunit/Makefile create mode 100644 kunit/test.c diff --git a/include/kunit/test.h b/include/kunit/test.h new file mode 100644 index 0000000000000..23c2ebedd6dd9 --- /dev/null +++ b/include/kunit/test.h @@ -0,0 +1,165 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Base unit test (KUnit) API. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#ifndef _KUNIT_TEST_H +#define _KUNIT_TEST_H + +#include +#include + +struct kunit; + +/** + * struct kunit_case - represents an individual test case. + * @run_case: the function representing the actual test case. + * @name: the name of the test case. + * + * A test case is a function with the signature, ``void (*)(struct kunit *)`` + * that makes expectations (see KUNIT_EXPECT_TRUE()) about code under test. Each + * test case is associated with a &struct kunit_module and will be run after the + * module's init function and followed by the module's exit function. + * + * A test case should be static and should only be created with the KUNIT_CASE() + * macro; additionally, every array of test cases should be terminated with an + * empty test case. + * + * Example: + * + * .. code-block:: c + * + * void add_test_basic(struct kunit *test) + * { + * KUNIT_EXPECT_EQ(test, 1, add(1, 0)); + * KUNIT_EXPECT_EQ(test, 2, add(1, 1)); + * KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); + * KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); + * KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); + * } + * + * static struct kunit_case example_test_cases[] = { + * KUNIT_CASE(add_test_basic), + * {}, + * }; + * + */ +struct kunit_case { + void (*run_case)(struct kunit *test); + const char name[256]; + + /* private: internal use only. */ + bool success; +}; + +/** + * KUNIT_CASE - A helper for creating a &struct kunit_case + * @test_name: a reference to a test case function. + * + * Takes a symbol for a function representing a test case and creates a + * &struct kunit_case object from it. See the documentation for + * &struct kunit_case for an example on how to use it. + */ +#define KUNIT_CASE(test_name) { .run_case = test_name, .name = #test_name } + +/** + * struct kunit_module - describes a related collection of &struct kunit_case s. + * @name: the name of the test. Purely informational. + * @init: called before every test case. + * @exit: called after every test case. + * @test_cases: a null terminated array of test cases. + * + * A kunit_module is a collection of related &struct kunit_case s, such that + * @init is called before every test case and @exit is called after every test + * case, similar to the notion of a *test fixture* or a *test class* in other + * unit testing frameworks like JUnit or Googletest. + * + * Every &struct kunit_case must be associated with a kunit_module for KUnit to + * run it. + */ +struct kunit_module { + const char name[256]; + int (*init)(struct kunit *test); + void (*exit)(struct kunit *test); + struct kunit_case *test_cases; +}; + +/** + * struct kunit - represents a running instance of a test. + * @priv: for user to store arbitrary data. Commonly used to pass data created + * in the init function (see &struct kunit_module). + * + * Used to store information about the current context under which the test is + * running. Most of this data is private and should only be accessed indirectly + * via public functions; the one exception is @priv which can be used by the + * test writer to store arbitrary data. + */ +struct kunit { + void *priv; + + /* private: internal use only. */ + const char *name; /* Read only after initialization! */ + spinlock_t lock; /* Gaurds all mutable test state. */ + bool success; /* Protected by lock. */ + void (*vprintk)(const struct kunit *test, + const char *level, + struct va_format *vaf); +}; + +int kunit_init_test(struct kunit *test, const char *name); + +int kunit_run_tests(struct kunit_module *module); + +/** + * module_test() - used to register a &struct kunit_module with KUnit. + * @module: a statically allocated &struct kunit_module. + * + * Registers @module with the test framework. See &struct kunit_module for more + * information. + */ +#define module_test(module) \ + static int module_kunit_init##module(void) \ + { \ + return kunit_run_tests(&module); \ + } \ + late_initcall(module_kunit_init##module) + +void __printf(3, 4) kunit_printk(const char *level, + const struct kunit *test, + const char *fmt, ...); + +/** + * kunit_info() - Prints an INFO level message associated with the current test. + * @test: The test context object. + * @fmt: A printk() style format string. + * + * Prints an info level message associated with the test module being run. Takes + * a variable number of format parameters just like printk(). + */ +#define kunit_info(test, fmt, ...) \ + kunit_printk(KERN_INFO, test, fmt, ##__VA_ARGS__) + +/** + * kunit_warn() - Prints a WARN level message associated with the current test. + * @test: The test context object. + * @fmt: A printk() style format string. + * + * See kunit_info(). + */ +#define kunit_warn(test, fmt, ...) \ + kunit_printk(KERN_WARNING, test, fmt, ##__VA_ARGS__) + +/** + * kunit_err() - Prints an ERROR level message associated with the current test. + * @test: The test context object. + * @fmt: A printk() style format string. + * + * See kunit_info(). + */ +#define kunit_err(test, fmt, ...) \ + kunit_printk(KERN_ERR, test, fmt, ##__VA_ARGS__) + +#endif /* _KUNIT_TEST_H */ diff --git a/kunit/Kconfig b/kunit/Kconfig new file mode 100644 index 0000000000000..64480092b2c24 --- /dev/null +++ b/kunit/Kconfig @@ -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 diff --git a/kunit/Makefile b/kunit/Makefile new file mode 100644 index 0000000000000..5efdc4dea2c08 --- /dev/null +++ b/kunit/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_KUNIT) += test.o diff --git a/kunit/test.c b/kunit/test.c new file mode 100644 index 0000000000000..0b4396f92086e --- /dev/null +++ b/kunit/test.c @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Base unit test (KUnit) API. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#include +#include +#include +#include + +static bool kunit_get_success(struct kunit *test) +{ + unsigned long flags; + bool success; + + spin_lock_irqsave(&test->lock, flags); + success = test->success; + spin_unlock_irqrestore(&test->lock, flags); + + return success; +} + +static void kunit_set_success(struct kunit *test, bool success) +{ + unsigned long flags; + + spin_lock_irqsave(&test->lock, flags); + test->success = success; + spin_unlock_irqrestore(&test->lock, flags); +} + +static int kunit_vprintk_emit(const struct kunit *test, + int level, + const char *fmt, + va_list args) +{ + return vprintk_emit(0, level, NULL, 0, fmt, args); +} + +static int kunit_printk_emit(const struct kunit *test, + int level, + const char *fmt, ...) +{ + va_list args; + int ret; + + va_start(args, fmt); + ret = kunit_vprintk_emit(test, level, fmt, args); + va_end(args); + + return ret; +} + +static void kunit_vprintk(const struct kunit *test, + const char *level, + struct va_format *vaf) +{ + kunit_printk_emit(test, + level[1] - '0', + "kunit %s: %pV", test->name, vaf); +} + +int kunit_init_test(struct kunit *test, const char *name) +{ + spin_lock_init(&test->lock); + test->name = name; + test->vprintk = kunit_vprintk; + + return 0; +} + +/* + * Initializes and runs test case. Does not clean up or do post validations. + */ +static void kunit_run_case_internal(struct kunit *test, + struct kunit_module *module, + struct kunit_case *test_case) +{ + int ret; + + if (module->init) { + ret = module->init(test); + if (ret) { + kunit_err(test, "failed to initialize: %d", ret); + kunit_set_success(test, false); + return; + } + } + + test_case->run_case(test); +} + +/* + * Performs post validations and cleanup after a test case was run. + * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal! + */ +static void kunit_run_case_cleanup(struct kunit *test, + struct kunit_module *module, + struct kunit_case *test_case) +{ + if (module->exit) + module->exit(test); +} + +/* + * Performs all logic to run a test case. + */ +static bool kunit_run_case(struct kunit *test, + struct kunit_module *module, + struct kunit_case *test_case) +{ + kunit_set_success(test, true); + + kunit_run_case_internal(test, module, test_case); + kunit_run_case_cleanup(test, module, test_case); + + return kunit_get_success(test); +} + +int kunit_run_tests(struct kunit_module *module) +{ + bool all_passed = true, success; + struct kunit_case *test_case; + struct kunit test; + int ret; + + ret = kunit_init_test(&test, module->name); + if (ret) + return ret; + + for (test_case = module->test_cases; test_case->run_case; test_case++) { + success = kunit_run_case(&test, module, test_case); + if (!success) + all_passed = false; + + kunit_info(&test, + "%s %s", + test_case->name, + success ? "passed" : "failed"); + } + + if (all_passed) + kunit_info(&test, "all tests passed"); + else + kunit_info(&test, "one or more tests failed"); + + return 0; +} + +void kunit_printk(const char *level, + const struct kunit *test, + const char *fmt, ...) +{ + struct va_format vaf; + va_list args; + + va_start(args, fmt); + + vaf.fmt = fmt; + vaf.va = &args; + + test->vprintk(test, level, &vaf); + + va_end(args); +} From patchwork Thu Feb 14 21:37:14 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813855 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id DAB3F1390 for ; Thu, 14 Feb 2019 21:38:35 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id C51102E955 for ; Thu, 14 Feb 2019 21:38:35 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id B860C2EB15; Thu, 14 Feb 2019 21:38:35 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 2C6AD2E955 for ; Thu, 14 Feb 2019 21:38:35 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 2699F208AE2B1; Thu, 14 Feb 2019 13:38:35 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::a4a; helo=mail-vk1-xa4a.google.com; envelope-from=32d9lxa4kdbo1h4d30d78668di6ee6b4.2ecb8dkn-dl38ccb8iji.qr.eh6@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-vk1-xa4a.google.com (mail-vk1-xa4a.google.com [IPv6:2607:f8b0:4864:20::a4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 45387208AE2A9 for ; Thu, 14 Feb 2019 13:38:34 -0800 (PST) Received: by mail-vk1-xa4a.google.com with SMTP id e10so3096651vke.20 for ; Thu, 14 Feb 2019 13:38:34 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=Ck1SOUdJg93el6zD9LDGMFhnqwNSeCUtCQQCuQIbiP4=; b=VA/ItiSbuOaetkN+jfPRqnUJgkZI4hwto2HSV3Gm6FBLPmENe5bhxzdvmjivyTAXUA YGHMRN6+Gt1lgz3HoO71QyIMYU5ebg8o0nYUvippGkwnj7o7URfecbrLSLQ9NrlV7Eaa kvy+M956vkivnGNcbkpOA2J1BoonYm/S83c83yedwd0PqrLwaHlsocfSXaazmfsDPwvA DSp/CngfDuZdD3gY6HVWBeCDexd6/EO5FUVhjFORfGxmfH3Gco9US+O7qGEhMJ0WW7Ll VdXQFHD+zJ85tfVCwsUnJ4UBTkyFpyEyZqhtMmgSr3Kn+oiQn2B4wCOEegSm213D2oTj 8/Iw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=Ck1SOUdJg93el6zD9LDGMFhnqwNSeCUtCQQCuQIbiP4=; b=rWXRT9TTx5jOZgN5r0eOFpVWXecFSXv/SNfoDGi/cp/52z8DSwkfjGmwaxBuIvCnHf NVU/g0yWJdBUPDuQBBIraNpCJ7DIQqcqqnx1UwNvm7Sn11R6KmZ8vtZ8TT4J2mbduiUq O0ElnKd7XlrmjqeoEQezo2hfkD0vuWshhwTomxBnvtlZJrEjb1MnO+DyygcXy51AkRXE zcdYUkuS1LMq3YIWepaHmoE/faUkzNVjQGsAWkw7Akdu9oYptcKTt7HksxJBfbKh+1Hk YdIK30RIB37YvIkuwlFcuTvgWYRBDOZDt6hpEz84KN/14dhJXB97QR4vo/ogRnSsYrKn D64Q== X-Gm-Message-State: AHQUAuYLEt7bi87TqvxPOEv+iZRNi7lsv9e8Nrc+cOXBq/OaVjtoPLj0 /jt5BFME3+pGLu3Qa/lMT7b852oG0/wXd9g/PqUzmg== X-Google-Smtp-Source: AHgI3Iazr0Z1RDXNcLVul5hMYFZInF41qQKyauDrUV9IP5z9uQe9taO8vIqq0bN35etCoYbaQtjLR4faogM/WzqWwU3Nhg== X-Received: by 2002:a05:6102:18f:: with SMTP id r15mr3864278vsq.46.1550180313281; Thu, 14 Feb 2019 13:38:33 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:14 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-3-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 02/17] kunit: test: add test resource management API From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Create a common API for test managed resources like memory and test objects. A lot of times a test will want to set up infrastructure to be used in test cases; this could be anything from just wanting to allocate some memory to setting up a driver stack; this defines facilities for creating "test resources" which are managed by the test infrastructure and are automatically cleaned up at the conclusion of the test. Signed-off-by: Brendan Higgins --- include/kunit/test.h | 109 +++++++++++++++++++++++++++++++++++++++++++ kunit/test.c | 95 +++++++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+) diff --git a/include/kunit/test.h b/include/kunit/test.h index 23c2ebedd6dd9..21abc9e953969 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -12,6 +12,69 @@ #include #include +struct kunit_resource; + +typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *); +typedef void (*kunit_resource_free_t)(struct kunit_resource *); + +/** + * struct kunit_resource - represents a *test managed resource* + * @allocation: for the user to store arbitrary data. + * @free: a user supplied function to free the resource. Populated by + * kunit_alloc_resource(). + * + * Represents a *test managed resource*, a resource which will automatically be + * cleaned up at the end of a test case. + * + * Example: + * + * .. code-block:: c + * + * struct kunit_kmalloc_params { + * size_t size; + * gfp_t gfp; + * }; + * + * static int kunit_kmalloc_init(struct kunit_resource *res, void *context) + * { + * struct kunit_kmalloc_params *params = context; + * res->allocation = kmalloc(params->size, params->gfp); + * + * if (!res->allocation) + * return -ENOMEM; + * + * return 0; + * } + * + * static void kunit_kmalloc_free(struct kunit_resource *res) + * { + * kfree(res->allocation); + * } + * + * void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp) + * { + * struct kunit_kmalloc_params params; + * struct kunit_resource *res; + * + * params.size = size; + * params.gfp = gfp; + * + * res = kunit_alloc_resource(test, kunit_kmalloc_init, + * kunit_kmalloc_free, ¶ms); + * if (res) + * return res->allocation; + * else + * return NULL; + * } + */ +struct kunit_resource { + void *allocation; + kunit_resource_free_t free; + + /* private: internal use only. */ + struct list_head node; +}; + struct kunit; /** @@ -104,6 +167,7 @@ struct kunit { const char *name; /* Read only after initialization! */ spinlock_t lock; /* Gaurds all mutable test state. */ bool success; /* Protected by lock. */ + struct list_head resources; /* Protected by lock. */ void (*vprintk)(const struct kunit *test, const char *level, struct va_format *vaf); @@ -127,6 +191,51 @@ int kunit_run_tests(struct kunit_module *module); } \ late_initcall(module_kunit_init##module) +/** + * kunit_alloc_resource() - Allocates a *test managed resource*. + * @test: The test context object. + * @init: a user supplied function to initialize the resource. + * @free: a user supplied function to free the resource. + * @context: for the user to pass in arbitrary data. + * + * Allocates a *test managed resource*, a resource which will automatically be + * cleaned up at the end of a test case. See &struct kunit_resource for an + * example. + */ +struct kunit_resource *kunit_alloc_resource(struct kunit *test, + kunit_resource_init_t init, + kunit_resource_free_t free, + void *context); + +void kunit_free_resource(struct kunit *test, struct kunit_resource *res); + +/** + * kunit_kmalloc() - Like kmalloc() except the allocation is *test managed*. + * @test: The test context object. + * @size: The size in bytes of the desired memory. + * @gfp: flags passed to underlying kmalloc(). + * + * Just like `kmalloc(...)`, except the allocation is managed by the test case + * and is automatically cleaned up after the test case concludes. See &struct + * kunit_resource for more information. + */ +void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp); + +/** + * kunit_kzalloc() - Just like kunit_kmalloc(), but zeroes the allocation. + * @test: The test context object. + * @size: The size in bytes of the desired memory. + * @gfp: flags passed to underlying kmalloc(). + * + * See kzalloc() and kunit_kmalloc() for more information. + */ +static inline void *kunit_kzalloc(struct kunit *test, size_t size, gfp_t gfp) +{ + return kunit_kmalloc(test, size, gfp | __GFP_ZERO); +} + +void kunit_cleanup(struct kunit *test); + void __printf(3, 4) kunit_printk(const char *level, const struct kunit *test, const char *fmt, ...); diff --git a/kunit/test.c b/kunit/test.c index 0b4396f92086e..84f2e1c040af3 100644 --- a/kunit/test.c +++ b/kunit/test.c @@ -66,6 +66,7 @@ static void kunit_vprintk(const struct kunit *test, int kunit_init_test(struct kunit *test, const char *name) { spin_lock_init(&test->lock); + INIT_LIST_HEAD(&test->resources); test->name = name; test->vprintk = kunit_vprintk; @@ -93,6 +94,11 @@ static void kunit_run_case_internal(struct kunit *test, test_case->run_case(test); } +static void kunit_case_internal_cleanup(struct kunit *test) +{ + kunit_cleanup(test); +} + /* * Performs post validations and cleanup after a test case was run. * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal! @@ -103,6 +109,8 @@ static void kunit_run_case_cleanup(struct kunit *test, { if (module->exit) module->exit(test); + + kunit_case_internal_cleanup(test); } /* @@ -150,6 +158,93 @@ int kunit_run_tests(struct kunit_module *module) return 0; } +struct kunit_resource *kunit_alloc_resource(struct kunit *test, + kunit_resource_init_t init, + kunit_resource_free_t free, + void *context) +{ + struct kunit_resource *res; + unsigned long flags; + int ret; + + res = kzalloc(sizeof(*res), GFP_KERNEL); + if (!res) + return NULL; + + ret = init(res, context); + if (ret) + return NULL; + + res->free = free; + spin_lock_irqsave(&test->lock, flags); + list_add_tail(&res->node, &test->resources); + spin_unlock_irqrestore(&test->lock, flags); + + return res; +} + +void kunit_free_resource(struct kunit *test, struct kunit_resource *res) +{ + res->free(res); + list_del(&res->node); + kfree(res); +} + +struct kunit_kmalloc_params { + size_t size; + gfp_t gfp; +}; + +static int kunit_kmalloc_init(struct kunit_resource *res, void *context) +{ + struct kunit_kmalloc_params *params = context; + + res->allocation = kmalloc(params->size, params->gfp); + if (!res->allocation) + return -ENOMEM; + + return 0; +} + +static void kunit_kmalloc_free(struct kunit_resource *res) +{ + kfree(res->allocation); +} + +void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp) +{ + struct kunit_kmalloc_params params; + struct kunit_resource *res; + + params.size = size; + params.gfp = gfp; + + res = kunit_alloc_resource(test, + kunit_kmalloc_init, + kunit_kmalloc_free, + ¶ms); + + if (res) + return res->allocation; + else + return NULL; +} + +void kunit_cleanup(struct kunit *test) +{ + struct kunit_resource *resource, *resource_safe; + unsigned long flags; + + spin_lock_irqsave(&test->lock, flags); + list_for_each_entry_safe(resource, + resource_safe, + &test->resources, + node) { + kunit_free_resource(test, resource); + } + spin_unlock_irqrestore(&test->lock, flags); +} + void kunit_printk(const char *level, const struct kunit *test, const char *fmt, ...) From patchwork Thu Feb 14 21:37:15 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813859 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id E18616C2 for ; Thu, 14 Feb 2019 21:38:38 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id CC1A42E955 for ; Thu, 14 Feb 2019 21:38:38 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id BF2AC2EAEC; Thu, 14 Feb 2019 21:38:38 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 4468B2EB35 for ; Thu, 14 Feb 2019 21:38:38 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 3D930208AE2B5; Thu, 14 Feb 2019 13:38:38 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::149; helo=mail-it1-x149.google.com; envelope-from=3299lxa4kdbw3j6f52f9a88afk8gg8d6.4gedafmp-fn5aeedaklk.st.gj8@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-it1-x149.google.com (mail-it1-x149.google.com [IPv6:2607:f8b0:4864:20::149]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id AC872208AE2B3 for ; Thu, 14 Feb 2019 13:38:36 -0800 (PST) Received: by mail-it1-x149.google.com with SMTP id v125so5601524itc.4 for ; Thu, 14 Feb 2019 13:38:36 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=iSAngcIaWP81iz096aRbzzNpQNwIWf0zdQBcJK8kOLU=; b=unyX3vp5W4a7b7+lOGI3B+B9v/eL3j7geJQKvlIjiBix/xEpqvZdIycDSczhbZ3tdJ PZ/BTKBfYmqBocAk7EMmC36owS+xpvM0psah9nflpf6tWtCC5T2aojz6bSqEhZMa2wXF a62POdTzkDp9adb2YVs+1hoRA1DdwEk861n6Zrbg33QrAkB8Yf8xaFi6xax02IrezVX9 JSUs8eeNbDYOjCPTctLi0qIeaERR5ESUKnnHKYY63XCGzhIjpuk0CmrXUsv5jPKVDoHa j5Pibr5dzDJMHtCdWgoPHwNjbRnMPl1N/Zqs0aVWwdGN72yVtBHVMToeCcweqzIyTdPj u0/w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=iSAngcIaWP81iz096aRbzzNpQNwIWf0zdQBcJK8kOLU=; b=tOxwVK7flZSaiMBHFl0TM2pzN73dOA9d/O2AJCMiLYK38IEyGpzA7Q84xTXID6v9bj FOkkDe5A9bjC9SPmfEUE/v+xGvqLtrMgj8NOl4oOy603VZQRFiNuLHnnXT2A8gIEVTT7 8anU74/ue4pMOfX45YnsyyAzV0OKeRqrYU54WJJJAKiiqixNkH2Qu691S9KgNwZK5Bqk xTwyp1vWJTRKed6gTt95Q0xUp+wKopelWGYy4O/Qk+zZbZQFtrS1n2JpnDUU9hGLaNrb 6SP2bNFbLtTT7eS6RVb0VAfdR6iELxm6zoYobocB6v2Hu6SdrrG3x2I8GUU5eeGwawpY /Ndg== X-Gm-Message-State: AHQUAuZdGZNqNvh3qMB99YpDF2UfbGYwZ3T3uR7MsOPhzYXAs7Mv+/El /sLAHyyx1/7QNur4X1W6NunNGbwDTkHXdWXBgzLg/Q== X-Google-Smtp-Source: AHgI3IZWoCy39HCg4hY6l5yPGEiEctMjQClHTRHvksaxX9kc8B37TXFAeWvoE86ZJ2U0GctXZOMbh24n4JraQxbyDz9asQ== X-Received: by 2002:a24:2782:: with SMTP id g124mr3818359ita.26.1550180315694; Thu, 14 Feb 2019 13:38:35 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:15 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-4-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 03/17] kunit: test: add string_stream a std::stream like string builder From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP A number of test features need to do pretty complicated string printing where it may not be possible to rely on a single preallocated string with parameters. So provide a library for constructing the string as you go similar to C++'s std::string. Signed-off-by: Brendan Higgins --- Changes Since Last Version - None. There was some discussion about maybe trying to generalize this or replace it with something existing, but it didn't seem feasible to generalize this, and there wasn't really anything that is a great replacement. --- include/kunit/string-stream.h | 44 ++++++++++ kunit/Makefile | 3 +- kunit/string-stream.c | 149 ++++++++++++++++++++++++++++++++++ 3 files changed, 195 insertions(+), 1 deletion(-) create mode 100644 include/kunit/string-stream.h create mode 100644 kunit/string-stream.c diff --git a/include/kunit/string-stream.h b/include/kunit/string-stream.h new file mode 100644 index 0000000000000..280ee67559588 --- /dev/null +++ b/include/kunit/string-stream.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * C++ stream style string builder used in KUnit for building messages. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#ifndef _KUNIT_STRING_STREAM_H +#define _KUNIT_STRING_STREAM_H + +#include +#include +#include +#include + +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 */ diff --git a/kunit/Makefile b/kunit/Makefile index 5efdc4dea2c08..275b565a0e81f 100644 --- a/kunit/Makefile +++ b/kunit/Makefile @@ -1 +1,2 @@ -obj-$(CONFIG_KUNIT) += test.o +obj-$(CONFIG_KUNIT) += test.o \ + string-stream.o diff --git a/kunit/string-stream.c b/kunit/string-stream.c new file mode 100644 index 0000000000000..e90fb595a5607 --- /dev/null +++ b/kunit/string-stream.c @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * C++ stream style string builder used in KUnit for building messages. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#include +#include +#include + +static int string_stream_vadd(struct string_stream *this, + const char *fmt, + va_list args) +{ + struct string_stream_fragment *fragment; + int len; + va_list args_for_counting; + unsigned long flags; + + /* Make a copy because `vsnprintf` could change it */ + va_copy(args_for_counting, args); + + /* Need space for null byte. */ + len = vsnprintf(NULL, 0, fmt, args_for_counting) + 1; + + va_end(args_for_counting); + + fragment = kmalloc(sizeof(*fragment), GFP_KERNEL); + if (!fragment) + return -ENOMEM; + + fragment->fragment = kmalloc(len, GFP_KERNEL); + if (!fragment->fragment) { + kfree(fragment); + return -ENOMEM; + } + + len = vsnprintf(fragment->fragment, len, fmt, args); + spin_lock_irqsave(&this->lock, flags); + this->length += len; + list_add_tail(&fragment->node, &this->fragments); + spin_unlock_irqrestore(&this->lock, flags); + return 0; +} + +static int string_stream_add(struct string_stream *this, const char *fmt, ...) +{ + va_list args; + int result; + + va_start(args, fmt); + result = string_stream_vadd(this, fmt, args); + va_end(args); + return result; +} + +static void string_stream_clear(struct string_stream *this) +{ + struct string_stream_fragment *fragment, *fragment_safe; + unsigned long flags; + + spin_lock_irqsave(&this->lock, flags); + list_for_each_entry_safe(fragment, + fragment_safe, + &this->fragments, + node) { + list_del(&fragment->node); + kfree(fragment->fragment); + kfree(fragment); + } + this->length = 0; + spin_unlock_irqrestore(&this->lock, flags); +} + +static char *string_stream_get_string(struct string_stream *this) +{ + struct string_stream_fragment *fragment; + size_t buf_len = this->length + 1; /* +1 for null byte. */ + char *buf; + unsigned long flags; + + buf = kzalloc(buf_len, GFP_KERNEL); + if (!buf) + return NULL; + + spin_lock_irqsave(&this->lock, flags); + list_for_each_entry(fragment, &this->fragments, node) + strlcat(buf, fragment->fragment, buf_len); + spin_unlock_irqrestore(&this->lock, flags); + + return buf; +} + +static bool string_stream_is_empty(struct string_stream *this) +{ + bool is_empty; + unsigned long flags; + + spin_lock_irqsave(&this->lock, flags); + is_empty = list_empty(&this->fragments); + spin_unlock_irqrestore(&this->lock, flags); + + return is_empty; +} + +void destroy_string_stream(struct string_stream *stream) +{ + stream->clear(stream); + kfree(stream); +} + +static void string_stream_destroy(struct kref *kref) +{ + struct string_stream *stream = container_of(kref, + struct string_stream, + refcount); + destroy_string_stream(stream); +} + +struct string_stream *new_string_stream(void) +{ + struct string_stream *stream = kzalloc(sizeof(*stream), GFP_KERNEL); + + if (!stream) + return NULL; + + INIT_LIST_HEAD(&stream->fragments); + spin_lock_init(&stream->lock); + kref_init(&stream->refcount); + stream->add = string_stream_add; + stream->vadd = string_stream_vadd; + stream->get_string = string_stream_get_string; + stream->clear = string_stream_clear; + stream->is_empty = string_stream_is_empty; + return stream; +} + +void string_stream_get(struct string_stream *stream) +{ + kref_get(&stream->refcount); +} + +int string_stream_put(struct string_stream *stream) +{ + return kref_put(&stream->refcount, &string_stream_destroy); +} + From patchwork Thu Feb 14 21:37:16 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813861 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 17A5B6C2 for ; Thu, 14 Feb 2019 21:38:41 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 046AE2E955 for ; Thu, 14 Feb 2019 21:38:41 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id EBEB32EB15; Thu, 14 Feb 2019 21:38:40 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 5DD5E2E955 for ; Thu, 14 Feb 2019 21:38:40 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 566C4208AE2B8; Thu, 14 Feb 2019 13:38:40 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::c49; helo=mail-yw1-xc49.google.com; envelope-from=33t9lxa4kdb86m9i85icdbbdinbjjbg9.7jhgdips-iq8dhhgdnon.vw.jmb@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-yw1-xc49.google.com (mail-yw1-xc49.google.com [IPv6:2607:f8b0:4864:20::c49]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 3F511208AE2B4 for ; Thu, 14 Feb 2019 13:38:39 -0800 (PST) Received: by mail-yw1-xc49.google.com with SMTP id j2so1641147ywj.14 for ; Thu, 14 Feb 2019 13:38:39 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=WTBEI9dhLaNpiQO1YgDhQ720EkT8ERelrq0kDAUjwEY=; b=axdrzy+nhyMVZsGRnUzmeHhDeifEzho1UzbukZw74FmTauMjIZU7cP58YkPnUjZiW7 0Ao3tvXxxjBkMBd3UtMhokcA4lSPks/PNdJtRZYLS7yDOgO2D33lmpGbg/QzvPlBNMOQ +VdtOXwYaltFcCnEW/E1YP13+wSduaT0N0dzdsrCPUHhHRqyR2CXDO3Jbd12YmycrMxx 1IMkZ3WboTv8EUUetPSD6gXPiKrwdXjM7UMcPpXWgMvjGJsb+WDu38mvj9ckOJySyqMK lb42o4h8YCGJWQNOpuFPOPofTMr4U6r8Axl1V0CbFgFUtSgyFWk8qcA0+rDtjCECxvPv 8asg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=WTBEI9dhLaNpiQO1YgDhQ720EkT8ERelrq0kDAUjwEY=; b=FkJEINJcow/1V3sSPn1T6n/sI1P4KzeDK07xHoHM1jz4mMQkzdUgFIQ55IVTi+dMf0 xnCNt+tMzq/xn2iL32iaFiD+ab2fUcJNN2gXFx45DH/Bd2JXq6Adm+TuBvodEZ1XD3YV 1JO/UFbE3WXVbdZQMbqJSaH30j07jAlCZoyORU5FA4h+LI5mfBxgPnNvWhzG5wDAwVM3 BVxXzEQ1btMS1tcf19xv5b8M4EqT3+Uai/AwGjU85Dd3h0yGbSlW6uYNdLCtclJOVrYk AWLOTWp4AwGWFIm+Tz3h/a/EDrAoaMNvLex7H1KeLIO8yvdR5b6/S0TVe1guB5P9lCym AX9A== X-Gm-Message-State: AHQUAubnuLvWi3khnDlBk3OfZjds45P+ryxeGQu/ogxooAcJ5DVvkIuy Vl8QEtkn56B1EtKBji3K54f6tzWp2BMYi9wOvvwN+Q== X-Google-Smtp-Source: AHgI3IZhWMnwZv9YzmJYf+KXD5jDzVDzPaGN3u1IDznZqCx9KWJhCfAbizN3bNOLO9fW7kqTri+BQRdtD6JBibyhWOhOMA== X-Received: by 2002:a25:2acd:: with SMTP id q196mr2636843ybq.57.1550180318154; Thu, 14 Feb 2019 13:38:38 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:16 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-5-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 04/17] kunit: test: add test_stream a std::stream like logger From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP A lot of the expectation and assertion infrastructure prints out fairly complicated test failure messages, so add a C++ style log library for for logging test results. Signed-off-by: Brendan Higgins --- include/kunit/kunit-stream.h | 50 ++++++++++++ include/kunit/test.h | 2 + kunit/Makefile | 3 +- kunit/kunit-stream.c | 153 +++++++++++++++++++++++++++++++++++ kunit/test.c | 8 ++ 5 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 include/kunit/kunit-stream.h create mode 100644 kunit/kunit-stream.c diff --git a/include/kunit/kunit-stream.h b/include/kunit/kunit-stream.h new file mode 100644 index 0000000000000..15ad83a6b7aae --- /dev/null +++ b/include/kunit/kunit-stream.h @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * C++ stream style string formatter and printer used in KUnit for outputting + * KUnit messages. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#ifndef _KUNIT_KUNIT_STREAM_H +#define _KUNIT_KUNIT_STREAM_H + +#include +#include + +struct kunit; + +/** + * struct kunit_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. + * @append: adds the contents of other to this. + * @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 kunit_stream { + void (*set_level)(struct kunit_stream *this, const char *level); + void (*add)(struct kunit_stream *this, const char *fmt, ...); + void (*append)(struct kunit_stream *this, struct kunit_stream *other); + void (*commit)(struct kunit_stream *this); + void (*clear)(struct kunit_stream *this); + /* private: internal use only. */ + struct kunit *test; + spinlock_t lock; /* Guards level. */ + const char *level; + struct string_stream *internal_stream; +}; + +/** + * kunit_new_stream() - constructs a new &struct kunit_stream. + * @test: The test context object. + * + * Constructs a new test managed &struct kunit_stream. + */ +struct kunit_stream *kunit_new_stream(struct kunit *test); + +#endif /* _KUNIT_KUNIT_STREAM_H */ diff --git a/include/kunit/test.h b/include/kunit/test.h index 21abc9e953969..75cd3c3ab1b4b 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -11,6 +11,7 @@ #include #include +#include struct kunit_resource; @@ -171,6 +172,7 @@ struct kunit { void (*vprintk)(const struct kunit *test, const char *level, struct va_format *vaf); + void (*fail)(struct kunit *test, struct kunit_stream *stream); }; int kunit_init_test(struct kunit *test, const char *name); diff --git a/kunit/Makefile b/kunit/Makefile index 275b565a0e81f..6ddc622ee6b1c 100644 --- a/kunit/Makefile +++ b/kunit/Makefile @@ -1,2 +1,3 @@ obj-$(CONFIG_KUNIT) += test.o \ - string-stream.o + string-stream.o \ + kunit-stream.o diff --git a/kunit/kunit-stream.c b/kunit/kunit-stream.c new file mode 100644 index 0000000000000..bc88638aef3b1 --- /dev/null +++ b/kunit/kunit-stream.c @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * C++ stream style string formatter and printer used in KUnit for outputting + * KUnit messages. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#include +#include +#include + +static const char *kunit_stream_get_level(struct kunit_stream *this) +{ + unsigned long flags; + const char *level; + + spin_lock_irqsave(&this->lock, flags); + level = this->level; + spin_unlock_irqrestore(&this->lock, flags); + + return level; +} + +static void kunit_stream_set_level(struct kunit_stream *this, const char *level) +{ + unsigned long flags; + + spin_lock_irqsave(&this->lock, flags); + this->level = level; + spin_unlock_irqrestore(&this->lock, flags); +} + +static void kunit_stream_add(struct kunit_stream *this, const char *fmt, ...) +{ + va_list args; + struct string_stream *stream = this->internal_stream; + + va_start(args, fmt); + if (stream->vadd(stream, fmt, args) < 0) + kunit_err(this->test, "Failed to allocate fragment: %s", fmt); + + va_end(args); +} + +static void kunit_stream_append(struct kunit_stream *this, + struct kunit_stream *other) +{ + struct string_stream *other_stream = other->internal_stream; + const char *other_content; + + other_content = other_stream->get_string(other_stream); + + if (!other_content) { + kunit_err(this->test, + "Failed to get string from second argument for appending."); + return; + } + + this->add(this, other_content); +} + +static void kunit_stream_clear(struct kunit_stream *this) +{ + this->internal_stream->clear(this->internal_stream); +} + +static void kunit_stream_commit(struct kunit_stream *this) +{ + struct string_stream *stream = this->internal_stream; + struct string_stream_fragment *fragment; + const char *level; + char *buf; + + level = kunit_stream_get_level(this); + if (!level) { + kunit_err(this->test, + "Stream was committed without a specified log level."); + level = KERN_ERR; + this->set_level(this, level); + } + + buf = stream->get_string(stream); + if (!buf) { + kunit_err(this->test, + "Could not allocate buffer, dumping stream:"); + list_for_each_entry(fragment, &stream->fragments, node) { + kunit_err(this->test, fragment->fragment); + } + goto cleanup; + } + + kunit_printk(level, this->test, buf); + kfree(buf); + +cleanup: + this->clear(this); +} + +static int kunit_stream_init(struct kunit_resource *res, void *context) +{ + struct kunit *test = context; + struct kunit_stream *stream; + + stream = kzalloc(sizeof(*stream), GFP_KERNEL); + if (!stream) + return -ENOMEM; + res->allocation = stream; + stream->test = test; + spin_lock_init(&stream->lock); + stream->internal_stream = new_string_stream(); + + if (!stream->internal_stream) + return -ENOMEM; + + stream->set_level = kunit_stream_set_level; + stream->add = kunit_stream_add; + stream->append = kunit_stream_append; + stream->commit = kunit_stream_commit; + stream->clear = kunit_stream_clear; + + return 0; +} + +static void kunit_stream_free(struct kunit_resource *res) +{ + struct kunit_stream *stream = res->allocation; + + if (!stream->internal_stream->is_empty(stream->internal_stream)) { + kunit_err(stream->test, + "End of test case reached with uncommitted stream entries."); + stream->commit(stream); + } + + destroy_string_stream(stream->internal_stream); + kfree(stream); +} + +struct kunit_stream *kunit_new_stream(struct kunit *test) +{ + struct kunit_resource *res; + + res = kunit_alloc_resource(test, + kunit_stream_init, + kunit_stream_free, + test); + + if (res) + return res->allocation; + else + return NULL; +} diff --git a/kunit/test.c b/kunit/test.c index 84f2e1c040af3..1a2e5e6b7ffee 100644 --- a/kunit/test.c +++ b/kunit/test.c @@ -63,12 +63,20 @@ static void kunit_vprintk(const struct kunit *test, "kunit %s: %pV", test->name, vaf); } +static void kunit_fail(struct kunit *test, struct kunit_stream *stream) +{ + kunit_set_success(test, false); + stream->set_level(stream, KERN_ERR); + stream->commit(stream); +} + int kunit_init_test(struct kunit *test, const char *name) { spin_lock_init(&test->lock); INIT_LIST_HEAD(&test->resources); test->name = name; test->vprintk = kunit_vprintk; + test->fail = kunit_fail; return 0; } From patchwork Thu Feb 14 21:37:17 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813863 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 992271390 for ; Thu, 14 Feb 2019 21:38:43 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 83E092E955 for ; Thu, 14 Feb 2019 21:38:43 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 76F602EB15; Thu, 14 Feb 2019 21:38:43 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 7BE822E955 for ; Thu, 14 Feb 2019 21:38:42 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 73B3D208AE2BD; Thu, 14 Feb 2019 13:38:42 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::64a; helo=mail-pl1-x64a.google.com; envelope-from=34n9lxa4kdce8obka7kefddfkpdlldib.9ljifkru-ksafjjifpqp.xy.lod@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-pl1-x64a.google.com (mail-pl1-x64a.google.com [IPv6:2607:f8b0:4864:20::64a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id CDBB1208AE2B3 for ; Thu, 14 Feb 2019 13:38:40 -0800 (PST) Received: by mail-pl1-x64a.google.com with SMTP id x14so5280848pln.5 for ; Thu, 14 Feb 2019 13:38:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=1IdEAu3TEGCwkCQa7JtbzdzfTRWPMjVxB+lNpvPGivM=; b=rqLXhFdjxHY2HdTiRf0we+YLof05LpYGQwxtsMVp81D3T0F8Lp9yQ6tsAEqx5kvFgi HvGNz4r8xXSL44AGXDWdu9FE6qYLFzHuNv/F7L/rQq7itkLCPOL0JpjwMEVoJ7PGYfy/ 64P7iXh54lDRUn1CPsmQbvlX6yt/FcWAwpK2UMoR9MpQSIR5Wqtc7a21N900mQm6ysEk kk4+I9ChODhdivdFpBf2ZWfdQ2TKAUpXe+va55uwwepJeDHl9t5+okj7fAaAkBQNZqfl 1lh/PBXgHW9wWPqkb5qq394o4Bo5H1D2iauBtyBPDLJEfpIzEKNtk+stA85ttv2f4Mj+ JWdg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=1IdEAu3TEGCwkCQa7JtbzdzfTRWPMjVxB+lNpvPGivM=; b=tB7NLlrkrRuQCD0h1TKrHZR3E3nt4rYuRIOWNNVaZSGHOH+tPP0eGK0Fr9cgTg1PBh qspTF/V9yi+sDKMVda3bV+Mm6wAEAqTLbGQX5qLJ8s70n+TC4LktRshgm1ZCQWsYNDIW gEvuJTz0grilxCI3pSznnkp9twptB/ed9UTrWao07MVRtl4oEan4i9e1vfxeWi6QvXXw 5GxPURxqtQQrzGbK/Di6Unv9Hpv4Dh4A8gLbA5RR26F/d4hpVOnFdzBSflbXBAj1bjSv NZEEu4j7wLBhTSrDg0MBD8226Qp6ctLMWpAvjP8Rd47CPHTGI9NhQXYeEwDcbwjcDxfe c7Nw== X-Gm-Message-State: AHQUAuZyLIKNiYIKDwIvIGNJnypD+q6cN18MN74LvnZMmFn+TxUtvux4 D9xDD7AxrJ+IirGg3iPCVPfSBXLue/MIHh+H4xWJZg== X-Google-Smtp-Source: AHgI3IaM2Wx073SlPrvqu+D3IQlIwbPzkFYznAwzK3zesRAfb0G9ozRadRLUuh9g3zxZ/PnKBHn7dQoejbI07Ft9rnP/xA== X-Received: by 2002:a17:902:7888:: with SMTP id q8mr1956946pll.130.1550180320363; Thu, 14 Feb 2019 13:38:40 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:17 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-6-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 05/17] kunit: test: add the concept of expectations From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add support for expectations, which allow properties to be specified and then verified in tests. Signed-off-by: Brendan Higgins --- include/kunit/test.h | 415 +++++++++++++++++++++++++++++++++++++++++++ kunit/test.c | 34 ++++ 2 files changed, 449 insertions(+) diff --git a/include/kunit/test.h b/include/kunit/test.h index 75cd3c3ab1b4b..a36ad1a502c66 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -273,4 +273,419 @@ void __printf(3, 4) kunit_printk(const char *level, #define kunit_err(test, fmt, ...) \ kunit_printk(KERN_ERR, test, fmt, ##__VA_ARGS__) +static inline struct kunit_stream *kunit_expect_start(struct kunit *test, + const char *file, + const char *line) +{ + struct kunit_stream *stream = kunit_new_stream(test); + + stream->add(stream, "EXPECTATION FAILED at %s:%s\n\t", file, line); + + return stream; +} + +static inline void kunit_expect_end(struct kunit *test, + bool success, + struct kunit_stream *stream) +{ + if (!success) + test->fail(test, stream); + else + stream->clear(stream); +} + +#define KUNIT_EXPECT_START(test) \ + kunit_expect_start(test, __FILE__, __stringify(__LINE__)) + +#define KUNIT_EXPECT_END(test, success, stream) \ + kunit_expect_end(test, success, stream) + +#define KUNIT_EXPECT_MSG(test, success, message, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + \ + __stream->add(__stream, message); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + KUNIT_EXPECT_END(test, success, __stream); \ +} while (0) + +#define KUNIT_EXPECT(test, success, message) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + \ + __stream->add(__stream, message); \ + KUNIT_EXPECT_END(test, success, __stream); \ +} while (0) + +/** + * KUNIT_SUCCEED() - A no-op expectation. Only exists for code clarity. + * @test: The test context object. + * + * The opposite of KUNIT_FAIL(), it is an expectation that cannot fail. In other + * words, it does nothing and only exists for code clarity. See + * KUNIT_EXPECT_TRUE() for more information. + */ +#define KUNIT_SUCCEED(test) do {} while (0) + +/** + * KUNIT_FAIL() - Always causes a test to fail when evaluated. + * @test: The test context object. + * @fmt: an informational message to be printed when the assertion is made. + * @...: string format arguments. + * + * The opposite of KUNIT_SUCCEED(), it is an expectation that always fails. In + * other words, it always results in a failed expectation, and consequently + * always causes the test case to fail when evaluated. See KUNIT_EXPECT_TRUE() + * for more information. + */ +#define KUNIT_FAIL(test, fmt, ...) \ + KUNIT_EXPECT_MSG(test, false, "", fmt, ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true. + * @test: The test context object. + * @condition: an arbitrary boolean expression. The test fails when this does + * not evaluate to true. + * + * This and expectations of the form `KUNIT_EXPECT_*` will cause the test case + * to fail when the specified condition is not met; however, it will not prevent + * the test case from continuing to run; this is otherwise known as an + * *expectation failure*. + */ +#define KUNIT_EXPECT_TRUE(test, condition) \ + KUNIT_EXPECT(test, (condition), \ + "Expected " #condition " is true, but is false.") + +#define KUNIT_EXPECT_TRUE_MSG(test, condition, fmt, ...) \ + KUNIT_EXPECT_MSG(test, (condition), \ + "Expected " #condition " is true, but is false.\n",\ + fmt, ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_FALSE() - Makes a test failure when the expression is not false. + * @test: The test context object. + * @condition: an arbitrary boolean expression. The test fails when this does + * not evaluate to false. + * + * Sets an expectation that @condition evaluates to false. See + * KUNIT_EXPECT_TRUE() for more information. + */ +#define KUNIT_EXPECT_FALSE(test, condition) \ + KUNIT_EXPECT(test, !(condition), \ + "Expected " #condition " is false, but is true.") + +#define KUNIT_EXPECT_FALSE_MSG(test, condition, fmt, ...) \ + KUNIT_EXPECT_MSG(test, !(condition), \ + "Expected " #condition " is false, but is true.\n",\ + fmt, ##__VA_ARGS__) + +void kunit_expect_binary_msg(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line, + const char *fmt, ...); + +static inline void kunit_expect_binary(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line) +{ + struct kunit_stream *stream = kunit_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); + + kunit_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 KUNIT_EXPECT_BINARY(test, left, condition, right) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + kunit_expect_binary(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__)); \ +} while (0) + +#define KUNIT_EXPECT_BINARY_MSG(test, left, condition, right, fmt, ...) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + kunit_expect_binary_msg(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__), \ + fmt, ##__VA_ARGS__); \ +} while (0) + +/** + * KUNIT_EXPECT_EQ() - Sets an expectation that @left and @right are equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the values that @left and @right evaluate to are + * equal. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, (@left) == (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_EQ(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, ==, right) + +#define KUNIT_EXPECT_EQ_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + ==, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_NE() - An expectation that @left and @right are not equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the values that @left and @right evaluate to are not + * equal. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, (@left) != (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_NE(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, !=, right) + +#define KUNIT_EXPECT_NE_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + !=, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_LT() - An expectation that @left is less than @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the value that @left evaluates to is less than the + * value that @right evaluates to. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, (@left) < (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_LT(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, <, right) + +#define KUNIT_EXPECT_LT_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + <, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_LE() - Expects that @left is less than or equal to @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the value that @left evaluates to is less than or + * equal to the value that @right evaluates to. Semantically this is equivalent + * to KUNIT_EXPECT_TRUE(@test, (@left) <= (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_LE(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, <=, right) + +#define KUNIT_EXPECT_LE_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + <=, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_GT() - An expectation that @left is greater than @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the value that @left evaluates to is greater than + * the value that @right evaluates to. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, (@left) > (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_GT(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, >, right) + +#define KUNIT_EXPECT_GT_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + >, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_GE() - Expects that @left is greater than or equal to @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an expectation that the value that @left evaluates to is greater than + * the value that @right evaluates to. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, (@left) >= (@right)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_GE(test, left, right) \ + KUNIT_EXPECT_BINARY(test, left, >=, right) + +#define KUNIT_EXPECT_GE_MSG(test, left, right, fmt, ...) \ + KUNIT_EXPECT_BINARY_MSG(test, \ + left, \ + >=, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_EXPECT_STREQ() - Expects that strings @left and @right are equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a null terminated string. + * @right: an arbitrary expression that evaluates to a null terminated string. + * + * Sets an expectation that the values that @left and @right evaluate to are + * equal. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, !strcmp((@left), (@right))). See KUNIT_EXPECT_TRUE() + * for more information. + */ +#define KUNIT_EXPECT_STREQ(test, left, right) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + \ + KUNIT_EXPECT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +#define KUNIT_EXPECT_STREQ_MSG(test, left, right, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + \ + KUNIT_EXPECT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +/** + * KUNIT_EXPECT_STRNEQ() - Expects that strings @left and @right are not equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a null terminated string. + * @right: an arbitrary expression that evaluates to a null terminated string. + * + * Sets an expectation that the values that @left and @right evaluate to are + * not equal. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, strcmp((@left), (@right))). See KUNIT_EXPECT_TRUE() + * for more information. + */ +#define KUNIT_EXPECT_STRNEQ(test, left, right) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + \ + KUNIT_EXPECT_END(test, strcmp(left, right), __stream); \ +} while (0) + +#define KUNIT_EXPECT_STRNEQ_MSG(test, left, right, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + \ + KUNIT_EXPECT_END(test, strcmp(left, right), __stream); \ +} while (0) + +/** + * KUNIT_EXPECT_NOT_ERR_OR_NULL() - Expects that @ptr is not null and not err. + * @test: The test context object. + * @ptr: an arbitrary pointer. + * + * Sets an expectation that the value that @ptr evaluates to is not null and not + * an errno stored in a pointer. This is semantically equivalent to + * KUNIT_EXPECT_TRUE(@test, !IS_ERR_OR_NULL(@ptr)). See KUNIT_EXPECT_TRUE() for + * more information. + */ +#define KUNIT_EXPECT_NOT_ERR_OR_NULL(test, ptr) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) \ + __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)); \ + \ + KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) + +#define KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, ptr, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_EXPECT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) { \ + __stream->add(__stream, \ + "Expected " #ptr " is not null, but is."); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + } \ + if (IS_ERR(__ptr)) { \ + __stream->add(__stream, \ + "Expected " #ptr " is not error, but is: %ld", \ + PTR_ERR(__ptr)); \ + \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + } \ + KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) + #endif /* _KUNIT_TEST_H */ diff --git a/kunit/test.c b/kunit/test.c index 1a2e5e6b7ffee..d18c50d5ed671 100644 --- a/kunit/test.c +++ b/kunit/test.c @@ -269,3 +269,37 @@ void kunit_printk(const char *level, va_end(args); } + +void kunit_expect_binary_msg(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line, + const char *fmt, ...) +{ + struct kunit_stream *stream = kunit_expect_start(test, file, line); + struct va_format vaf; + va_list args; + + 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); + + if (fmt) { + va_start(args, fmt); + + vaf.fmt = fmt; + vaf.va = &args; + + stream->add(stream, "\n%pV", &vaf); + + va_end(args); + } + + kunit_expect_end(test, compare_result, stream); +} + From patchwork Thu Feb 14 21:37:18 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813865 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 07CEF1390 for ; Thu, 14 Feb 2019 21:38:46 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id E73FA2EAEC for ; Thu, 14 Feb 2019 21:38:45 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id DA2A62EC18; Thu, 14 Feb 2019 21:38:45 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 9544A2EAEC for ; Thu, 14 Feb 2019 21:38:45 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 8EC26208AE2BF; Thu, 14 Feb 2019 13:38:45 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::74a; helo=mail-qk1-x74a.google.com; envelope-from=3499lxa4kdcqbrendanhigginsgoogle.comlinux-nvdimmlists.ab.org@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-qk1-x74a.google.com (mail-qk1-x74a.google.com [IPv6:2607:f8b0:4864:20::74a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 604B5208AE2B3 for ; Thu, 14 Feb 2019 13:38:44 -0800 (PST) Received: by mail-qk1-x74a.google.com with SMTP id b187so6430737qkf.3 for ; Thu, 14 Feb 2019 13:38:44 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=h+keLiQ8UrSvEm7+wL7InKcQs/d0wg/MdPLT1U+V0Ho=; b=BXI2cnVYMUYwcQEU11+rgRhxE47n/thlxwGOpDjMnOxVeEQP0xokJ4nExSRcuK7SM0 QAAmlXECYYny7H4j6j51UL6iuiHYQF3g9l7aEuX2Jvz6oXm+2+CaJkevycJsRcEdkukZ AOTE+D/EYnpm5ajS1mu5g+SjJ9JXgvOFvJ5n1t49w29nl+2WdwVh2sdKeQyBUMSrPWNH fzldV7om7MT58A6bj4ylmdSIJhce8j1K2OfKJiif1T5QxSUGn4JvJ6fTMIn5/RTlHAyq be0LePsoUOPZVHvloaYd2XW+4pmC2FjvjAgvvCvI3eecIy5Y5XwruIR0CekLlogHJIyO 6aiw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=h+keLiQ8UrSvEm7+wL7InKcQs/d0wg/MdPLT1U+V0Ho=; b=UftE8LV+I1kn4W1fyxbhqC3vEthzoj+mtlDQZpKS6vq8EK1QCztr5eFMVdR3Y9Bav5 nA18R3pXZx2bMrCRwWFZ/ub0HFxqpAxPxym/ETkn4yUccRwSBw9cdPthptuXqVdtPfyr FJwr2DXNyDGr0+oxtI0ygyGuy+egX6MeZtz8P66OIwVe5QDC1HNf/lXxzicz9ZH+pYbX xMv9W4xe1rn/mc435vS4a57QwE8ZQWVd0foYKOHWAVPg4CxUbpBcOSxknK/Za8//cXXu 8q4yBjoRrcvfpUmNMygPgKeA/vnUUgJotfBrPoqBsLdPUPtB6X0eFX7ikAgIeJ3xoi/j 4uog== X-Gm-Message-State: AHQUAuYVOoszmf2ynU2eZfjmKzrezb8/tHJXR08AXXPC7i54vEsC0F33 SD7RjL5+qPLSHIR7ZKkgoHK7cvz2SpcDr10R/YIsYg== X-Google-Smtp-Source: AHgI3IYUSLyNNiD4a/w4HRwz+V30pDMQuGVooAEVXS4EAMj7mLItRzehEypNmaAk0pIfzA4HniHpwAB5iH9j08ChjsRL2w== X-Received: by 2002:aed:22ac:: with SMTP id p41mr2368970qtc.55.1550180323042; Thu, 14 Feb 2019 13:38:43 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:18 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-7-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 06/17] kbuild: enable building KUnit From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add KUnit to root Kconfig and Makefile allowing it to actually be built. Signed-off-by: Brendan Higgins --- Changes Since Last Version - Rewrote patch description. This was previously called "[RFC v3 06/19] arch: um: enable running kunit from User Mode Linux," which was incorrect since this patch does not have any UML specific bits in it. --- Kconfig | 2 ++ Makefile | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Kconfig b/Kconfig index 48a80beab6853..10428501edb78 100644 --- a/Kconfig +++ b/Kconfig @@ -30,3 +30,5 @@ source "crypto/Kconfig" source "lib/Kconfig" source "lib/Kconfig.debug" + +source "kunit/Kconfig" diff --git a/Makefile b/Makefile index 3142e67d03f1b..d10308eb7f214 100644 --- a/Makefile +++ b/Makefile @@ -958,7 +958,7 @@ endif PHONY += prepare0 ifeq ($(KBUILD_EXTMOD),) -core-y += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/ +core-y += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/ kunit/ vmlinux-dirs := $(patsubst %/,%,$(filter %/, $(init-y) $(init-m) \ $(core-y) $(core-m) $(drivers-y) $(drivers-m) \ From patchwork Thu Feb 14 21:37:19 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813869 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 662B11390 for ; Thu, 14 Feb 2019 21:38:48 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 51CA72EAEC for ; Thu, 14 Feb 2019 21:38:48 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 45A742EB35; Thu, 14 Feb 2019 21:38:48 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id AC5192EAEC for ; Thu, 14 Feb 2019 21:38:47 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id A5AE1208AE2C4; Thu, 14 Feb 2019 13:38:47 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::549; helo=mail-pg1-x549.google.com; envelope-from=35d9lxa4kdcydtgpfcpjkiikpuiqqing.eqonkpwz-pxfkoonkuvu.cd.qti@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-pg1-x549.google.com (mail-pg1-x549.google.com [IPv6:2607:f8b0:4864:20::549]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 8DEED208AE2B4 for ; Thu, 14 Feb 2019 13:38:46 -0800 (PST) Received: by mail-pg1-x549.google.com with SMTP id 11so1893880pgd.19 for ; Thu, 14 Feb 2019 13:38:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=cDMRDRCAlooQqtKbNZe3mHp8Nf74M7H0TRYUBwRK+90=; b=YD0djaj8uAXMKZE/bLyWHMvkjXaVCHyCujJ7HIf8k2LK7+cyL+G4V8oMZMh4xD/DhF 3CRKbYN+U+oiXoMPd5XaaoutV9cRyswnv7mGxCYUC/OIWUlR4dH8gxVTp5a1SAvcCLvW o/KnvwDFlrus5phWIEvUET9RGZf8o41uxxm7/6faUyymAlMj0FpGrY9/GWYo7cDcRkFf uufQ1ChaQXZB7kYz/XDTtaDe01p1bru2JB90sfkjNYsMmJSsA5/y87Wf+8UEwfmxZqe2 g4b6kYkELhKsqjzq6Rkb0m6Oxk8nMFDbHDNv/jvy1rOZlrLxoLSVTXdGEAG/kWcvsg+7 qN2Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=cDMRDRCAlooQqtKbNZe3mHp8Nf74M7H0TRYUBwRK+90=; b=n2vfehhfgWrUkPQngJIvGYiPtYCjrrL8CgygulwiCC/eBAbKUF3Ra5GGTDWAfotjd8 NLYCW4TwW/AVJSOINxDa7qhuZ1hDAw2B8nYtn1Ez5PJV0QFf1PJDis2ZbNeXHzFx7Vif +yxMfhF9oKdwrSiM1jSt9baV8ThANrsBIzzR82gaslCrIddVDULlI8qESiy649ZQevQb Qr8+bTWmHfptzUmmWMsmAMpPC3/c5VCZnwBnuiXNDWfKNYrfwMh7TEj135em8yQlGIvQ uH/sp6sRdruRauCJVRj9xsXZdle9dXM5xEKRzsBl4IIhihH/z37YS2Pt9dDuarhKExR6 VJHw== X-Gm-Message-State: AHQUAuYb5DL6HLPx19xCSW8awq/fYehz+W6cpR/gTJbpJEH3pzrwRP4D zaz3w0hr2IU+1ym/xsVT+4Y777ltTpw0RS74TNzUxQ== X-Google-Smtp-Source: AHgI3IYZqykWPbNRxaAWHvyvjK7un9lYLHAch5SAzkwe/bGzSaIPXlfqdx9paWdx+9WnB7Ya/avgvlR2hoFJYdTLz/bcOw== X-Received: by 2002:a62:f550:: with SMTP id n77mr2348156pfh.117.1550180325957; Thu, 14 Feb 2019 13:38:45 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:19 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-8-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 07/17] kunit: test: add initial tests From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add a test for string stream along with a simpler example. Signed-off-by: Brendan Higgins --- kunit/Kconfig | 12 ++++++ kunit/Makefile | 4 ++ kunit/example-test.c | 88 ++++++++++++++++++++++++++++++++++++++ kunit/string-stream-test.c | 61 ++++++++++++++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 kunit/example-test.c create mode 100644 kunit/string-stream-test.c diff --git a/kunit/Kconfig b/kunit/Kconfig index 64480092b2c24..5cb500355c873 100644 --- a/kunit/Kconfig +++ b/kunit/Kconfig @@ -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 diff --git a/kunit/Makefile b/kunit/Makefile index 6ddc622ee6b1c..60a9ea6cb4697 100644 --- a/kunit/Makefile +++ b/kunit/Makefile @@ -1,3 +1,7 @@ obj-$(CONFIG_KUNIT) += test.o \ string-stream.o \ kunit-stream.o + +obj-$(CONFIG_KUNIT_TEST) += string-stream-test.o + +obj-$(CONFIG_KUNIT_EXAMPLE_TEST) += example-test.o diff --git a/kunit/example-test.c b/kunit/example-test.c new file mode 100644 index 0000000000000..352f64a423e7c --- /dev/null +++ b/kunit/example-test.c @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Example KUnit test to show how to use KUnit. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#include + +/* + * This is the most fundamental element of KUnit, the test case. A test case + * makes a set EXPECTATIONs and ASSERTIONs about the behavior of some code; if + * any expectations or assertions are not met, the test fails; otherwise, the + * test passes. + * + * In KUnit, a test case is just a function with the signature + * `void (*)(struct kunit *)`. `struct kunit` is a context object that stores + * information about the current test. + */ +static void example_simple_test(struct kunit *test) +{ + /* + * This is an EXPECTATION; it is how KUnit tests things. When you want + * to test a piece of code, you set some expectations about what the + * code should do. KUnit then runs the test and verifies that the code's + * behavior matched what was expected. + */ + KUNIT_EXPECT_EQ(test, 1 + 1, 2); +} + +/* + * This is run once before each test case, see the comment on + * example_test_module for more information. + */ +static int example_test_init(struct kunit *test) +{ + kunit_info(test, "initializing"); + + return 0; +} + +/* + * Here we make a list of all the test cases we want to add to the test module + * below. + */ +static struct kunit_case example_test_cases[] = { + /* + * This is a helper to create a test case object from a test case + * function; its exact function is not important to understand how to + * use KUnit, just know that this is how you associate test cases with a + * test module. + */ + KUNIT_CASE(example_simple_test), + {}, +}; + +/* + * This defines a suite or grouping of tests. + * + * Test cases are defined as belonging to the suite by adding them to + * `kunit_cases`. + * + * Often it is desirable to run some function which will set up things which + * will be used by every test; this is accomplished with an `init` function + * which runs before each test case is invoked. Similarly, an `exit` function + * may be specified which runs after every test case and can be used to for + * cleanup. For clarity, running tests in a test module would behave as follows: + * + * module.init(test); + * module.test_case[0](test); + * module.exit(test); + * module.init(test); + * module.test_case[1](test); + * module.exit(test); + * ...; + */ +static struct kunit_module example_test_module = { + .name = "example", + .init = example_test_init, + .test_cases = example_test_cases, +}; + +/* + * This registers the above test module telling KUnit that this is a suite of + * tests that need to be run. + */ +module_test(example_test_module); diff --git a/kunit/string-stream-test.c b/kunit/string-stream-test.c new file mode 100644 index 0000000000000..6cfef69568011 --- /dev/null +++ b/kunit/string-stream-test.c @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit test for struct string_stream. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ + +#include +#include +#include + +static void string_stream_test_get_string(struct kunit *test) +{ + struct string_stream *stream = new_string_stream(); + char *output; + + stream->add(stream, "Foo"); + stream->add(stream, " %s", "bar"); + + output = stream->get_string(stream); + KUNIT_EXPECT_STREQ(test, output, "Foo bar"); + kfree(output); + destroy_string_stream(stream); +} + +static void string_stream_test_add_and_clear(struct kunit *test) +{ + struct string_stream *stream = new_string_stream(); + char *output; + int i; + + for (i = 0; i < 10; i++) + stream->add(stream, "A"); + + output = stream->get_string(stream); + KUNIT_EXPECT_STREQ(test, output, "AAAAAAAAAA"); + KUNIT_EXPECT_EQ(test, stream->length, 10); + KUNIT_EXPECT_FALSE(test, stream->is_empty(stream)); + kfree(output); + + stream->clear(stream); + + output = stream->get_string(stream); + KUNIT_EXPECT_STREQ(test, output, ""); + KUNIT_EXPECT_TRUE(test, stream->is_empty(stream)); + destroy_string_stream(stream); +} + +static struct kunit_case string_stream_test_cases[] = { + KUNIT_CASE(string_stream_test_get_string), + KUNIT_CASE(string_stream_test_add_and_clear), + {} +}; + +static struct kunit_module string_stream_test_module = { + .name = "string-stream-test", + .test_cases = string_stream_test_cases +}; +module_test(string_stream_test_module); + From patchwork Thu Feb 14 21:37:20 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813871 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 213401390 for ; Thu, 14 Feb 2019 21:38:54 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 069412A397 for ; Thu, 14 Feb 2019 21:38:54 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id E8B3E2961E; Thu, 14 Feb 2019 21:38:53 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id CD0E62E76A for ; Thu, 14 Feb 2019 21:38:52 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id C5AE7208AE2C0; Thu, 14 Feb 2019 13:38:52 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::a4a; helo=mail-vk1-xa4a.google.com; envelope-from=36t9lxa4kdcsiylukhuopnnpuznvvnsl.jvtspube-uckpttspzaz.hi.vyn@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-vk1-xa4a.google.com (mail-vk1-xa4a.google.com [IPv6:2607:f8b0:4864:20::a4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 2BF18208AE2AC for ; Thu, 14 Feb 2019 13:38:51 -0800 (PST) Received: by mail-vk1-xa4a.google.com with SMTP id 14so3053030vkx.16 for ; Thu, 14 Feb 2019 13:38:51 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=yNClPyxjZvmuw8r1ManJTbqMjXjEKEkcQNWEPYBLx1w=; b=IIIriDPLjSxiquqPp/QncbA0PAvuWBcCJNX3fL7k9JXgEpKMyQGZcz2EbgIoa7XhDF byA+U9X5J1oyQsRnXuDxu+GdR0d+Bku0xqfuhnoqwU+xqu/EmByc+5QkR7iieFG+Z2/J Aahld+Odu+2t3cMB6T+0YzufUsCHQusJCnve35O6v4Snbr+wnIHTBaXTjPFBdzyfToh0 uWmhbTckTU5XKRYNt58lp9ZfUNj/F3dS00DLi31IifR253aAhJBnxFjp2ufwJocfm964 bxIVjcYaTtN6UjAih8a2B3GJ3KkArCUnZn2aNA0zREQIHu1M458X4LN1FEQq7eYnsfeh j6Pg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=yNClPyxjZvmuw8r1ManJTbqMjXjEKEkcQNWEPYBLx1w=; b=ro5zMGcGvIeI8Rl+AYLrmUg/PNBryFLW5kueVAjI2zk4NxjG4Tj7HEjcsmuYm0HbsG xN02EDC8Z1VyuWj3/t57iS76bnTMALF1zohez4SQtTTgP6zjVaSB+kES2+CDdygj0yvb o9MHl7EeZ8r8HLs4THVcdeyM01c8RYkcYUALNN3M0z+SB8nYDt1HoKKgsoSNgReRFyuc OfQRY5EOxY5J1Ok4h/xJIHdrzuw2HA06llSTPWgpSfAV9tn6NoUXupR5+M0XNLSWC/vd +Dt2AGJqEyqb05gI4P9YZIxinrXvSpKjlrlHKt/f8mvIgq+rnnzZIzlw6acJkI7x2bOc quLg== X-Gm-Message-State: AHQUAuY1jWGb1Rj3yD++UoXnjUbBjUvBAFPUh/2Y/0VX6cMq/J/EPtcz iOba8Y67Rs2cESUv71Sx6FEhPmmxQsgJ143+SY+Yjg== X-Google-Smtp-Source: AHgI3IZT3IlbgURrHay8Q8QnLVDeUZjwN5z80B2qvrv3+XOJgehKM7M206h7y4k2ua0FGPoKqSdBcmbCzb5u+qczWAWalw== X-Received: by 2002:a67:ee8e:: with SMTP id n14mr3912950vsp.45.1550180330247; Thu, 14 Feb 2019 13:38:50 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:20 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-9-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 08/17] kunit: test: add support for test abort From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add support for aborting/bailing out of test cases. Needed for implementing assertions. Signed-off-by: Brendan Higgins --- Changes Since Last Version - This patch is new introducing a new cross-architecture way to abort out of a test case (needed for KUNIT_ASSERT_*, see next patch for details). - On a side note, this is not a complete replacement for the UML abort mechanism, but covers the majority of necessary functionality. UML architecture specific featurs have been dropped from the initial patchset. --- include/kunit/test.h | 24 +++++ kunit/Makefile | 3 +- kunit/test-test.c | 127 ++++++++++++++++++++++++++ kunit/test.c | 208 +++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 353 insertions(+), 9 deletions(-) create mode 100644 kunit/test-test.c diff --git a/include/kunit/test.h b/include/kunit/test.h index a36ad1a502c66..cd02dca96eb61 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -151,6 +151,26 @@ struct kunit_module { struct kunit_case *test_cases; }; +struct kunit_try_catch_context { + struct kunit *test; + struct kunit_module *module; + struct kunit_case *test_case; + struct completion *try_completion; + int try_result; +}; + +struct kunit_try_catch { + void (*run)(struct kunit_try_catch *try_catch); + void (*throw)(struct kunit_try_catch *try_catch); + struct kunit_try_catch_context context; + void (*try)(struct kunit_try_catch_context *context); + void (*catch)(struct kunit_try_catch_context *context); +}; + +void kunit_try_catch_init(struct kunit_try_catch *try_catch); + +void kunit_generic_try_catch_init(struct kunit_try_catch *try_catch); + /** * struct kunit - represents a running instance of a test. * @priv: for user to store arbitrary data. Commonly used to pass data created @@ -166,13 +186,17 @@ struct kunit { /* private: internal use only. */ const char *name; /* Read only after initialization! */ + struct kunit_try_catch try_catch; spinlock_t lock; /* Gaurds all mutable test state. */ bool success; /* Protected by lock. */ + bool death_test; /* Protected by lock. */ struct list_head resources; /* Protected by lock. */ + void (*set_death_test)(struct kunit *test, bool death_test); void (*vprintk)(const struct kunit *test, const char *level, struct va_format *vaf); void (*fail)(struct kunit *test, struct kunit_stream *stream); + void (*abort)(struct kunit *test); }; int kunit_init_test(struct kunit *test, const char *name); diff --git a/kunit/Makefile b/kunit/Makefile index 60a9ea6cb4697..e4c300f67479a 100644 --- a/kunit/Makefile +++ b/kunit/Makefile @@ -2,6 +2,7 @@ obj-$(CONFIG_KUNIT) += test.o \ string-stream.o \ kunit-stream.o -obj-$(CONFIG_KUNIT_TEST) += string-stream-test.o +obj-$(CONFIG_KUNIT_TEST) += test-test.o \ + string-stream-test.o obj-$(CONFIG_KUNIT_EXAMPLE_TEST) += example-test.o diff --git a/kunit/test-test.c b/kunit/test-test.c new file mode 100644 index 0000000000000..a936c041f1c8f --- /dev/null +++ b/kunit/test-test.c @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit test for core test infrastructure. + * + * Copyright (C) 2019, Google LLC. + * Author: Brendan Higgins + */ +#include + +struct kunit_try_catch_test_context { + struct kunit_try_catch *try_catch; + bool function_called; +}; + +void kunit_test_successful_try(struct kunit_try_catch_context *context) +{ + struct kunit_try_catch_test_context *ctx = context->test->priv; + + ctx->function_called = true; +} + +void kunit_test_no_catch(struct kunit_try_catch_context *context) +{ + KUNIT_FAIL(context->test, "Catch should not be called."); +} + +static void kunit_test_try_catch_successful_try_no_catch(struct kunit *test) +{ + struct kunit_try_catch_test_context *ctx = test->priv; + struct kunit_try_catch *try_catch = ctx->try_catch; + + try_catch->try = kunit_test_successful_try; + try_catch->catch = kunit_test_no_catch; + try_catch->run(try_catch); + + KUNIT_EXPECT_TRUE(test, ctx->function_called); +} + +void kunit_test_unsuccessful_try(struct kunit_try_catch_context *context) +{ + struct kunit_try_catch *try_catch = container_of(context, + struct kunit_try_catch, + context); + + try_catch->throw(try_catch); + KUNIT_FAIL(context->test, "This line should never be reached."); +} + +void kunit_test_catch(struct kunit_try_catch_context *context) +{ + struct kunit_try_catch_test_context *ctx = context->test->priv; + + ctx->function_called = true; +} + +static void kunit_test_try_catch_unsuccessful_try_does_catch(struct kunit *test) +{ + struct kunit_try_catch_test_context *ctx = test->priv; + struct kunit_try_catch *try_catch = ctx->try_catch; + + try_catch->try = kunit_test_unsuccessful_try; + try_catch->catch = kunit_test_catch; + try_catch->run(try_catch); + + KUNIT_EXPECT_TRUE(test, ctx->function_called); +} + +static void kunit_test_generic_try_catch_successful_try_no_catch( + struct kunit *test) +{ + struct kunit_try_catch_test_context *ctx = test->priv; + struct kunit_try_catch *try_catch = ctx->try_catch; + + kunit_generic_try_catch_init(try_catch); + + try_catch->try = kunit_test_successful_try; + try_catch->catch = kunit_test_no_catch; + try_catch->run(try_catch); + + KUNIT_EXPECT_TRUE(test, ctx->function_called); +} + +static void kunit_test_generic_try_catch_unsuccessful_try_does_catch( + struct kunit *test) +{ + struct kunit_try_catch_test_context *ctx = test->priv; + struct kunit_try_catch *try_catch = ctx->try_catch; + + kunit_generic_try_catch_init(try_catch); + + try_catch->try = kunit_test_unsuccessful_try; + try_catch->catch = kunit_test_catch; + try_catch->run(try_catch); + + KUNIT_EXPECT_TRUE(test, ctx->function_called); +} + +static int kunit_try_catch_test_init(struct kunit *test) +{ + struct kunit_try_catch_test_context *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + test->priv = ctx; + + ctx->try_catch = kunit_kmalloc(test, + sizeof(*ctx->try_catch), + GFP_KERNEL); + kunit_try_catch_init(ctx->try_catch); + ctx->try_catch->context.test = test; + + return 0; +} + +static struct kunit_case kunit_try_catch_test_cases[] = { + KUNIT_CASE(kunit_test_try_catch_successful_try_no_catch), + KUNIT_CASE(kunit_test_try_catch_unsuccessful_try_does_catch), + KUNIT_CASE(kunit_test_generic_try_catch_successful_try_no_catch), + KUNIT_CASE(kunit_test_generic_try_catch_unsuccessful_try_does_catch), + {}, +}; + +static struct kunit_module kunit_try_catch_test_module = { + .name = "kunit-try-catch-test", + .init = kunit_try_catch_test_init, + .test_cases = kunit_try_catch_test_cases, +}; +module_test(kunit_try_catch_test_module); diff --git a/kunit/test.c b/kunit/test.c index d18c50d5ed671..6e5244642ab07 100644 --- a/kunit/test.c +++ b/kunit/test.c @@ -6,9 +6,9 @@ * Author: Brendan Higgins */ -#include #include -#include +#include +#include #include static bool kunit_get_success(struct kunit *test) @@ -32,6 +32,27 @@ static void kunit_set_success(struct kunit *test, bool success) spin_unlock_irqrestore(&test->lock, flags); } +static bool kunit_get_death_test(struct kunit *test) +{ + unsigned long flags; + bool death_test; + + spin_lock_irqsave(&test->lock, flags); + death_test = test->death_test; + spin_unlock_irqrestore(&test->lock, flags); + + return death_test; +} + +static void kunit_set_death_test(struct kunit *test, bool death_test) +{ + unsigned long flags; + + spin_lock_irqsave(&test->lock, flags); + test->death_test = death_test; + spin_unlock_irqrestore(&test->lock, flags); +} + static int kunit_vprintk_emit(const struct kunit *test, int level, const char *fmt, @@ -70,13 +91,29 @@ static void kunit_fail(struct kunit *test, struct kunit_stream *stream) stream->commit(stream); } +static void __noreturn kunit_abort(struct kunit *test) +{ + kunit_set_death_test(test, true); + + test->try_catch.throw(&test->try_catch); + + /* + * Throw could not abort from test. + */ + kunit_err(test, "Throw could not abort from test!"); + show_stack(NULL, NULL); + BUG(); +} + int kunit_init_test(struct kunit *test, const char *name) { spin_lock_init(&test->lock); INIT_LIST_HEAD(&test->resources); test->name = name; + test->set_death_test = kunit_set_death_test; test->vprintk = kunit_vprintk; test->fail = kunit_fail; + test->abort = kunit_abort; return 0; } @@ -122,16 +159,171 @@ static void kunit_run_case_cleanup(struct kunit *test, } /* - * Performs all logic to run a test case. + * Handles an unexpected crash in a test case. */ -static bool kunit_run_case(struct kunit *test, - struct kunit_module *module, - struct kunit_case *test_case) +static void kunit_handle_test_crash(struct kunit *test, + struct kunit_module *module, + struct kunit_case *test_case) { - kunit_set_success(test, true); + kunit_err(test, "%s crashed", test_case->name); + /* + * TODO(brendanhiggins@google.com): This prints the stack trace up + * through this frame, not up to the frame that caused the crash. + */ + show_stack(NULL, NULL); + + kunit_case_internal_cleanup(test); +} + +static void kunit_generic_throw(struct kunit_try_catch *try_catch) +{ + try_catch->context.try_result = -EFAULT; + complete_and_exit(try_catch->context.try_completion, -EFAULT); +} + +static int kunit_generic_run_threadfn_adapter(void *data) +{ + struct kunit_try_catch *try_catch = data; + try_catch->try(&try_catch->context); + + complete_and_exit(try_catch->context.try_completion, 0); +} + +static void kunit_generic_run_try_catch(struct kunit_try_catch *try_catch) +{ + struct task_struct *task_struct; + struct kunit *test = try_catch->context.test; + int exit_code, wake_result; + DECLARE_COMPLETION(test_case_completion); + + try_catch->context.try_completion = &test_case_completion; + try_catch->context.try_result = 0; + task_struct = kthread_create(kunit_generic_run_threadfn_adapter, + try_catch, + "kunit_try_catch_thread"); + if (IS_ERR_OR_NULL(task_struct)) { + try_catch->catch(&try_catch->context); + return; + } + + wake_result = wake_up_process(task_struct); + if (wake_result != 0 && wake_result != 1) { + kunit_err(test, "task was not woken properly: %d", wake_result); + try_catch->catch(&try_catch->context); + } + + /* + * TODO(brendanhiggins@google.com): We should probably have some type of + * timeout here. The only question is what that timeout value should be. + * + * The intention has always been, at some point, to be able to label + * tests with some type of size bucket (unit/small, integration/medium, + * large/system/end-to-end, etc), where each size bucket would get a + * default timeout value kind of like what Bazel does: + * https://docs.bazel.build/versions/master/be/common-definitions.html#test.size + * There is still some debate to be had on exactly how we do this. (For + * one, we probably want to have some sort of test runner level + * timeout.) + * + * For more background on this topic, see: + * https://mike-bland.com/2011/11/01/small-medium-large.html + */ + wait_for_completion(&test_case_completion); + + exit_code = try_catch->context.try_result; + if (exit_code == -EFAULT) + try_catch->catch(&try_catch->context); + else if (exit_code == -EINTR) + kunit_err(test, "wake_up_process() was never called."); + else if (exit_code) + kunit_err(test, "Unknown error: %d", exit_code); +} + +void kunit_generic_try_catch_init(struct kunit_try_catch *try_catch) +{ + try_catch->run = kunit_generic_run_try_catch; + try_catch->throw = kunit_generic_throw; +} + +void __weak kunit_try_catch_init(struct kunit_try_catch *try_catch) +{ + kunit_generic_try_catch_init(try_catch); +} + +static void kunit_try_run_case(struct kunit_try_catch_context *context) +{ + struct kunit_try_catch_context *ctx = context; + struct kunit *test = ctx->test; + struct kunit_module *module = ctx->module; + struct kunit_case *test_case = ctx->test_case; + + /* + * kunit_run_case_internal may encounter a fatal error; if it does, we + * will jump to ENTER_HANDLER above instead of continuing normal control + * flow. + */ kunit_run_case_internal(test, module, test_case); + /* This line may never be reached. */ kunit_run_case_cleanup(test, module, test_case); +} + +static void kunit_catch_run_case(struct kunit_try_catch_context *context) +{ + struct kunit_try_catch_context *ctx = context; + struct kunit *test = ctx->test; + struct kunit_module *module = ctx->module; + struct kunit_case *test_case = ctx->test_case; + + if (kunit_get_death_test(test)) { + /* + * EXPECTED DEATH: kunit_run_case_internal encountered + * anticipated fatal error. Everything should be in a safe + * state. + */ + kunit_run_case_cleanup(test, module, test_case); + } else { + /* + * UNEXPECTED DEATH: kunit_run_case_internal encountered an + * unanticipated fatal error. We have no idea what the state of + * the test case is in. + */ + kunit_handle_test_crash(test, module, test_case); + kunit_set_success(test, false); + } +} + +/* + * Performs all logic to run a test case. It also catches most errors that + * occurs in a test case and reports them as failures. + * + * XXX: THIS DOES NOT FOLLOW NORMAL CONTROL FLOW. READ CAREFULLY!!! + */ +static bool kunit_run_case_catch_errors(struct kunit *test, + struct kunit_module *module, + struct kunit_case *test_case) +{ + struct kunit_try_catch *try_catch = &test->try_catch; + struct kunit_try_catch_context *context = &try_catch->context; + + kunit_try_catch_init(try_catch); + + kunit_set_success(test, true); + kunit_set_death_test(test, false); + + /* + * ENTER HANDLER: If a failure occurs, we enter here. + */ + context->test = test; + context->module = module; + context->test_case = test_case; + try_catch->try = kunit_try_run_case; + try_catch->catch = kunit_catch_run_case; + try_catch->run(try_catch); + /* + * EXIT HANDLER: test case has been run and all possible errors have + * been handled. + */ return kunit_get_success(test); } @@ -148,7 +340,7 @@ int kunit_run_tests(struct kunit_module *module) return ret; for (test_case = module->test_cases; test_case->run_case; test_case++) { - success = kunit_run_case(&test, module, test_case); + success = kunit_run_case_catch_errors(&test, module, test_case); if (!success) all_passed = false; From patchwork Thu Feb 14 21:37:21 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813875 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 2C6C017E0 for ; Thu, 14 Feb 2019 21:38:57 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 121222C05D for ; Thu, 14 Feb 2019 21:38:57 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 029492DBD4; Thu, 14 Feb 2019 21:38:56 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id E3D8B2DBAA for ; Thu, 14 Feb 2019 21:38:55 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id DD9D7208AE2CB; Thu, 14 Feb 2019 13:38:55 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::a4a; helo=mail-vk1-xa4a.google.com; envelope-from=37d9lxa4kdc4lboxnkxrsqqsxcqyyqvo.mywvsxeh-xfnswwvscdc.kl.ybq@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-vk1-xa4a.google.com (mail-vk1-xa4a.google.com [IPv6:2607:f8b0:4864:20::a4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 49E55208AE2BA for ; Thu, 14 Feb 2019 13:38:54 -0800 (PST) Received: by mail-vk1-xa4a.google.com with SMTP id y196so3129195vkd.0 for ; Thu, 14 Feb 2019 13:38:54 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=p+8Sydh82vyN+n72H3piuOaUY+1R5pAJ5gGQhUIxqHY=; b=B4l464YWE/Ejr/IkKV2eEkHWPAgZNWVMqwKaoniX9GIOuStKv1Zfoe4c6VWhLTnbum bJLvMfvM+j4SwJwDzIWUG1f+xrjxmSoR/dxy8o+IvFyQq1O5x1fWnbNhrkgcUEaBZh1b 0kA0I7exKkZcIL6EveKrW32iFQAD6WtrbZeU7T1NTyxV+YVgJW7QTm1L2Kv5r41JMdRb 8fCWRXx9Vcut27JIBvhzTQeDminqkRZ+RKXKwg9hEZl68yLxMW01skw0VqHMxXEnzqf7 QANp9NHIi9Sg771W1K/OTxrDHnBHtQM5jxC7MXppF5gIgXdR3AicscEcUXw8888i9Cjo TfZg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=p+8Sydh82vyN+n72H3piuOaUY+1R5pAJ5gGQhUIxqHY=; b=Ij1kbqCCZGGX08+iHKkuEMlcqvJkY6D/yf7tc3+15SxvA/8vNhkqblgMmvaz5fwyX3 7OhpJPYneSTbU6ywzQEvhHCte32n3T96HvomoLkpq8RahYYxu9Z2xXouU3y3sGC99urT PbuGE++9t8GmeNzBosg1fBGDZu5tNoL/ZdcuQ2hsY+bsMUIimLMKEa52yk6SofrUQNNH 6Q28LtjNfkT1GE/6cx13Ui5yyYqHutY57IyjWix0bnWFKYQwKjDCOAQstduUGcVFxAln tLEs/51IQ46ML8cxqJCGQFyEPx+aqCrLBgydFMtXJbAZYUha9MF50i8auQJwZfZZo0hc SFnw== X-Gm-Message-State: AHQUAuZHMGBSHTZ27Pcza/zcvSx36GIkiZaE1siGiKjBkb6SR5fK+g/K d40wmnKxbCbSmkQh4KhrugjNBhFLX/zxx09p2lay5Q== X-Google-Smtp-Source: AHgI3IbfpSoj34fZe2+Rs1/NLBevcLz4pYm3cNcYqwbF92z8VYdVp5wHUh3J+jvSbJ1ey4Fa11nWtv/ST7nTKceB2zM9Jg== X-Received: by 2002:a67:ee8e:: with SMTP id n14mr3913058vsp.45.1550180333374; Thu, 14 Feb 2019 13:38:53 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:21 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-10-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 09/17] kunit: test: add the concept of assertions From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add support for assertions which are like expectations except the test terminates if the assertion is not satisfied. Signed-off-by: Brendan Higgins --- include/kunit/test.h | 397 ++++++++++++++++++++++++++++++++++++- kunit/string-stream-test.c | 12 +- kunit/test-test.c | 2 + kunit/test.c | 33 +++ 4 files changed, 435 insertions(+), 9 deletions(-) diff --git a/include/kunit/test.h b/include/kunit/test.h index cd02dca96eb61..c42c67a9729fd 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -84,9 +84,10 @@ struct kunit; * @name: the name of the test case. * * A test case is a function with the signature, ``void (*)(struct kunit *)`` - * that makes expectations (see KUNIT_EXPECT_TRUE()) about code under test. Each - * test case is associated with a &struct kunit_module and will be run after the - * module's init function and followed by the module's exit function. + * that makes expectations and assertions (see KUNIT_EXPECT_TRUE() and + * KUNIT_ASSERT_TRUE()) about code under test. Each test case is associated with + * a &struct kunit_module and will be run after the module's init function and + * followed by the module's exit function. * * A test case should be static and should only be created with the KUNIT_CASE() * macro; additionally, every array of test cases should be terminated with an @@ -712,4 +713,394 @@ static inline void kunit_expect_binary(struct kunit *test, KUNIT_EXPECT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ } while (0) +static inline struct kunit_stream *kunit_assert_start(struct kunit *test, + const char *file, + const char *line) +{ + struct kunit_stream *stream = kunit_new_stream(test); + + stream->add(stream, "ASSERTION FAILED at %s:%s\n\t", file, line); + + return stream; +} + +static inline void kunit_assert_end(struct kunit *test, + bool success, + struct kunit_stream *stream) +{ + if (!success) { + test->fail(test, stream); + test->abort(test); + } else { + stream->clear(stream); + } +} + +#define KUNIT_ASSERT_START(test) \ + kunit_assert_start(test, __FILE__, __stringify(__LINE__)) + +#define KUNIT_ASSERT_END(test, success, stream) \ + kunit_assert_end(test, success, stream) + +#define KUNIT_ASSERT(test, success, message) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + \ + __stream->add(__stream, message); \ + KUNIT_ASSERT_END(test, success, __stream); \ +} while (0) + +#define KUNIT_ASSERT_MSG(test, success, message, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + \ + __stream->add(__stream, message); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + KUNIT_ASSERT_END(test, success, __stream); \ +} while (0) + +#define KUNIT_ASSERT_FAILURE(test, fmt, ...) \ + KUNIT_ASSERT_MSG(test, false, "", fmt, ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_TRUE() - Sets an assertion that @condition is true. + * @test: The test context object. + * @condition: an arbitrary boolean expression. The test fails and aborts when + * this does not evaluate to true. + * + * This and assertions of the form `KUNIT_ASSERT_*` will cause the test case to + * fail *and immediately abort* when the specified condition is not met. Unlike + * an expectation failure, it will prevent the test case from continuing to run; + * this is otherwise known as an *assertion failure*. + */ +#define KUNIT_ASSERT_TRUE(test, condition) \ + KUNIT_ASSERT(test, (condition), \ + "Asserted " #condition " is true, but is false.") + +#define KUNIT_ASSERT_TRUE_MSG(test, condition, fmt, ...) \ + KUNIT_ASSERT_MSG(test, (condition), \ + "Asserted " #condition " is true, but is false.\n",\ + fmt, ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_FALSE() - Sets an assertion that @condition is false. + * @test: The test context object. + * @condition: an arbitrary boolean expression. + * + * Sets an assertion that the value that @condition evaluates to is false. This + * is the same as KUNIT_EXPECT_FALSE(), except it causes an assertion failure + * (see KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_FALSE(test, condition) \ + KUNIT_ASSERT(test, !(condition), \ + "Asserted " #condition " is false, but is true.") + +#define KUNIT_ASSERT_FALSE_MSG(test, condition, fmt, ...) \ + KUNIT_ASSERT_MSG(test, !(condition), \ + "Asserted " #condition " is false, but is true.\n",\ + fmt, ##__VA_ARGS__) + +void kunit_assert_binary_msg(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line, + const char *fmt, ...); + +static inline void kunit_assert_binary(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line) +{ + kunit_assert_binary_msg(test, + left, left_name, + right, right_name, + compare_result, + compare_name, + file, + line, + NULL); +} + +/* + * A factory macro for defining the expectations for the basic comparisons + * defined for the built in types. + * + * Unfortunately, there is no common type that all types can be promoted to for + * which all the binary operators behave the same way as for the actual types + * (for example, there is no type that long long and unsigned long long can + * both be cast to where the comparison result is preserved for all values). So + * the best we can do is do the comparison in the original types and then coerce + * everything to long long for printing; this way, the comparison behaves + * correctly and the printed out value usually makes sense without + * interpretation, but can always be interpretted to figure out the actual + * value. + */ +#define KUNIT_ASSERT_BINARY(test, left, condition, right) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + kunit_assert_binary(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__)); \ +} while (0) + +#define KUNIT_ASSERT_BINARY_MSG(test, left, condition, right, fmt, ...) do { \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + kunit_assert_binary_msg(test, \ + (long long) __left, #left, \ + (long long) __right, #right, \ + __left condition __right, #condition, \ + __FILE__, __stringify(__LINE__), \ + fmt, ##__VA_ARGS__); \ +} while (0) + +/** + * KUNIT_ASSERT_EQ() - Sets an assertion that @left and @right are equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the values that @left and @right evaluate to are + * equal. This is the same as KUNIT_EXPECT_EQ(), except it causes an assertion + * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_EQ(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, ==, right) + +#define KUNIT_ASSERT_EQ_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + ==, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_NE() - An assertion that @left and @right are not equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the values that @left and @right evaluate to are not + * equal. This is the same as KUNIT_EXPECT_NE(), except it causes an assertion + * failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_NE(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, !=, right) + +#define KUNIT_ASSERT_NE_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + !=, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_LT() - An assertion that @left is less than @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the value that @left evaluates to is less than the + * value that @right evaluates to. This is the same as KUNIT_EXPECT_LT(), except + * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion + * is not met. + */ +#define KUNIT_ASSERT_LT(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, <, right) + +#define KUNIT_ASSERT_LT_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + <, \ + right, \ + fmt, \ + ##__VA_ARGS__) +/** + * KUNIT_ASSERT_LE() - An assertion that @left is less than or equal to @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the value that @left evaluates to is less than or + * equal to the value that @right evaluates to. This is the same as + * KUNIT_EXPECT_LE(), except it causes an assertion failure (see + * KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_LE(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, <=, right) + +#define KUNIT_ASSERT_LE_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + <=, \ + right, \ + fmt, \ + ##__VA_ARGS__) +/** + * KUNIT_ASSERT_GT() - An assertion that @left is greater than @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the value that @left evaluates to is greater than the + * value that @right evaluates to. This is the same as KUNIT_EXPECT_GT(), except + * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion + * is not met. + */ +#define KUNIT_ASSERT_GT(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, >, right) + +#define KUNIT_ASSERT_GT_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + >, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_GE() - Assertion that @left is greater than or equal to @right. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a primitive C type. + * @right: an arbitrary expression that evaluates to a primitive C type. + * + * Sets an assertion that the value that @left evaluates to is greater than the + * value that @right evaluates to. This is the same as KUNIT_EXPECT_GE(), except + * it causes an assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion + * is not met. + */ +#define KUNIT_ASSERT_GE(test, left, right) \ + KUNIT_ASSERT_BINARY(test, left, >=, right) + +#define KUNIT_ASSERT_GE_MSG(test, left, right, fmt, ...) \ + KUNIT_ASSERT_BINARY_MSG(test, \ + left, \ + >=, \ + right, \ + fmt, \ + ##__VA_ARGS__) + +/** + * KUNIT_ASSERT_STREQ() - An assertion that strings @left and @right are equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a null terminated string. + * @right: an arbitrary expression that evaluates to a null terminated string. + * + * Sets an assertion that the values that @left and @right evaluate to are + * equal. This is the same as KUNIT_EXPECT_STREQ(), except it causes an + * assertion failure (see KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_STREQ(test, left, right) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + \ + KUNIT_ASSERT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +#define KUNIT_ASSERT_STREQ_MSG(test, left, right, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + \ + KUNIT_ASSERT_END(test, !strcmp(left, right), __stream); \ +} while (0) + +/** + * KUNIT_ASSERT_STRNEQ() - Expects that strings @left and @right are not equal. + * @test: The test context object. + * @left: an arbitrary expression that evaluates to a null terminated string. + * @right: an arbitrary expression that evaluates to a null terminated string. + * + * Sets an expectation that the values that @left and @right evaluate to are + * not equal. This is semantically equivalent to + * KUNIT_ASSERT_TRUE(@test, strcmp((@left), (@right))). See KUNIT_ASSERT_TRUE() + * for more information. + */ +#define KUNIT_ASSERT_STRNEQ(test, left, right) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + \ + KUNIT_ASSERT_END(test, strcmp(left, right), __stream); \ +} while (0) + +#define KUNIT_ASSERT_STRNEQ_MSG(test, left, right, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(left) __left = (left); \ + typeof(right) __right = (right); \ + \ + __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); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + \ + KUNIT_ASSERT_END(test, strcmp(left, right), __stream); \ +} while (0) + +/** + * KUNIT_ASSERT_NOT_ERR_OR_NULL() - Assertion that @ptr is not null and not err. + * @test: The test context object. + * @ptr: an arbitrary pointer. + * + * Sets an assertion that the value that @ptr evaluates to is not null and not + * an errno stored in a pointer. This is the same as + * KUNIT_EXPECT_NOT_ERR_OR_NULL(), except it causes an assertion failure (see + * KUNIT_ASSERT_TRUE()) when the assertion is not met. + */ +#define KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) \ + __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)); \ + \ + KUNIT_ASSERT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) + +#define KUNIT_ASSERT_NOT_ERR_OR_NULL_MSG(test, ptr, fmt, ...) do { \ + struct kunit_stream *__stream = KUNIT_ASSERT_START(test); \ + typeof(ptr) __ptr = (ptr); \ + \ + if (!__ptr) { \ + __stream->add(__stream, \ + "Asserted " #ptr " is not null, but is."); \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + } \ + if (IS_ERR(__ptr)) { \ + __stream->add(__stream, \ + "Asserted " #ptr " is not error, but is: %ld", \ + PTR_ERR(__ptr)); \ + \ + __stream->add(__stream, fmt, ##__VA_ARGS__); \ + } \ + KUNIT_ASSERT_END(test, !IS_ERR_OR_NULL(__ptr), __stream); \ +} while (0) + #endif /* _KUNIT_TEST_H */ diff --git a/kunit/string-stream-test.c b/kunit/string-stream-test.c index 6cfef69568011..441afd11b43de 100644 --- a/kunit/string-stream-test.c +++ b/kunit/string-stream-test.c @@ -19,7 +19,7 @@ static void string_stream_test_get_string(struct kunit *test) stream->add(stream, " %s", "bar"); output = stream->get_string(stream); - KUNIT_EXPECT_STREQ(test, output, "Foo bar"); + KUNIT_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 kunit *test) stream->add(stream, "A"); output = stream->get_string(stream); - KUNIT_EXPECT_STREQ(test, output, "AAAAAAAAAA"); - KUNIT_EXPECT_EQ(test, stream->length, 10); - KUNIT_EXPECT_FALSE(test, stream->is_empty(stream)); + KUNIT_ASSERT_STREQ(test, output, "AAAAAAAAAA"); + KUNIT_ASSERT_EQ(test, stream->length, 10); + KUNIT_ASSERT_FALSE(test, stream->is_empty(stream)); kfree(output); stream->clear(stream); output = stream->get_string(stream); - KUNIT_EXPECT_STREQ(test, output, ""); - KUNIT_EXPECT_TRUE(test, stream->is_empty(stream)); + KUNIT_ASSERT_STREQ(test, output, ""); + KUNIT_ASSERT_TRUE(test, stream->is_empty(stream)); destroy_string_stream(stream); } diff --git a/kunit/test-test.c b/kunit/test-test.c index a936c041f1c8f..0b4ad6690310d 100644 --- a/kunit/test-test.c +++ b/kunit/test-test.c @@ -100,11 +100,13 @@ static int kunit_try_catch_test_init(struct kunit *test) struct kunit_try_catch_test_context *ctx; ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); test->priv = ctx; ctx->try_catch = kunit_kmalloc(test, sizeof(*ctx->try_catch), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->try_catch); kunit_try_catch_init(ctx->try_catch); ctx->try_catch->context.test = test; diff --git a/kunit/test.c b/kunit/test.c index 6e5244642ab07..9cc8ecdb079b0 100644 --- a/kunit/test.c +++ b/kunit/test.c @@ -495,3 +495,36 @@ void kunit_expect_binary_msg(struct kunit *test, kunit_expect_end(test, compare_result, stream); } +void kunit_assert_binary_msg(struct kunit *test, + long long left, const char *left_name, + long long right, const char *right_name, + bool compare_result, + const char *compare_name, + const char *file, + const char *line, + const char *fmt, ...) +{ + struct kunit_stream *stream = kunit_assert_start(test, file, line); + struct va_format vaf; + va_list args; + + 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); + + if (fmt) { + va_start(args, fmt); + + vaf.fmt = fmt; + vaf.va = &args; + + stream->add(stream, "\n%pV", &vaf); + + va_end(args); + } + + kunit_assert_end(test, compare_result, stream); +} + From patchwork Thu Feb 14 21:37:22 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813877 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 9FBB61390 for ; Thu, 14 Feb 2019 21:38:59 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 858B42E7C5 for ; Thu, 14 Feb 2019 21:38:59 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 784B82E7D1; Thu, 14 Feb 2019 21:38:59 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 148D12E7C5 for ; Thu, 14 Feb 2019 21:38:59 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 09C6B208AE2CA; Thu, 14 Feb 2019 13:38:59 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::e4a; helo=mail-vs1-xe4a.google.com; envelope-from=3799lxa4kddandqzpmztussuzesaasxq.oayxuzgj-zhpuyyxuefe.mn.ads@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-vs1-xe4a.google.com (mail-vs1-xe4a.google.com [IPv6:2607:f8b0:4864:20::e4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 20396208AE2C8 for ; Thu, 14 Feb 2019 13:38:57 -0800 (PST) Received: by mail-vs1-xe4a.google.com with SMTP id 184so1830645vso.13 for ; Thu, 14 Feb 2019 13:38:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=lFB3ckD9wxM7bLXj4FIGXk/8wLU/9JJW8w6AYqQ9grk=; b=wR5UZ8MnBfmgt0mrk9OI2zfDUhZY2FSpJFlc0H37jwgc96pBztb7fGKWTkoOFM28Ga QdMIu5N3UkjMmm7021TzRYk/cV1BnPbW4MtjUKPwt51uaE+fMNPFoimjbpRGCDHRC4qG rF/9HGEJTgXVmjERaYbSkHQNurtVfrADHvm+4f2etjUc19ab4p6e7BsAxhXpCzh2DVbh 1qIqHUMYZmAhWwLj0wStuzKrlp2f5ArmCo8Pw4WHmaV0ubR/6cHsjshHUAlvy2ad4Zc7 fT6+TNOikOpDCk2iZY9GB/1MB0KgGDOgjPxVqJZHudZCO4TukRT9wX0iqh4to7EcadBk jKQg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=lFB3ckD9wxM7bLXj4FIGXk/8wLU/9JJW8w6AYqQ9grk=; b=CoMrqWPw7WRR/k81PKkSXKDhx+SxdTZ0llV0slCUNTeQucYwbymApqBMvY6QdXwkAD ZqVm9ZfowqTrYgMRIsjWRES53h4RQ1hw0NWWF6guLNz5tYUH8BH4lbeZsHyxAjcJg9Vq ex6CM+RCc2Mtnuem8YzkPxavk7m21P3jX/HHvrzZv237opaW2Zc0bYxmFovmhS9WAgNx zx7rnL96woiSbPpr6Kemwkttqy7d6lo8xNfUB45aUqzQZK0zlYX9coqkaqhtkrR/stg9 uc46XKdBeiDT0Yro9Wp00W58DeHkTs94N/qpTcBONz2n3tcM1O1r5qDv0IFrbco3kGiv UPOg== X-Gm-Message-State: AHQUAuZeN+FD/On6sERAKpG4MhMXMdbm68kpVvi1QpbqaTS8Bki4zMzY oO9NxTna4Zs5NhJvON5lx5F8/5g6OJeixF2m6TZ+fA== X-Google-Smtp-Source: AHgI3IZSFaDNk0CEH4L9GvdAED7vCeS8gXXQOioZtPpSgMCEqNw/swX6iIzcGwBJejpW5Xow4Gqbz47ePA5Svka1+dm8fw== X-Received: by 2002:ac5:c203:: with SMTP id m3mr3934061vkk.19.1550180335945; Thu, 14 Feb 2019 13:38:55 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:22 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-11-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 10/17] kunit: test: add test managed resource tests From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, Avinash Kondareddy , daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Tests how tests interact with test managed resources in their lifetime. Signed-off-by: Avinash Kondareddy Signed-off-by: Brendan Higgins --- kunit/test-test.c | 121 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) diff --git a/kunit/test-test.c b/kunit/test-test.c index 0b4ad6690310d..bb34431398526 100644 --- a/kunit/test-test.c +++ b/kunit/test-test.c @@ -127,3 +127,124 @@ static struct kunit_module kunit_try_catch_test_module = { .test_cases = kunit_try_catch_test_cases, }; module_test(kunit_try_catch_test_module); + +/* + * Context for testing test managed resources + * is_resource_initialized is used to test arbitrary resources + */ +struct kunit_test_resource_context { + struct kunit test; + bool is_resource_initialized; +}; + +static int fake_resource_init(struct kunit_resource *res, void *context) +{ + struct kunit_test_resource_context *ctx = context; + + res->allocation = &ctx->is_resource_initialized; + ctx->is_resource_initialized = true; + return 0; +} + +static void fake_resource_free(struct kunit_resource *res) +{ + bool *is_resource_initialized = res->allocation; + + *is_resource_initialized = false; +} + +static void kunit_resource_test_init_resources(struct kunit *test) +{ + struct kunit_test_resource_context *ctx = test->priv; + + kunit_init_test(&ctx->test, "testing_test_init_test"); + + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources)); +} + +static void kunit_resource_test_alloc_resource(struct kunit *test) +{ + struct kunit_test_resource_context *ctx = test->priv; + struct kunit_resource *res; + kunit_resource_free_t free = fake_resource_free; + + res = kunit_alloc_resource(&ctx->test, + fake_resource_init, + fake_resource_free, + ctx); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, res); + KUNIT_EXPECT_EQ(test, &ctx->is_resource_initialized, res->allocation); + KUNIT_EXPECT_TRUE(test, list_is_last(&res->node, &ctx->test.resources)); + KUNIT_EXPECT_EQ(test, free, res->free); +} + +static void kunit_resource_test_free_resource(struct kunit *test) +{ + struct kunit_test_resource_context *ctx = test->priv; + struct kunit_resource *res = kunit_alloc_resource(&ctx->test, + fake_resource_init, + fake_resource_free, + ctx); + + kunit_free_resource(&ctx->test, res); + + KUNIT_EXPECT_EQ(test, false, ctx->is_resource_initialized); + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources)); +} + +#define KUNIT_RESOURCE_NUM 5 +static void kunit_resource_test_cleanup_resources(struct kunit *test) +{ + int i; + struct kunit_test_resource_context *ctx = test->priv; + struct kunit_resource *resources[KUNIT_RESOURCE_NUM]; + + for (i = 0; i < KUNIT_RESOURCE_NUM; i++) { + resources[i] = kunit_alloc_resource(&ctx->test, + fake_resource_init, + fake_resource_free, + ctx); + } + + kunit_cleanup(&ctx->test); + + KUNIT_EXPECT_TRUE(test, list_empty(&ctx->test.resources)); +} + +static int kunit_resource_test_init(struct kunit *test) +{ + struct kunit_test_resource_context *ctx = + kzalloc(sizeof(*ctx), GFP_KERNEL); + + if (!ctx) + return -ENOMEM; + test->priv = ctx; + + kunit_init_test(&ctx->test, "test_test_context"); + return 0; +} + +static void kunit_resource_test_exit(struct kunit *test) +{ + struct kunit_test_resource_context *ctx = test->priv; + + kunit_cleanup(&ctx->test); + kfree(ctx); +} + +static struct kunit_case kunit_resource_test_cases[] = { + KUNIT_CASE(kunit_resource_test_init_resources), + KUNIT_CASE(kunit_resource_test_alloc_resource), + KUNIT_CASE(kunit_resource_test_free_resource), + KUNIT_CASE(kunit_resource_test_cleanup_resources), + {}, +}; + +static struct kunit_module kunit_resource_test_module = { + .name = "kunit-resource-test", + .init = kunit_resource_test_init, + .exit = kunit_resource_test_exit, + .test_cases = kunit_resource_test_cases, +}; +module_test(kunit_resource_test_module); From patchwork Thu Feb 14 21:37:23 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813879 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 6244B1390 for ; Thu, 14 Feb 2019 21:39:02 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 464B82E7C5 for ; Thu, 14 Feb 2019 21:39:02 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 336762E7D1; Thu, 14 Feb 2019 21:39:02 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 3CF7E2E7C5 for ; Thu, 14 Feb 2019 21:39:01 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 231CC208AE2C6; Thu, 14 Feb 2019 13:39:01 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::34a; helo=mail-ot1-x34a.google.com; envelope-from=38t9lxa4kddmqgtcspcwxvvxchvddvat.rdbaxcjm-cksxbbaxhih.pq.dgv@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-ot1-x34a.google.com (mail-ot1-x34a.google.com [IPv6:2607:f8b0:4864:20::34a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id DF4F5208AE2C3 for ; Thu, 14 Feb 2019 13:38:59 -0800 (PST) Received: by mail-ot1-x34a.google.com with SMTP id a1so5764559otl.9 for ; Thu, 14 Feb 2019 13:38:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=08p6LXJC2eOmIY3InQ6qxCCQbTx/hOsrRz7mzip6vVQ=; b=jZgYCZZ0MJv5+THlsUyohqICtQNgP0QaHQK/z9dQ2yAutpNoCti9uoBKok2HYqelyW gNQWrF4dJ2nbUIlEWXh0OM6Ix7d+/K1UdFZIMSVAak2NeEqjbUL+bAosONxScwg4u7vS KI5Mu/NkXBzKRl5Ph8Le2SYZUgjcCzPNW+1i90dRSr6A+y6rImMVIN2/va9OiohuEFKU 89ofCGsxPlE6O+8E9OxxCpl5fem25H4WjtaTaBI8PVfu3MhEKuhgmUIZe7Abah36BPSk /jS2Bf5ErscJrHLgSQ1e/zy9aA36kKK3DKdxNG2dnHPMX+E0DySaDDJuZsv+C67+Jz1N V1ag== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=08p6LXJC2eOmIY3InQ6qxCCQbTx/hOsrRz7mzip6vVQ=; b=oTh5A+FeQ0+7f95izfPUJ3q09pQgmAOD9CKMcUERmrv1cXj1bNxfE3jkzS2bod+dkV s7N/+wHrUoGDDZaOG8plulQDCFKNNYyhD6LJMJPXSv5LB3687sBbKKBrALDGF5qdHHbV 9vwI4lbUpJvwqtm7xJ4tVWjSibRmhDzhRQEkNQALS2kXUrNvZAQM4FUmKkBiCQ9dWkdg xqdr/BhEsOFpJpj556mHR2iaV2chfmr0Q5ZcyZMw4/l2Ak1A2phcUe0nGjjkRp76Fswe OD6tgN/S95nmABJudgrKRU9taMP1y36jeAU/jDDsm1NLZefmWEafLAnAVsZb2HujyQYr 9BsA== X-Gm-Message-State: AHQUAuZyANH03rMHglsq6mpBUlPaKZ3KGB+reVguefvAzBUik35XxrdN 2vSFj+Z9beLeU9vDCcUsTFoCGYWAT+/tZBGPuY8bcA== X-Google-Smtp-Source: AHgI3IaWH68HDxcFPg1bCdiky+YA+574zMEFM7qIisxkFQKBKPnLp5yjulce0WtytgimJQ14iCu4iLWCWqMFhNeNugRx6A== X-Received: by 2002:a05:6830:8b:: with SMTP id a11mr3441406oto.33.1550180338477; Thu, 14 Feb 2019 13:38:58 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:23 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-12-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 11/17] kunit: tool: add Python wrappers for running KUnit tests From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, Felix Guo , wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP From: Felix Guo The ultimate goal is to create minimal isolated test binaries; in the meantime we are using UML to provide the infrastructure to run tests, so define an abstract way to configure and run tests that allow us to change the context in which tests are built without affecting the user. This also makes pretty and dynamic error reporting, and a lot of other nice features easier. kunit_config.py: - parse .config and Kconfig files. kunit_kernel.py: provides helper functions to: - configure the kernel using kunitconfig. - build the kernel with the appropriate configuration. - provide function to invoke the kernel and stream the output back. Signed-off-by: Felix Guo Signed-off-by: Brendan Higgins --- Changes Since Last Version - Added support for building and running tests in an external directory. - Squashed with most other kunit_tool commits, since most did not represent a coherent new feature. --- tools/testing/kunit/.gitignore | 3 + tools/testing/kunit/kunit.py | 78 +++++++++++++++ tools/testing/kunit/kunit_config.py | 66 +++++++++++++ tools/testing/kunit/kunit_kernel.py | 148 ++++++++++++++++++++++++++++ tools/testing/kunit/kunit_parser.py | 119 ++++++++++++++++++++++ 5 files changed, 414 insertions(+) create mode 100644 tools/testing/kunit/.gitignore create mode 100755 tools/testing/kunit/kunit.py create mode 100644 tools/testing/kunit/kunit_config.py create mode 100644 tools/testing/kunit/kunit_kernel.py create mode 100644 tools/testing/kunit/kunit_parser.py diff --git a/tools/testing/kunit/.gitignore b/tools/testing/kunit/.gitignore new file mode 100644 index 0000000000000..c791ff59a37a9 --- /dev/null +++ b/tools/testing/kunit/.gitignore @@ -0,0 +1,3 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] \ No newline at end of file diff --git a/tools/testing/kunit/kunit.py b/tools/testing/kunit/kunit.py new file mode 100755 index 0000000000000..7413ec7351a20 --- /dev/null +++ b/tools/testing/kunit/kunit.py @@ -0,0 +1,78 @@ +#!/usr/bin/python3 +# SPDX-License-Identifier: GPL-2.0 +# +# A thin wrapper on top of the KUnit Kernel +# +# Copyright (C) 2019, Google LLC. +# Author: Felix Guo +# Author: Brendan Higgins + +import argparse +import sys +import os +import time + +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') + +parser.add_argument('--jobs', + help='As in the make command, "Specifies the number of ' + 'jobs (commands) to run simultaneously."', + type=int, default=8, metavar='jobs') + +parser.add_argument('--build_dir', + help='As in the make command, it specifies the build ' + 'directory.', + type=str, default=None, metavar='build_dir') + +cli_args = parser.parse_args() + +linux = kunit_kernel.LinuxSourceTree() + +build_dir = None +if cli_args.build_dir: + build_dir = cli_args.build_dir + +config_start = time.time() +success = linux.build_reconfig(build_dir) +config_end = time.time() +if not success: + quit() + +kunit_parser.print_with_timestamp('Building KUnit Kernel ...') + +build_start = time.time() + +success = linux.build_um_kernel(jobs=cli_args.jobs, build_dir=build_dir) +build_end = time.time() +if not success: + quit() + +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, + build_dir=build_dir)) +else: + kunit_parser.parse_run_tests(linux.run_kernel(timeout=cli_args.timeout, + build_dir=build_dir)) + +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)) diff --git a/tools/testing/kunit/kunit_config.py b/tools/testing/kunit/kunit_config.py new file mode 100644 index 0000000000000..167f47d9ab8e4 --- /dev/null +++ b/tools/testing/kunit/kunit_config.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Builds a .config from a kunitconfig. +# +# Copyright (C) 2019, Google LLC. +# Author: Felix Guo +# Author: Brendan Higgins + +import collections +import re + +CONFIG_IS_NOT_SET_PATTERN = r'^# CONFIG_\w+ is not set$' +CONFIG_PATTERN = r'^CONFIG_\w+=\S+$' + +KconfigEntryBase = collections.namedtuple('KconfigEntry', ['raw_entry']) + + +class KconfigEntry(KconfigEntryBase): + + def __str__(self) -> str: + return self.raw_entry + + +class KconfigParseError(Exception): + """Error parsing Kconfig defconfig or .config.""" + + +class Kconfig(object): + """Represents defconfig or .config specified using the Kconfig language.""" + + def __init__(self): + self._entries = [] + + def entries(self): + return set(self._entries) + + def add_entry(self, entry: KconfigEntry) -> None: + self._entries.append(entry) + + def is_subset_of(self, other: "Kconfig") -> bool: + return self.entries().issubset(other.entries()) + + def write_to_file(self, path: str) -> None: + with open(path, 'w') as f: + for entry in self.entries(): + f.write(str(entry) + '\n') + + def parse_from_string(self, blob: str) -> None: + """Parses a string containing KconfigEntrys and populates this Kconfig.""" + self._entries = [] + is_not_set_matcher = re.compile(CONFIG_IS_NOT_SET_PATTERN) + config_matcher = re.compile(CONFIG_PATTERN) + for line in blob.split('\n'): + line = line.strip() + if not line: + continue + elif config_matcher.match(line) or is_not_set_matcher.match(line): + self._entries.append(KconfigEntry(line)) + elif line[0] == '#': + continue + else: + raise KconfigParseError('Failed to parse: ' + line) + + def read_from_file(self, path: str) -> None: + with open(path, 'r') as f: + self.parse_from_string(f.read()) diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py new file mode 100644 index 0000000000000..07c0abf2f47df --- /dev/null +++ b/tools/testing/kunit/kunit_kernel.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Runs UML kernel, collects output, and handles errors. +# +# Copyright (C) 2019, Google LLC. +# Author: Felix Guo +# Author: Brendan Higgins + + +import logging +import subprocess +import os + +import kunit_config + +KCONFIG_PATH = '.config' + +class ConfigError(Exception): + """Represents an error trying to configure the Linux kernel.""" + + +class BuildError(Exception): + """Represents an error trying to build the Linux kernel.""" + + +class LinuxSourceTreeOperations(object): + """An abstraction over command line operations performed on a source tree.""" + + def make_mrproper(self): + try: + subprocess.check_output(['make', 'mrproper']) + except OSError as e: + raise ConfigError('Could not call make command: ' + e) + except subprocess.CalledProcessError as e: + raise ConfigError(e.output) + + def make_olddefconfig(self, build_dir): + command = ['make', 'ARCH=um', 'olddefconfig'] + if build_dir: + command += ['O=' + build_dir] + try: + subprocess.check_output(command) + except OSError as e: + raise ConfigError('Could not call make command: ' + e) + except subprocess.CalledProcessError as e: + raise ConfigError(e.output) + + def make(self, jobs, build_dir): + command = ['make', 'ARCH=um', '--jobs=' + str(jobs)] + if build_dir: + command += ['O=' + build_dir] + try: + subprocess.check_output(command) + except OSError as e: + raise BuildError('Could not call execute make: ' + e) + except subprocess.CalledProcessError as e: + raise BuildError(e.output) + + def linux_bin(self, params, timeout, build_dir): + """Runs the Linux UML binary. Must be named 'linux'.""" + linux_bin = './linux' + if build_dir: + linux_bin = os.path.join(build_dir, 'linux') + process = subprocess.Popen( + [linux_bin] + params, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + process.wait(timeout=timeout) + return process + + +def get_kconfig_path(build_dir): + kconfig_path = KCONFIG_PATH + if build_dir: + kconfig_path = os.path.join(build_dir, KCONFIG_PATH) + return kconfig_path + +class LinuxSourceTree(object): + """Represents a Linux kernel source tree with KUnit tests.""" + + def __init__(self): + self._kconfig = kunit_config.Kconfig() + self._kconfig.read_from_file('kunitconfig') + self._ops = LinuxSourceTreeOperations() + + def clean(self): + try: + self._ops.make_mrproper() + except ConfigError as e: + logging.error(e) + return False + return True + + def build_config(self, build_dir): + kconfig_path = get_kconfig_path(build_dir) + if build_dir and not os.path.exists(build_dir): + os.mkdir(build_dir) + self._kconfig.write_to_file(kconfig_path) + try: + self._ops.make_olddefconfig(build_dir) + except ConfigError as e: + logging.error(e) + return False + validated_kconfig = kunit_config.Kconfig() + validated_kconfig.read_from_file(kconfig_path) + if not self._kconfig.is_subset_of(validated_kconfig): + logging.error('Provided Kconfig is not contained in validated .config!') + return False + return True + + def build_reconfig(self, build_dir): + """Creates a new .config if it is not a subset of the kunitconfig.""" + kconfig_path = get_kconfig_path(build_dir) + if os.path.exists(kconfig_path): + existing_kconfig = kunit_config.Kconfig() + existing_kconfig.read_from_file(kconfig_path) + if not self._kconfig.is_subset_of(existing_kconfig): + print('Regenerating .config ...') + os.remove(kconfig_path) + return self.build_config(build_dir) + else: + return True + else: + print('Generating .config ...') + return self.build_config(build_dir) + + def build_um_kernel(self, jobs, build_dir): + try: + self._ops.make_olddefconfig(build_dir) + self._ops.make(jobs, build_dir) + except (ConfigError, BuildError) as e: + logging.error(e) + return False + used_kconfig = kunit_config.Kconfig() + used_kconfig.read_from_file(get_kconfig_path(build_dir)) + if not self._kconfig.is_subset_of(used_kconfig): + logging.error('Provided Kconfig is not contained in final config!') + return False + return True + + def run_kernel(self, args=[], timeout=None, build_dir=None): + args.extend(['mem=256M']) + process = self._ops.linux_bin(args, timeout, build_dir) + with open('test.log', 'w') as f: + for line in process.stdout: + f.write(line.rstrip().decode('ascii') + '\n') + yield line.rstrip().decode('ascii') diff --git a/tools/testing/kunit/kunit_parser.py b/tools/testing/kunit/kunit_parser.py new file mode 100644 index 0000000000000..6c81d4dcfabb5 --- /dev/null +++ b/tools/testing/kunit/kunit_parser.py @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Parses test results from a kernel dmesg log. +# +# Copyright (C) 2019, Google LLC. +# Author: Felix Guo +# Author: Brendan Higgins + +import re +from datetime import datetime + +kunit_start_re = re.compile('printk: 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) + +DIVIDER = "=" * 30 + +RESET = '\033[0;0m' + +def red(text): + return '\033[1;31m' + text + RESET + +def yellow(text): + return '\033[1;33m' + text + RESET + +def green(text): + return '\033[1;32m' + text + RESET + +def print_with_timestamp(message): + print('[%s] %s' % (datetime.now().strftime('%H:%M:%S'), message)) + +def print_log(log): + for m in log: + print_with_timestamp(m) + +def parse_run_tests(kernel_output): + test_case_output = re.compile('^kunit .*?: (.*)$') + + test_module_success = re.compile('^kunit .*: all tests passed') + test_module_fail = re.compile('^kunit .*: one or more tests failed') + + test_case_success = re.compile('^kunit (.*): (.*) passed') + test_case_fail = re.compile('^kunit (.*): (.*) failed') + test_case_crash = re.compile('^kunit (.*): (.*) crashed') + + total_tests = set() + failed_tests = set() + crashed_tests = set() + + def get_test_name(match): + return match.group(1) + ":" + match.group(2) + + current_case_log = [] + def end_one_test(match, log): + log.clear() + total_tests.add(get_test_name(match)) + + print_with_timestamp(DIVIDER) + for line in isolate_kunit_output(kernel_output): + # Ignore module output: + if (test_module_success.match(line) or + test_module_fail.match(line)): + print_with_timestamp(DIVIDER) + continue + + match = re.match(test_case_success, line) + if match: + print_with_timestamp(green("[PASSED] ") + + get_test_name(match)) + end_one_test(match, current_case_log) + continue + + match = re.match(test_case_fail, line) + # Crashed tests will report as both failed and crashed. We only + # want to show and count it once. + if match and get_test_name(match) not in crashed_tests: + failed_tests.add(get_test_name(match)) + print_with_timestamp(red("[FAILED] " + + get_test_name(match))) + print_log(map(yellow, current_case_log)) + print_with_timestamp("") + end_one_test(match, current_case_log) + continue + + match = re.match(test_case_crash, line) + if match: + crashed_tests.add(get_test_name(match)) + print_with_timestamp(yellow("[CRASH] " + + get_test_name(match))) + print_log(current_case_log) + print_with_timestamp("") + end_one_test(match, current_case_log) + continue + + # Strip off the `kunit module-name:` prefix + match = re.match(test_case_output, line) + if match: + current_case_log.append(match.group(1)) + else: + current_case_log.append(line) + + fmt = green if (len(failed_tests) + len(crashed_tests) == 0) else red + print_with_timestamp( + fmt("Testing complete. %d tests run. %d failed. %d crashed." % + (len(total_tests), len(failed_tests), len(crashed_tests)))) + From patchwork Thu Feb 14 21:37:24 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813881 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id D74856C2 for ; Thu, 14 Feb 2019 21:39:03 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id C2D3C2E7C5 for ; Thu, 14 Feb 2019 21:39:03 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id B48E22E7D1; Thu, 14 Feb 2019 21:39:03 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 542C72E7C5 for ; Thu, 14 Feb 2019 21:39:03 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 3B0B1208AE2C9; Thu, 14 Feb 2019 13:39:03 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::a4a; helo=mail-vk1-xa4a.google.com; envelope-from=39d9lxa4kddytjwfvsfzayyafkyggydw.ugedafmp-fnvaeedaklk.st.gjy@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-vk1-xa4a.google.com (mail-vk1-xa4a.google.com [IPv6:2607:f8b0:4864:20::a4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 05A69208AE2CF for ; Thu, 14 Feb 2019 13:39:02 -0800 (PST) Received: by mail-vk1-xa4a.google.com with SMTP id x85so3131559vkx.2 for ; Thu, 14 Feb 2019 13:39:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=GNGjlJhCWVkVbVZkHNZ4j2GxkLtq29hBLpGHCevAScI=; b=e55gdBIhIqOGFWr69kTRFk5llbRffDUr5rOzT3ycf9t0WLuBIwZ59KoZDVu2n1ATc9 ADuvo2RP80FpwpHyTraJSjbeVO4LzYWuveXK4GhciRPBu2p5rZb+0aIWm/U2ZP6MbJjg +Gacyv5qsq9aU/91B7Id1Zn5H3644UmrAejmddOu3KWxwrt1IPlWYZhk/MvpAU6iZJos a5sFD3XTnhZHI39EEpHOUcRRDnz4fUvO2qw6FhFsD6G1tB9GS097AGjgocTFm3oIQ/Mk m44ICVaeg97H4fSCw7U7GDQMJaJnE56CyunaJiRSS9EuifWcoyGTs0bBdqBIOGTtQ6io mqOw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=GNGjlJhCWVkVbVZkHNZ4j2GxkLtq29hBLpGHCevAScI=; b=nyT1afaMpNXyWjpvAQURJn/q1I18OF/aknJ8rMHXWqyutB5BCPbvDs98p3sJ6EUnHW qw0+G0TKJxDFEGiRqfuC7I5Z8Q7kqOIME5rBsL0WEZCZjcdc3SOzQ9w1da1iad5ht9Me bZnjJ7W6Po0umFrDkI53Wkt03mszdKhZ62g4wxY4W7ptRh3hy8mNJJYKSkDtE5MBffwA yZqrS333yp38SDc0+gIj29F4ouAlEfwZ6n1zNGqVZVAev4dVxjawKU8ZLD0yUMzqjPtU 4sMRAwhkCX/1oQI5ezKqh51/JfMQXYsCELcaZHM2ndII9kT3f1YE4e/OzoSN56TE9O/g 7JyA== X-Gm-Message-State: AHQUAubS0Nrem8lexo3AHt+M+IVLk017CPiRe0qj1ZndpX9HQoQFzld0 DnV0tXLyCWXjg4mL0EsM6wT3UzzBGONz9NR+fprmlw== X-Google-Smtp-Source: AHgI3Ib+6QisURxJgK8DqnTorQ+Dxqa7Fcsh0aQhVSV3Kh6hxIJ1cHBWJPRflApfNfu8H17D8PJsiQS18I9aJd06tS/oFw== X-Received: by 2002:a67:ee8e:: with SMTP id n14mr3913380vsp.45.1550180341082; Thu, 14 Feb 2019 13:39:01 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:24 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-13-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 12/17] kunit: defconfig: add defconfigs for building KUnit tests From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add defconfig for UML and a fragment that can be used to configure other architectures for building KUnit tests. Add option to kunit_tool to use a defconfig to create the kunitconfig. Signed-off-by: Brendan Higgins --- Changes Since Last Version - This patch is new adding default configs to build KUnit. - NOTE: there is still some discussion to be had here about whether we should go with a defconfig, a config fragment, or both. --- arch/um/configs/kunit_defconfig | 8 ++++++++ tools/testing/kunit/configs/all_tests.config | 8 ++++++++ tools/testing/kunit/kunit.py | 17 +++++++++++++++-- tools/testing/kunit/kunit_kernel.py | 3 ++- 4 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 arch/um/configs/kunit_defconfig create mode 100644 tools/testing/kunit/configs/all_tests.config diff --git a/arch/um/configs/kunit_defconfig b/arch/um/configs/kunit_defconfig new file mode 100644 index 0000000000000..bfe49689038f1 --- /dev/null +++ b/arch/um/configs/kunit_defconfig @@ -0,0 +1,8 @@ +CONFIG_OF=y +CONFIG_OF_UNITTEST=y +CONFIG_OF_OVERLAY=y +CONFIG_I2C=y +CONFIG_I2C_MUX=y +CONFIG_KUNIT=y +CONFIG_KUNIT_TEST=y +CONFIG_KUNIT_EXAMPLE_TEST=y diff --git a/tools/testing/kunit/configs/all_tests.config b/tools/testing/kunit/configs/all_tests.config new file mode 100644 index 0000000000000..bfe49689038f1 --- /dev/null +++ b/tools/testing/kunit/configs/all_tests.config @@ -0,0 +1,8 @@ +CONFIG_OF=y +CONFIG_OF_UNITTEST=y +CONFIG_OF_OVERLAY=y +CONFIG_I2C=y +CONFIG_I2C_MUX=y +CONFIG_KUNIT=y +CONFIG_KUNIT_TEST=y +CONFIG_KUNIT_EXAMPLE_TEST=y diff --git a/tools/testing/kunit/kunit.py b/tools/testing/kunit/kunit.py index 7413ec7351a20..63e9fb3b60200 100755 --- a/tools/testing/kunit/kunit.py +++ b/tools/testing/kunit/kunit.py @@ -11,6 +11,7 @@ import argparse import sys import os import time +import shutil import kunit_config import kunit_kernel @@ -36,14 +37,26 @@ parser.add_argument('--build_dir', 'directory.', type=str, default=None, metavar='build_dir') -cli_args = parser.parse_args() +parser.add_argument('--defconfig', + help='Uses a default kunitconfig.', + action='store_true') -linux = kunit_kernel.LinuxSourceTree() +def create_default_kunitconfig(): + if not os.path.exists(kunit_kernel.KUNITCONFIG_PATH): + shutil.copyfile('arch/um/configs/kunit_defconfig', + kunit_kernel.KUNITCONFIG_PATH) + +cli_args = parser.parse_args() build_dir = None if cli_args.build_dir: build_dir = cli_args.build_dir +if cli_args.defconfig: + create_default_kunitconfig() + +linux = kunit_kernel.LinuxSourceTree() + config_start = time.time() success = linux.build_reconfig(build_dir) config_end = time.time() diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py index 07c0abf2f47df..bf38768353313 100644 --- a/tools/testing/kunit/kunit_kernel.py +++ b/tools/testing/kunit/kunit_kernel.py @@ -14,6 +14,7 @@ import os import kunit_config KCONFIG_PATH = '.config' +KUNITCONFIG_PATH = 'kunitconfig' class ConfigError(Exception): """Represents an error trying to configure the Linux kernel.""" @@ -81,7 +82,7 @@ class LinuxSourceTree(object): def __init__(self): self._kconfig = kunit_config.Kconfig() - self._kconfig.read_from_file('kunitconfig') + self._kconfig.read_from_file(KUNITCONFIG_PATH) self._ops = LinuxSourceTreeOperations() def clean(self): From patchwork Thu Feb 14 21:37:25 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813885 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 4637B17E0 for ; Thu, 14 Feb 2019 21:39:09 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 306682E7C5 for ; Thu, 14 Feb 2019 21:39:09 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 234322E7D1; Thu, 14 Feb 2019 21:39:09 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 5D6772E7C5 for ; Thu, 14 Feb 2019 21:39:06 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 57AB3208AE2D2; Thu, 14 Feb 2019 13:39:06 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::b4a; helo=mail-yb1-xb4a.google.com; envelope-from=3999lxa4kddgvlyhxuhbcaachmaiiafy.wigfchor-hpxcggfcmnm.uv.ila@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-yb1-xb4a.google.com (mail-yb1-xb4a.google.com [IPv6:2607:f8b0:4864:20::b4a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 0670D208AE2A8 for ; Thu, 14 Feb 2019 13:39:04 -0800 (PST) Received: by mail-yb1-xb4a.google.com with SMTP id w3so4491689ybk.19 for ; Thu, 14 Feb 2019 13:39:04 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=f2wa2equXX0Uxv32W1z3RSapSiZpl47DzRFek4cVN+E=; b=hQ+9SEU2BXhRthIqXbbxwnORMXGh8cVLmhcD9GTucG7YR8YyBSkhzs1X+WCWAFugOM 0tqHVnpLIqiM27g26aFoJmN8mIu2c3o0miFlEmQcwVfISVld/+3XyvzallOIGl4UFD10 qA65w1wr9QBu5eW9NXUm2EzUI2t3xVOlscFL3WXo3Y5t9kFJqN9mgTROrvtrgPrHiOEe Nk64WPJWDcmGCaCi4fX92YoJQpM5PF1tPBTxt8MHw/yjBs6b369giBrSeqpLTYqP2LgA W1T3GufJf8uGilYKvzxVOE88P6RK6B5UB4CxkxgamWARLqzUZaCSGXmKW+o38ObKBdxR 1JJg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=f2wa2equXX0Uxv32W1z3RSapSiZpl47DzRFek4cVN+E=; b=exRZbpwCXXv+cbZ7K7CBplPZbUlSok+DRzaqF+mo3Hkah/56xY8tJ7NAQhInCrJ3j0 vlqNNcYlFgIzlV93ZhTizw7+KOma8v2QfE1LCnIfxkllchCW/PJbeASClcK/zEBzltDw XhjP4xTYNZSOXn0+N1aCvlvDw5ZBpTnyEa3opBaawef+VzViKoXz0Zf8B2oKutO7juyz kcHRjZCcBKt+JjbWE0QxsUu5R4Z2SyWuSt5zAAgesbzM9/+rEXawihrcPn7MzosDQf+U ZgyaM/W5GaWzRn9+y1D72O1gcY6snKUMV/amdrFqRfVoXEw9fEbCJsep1tmLH7b64vwo m5WQ== X-Gm-Message-State: AHQUAuYoCyFNmQsX9QiGG9+riXXXB8lj26qWzeEPMoTBrECxqoMuRjhX iomqHnlmzo/uI1bYcWq2Ehyu2MojZIdiczmUe6T8Tg== X-Google-Smtp-Source: AHgI3IZgYWfJyxJREZSe13lsXNnaZTXjzW8qZKuiy29JOyParXycVnIyBwX4vvwgltI1l4yqdfN/ODKRJd+roBN2exsbKQ== X-Received: by 2002:a5b:d11:: with SMTP id y17mr2944152ybp.40.1550180343982; Thu, 14 Feb 2019 13:39:03 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:25 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-14-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 13/17] Documentation: kunit: add documentation for KUnit From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, Felix Guo , wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add documentation for KUnit, the Linux kernel unit testing framework. - Add intro and usage guide for KUnit - Add API reference Signed-off-by: Felix Guo Signed-off-by: Brendan Higgins --- Documentation/index.rst | 1 + Documentation/kunit/api/index.rst | 16 ++ Documentation/kunit/api/test.rst | 15 + Documentation/kunit/faq.rst | 46 +++ Documentation/kunit/index.rst | 80 ++++++ Documentation/kunit/start.rst | 180 ++++++++++++ Documentation/kunit/usage.rst | 447 ++++++++++++++++++++++++++++++ 7 files changed, 785 insertions(+) create mode 100644 Documentation/kunit/api/index.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 diff --git a/Documentation/index.rst b/Documentation/index.rst index c858c2e66e361..9512de536b34a 100644 --- a/Documentation/index.rst +++ b/Documentation/index.rst @@ -65,6 +65,7 @@ merged much easier. kernel-hacking/index trace/index maintainer/index + kunit/index Kernel API documentation ------------------------ diff --git a/Documentation/kunit/api/index.rst b/Documentation/kunit/api/index.rst new file mode 100644 index 0000000000000..c31c530088153 --- /dev/null +++ b/Documentation/kunit/api/index.rst @@ -0,0 +1,16 @@ +.. SPDX-License-Identifier: GPL-2.0 + +============= +API Reference +============= +.. toctree:: + + test + +This section documents the KUnit kernel testing API. It is divided into 3 +sections: + +================================= ============================================== +:doc:`test` documents all of the standard testing API + excluding mocking or mocking related features. +================================= ============================================== diff --git a/Documentation/kunit/api/test.rst b/Documentation/kunit/api/test.rst new file mode 100644 index 0000000000000..7c926014f047c --- /dev/null +++ b/Documentation/kunit/api/test.rst @@ -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/kunit-stream.h + :internal: + diff --git a/Documentation/kunit/faq.rst b/Documentation/kunit/faq.rst new file mode 100644 index 0000000000000..cb8e4fb2257a0 --- /dev/null +++ b/Documentation/kunit/faq.rst @@ -0,0 +1,46 @@ +.. SPDX-License-Identifier: GPL-2.0 + +========================================= +Frequently Asked Questions +========================================= + +How is this different from Autotest, kselftest, etc? +==================================================== +KUnit is a unit testing framework. Autotest, kselftest (and some others) are +not. + +A `unit test `_ is supposed to +test a single unit of code in isolation, hence the name. A unit test should be +the finest granularity of testing and as such should allow all possible code +paths to be tested in the code under test; this is only possible if the code +under test is very small and does not have any external dependencies outside of +the test's control like hardware. + +There are no testing frameworks currently available for the kernel that do not +require installing the kernel on a test machine or in a VM and all require +tests to be written in userspace and run on the kernel under test; this is true +for Autotest, kselftest, and some others, disqualifying any of them from being +considered unit testing frameworks. + +What is the difference between a unit test and these other kinds of tests? +========================================================================== +Most existing tests for the Linux kernel would be categorized as an integration +test, or an end-to-end test. + +- A unit test is supposed to test a single unit of code in isolation, hence the + name. A unit test should be the finest granularity of testing and as such + should allow all possible code paths to be tested in the code under test; this + is only possible if the code under test is very small and does not have any + external dependencies outside of the test's control like hardware. +- An integration test tests the interaction between a minimal set of components, + usually just two or three. For example, someone might write an integration + test to test the interaction between a driver and a piece of hardware, or to + test the interaction between the userspace libraries the kernel provides and + the kernel itself; however, one of these tests would probably not test the + entire kernel along with hardware interactions and interactions with the + userspace. +- An end-to-end test usually tests the entire system from the perspective of the + code under test. For example, someone might write an end-to-end test for the + kernel by installing a production configuration of the kernel on production + hardware with a production userspace and then trying to exercise some behavior + that depends on interactions between the hardware, the kernel, and userspace. diff --git a/Documentation/kunit/index.rst b/Documentation/kunit/index.rst new file mode 100644 index 0000000000000..c6710211b647f --- /dev/null +++ b/Documentation/kunit/index.rst @@ -0,0 +1,80 @@ +.. SPDX-License-Identifier: GPL-2.0 + +========================================= +KUnit - Unit Testing for the Linux Kernel +========================================= + +.. toctree:: + :maxdepth: 2 + + start + usage + api/index + faq + +What is KUnit? +============== + +KUnit is 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. + +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, and much more. + +Get started now: :doc:`start` + +Why KUnit? +========== + +A unit test is supposed to test a single unit of code in isolation, hence the +name. A unit test should be the finest granularity of testing and as such should +allow all possible code paths to be tested in the code under test; this is only +possible if the code under test is very small and does not have any external +dependencies outside of the test's control like hardware. + +Outside of KUnit, there are no testing frameworks currently +available for the kernel that do not require installing the kernel on a test +machine or in a VM and all require tests to be written in userspace running on +the kernel; this is true for Autotest, and kselftest, disqualifying +any of them from being considered unit testing frameworks. + +KUnit addresses the problem of being able to run tests without needing a virtual +machine or actual hardware with User Mode Linux. User Mode Linux is a Linux +architecture, like ARM or x86; however, unlike other architectures it compiles +to a standalone program that can be run like any other program directly inside +of a host operating system; to be clear, it does not require any virtualization +support; it is just a regular program. + +KUnit is fast. Excluding build time, from invocation to completion KUnit can run +several dozen tests in only 10 to 20 seconds; this might not sound like a big +deal to some people, but having such fast and easy to run tests fundamentally +changes the way you go about testing and even writing code in the first place. +Linus himself said in his `git talk at Google +`_: + + "... a lot of people seem to think that performance is about doing the + same thing, just doing it faster, and that is not true. That is not what + performance is all about. If you can do something really fast, really + well, people will start using it differently." + +In this context Linus was talking about branching and merging, +but this point also applies to testing. If your tests are slow, unreliable, are +difficult to write, and require a special setup or special hardware to run, +then you wait a lot longer to write tests, and you wait a lot longer to run +tests; this means that tests are likely to break, unlikely to test a lot of +things, and are unlikely to be rerun once they pass. If your tests are really +fast, you run them all the time, every time you make a change, and every time +someone sends you some code. Why trust that someone ran all their tests +correctly on every change when you can just run them yourself in less time than +it takes to read his / her test log? + +How do I use it? +=================== + +* :doc:`start` - for new users of KUnit +* :doc:`usage` - for a more detailed explanation of KUnit features +* :doc:`api/index` - for the list of KUnit APIs used for testing + diff --git a/Documentation/kunit/start.rst b/Documentation/kunit/start.rst new file mode 100644 index 0000000000000..5cdba5091905e --- /dev/null +++ b/Documentation/kunit/start.rst @@ -0,0 +1,180 @@ +.. SPDX-License-Identifier: GPL-2.0 + +=============== +Getting Started +=============== + +Installing dependencies +======================= +KUnit has the same dependencies as the Linux kernel. As long as you can build +the kernel, you can run KUnit. + +KUnit Wrapper +============= +Included with KUnit is a simple Python wrapper that helps format the output to +easily use and read KUnit output. It handles building and running the kernel, as +well as formatting the output. + +The wrapper can be run with: + +.. code-block:: bash + + ./tools/testing/kunit/kunit.py + +Creating a kunitconfig +====================== +The Python script is a thin wrapper around Kbuild as such, it needs to be +configured with a ``kunitconfig`` file. This file essentially contains the +regular Kernel config, with the specific test targets as well. + +.. code-block:: bash + + git clone -b master https://kunit.googlesource.com/kunitconfig $PATH_TO_KUNITCONFIG_REPO + cd $PATH_TO_LINUX_REPO + ln -s $PATH_TO_KUNIT_CONFIG_REPO/kunitconfig kunitconfig + +You may want to add kunitconfig to your local gitignore. + +Verifying KUnit Works +------------------------- + +To make sure that everything is set up correctly, simply invoke the Python +wrapper from your kernel repo: + +.. code-block:: bash + + ./tools/testing/kunit/kunit.py + +.. note:: + You may want to run ``make mrproper`` first. + +If everything worked correctly, you should see the following: + +.. code-block:: bash + + Generating .config ... + Building KUnit Kernel ... + Starting KUnit Kernel ... + +followed by a list of tests that are run. All of them should be passing. + +.. note:: + Because it is building a lot of sources for the first time, the ``Building + kunit kernel`` step may take a while. + +Writing your first test +========================== + +In your kernel repo let's add some code that we can test. Create a file +``drivers/misc/example.h`` with the contents: + +.. code-block:: c + + int misc_example_add(int left, int right); + +create a file ``drivers/misc/example.c``: + +.. code-block:: c + + #include + + #include "example.h" + + int misc_example_add(int left, int right) + { + return left + right; + } + +Now add the following lines to ``drivers/misc/Kconfig``: + +.. code-block:: kconfig + + config MISC_EXAMPLE + bool "My example" + +and the following lines to ``drivers/misc/Makefile``: + +.. code-block:: make + + obj-$(CONFIG_MISC_EXAMPLE) += example.o + +Now we are ready to write the test. The test will be in +``drivers/misc/example-test.c``: + +.. code-block:: c + + #include + #include "example.h" + + /* Define the test cases. */ + + static void misc_example_add_test_basic(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, 1, misc_example_add(1, 0)); + KUNIT_EXPECT_EQ(test, 2, misc_example_add(1, 1)); + KUNIT_EXPECT_EQ(test, 0, misc_example_add(-1, 1)); + KUNIT_EXPECT_EQ(test, INT_MAX, misc_example_add(0, INT_MAX)); + KUNIT_EXPECT_EQ(test, -1, misc_example_add(INT_MAX, INT_MIN)); + } + + static void misc_example_test_failure(struct kunit *test) + { + KUNIT_FAIL(test, "This test never passes."); + } + + static struct kunit_case misc_example_test_cases[] = { + KUNIT_CASE(misc_example_add_test_basic), + KUNIT_CASE(misc_example_test_failure), + {}, + }; + + static struct kunit_module misc_example_test_module = { + .name = "misc-example", + .test_cases = misc_example_test_cases, + }; + module_test(misc_example_test_module); + +Now add the following to ``drivers/misc/Kconfig``: + +.. code-block:: kconfig + + config MISC_EXAMPLE_TEST + bool "Test for my example" + depends on MISC_EXAMPLE && KUNIT + +and the following to ``drivers/misc/Makefile``: + +.. code-block:: make + + obj-$(CONFIG_MISC_EXAMPLE_TEST) += example-test.o + +Now add it to your ``kunitconfig``: + +.. code-block:: none + + CONFIG_MISC_EXAMPLE=y + CONFIG_MISC_EXAMPLE_TEST=y + +Now you can run the test: + +.. code-block:: bash + + ./tools/testing/kunit/kunit.py + +You should see the following failure: + +.. code-block:: none + + ... + [16:08:57] [PASSED] misc-example:misc_example_add_test_basic + [16:08:57] [FAILED] misc-example:misc_example_test_failure + [16:08:57] EXPECTATION FAILED at drivers/misc/example-test.c:17 + [16:08:57] This test never passes. + ... + +Congrats! You just wrote your first KUnit test! + +Next Steps +============= +* Check out the :doc:`usage` page for a more + in-depth explanation of KUnit. diff --git a/Documentation/kunit/usage.rst b/Documentation/kunit/usage.rst new file mode 100644 index 0000000000000..96ef7f9a1add4 --- /dev/null +++ b/Documentation/kunit/usage.rst @@ -0,0 +1,447 @@ +.. SPDX-License-Identifier: GPL-2.0 + +============= +Using KUnit +============= + +The purpose of this document is to describe what KUnit is, how it works, how it +is intended to be used, and all the concepts and terminology that are needed to +understand it. This guide assumes a working knowledge of the Linux kernel and +some basic knowledge of testing. + +For a high level introduction to KUnit, including setting up KUnit for your +project, see :doc:`start`. + +Organization of this document +================================= + +This document is organized into two main sections: Testing and Isolating +Behavior. The first covers what a unit test is and how to use KUnit to write +them. The second covers how to use KUnit to isolate code and make it possible +to unit test code that was otherwise un-unit-testable. + +Testing +========== + +What is KUnit? +------------------ + +"K" is short for "kernel" so "KUnit" is the "(Linux) Kernel Unit Testing +Framework." KUnit is intended first and foremost for writing unit tests; it is +general enough that it can be used to write integration tests; however, this is +a secondary goal. KUnit has no ambition of being the only testing framework for +the kernel; for example, it does not intend to be an end-to-end testing +framework. + +What is Unit Testing? +------------------------- + +A `unit test `_ is a test that +tests code at the smallest possible scope, a *unit* of code. In the C +programming language that's a function. + +Unit tests should be written for all the publicly exposed functions in a +compilation unit; so that is all the functions that are exported in either a +*class* (defined below) or all functions which are **not** static. + +Writing Tests +------------- + +Test Cases +~~~~~~~~~~ + +The fundamental unit in KUnit is the test case. A test case is a function with +the signature ``void (*)(struct kunit *test)``. It calls a function to be tested +and then sets *expectations* for what should happen. For example: + +.. code-block:: c + + void example_test_success(struct kunit *test) + { + } + + void example_test_failure(struct kunit *test) + { + KUNIT_FAIL(test, "This test never passes."); + } + +In the above example ``example_test_success`` always passes because it does +nothing; no expectations are set, so all expectations pass. On the other hand +``example_test_failure`` always fails because it calls ``KUNIT_FAIL``, which is +a special expectation that logs a message and causes the test case to fail. + +Expectations +~~~~~~~~~~~~ +An *expectation* is a way to specify that you expect a piece of code to do +something in a test. An expectation is called like a function. A test is made +by setting expectations about the behavior of a piece of code under test; when +one or more of the expectations fail, the test case fails and information about +the failure is logged. For example: + +.. code-block:: c + + void add_test_basic(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, 1, add(1, 0)); + KUNIT_EXPECT_EQ(test, 2, add(1, 1)); + } + +In the above example ``add_test_basic`` makes a number of assertions about the +behavior of a function called ``add``; the first parameter is always of type +``struct kunit *``, which contains information about the current test context; +the second parameter, in this case, is what the value is expected to be; the +last value is what the value actually is. If ``add`` passes all of these +expectations, the test case, ``add_test_basic`` will pass; if any one of these +expectations fail, the test case will fail. + +It is important to understand that a test case *fails* when any expectation is +violated; however, the test will continue running, potentially trying other +expectations until the test case ends or is otherwise terminated. This is as +opposed to *assertions* which are discussed later. + +To learn about more expectations supported by KUnit, see :doc:`api/test`. + +.. note:: + A single test case should be pretty short, pretty easy to understand, + focused on a single behavior. + +For example, if we wanted to properly test the add function above, we would +create additional tests cases which would each test a different property that an +add function should have like this: + +.. code-block:: c + + void add_test_basic(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, 1, add(1, 0)); + KUNIT_EXPECT_EQ(test, 2, add(1, 1)); + } + + void add_test_negative(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, 0, add(-1, 1)); + } + + void add_test_max(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, INT_MAX, add(0, INT_MAX)); + KUNIT_EXPECT_EQ(test, -1, add(INT_MAX, INT_MIN)); + } + + void add_test_overflow(struct kunit *test) + { + KUNIT_EXPECT_EQ(test, INT_MIN, add(INT_MAX, 1)); + } + +Notice how it is immediately obvious what all the properties that we are testing +for are. + +Assertions +~~~~~~~~~~ + +KUnit also has the concept of an *assertion*. An assertion is just like an +expectation except the assertion immediately terminates the test case if it is +not satisfied. + +For example: + +.. code-block:: c + + static void mock_test_do_expect_default_return(struct kunit *test) + { + struct mock_test_context *ctx = test->priv; + struct mock *mock = ctx->mock; + int param0 = 5, param1 = -5; + const char *two_param_types[] = {"int", "int"}; + const void *two_params[] = {¶m0, ¶m1}; + const void *ret; + + ret = mock->do_expect(mock, + "test_printk", test_printk, + two_param_types, two_params, + ARRAY_SIZE(two_params)); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ret); + KUNIT_EXPECT_EQ(test, -4, *((int *) ret)); + } + +In this example, the method under test should return a pointer to a value, so +if the pointer returned by the method is null or an errno, we don't want to +bother continuing the test since the following expectation could crash the test +case. `ASSERT_NOT_ERR_OR_NULL(...)` allows us to bail out of the test case if +the appropriate conditions have not been satisfied to complete the test. + +Modules / Test Suites +~~~~~~~~~~~~~~~~~~~~~ + +Now obviously one unit test isn't very helpful; the power comes from having +many test cases covering all of your behaviors. Consequently it is common to +have many *similar* tests; in order to reduce duplication in these closely +related tests most unit testing frameworks provide the concept of a *test +suite*, in KUnit we call it a *test module*; all it is is just a collection of +test cases for a unit of code with a set up function that gets invoked before +every test cases and then a tear down function that gets invoked after every +test case completes. + +Example: + +.. code-block:: c + + static struct kunit_case example_test_cases[] = { + KUNIT_CASE(example_test_foo), + KUNIT_CASE(example_test_bar), + KUNIT_CASE(example_test_baz), + {}, + }; + + static struct kunit_module example_test_module[] = { + .name = "example", + .init = example_test_init, + .exit = example_test_exit, + .test_cases = example_test_cases, + }; + module_test(example_test_module); + +In the above example the test suite, ``example_test_module``, would run the test +cases ``example_test_foo``, ``example_test_bar``, and ``example_test_baz``, each +would have ``example_test_init`` called immediately before it and would have +``example_test_exit`` called immediately after it. +``module_test(example_test_module)`` registers the test suite with the KUnit +test framework. + +.. note:: + A test case will only be run if it is associated with a test suite. + +For a more information on these types of things see the :doc:`api/test`. + +Isolating Behavior +================== + +The most important aspect of unit testing that other forms of testing do not +provide is the ability to limit the amount of code under test to a single unit. +In practice, this is only possible by being able to control what code gets run +when the unit under test calls a function and this is usually accomplished +through some sort of indirection where a function is exposed as part of an API +such that the definition of that function can be changed without affecting the +rest of the code base. In the kernel this primarily comes from two constructs, +classes, structs that contain function pointers that are provided by the +implementer, and architecture specific functions which have definitions selected +at compile time. + +Classes +------- + +Classes are not a construct that is built into the C programming language; +however, it is an easily derived concept. Accordingly, pretty much every project +that does not use a standardized object oriented library (like GNOME's GObject) +has their own slightly different way of doing object oriented programming; the +Linux kernel is no exception. + +The central concept in kernel object oriented programming is the class. In the +kernel, a *class* is a struct that contains function pointers. This creates a +contract between *implementers* and *users* since it forces them to use the +same function signature without having to call the function directly. In order +for it to truly be a class, the function pointers must specify that a pointer +to the class, known as a *class handle*, be one of the parameters; this makes +it possible for the member functions (also known as *methods*) to have access +to member variables (more commonly known as *fields*) allowing the same +implementation to have multiple *instances*. + +Typically a class can be *overridden* by *child classes* by embedding the +*parent class* in the child class. Then when a method provided by the child +class is called, the child implementation knows that the pointer passed to it is +of a parent contained within the child; because of this, the child can compute +the pointer to itself because the pointer to the parent is always a fixed offset +from the pointer to the child; this offset is the offset of the parent contained +in the child struct. For example: + +.. code-block:: c + + struct shape { + int (*area)(struct shape *this); + }; + + struct rectangle { + struct shape parent; + int length; + int width; + }; + + int rectangle_area(struct shape *this) + { + struct rectangle *self = container_of(this, struct shape, parent); + + return self->length * self->width; + }; + + void rectangle_new(struct rectangle *self, int length, int width) + { + self->parent.area = rectangle_area; + self->length = length; + self->width = width; + } + +In this example (as in most kernel code) the operation of computing the pointer +to the child from the pointer to the parent is done by ``container_of``. + +Faking Classes +~~~~~~~~~~~~~~ + +In order to unit test a piece of code that calls a method in a class, the +behavior of the method must be controllable, otherwise the test ceases to be a +unit test and becomes an integration test. + +A fake just provides an implementation of a piece of code that is different than +what runs in a production instance, but behaves identically from the standpoint +of the callers; this is usually done to replace a dependency that is hard to +deal with, or is slow. + +A good example for this might be implementing a fake EEPROM that just stores the +"contents" in an internal buffer. For example, let's assume we have a class that +represents an EEPROM: + +.. code-block:: c + + struct eeprom { + ssize_t (*read)(struct eeprom *this, size_t offset, char *buffer, size_t count); + ssize_t (*write)(struct eeprom *this, size_t offset, const char *buffer, size_t count); + }; + +And we want to test some code that buffers writes to the EEPROM: + +.. code-block:: c + + struct eeprom_buffer { + ssize_t (*write)(struct eeprom_buffer *this, const char *buffer, size_t count); + int flush(struct eeprom_buffer *this); + size_t flush_count; /* Flushes when buffer exceeds flush_count. */ + }; + + struct eeprom_buffer *new_eeprom_buffer(struct eeprom *eeprom); + void destroy_eeprom_buffer(struct eeprom *eeprom); + +We can easily test this code by *faking out* the underlying EEPROM: + +.. code-block:: c + + struct fake_eeprom { + struct eeprom parent; + char contents[FAKE_EEPROM_CONTENTS_SIZE]; + }; + + ssize_t fake_eeprom_read(struct eeprom *parent, size_t offset, char *buffer, size_t count) + { + struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); + + count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); + memcpy(buffer, this->contents + offset, count); + + return count; + } + + ssize_t fake_eeprom_write(struct eeprom *this, size_t offset, const char *buffer, size_t count) + { + struct fake_eeprom *this = container_of(parent, struct fake_eeprom, parent); + + count = min(count, FAKE_EEPROM_CONTENTS_SIZE - offset); + memcpy(this->contents + offset, buffer, count); + + return count; + } + + void fake_eeprom_init(struct fake_eeprom *this) + { + this->parent.read = fake_eeprom_read; + this->parent.write = fake_eeprom_write; + memset(this->contents, 0, FAKE_EEPROM_CONTENTS_SIZE); + } + +We can now use it to test ``struct eeprom_buffer``: + +.. code-block:: c + + struct eeprom_buffer_test { + struct fake_eeprom *fake_eeprom; + struct eeprom_buffer *eeprom_buffer; + }; + + static void eeprom_buffer_test_does_not_write_until_flush(struct kunit *test) + { + struct eeprom_buffer_test *ctx = test->priv; + struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; + struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; + char buffer[] = {0xff}; + + eeprom_buffer->flush_count = SIZE_MAX; + + eeprom_buffer->write(eeprom_buffer, buffer, 1); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); + + eeprom_buffer->write(eeprom_buffer, buffer, 1); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0); + + eeprom_buffer->flush(eeprom_buffer); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); + } + + static void eeprom_buffer_test_flushes_after_flush_count_met(struct kunit *test) + { + struct eeprom_buffer_test *ctx = test->priv; + struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; + struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; + char buffer[] = {0xff}; + + eeprom_buffer->flush_count = 2; + + eeprom_buffer->write(eeprom_buffer, buffer, 1); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); + + eeprom_buffer->write(eeprom_buffer, buffer, 1); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); + } + + static void eeprom_buffer_test_flushes_increments_of_flush_count(struct kunit *test) + { + struct eeprom_buffer_test *ctx = test->priv; + struct eeprom_buffer *eeprom_buffer = ctx->eeprom_buffer; + struct fake_eeprom *fake_eeprom = ctx->fake_eeprom; + char buffer[] = {0xff, 0xff}; + + eeprom_buffer->flush_count = 2; + + eeprom_buffer->write(eeprom_buffer, buffer, 1); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0); + + eeprom_buffer->write(eeprom_buffer, buffer, 2); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[0], 0xff); + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[1], 0xff); + /* Should have only flushed the first two bytes. */ + KUNIT_EXPECT_EQ(test, fake_eeprom->contents[2], 0); + } + + static int eeprom_buffer_test_init(struct kunit *test) + { + struct eeprom_buffer_test *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + ASSERT_NOT_ERR_OR_NULL(test, ctx); + + ctx->fake_eeprom = kunit_kzalloc(test, sizeof(*ctx->fake_eeprom), GFP_KERNEL); + ASSERT_NOT_ERR_OR_NULL(test, ctx->fake_eeprom); + + ctx->eeprom_buffer = new_eeprom_buffer(&ctx->fake_eeprom->parent); + ASSERT_NOT_ERR_OR_NULL(test, ctx->eeprom_buffer); + + test->priv = ctx; + + return 0; + } + + static void eeprom_buffer_test_exit(struct kunit *test) + { + struct eeprom_buffer_test *ctx = test->priv; + + destroy_eeprom_buffer(ctx->eeprom_buffer); + } + From patchwork Thu Feb 14 21:37:26 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813883 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id E4D5B1390 for ; Thu, 14 Feb 2019 21:39:08 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id D10AC2E7CA for ; Thu, 14 Feb 2019 21:39:08 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id C493E2E7D3; Thu, 14 Feb 2019 21:39:08 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 801032E7CA for ; Thu, 14 Feb 2019 21:39:08 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 7955A208AE2D7; Thu, 14 Feb 2019 13:39:08 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::74a; helo=mail-qk1-x74a.google.com; envelope-from=3-t9lxa4kddsyobkaxkefddfkpdlldib.zljifkru-ksafjjifpqp.xy.lod@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-qk1-x74a.google.com (mail-qk1-x74a.google.com [IPv6:2607:f8b0:4864:20::74a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id AFB17208AE2AC for ; Thu, 14 Feb 2019 13:39:07 -0800 (PST) Received: by mail-qk1-x74a.google.com with SMTP id 207so6416285qkf.9 for ; Thu, 14 Feb 2019 13:39:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=dpMyNLjbaEoBN2fIt+0XMlt5wSIklA/mX/UHQ1WvfMQ=; b=tHZTGnrRF6tZNdOyIbQW15sL1g+Qw3v7vALbKugbns0kuMvcT5DKYt7ydUYMn+U2Np Nk+L+f9RxHcktbClu4h5LhOuMWL3KCLjrUW2cVARNa9SLGwOdcMcLWkczCB1Sj4N+4VN AXiNi+MR3bnEdrzw1VQuWc9V625xRsZYJWdui5Ct3RhMUBILk7Chcvh2c5471w3kJO0D QECkjtRxYxlaxzMT30nTuHpHlXW/ZdYN4e+lqi/6W8dyAP7rQTVV9UUcmgZjmSCi2H49 fNpejBhDBa4DnumoPCUajGfQZAfgRxxh/FB3aaDdRxduSPES7ShJsInA7bW6LQ5xbEfv 8d7g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=dpMyNLjbaEoBN2fIt+0XMlt5wSIklA/mX/UHQ1WvfMQ=; b=I7sLwYju4ym7xmnAOb05F3+uHijah6m6N3MJjdXTFLlvNT3hlfqCW6Ga4adNaKduFe 9rjom5rHcavvpUDL5ZnHsz3R+bm1heo1M3e3D5ochF9fElpYcMzoWQYnl187KfX9/tZY 8Vh7JodRKMQm0yd1nAvX+ynp/BObSHNeA/Pco3LTiqnGe5zcCNlUIfGBbRJAMy7eBo86 61JSWriVDCVYVgImKlpYWoeeggbiEMDmkbtOeGYGy257gbFJmIEvyvzlHTvECrpsv5FO v473AW/p29Os8FdNtpIaPMbnEwfqJOsW+UC76TCZ+SPPmxT5vyaFvywP1E/YQGZttZHw JLPw== X-Gm-Message-State: AHQUAuaOZQM4LamCID/IfKG0OPsmL19mXnqroVJn2aIJ2JI6ICZeFI5m 10/LuhuwPEm5AxrOrsn3hhO108Ydl06njaWkm5Kt9g== X-Google-Smtp-Source: AHgI3Ib96SBAmaHj0hccf6Xwyo7GzGo8ekoaCNzOP60dVFW5l3gJ8yVzrFenYf29uVbJ1/FHiSJ2kSpq4Bk4SqiXNSoajQ== X-Received: by 2002:aed:23fd:: with SMTP id k58mr3493988qtc.39.1550180346797; Thu, 14 Feb 2019 13:39:06 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:26 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-15-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 14/17] MAINTAINERS: add entry for KUnit the unit testing framework From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Add myself as maintainer of KUnit, the Linux kernel's unit testing framework. Signed-off-by: Brendan Higgins --- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 8c68de3cfd80e..ff2cc9fcb49ad 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -8267,6 +8267,16 @@ S: Maintained F: tools/testing/selftests/ F: Documentation/dev-tools/kselftest* +KERNEL UNIT TESTING FRAMEWORK (KUnit) +M: Brendan Higgins +L: kunit-dev@googlegroups.com +W: https://google.github.io/kunit-docs/third_party/kernel/docs/ +S: Maintained +F: Documentation/kunit/ +F: include/kunit/ +F: kunit/ +F: tools/testing/kunit/ + KERNEL USERMODE HELPER M: Luis Chamberlain L: linux-kernel@vger.kernel.org From patchwork Thu Feb 14 21:37:27 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813889 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 062F86C2 for ; Thu, 14 Feb 2019 21:39:15 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id DE49A2E7CA for ; Thu, 14 Feb 2019 21:39:14 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id D0DB32E7D1; Thu, 14 Feb 2019 21:39:14 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 9BE132E7C5 for ; Thu, 14 Feb 2019 21:39:11 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 94A62208AE2DC; Thu, 14 Feb 2019 13:39:11 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::54a; helo=mail-pg1-x54a.google.com; envelope-from=3_d9lxa4kdd4gwjsifsmnllnsxlttlqj.htrqnsz2-s0inrrqnxyx.56.twl@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-pg1-x54a.google.com (mail-pg1-x54a.google.com [IPv6:2607:f8b0:4864:20::54a]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 1E4F3208AE2DC for ; Thu, 14 Feb 2019 13:39:10 -0800 (PST) Received: by mail-pg1-x54a.google.com with SMTP id j32so5279172pgm.5 for ; Thu, 14 Feb 2019 13:39:10 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=71K71ArZbzWrWkhx64DLd7rEkOvM9Nc1C5hMJ5wXce8=; b=XSjRMLnSmAYrypO4H7F+MckjeEdwLjkvNN4QkdUgC8dMaMPteQAsYWaR5jWYD2XBV0 nXRiwiMw23g+s3+YCRulFdPAzyHJHCKDvYGU4jGyHBjY+H7wI1eKH0hOgR+rvFVI516b stsoy9lcrgNP7hbBoC7eBOrB3ddODq9ICcaDHFqZYDy3hEvopThUfiz9Fh7z1FwZBc7D 9cK7jWG0oQ9SCNWgR46MaO3pJRSIPpXcwDeebeqDSHW3fxaervOYNvHGJX6si4XcaCVm o22zcmhIeyaEjWe3yeo/UegZ0SYDDkEOiWVBw/psekqfCVRvF/2bCeRE6tH5O0r+JN5V 4ACA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=71K71ArZbzWrWkhx64DLd7rEkOvM9Nc1C5hMJ5wXce8=; b=p6YG3/EtK3Es028mgmW1fyQ5UgmBHdyBCVPJwQAgdd8b6q0yhCnmwCVngYhWUF3wsN q81P3vOYWzRxlc+uJMCDTAI85xSbHeki0kS0/beFqfBQsDiweO0VKZPYUhFvLWPWZcd6 CBlAf7LjxYu/M+nbz2vILw0b34O+JdBTKU22TBW3bvjL+1r/BBch6B7JihoHGGe/Y/Te 3GOV/FgZxkIeCfIW14vCMH4mQF1k004sXryD4rpL6Jjfgoqy/Wr9/DlKojRJRsvXSFA5 fPfsq63jL7dAqXnC+Kl2ZVWVpp/iTEpkvoWqsfiwPAzmrKzPLbOKLm5DhUfmpwwwZq/E Zjzw== X-Gm-Message-State: AHQUAuZ2Be/yO/JkuLVJyxYOXIMKkCouguA5I2Fenjf5FrAcn7bmQqew ksUncjFvNjpm6jrX57rGIMOYMCq3hjWbJpNp8tkWbA== X-Google-Smtp-Source: AHgI3IYhSWo1clgx6Z1JkoEPVPdWJ2CF8ctLjQUlQOXbVOal+57IUwP61A+/uN5XhIweE/AwguXUrNZv9w6GgXd0FXTeUA== X-Received: by 2002:a63:6b84:: with SMTP id g126mr2380588pgc.19.1550180349349; Thu, 14 Feb 2019 13:39:09 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:27 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-16-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 15/17] of: unittest: migrate tests to run on KUnit From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Migrate tests without any cleanup, or modifying test logic in anyway to run under KUnit using the KUnit expectation and assertion API. Signed-off-by: Brendan Higgins --- drivers/of/Kconfig | 1 + drivers/of/unittest.c | 1310 +++++++++++++++++++++-------------------- 2 files changed, 671 insertions(+), 640 deletions(-) diff --git a/drivers/of/Kconfig b/drivers/of/Kconfig index ad3fcad4d75b8..f309399deac20 100644 --- a/drivers/of/Kconfig +++ b/drivers/of/Kconfig @@ -15,6 +15,7 @@ if OF config OF_UNITTEST bool "Device Tree runtime unit tests" depends on !SPARC + depends on KUNIT select IRQ_DOMAIN select OF_EARLY_FLATTREE select OF_RESOLVE diff --git a/drivers/of/unittest.c b/drivers/of/unittest.c index effa4e2b9d992..96de69ccb3e63 100644 --- a/drivers/of/unittest.c +++ b/drivers/of/unittest.c @@ -26,186 +26,189 @@ #include +#include + #include "of_private.h" -static struct unittest_results { - int passed; - int failed; -} unittest_results; - -#define unittest(result, fmt, ...) ({ \ - bool failed = !(result); \ - if (failed) { \ - unittest_results.failed++; \ - pr_err("FAIL %s():%i " fmt, __func__, __LINE__, ##__VA_ARGS__); \ - } else { \ - unittest_results.passed++; \ - pr_debug("pass %s():%i\n", __func__, __LINE__); \ - } \ - failed; \ -}) - -static void __init of_unittest_find_node_by_name(void) +static void of_unittest_find_node_by_name(struct kunit *test) { struct device_node *np; const char *options, *name; np = of_find_node_by_path("/testcase-data"); name = kasprintf(GFP_KERNEL, "%pOF", np); - unittest(np && !strcmp("/testcase-data", name), - "find /testcase-data failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, + "find /testcase-data failed\n"); of_node_put(np); kfree(name); /* Test if trailing '/' works */ - np = of_find_node_by_path("/testcase-data/"); - unittest(!np, "trailing '/' on /testcase-data/ should fail\n"); + KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("/testcase-data/"), NULL, + "trailing '/' on /testcase-data/ should fail\n"); np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); name = kasprintf(GFP_KERNEL, "%pOF", np); - unittest(np && !strcmp("/testcase-data/phandle-tests/consumer-a", name), + KUNIT_EXPECT_STREQ_MSG( + test, "/testcase-data/phandle-tests/consumer-a", name, "find /testcase-data/phandle-tests/consumer-a failed\n"); of_node_put(np); kfree(name); np = of_find_node_by_path("testcase-alias"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); name = kasprintf(GFP_KERNEL, "%pOF", np); - unittest(np && !strcmp("/testcase-data", name), - "find testcase-alias failed\n"); + KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, + "find testcase-alias failed\n"); of_node_put(np); kfree(name); /* Test if trailing '/' works on aliases */ - np = of_find_node_by_path("testcase-alias/"); - unittest(!np, "trailing '/' on testcase-alias/ should fail\n"); + KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("testcase-alias/"), NULL, + "trailing '/' on testcase-alias/ should fail\n"); np = of_find_node_by_path("testcase-alias/phandle-tests/consumer-a"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); name = kasprintf(GFP_KERNEL, "%pOF", np); - unittest(np && !strcmp("/testcase-data/phandle-tests/consumer-a", name), + KUNIT_EXPECT_STREQ_MSG( + test, "/testcase-data/phandle-tests/consumer-a", name, "find testcase-alias/phandle-tests/consumer-a failed\n"); of_node_put(np); kfree(name); - np = of_find_node_by_path("/testcase-data/missing-path"); - unittest(!np, "non-existent path returned node %pOF\n", np); + KUNIT_EXPECT_EQ_MSG( + test, + np = of_find_node_by_path("/testcase-data/missing-path"), NULL, + "non-existent path returned node %pOF\n", np); of_node_put(np); - np = of_find_node_by_path("missing-alias"); - unittest(!np, "non-existent alias returned node %pOF\n", np); + KUNIT_EXPECT_EQ_MSG( + test, np = of_find_node_by_path("missing-alias"), NULL, + "non-existent alias returned node %pOF\n", np); of_node_put(np); - np = of_find_node_by_path("testcase-alias/missing-path"); - unittest(!np, "non-existent alias with relative path returned node %pOF\n", np); + KUNIT_EXPECT_EQ_MSG( + test, + np = of_find_node_by_path("testcase-alias/missing-path"), NULL, + "non-existent alias with relative path returned node %pOF\n", + np); of_node_put(np); np = of_find_node_opts_by_path("/testcase-data:testoption", &options); - unittest(np && !strcmp("testoption", options), - "option path test failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "testoption", options, + "option path test failed\n"); of_node_put(np); np = of_find_node_opts_by_path("/testcase-data:test/option", &options); - unittest(np && !strcmp("test/option", options), - "option path test, subcase #1 failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, + "option path test, subcase #1 failed\n"); of_node_put(np); np = of_find_node_opts_by_path("/testcase-data/testcase-device1:test/option", &options); - unittest(np && !strcmp("test/option", options), - "option path test, subcase #2 failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, + "option path test, subcase #2 failed\n"); of_node_put(np); np = of_find_node_opts_by_path("/testcase-data:testoption", NULL); - unittest(np, "NULL option path test failed\n"); + KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, np, + "NULL option path test failed\n"); of_node_put(np); np = of_find_node_opts_by_path("testcase-alias:testaliasoption", &options); - unittest(np && !strcmp("testaliasoption", options), - "option alias path test failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "testaliasoption", options, + "option alias path test failed\n"); of_node_put(np); np = of_find_node_opts_by_path("testcase-alias:test/alias/option", &options); - unittest(np && !strcmp("test/alias/option", options), - "option alias path test, subcase #1 failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/alias/option", options, + "option alias path test, subcase #1 failed\n"); of_node_put(np); np = of_find_node_opts_by_path("testcase-alias:testaliasoption", NULL); - unittest(np, "NULL option alias path test failed\n"); + KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG( + test, np, "NULL option alias path test failed\n"); of_node_put(np); options = "testoption"; np = of_find_node_opts_by_path("testcase-alias", &options); - unittest(np && !options, "option clearing test failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_EQ_MSG(test, options, NULL, + "option clearing test failed\n"); of_node_put(np); options = "testoption"; np = of_find_node_opts_by_path("/", &options); - unittest(np && !options, "option clearing root node test failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_EQ_MSG(test, options, NULL, + "option clearing root node test failed\n"); of_node_put(np); } -static void __init of_unittest_dynamic(void) +static void of_unittest_dynamic(struct kunit *test) { struct device_node *np; struct property *prop; np = of_find_node_by_path("/testcase-data"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); /* Array of 4 properties for the purpose of testing */ prop = kcalloc(4, sizeof(*prop), GFP_KERNEL); - if (!prop) { - unittest(0, "kzalloc() failed\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop); /* Add a new property - should pass*/ prop->name = "new-property"; prop->value = "new-property-data"; prop->length = strlen(prop->value) + 1; - unittest(of_add_property(np, prop) == 0, "Adding a new property failed\n"); + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + "Adding a new property failed\n"); /* Try to add an existing property - should fail */ prop++; prop->name = "new-property"; prop->value = "new-property-data-should-fail"; prop->length = strlen(prop->value) + 1; - unittest(of_add_property(np, prop) != 0, - "Adding an existing property should have failed\n"); + KUNIT_EXPECT_NE_MSG(test, of_add_property(np, prop), 0, + "Adding an existing property should have failed\n"); /* Try to modify an existing property - should pass */ prop->value = "modify-property-data-should-pass"; prop->length = strlen(prop->value) + 1; - unittest(of_update_property(np, prop) == 0, - "Updating an existing property should have passed\n"); + KUNIT_EXPECT_EQ_MSG( + test, of_update_property(np, prop), 0, + "Updating an existing property should have passed\n"); /* Try to modify non-existent property - should pass*/ prop++; prop->name = "modify-property"; prop->value = "modify-missing-property-data-should-pass"; prop->length = strlen(prop->value) + 1; - unittest(of_update_property(np, prop) == 0, - "Updating a missing property should have passed\n"); + KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop), 0, + "Updating a missing property should have passed\n"); /* Remove property - should pass */ - unittest(of_remove_property(np, prop) == 0, - "Removing a property should have passed\n"); + KUNIT_EXPECT_EQ_MSG(test, of_remove_property(np, prop), 0, + "Removing a property should have passed\n"); /* Adding very large property - should pass */ prop++; prop->name = "large-property-PAGE_SIZEx8"; prop->length = PAGE_SIZE * 8; prop->value = kzalloc(prop->length, GFP_KERNEL); - unittest(prop->value != NULL, "Unable to allocate large buffer\n"); - if (prop->value) - unittest(of_add_property(np, prop) == 0, - "Adding a large property should have passed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop->value); + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + "Adding a large property should have passed\n"); } -static int __init of_unittest_check_node_linkage(struct device_node *np) +static int of_unittest_check_node_linkage(struct device_node *np) { struct device_node *child; int count = 0, rc; @@ -230,27 +233,30 @@ static int __init of_unittest_check_node_linkage(struct device_node *np) return rc; } -static void __init of_unittest_check_tree_linkage(void) +static void of_unittest_check_tree_linkage(struct kunit *test) { struct device_node *np; int allnode_count = 0, child_count; - if (!of_root) - return; + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, of_root); for_each_of_allnodes(np) allnode_count++; child_count = of_unittest_check_node_linkage(of_root); - unittest(child_count > 0, "Device node data structure is corrupted\n"); - unittest(child_count == allnode_count, - "allnodes list size (%i) doesn't match sibling lists size (%i)\n", - allnode_count, child_count); + KUNIT_EXPECT_GT_MSG(test, child_count, 0, + "Device node data structure is corrupted\n"); + KUNIT_EXPECT_EQ_MSG( + test, child_count, allnode_count, + "allnodes list size (%i) doesn't match sibling lists size (%i)\n", + allnode_count, child_count); pr_debug("allnodes list size (%i); sibling lists size (%i)\n", allnode_count, child_count); } -static void __init of_unittest_printf_one(struct device_node *np, const char *fmt, - const char *expected) +static void of_unittest_printf_one(struct kunit *test, + struct device_node *np, + const char *fmt, + const char *expected) { unsigned char *buf; int buf_size; @@ -265,8 +271,12 @@ static void __init of_unittest_printf_one(struct device_node *np, const char *fm memset(buf, 0xff, buf_size); size = snprintf(buf, buf_size - 2, fmt, np); - /* use strcmp() instead of strncmp() here to be absolutely sure strings match */ - unittest((strcmp(buf, expected) == 0) && (buf[size+1] == 0xff), + KUNIT_EXPECT_STREQ_MSG( + test, buf, expected, + "sprintf failed; fmt='%s' expected='%s' rslt='%s'\n", + fmt, expected, buf); + KUNIT_EXPECT_EQ_MSG( + test, buf[size+1], 0xff, "sprintf failed; fmt='%s' expected='%s' rslt='%s'\n", fmt, expected, buf); @@ -276,44 +286,49 @@ static void __init of_unittest_printf_one(struct device_node *np, const char *fm /* Clear the buffer, and make sure it works correctly still */ memset(buf, 0xff, buf_size); snprintf(buf, size+1, fmt, np); - unittest(strncmp(buf, expected, size) == 0 && (buf[size+1] == 0xff), + KUNIT_EXPECT_STREQ_MSG( + test, buf, expected, + "snprintf failed; size=%i fmt='%s' expected='%s' rslt='%s'\n", + size, fmt, expected, buf); + KUNIT_EXPECT_EQ_MSG( + test, buf[size+1], 0xff, "snprintf failed; size=%i fmt='%s' expected='%s' rslt='%s'\n", size, fmt, expected, buf); } kfree(buf); } -static void __init of_unittest_printf(void) +static void of_unittest_printf(struct kunit *test) { struct device_node *np; const char *full_name = "/testcase-data/platform-tests/test-device@1/dev@100"; char phandle_str[16] = ""; np = of_find_node_by_path(full_name); - if (!np) { - unittest(np, "testcase data missing\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); num_to_str(phandle_str, sizeof(phandle_str), np->phandle, 0); - of_unittest_printf_one(np, "%pOF", full_name); - of_unittest_printf_one(np, "%pOFf", full_name); - of_unittest_printf_one(np, "%pOFn", "dev"); - of_unittest_printf_one(np, "%2pOFn", "dev"); - of_unittest_printf_one(np, "%5pOFn", " dev"); - of_unittest_printf_one(np, "%pOFnc", "dev:test-sub-device"); - of_unittest_printf_one(np, "%pOFp", phandle_str); - of_unittest_printf_one(np, "%pOFP", "dev@100"); - of_unittest_printf_one(np, "ABC %pOFP ABC", "ABC dev@100 ABC"); - of_unittest_printf_one(np, "%10pOFP", " dev@100"); - of_unittest_printf_one(np, "%-10pOFP", "dev@100 "); - of_unittest_printf_one(of_root, "%pOFP", "/"); - of_unittest_printf_one(np, "%pOFF", "----"); - of_unittest_printf_one(np, "%pOFPF", "dev@100:----"); - of_unittest_printf_one(np, "%pOFPFPc", "dev@100:----:dev@100:test-sub-device"); - of_unittest_printf_one(np, "%pOFc", "test-sub-device"); - of_unittest_printf_one(np, "%pOFC", + of_unittest_printf_one(test, np, "%pOF", full_name); + of_unittest_printf_one(test, np, "%pOFf", full_name); + of_unittest_printf_one(test, np, "%pOFn", "dev"); + of_unittest_printf_one(test, np, "%2pOFn", "dev"); + of_unittest_printf_one(test, np, "%5pOFn", " dev"); + of_unittest_printf_one(test, np, "%pOFnc", "dev:test-sub-device"); + of_unittest_printf_one(test, np, "%pOFp", phandle_str); + of_unittest_printf_one(test, np, "%pOFP", "dev@100"); + of_unittest_printf_one(test, np, "ABC %pOFP ABC", "ABC dev@100 ABC"); + of_unittest_printf_one(test, np, "%10pOFP", " dev@100"); + of_unittest_printf_one(test, np, "%-10pOFP", "dev@100 "); + of_unittest_printf_one(test, of_root, "%pOFP", "/"); + of_unittest_printf_one(test, np, "%pOFF", "----"); + of_unittest_printf_one(test, np, "%pOFPF", "dev@100:----"); + of_unittest_printf_one(test, + np, + "%pOFPFPc", + "dev@100:----:dev@100:test-sub-device"); + of_unittest_printf_one(test, np, "%pOFc", "test-sub-device"); + of_unittest_printf_one(test, np, "%pOFC", "\"test-sub-device\",\"test-compat2\",\"test-compat3\""); } @@ -323,7 +338,7 @@ struct node_hash { }; static DEFINE_HASHTABLE(phandle_ht, 8); -static void __init of_unittest_check_phandles(void) +static void of_unittest_check_phandles(struct kunit *test) { struct device_node *np; struct node_hash *nh; @@ -335,24 +350,26 @@ static void __init of_unittest_check_phandles(void) continue; hash_for_each_possible(phandle_ht, nh, node, np->phandle) { + KUNIT_EXPECT_NE_MSG( + test, nh->np->phandle, np->phandle, + "Duplicate phandle! %i used by %pOF and %pOF\n", + np->phandle, nh->np, np); if (nh->np->phandle == np->phandle) { - pr_info("Duplicate phandle! %i used by %pOF and %pOF\n", - np->phandle, nh->np, np); dup_count++; break; } } nh = kzalloc(sizeof(*nh), GFP_KERNEL); - if (WARN_ON(!nh)) - return; + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nh); nh->np = np; hash_add(phandle_ht, &nh->node, np->phandle); phandle_count++; } - unittest(dup_count == 0, "Found %i duplicates in %i phandles\n", - dup_count, phandle_count); + KUNIT_EXPECT_EQ_MSG(test, dup_count, 0, + "Found %i duplicates in %i phandles\n", + dup_count, phandle_count); /* Clean up */ hash_for_each_safe(phandle_ht, i, tmp, nh, node) { @@ -361,20 +378,21 @@ static void __init of_unittest_check_phandles(void) } } -static void __init of_unittest_parse_phandle_with_args(void) +static void of_unittest_parse_phandle_with_args(struct kunit *test) { struct device_node *np; struct of_phandle_args args; - int i, rc; + int i, rc = 0; np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - rc = of_count_phandle_with_args(np, "phandle-list", "#phandle-cells"); - unittest(rc == 7, "of_count_phandle_with_args() returned %i, expected 7\n", rc); + KUNIT_EXPECT_EQ_MSG( + test, + of_count_phandle_with_args( + np, "phandle-list", "#phandle-cells"), + 7, + "of_count_phandle_with_args() returned %i, expected 7\n", rc); for (i = 0; i < 8; i++) { bool passed = true; @@ -428,85 +446,91 @@ static void __init of_unittest_parse_phandle_with_args(void) passed = false; } - unittest(passed, "index %i - data error on node %pOF rc=%i\n", - i, args.np, rc); + KUNIT_EXPECT_TRUE_MSG( + test, passed, + "index %i - data error on node %pOF rc=%i\n", + i, args.np, rc); } /* Check for missing list property */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args(np, "phandle-list-missing", - "#phandle-cells", 0, &args); - unittest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc); - rc = of_count_phandle_with_args(np, "phandle-list-missing", - "#phandle-cells"); - unittest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args( + np, "phandle-list-missing", "#phandle-cells", 0, &args), + -ENOENT); + KUNIT_EXPECT_EQ( + test, + of_count_phandle_with_args( + np, "phandle-list-missing", "#phandle-cells"), + -ENOENT); /* Check for missing cells property */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args(np, "phandle-list", - "#phandle-cells-missing", 0, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); - rc = of_count_phandle_with_args(np, "phandle-list", - "#phandle-cells-missing"); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args( + np, "phandle-list", "#phandle-cells-missing", 0, &args), + -EINVAL); + KUNIT_EXPECT_EQ( + test, + of_count_phandle_with_args( + np, "phandle-list", "#phandle-cells-missing"), + -EINVAL); /* Check for bad phandle in list */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args(np, "phandle-list-bad-phandle", - "#phandle-cells", 0, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); - rc = of_count_phandle_with_args(np, "phandle-list-bad-phandle", - "#phandle-cells"); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args(np, "phandle-list-bad-phandle", + "#phandle-cells", 0, &args), + -EINVAL); + KUNIT_EXPECT_EQ( + test, + of_count_phandle_with_args( + np, "phandle-list-bad-phandle", "#phandle-cells"), + -EINVAL); /* Check for incorrectly formed argument list */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args(np, "phandle-list-bad-args", - "#phandle-cells", 1, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); - rc = of_count_phandle_with_args(np, "phandle-list-bad-args", - "#phandle-cells"); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args(np, "phandle-list-bad-args", + "#phandle-cells", 1, &args), + -EINVAL); + KUNIT_EXPECT_EQ( + test, + of_count_phandle_with_args( + np, "phandle-list-bad-args", "#phandle-cells"), + -EINVAL); } -static void __init of_unittest_parse_phandle_with_args_map(void) +static void of_unittest_parse_phandle_with_args_map(struct kunit *test) { struct device_node *np, *p0, *p1, *p2, *p3; struct of_phandle_args args; int i, rc; np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-b"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); p0 = of_find_node_by_path("/testcase-data/phandle-tests/provider0"); - if (!p0) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p0); p1 = of_find_node_by_path("/testcase-data/phandle-tests/provider1"); - if (!p1) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p1); p2 = of_find_node_by_path("/testcase-data/phandle-tests/provider2"); - if (!p2) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p2); p3 = of_find_node_by_path("/testcase-data/phandle-tests/provider3"); - if (!p3) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p3); - rc = of_count_phandle_with_args(np, "phandle-list", "#phandle-cells"); - unittest(rc == 7, "of_count_phandle_with_args() returned %i, expected 7\n", rc); + KUNIT_EXPECT_EQ(test, + of_count_phandle_with_args(np, + "phandle-list", + "#phandle-cells"), + 7); for (i = 0; i < 8; i++) { bool passed = true; @@ -564,121 +588,186 @@ static void __init of_unittest_parse_phandle_with_args_map(void) passed = false; } - unittest(passed, "index %i - data error on node %s rc=%i\n", - i, args.np->full_name, rc); + KUNIT_EXPECT_TRUE_MSG( + test, passed, + "index %i - data error on node %s rc=%i\n", + i, (args.np ? args.np->full_name : "missing np"), rc); } /* Check for missing list property */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args_map(np, "phandle-list-missing", - "phandle", 0, &args); - unittest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args_map( + np, "phandle-list-missing", "phandle", 0, &args), + -ENOENT); /* Check for missing cells,map,mask property */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args_map(np, "phandle-list", - "phandle-missing", 0, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args_map( + np, "phandle-list", "phandle-missing", 0, &args), + -EINVAL); /* Check for bad phandle in list */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args_map(np, "phandle-list-bad-phandle", - "phandle", 0, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args_map( + np, "phandle-list-bad-phandle", "phandle", 0, &args), + -EINVAL); /* Check for incorrectly formed argument list */ memset(&args, 0, sizeof(args)); - rc = of_parse_phandle_with_args_map(np, "phandle-list-bad-args", - "phandle", 1, &args); - unittest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc); + KUNIT_EXPECT_EQ( + test, + of_parse_phandle_with_args_map( + np, "phandle-list-bad-args", "phandle", 1, &args), + -EINVAL); } -static void __init of_unittest_property_string(void) +static void of_unittest_property_string(struct kunit *test) { const char *strings[4]; struct device_node *np; int rc; np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); - if (!np) { - pr_err("No testcase data in device tree\n"); - return; - } - - rc = of_property_match_string(np, "phandle-list-names", "first"); - unittest(rc == 0, "first expected:0 got:%i\n", rc); - rc = of_property_match_string(np, "phandle-list-names", "second"); - unittest(rc == 1, "second expected:1 got:%i\n", rc); - rc = of_property_match_string(np, "phandle-list-names", "third"); - unittest(rc == 2, "third expected:2 got:%i\n", rc); - rc = of_property_match_string(np, "phandle-list-names", "fourth"); - unittest(rc == -ENODATA, "unmatched string; rc=%i\n", rc); - rc = of_property_match_string(np, "missing-property", "blah"); - unittest(rc == -EINVAL, "missing property; rc=%i\n", rc); - rc = of_property_match_string(np, "empty-property", "blah"); - unittest(rc == -ENODATA, "empty property; rc=%i\n", rc); - rc = of_property_match_string(np, "unterminated-string", "blah"); - unittest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + + KUNIT_EXPECT_EQ( + test, + of_property_match_string(np, "phandle-list-names", "first"), + 0); + KUNIT_EXPECT_EQ( + test, + of_property_match_string(np, "phandle-list-names", "second"), + 1); + KUNIT_EXPECT_EQ( + test, + of_property_match_string(np, "phandle-list-names", "third"), + 2); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_match_string(np, "phandle-list-names", "fourth"), + -ENODATA, + "unmatched string"); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_match_string(np, "missing-property", "blah"), + -EINVAL, + "missing property"); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_match_string(np, "empty-property", "blah"), + -ENODATA, + "empty property"); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_match_string(np, "unterminated-string", "blah"), + -EILSEQ, + "unterminated string"); /* of_property_count_strings() tests */ - rc = of_property_count_strings(np, "string-property"); - unittest(rc == 1, "Incorrect string count; rc=%i\n", rc); - rc = of_property_count_strings(np, "phandle-list-names"); - unittest(rc == 3, "Incorrect string count; rc=%i\n", rc); - rc = of_property_count_strings(np, "unterminated-string"); - unittest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc); - rc = of_property_count_strings(np, "unterminated-string-list"); - unittest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc); + KUNIT_EXPECT_EQ(test, + of_property_count_strings(np, "string-property"), 1); + KUNIT_EXPECT_EQ(test, + of_property_count_strings(np, "phandle-list-names"), 3); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_count_strings(np, "unterminated-string"), -EILSEQ, + "unterminated string"); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_count_strings(np, "unterminated-string-list"), + -EILSEQ, + "unterminated string array"); /* of_property_read_string_index() tests */ rc = of_property_read_string_index(np, "string-property", 0, strings); - unittest(rc == 0 && !strcmp(strings[0], "foobar"), "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_ASSERT_EQ(test, rc, 0); + KUNIT_EXPECT_STREQ(test, strings[0], "foobar"); + strings[0] = NULL; rc = of_property_read_string_index(np, "string-property", 1, strings); - unittest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_EXPECT_EQ(test, rc, -ENODATA); + KUNIT_EXPECT_EQ(test, strings[0], NULL); + rc = of_property_read_string_index(np, "phandle-list-names", 0, strings); - unittest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_ASSERT_EQ(test, rc, 0); + KUNIT_EXPECT_STREQ(test, strings[0], "first"); + rc = of_property_read_string_index(np, "phandle-list-names", 1, strings); - unittest(rc == 0 && !strcmp(strings[0], "second"), "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_ASSERT_EQ(test, rc, 0); + KUNIT_EXPECT_STREQ(test, strings[0], "second"); + rc = of_property_read_string_index(np, "phandle-list-names", 2, strings); - unittest(rc == 0 && !strcmp(strings[0], "third"), "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_ASSERT_EQ(test, rc, 0); + KUNIT_EXPECT_STREQ(test, strings[0], "third"); + strings[0] = NULL; rc = of_property_read_string_index(np, "phandle-list-names", 3, strings); - unittest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_EXPECT_EQ(test, rc, -ENODATA); + KUNIT_EXPECT_EQ(test, strings[0], NULL); + strings[0] = NULL; rc = of_property_read_string_index(np, "unterminated-string", 0, strings); - unittest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_EXPECT_EQ(test, rc, -EILSEQ); + KUNIT_EXPECT_EQ(test, strings[0], NULL); + rc = of_property_read_string_index(np, "unterminated-string-list", 0, strings); - unittest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc); + KUNIT_ASSERT_EQ(test, rc, 0); + KUNIT_EXPECT_STREQ(test, strings[0], "first"); + strings[0] = NULL; rc = of_property_read_string_index(np, "unterminated-string-list", 2, strings); /* should fail */ - unittest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc); - strings[1] = NULL; + KUNIT_EXPECT_EQ(test, rc, -EILSEQ); + KUNIT_EXPECT_EQ(test, strings[0], NULL); /* of_property_read_string_array() tests */ - rc = of_property_read_string_array(np, "string-property", strings, 4); - unittest(rc == 1, "Incorrect string count; rc=%i\n", rc); - rc = of_property_read_string_array(np, "phandle-list-names", strings, 4); - unittest(rc == 3, "Incorrect string count; rc=%i\n", rc); - rc = of_property_read_string_array(np, "unterminated-string", strings, 4); - unittest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc); + strings[1] = NULL; + KUNIT_EXPECT_EQ( + test, + of_property_read_string_array( + np, "string-property", strings, 4), + 1); + KUNIT_EXPECT_EQ( + test, + of_property_read_string_array( + np, "phandle-list-names", strings, 4), + 3); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_read_string_array( + np, "unterminated-string", strings, 4), + -EILSEQ, + "unterminated string"); /* -- An incorrectly formed string should cause a failure */ - rc = of_property_read_string_array(np, "unterminated-string-list", strings, 4); - unittest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc); + KUNIT_EXPECT_EQ_MSG( + test, + of_property_read_string_array( + np, "unterminated-string-list", strings, 4), + -EILSEQ, + "unterminated string array"); /* -- parsing the correctly formed strings should still work: */ strings[2] = NULL; rc = of_property_read_string_array(np, "unterminated-string-list", strings, 2); - unittest(rc == 2 && strings[2] == NULL, "of_property_read_string_array() failure; rc=%i\n", rc); + KUNIT_EXPECT_EQ(test, rc, 2); + KUNIT_EXPECT_EQ(test, strings[2], NULL); + strings[1] = NULL; rc = of_property_read_string_array(np, "phandle-list-names", strings, 1); - unittest(rc == 1 && strings[1] == NULL, "Overwrote end of string array; rc=%i, str='%s'\n", rc, strings[1]); + KUNIT_ASSERT_EQ(test, rc, 1); + KUNIT_EXPECT_EQ_MSG(test, strings[1], NULL, + "Overwrote end of string array"); } #define propcmp(p1, p2) (((p1)->length == (p2)->length) && \ (p1)->value && (p2)->value && \ !memcmp((p1)->value, (p2)->value, (p1)->length) && \ !strcmp((p1)->name, (p2)->name)) -static void __init of_unittest_property_copy(void) +static void of_unittest_property_copy(struct kunit *test) { #ifdef CONFIG_OF_DYNAMIC struct property p1 = { .name = "p1", .length = 0, .value = "" }; @@ -686,20 +775,24 @@ static void __init of_unittest_property_copy(void) struct property *new; new = __of_prop_dup(&p1, GFP_KERNEL); - unittest(new && propcmp(&p1, new), "empty property didn't copy correctly\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, new); + KUNIT_EXPECT_TRUE_MSG(test, propcmp(&p1, new), + "empty property didn't copy correctly"); kfree(new->value); kfree(new->name); kfree(new); new = __of_prop_dup(&p2, GFP_KERNEL); - unittest(new && propcmp(&p2, new), "non-empty property didn't copy correctly\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, new); + KUNIT_EXPECT_TRUE_MSG(test, propcmp(&p2, new), + "non-empty property didn't copy correctly"); kfree(new->value); kfree(new->name); kfree(new); #endif } -static void __init of_unittest_changeset(void) +static void of_unittest_changeset(struct kunit *test) { #ifdef CONFIG_OF_DYNAMIC struct property *ppadd, padd = { .name = "prop-add", .length = 1, .value = "" }; @@ -712,32 +805,32 @@ static void __init of_unittest_changeset(void) struct of_changeset chgset; n1 = __of_node_dup(NULL, "n1"); - unittest(n1, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, n1); n2 = __of_node_dup(NULL, "n2"); - unittest(n2, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, n2); n21 = __of_node_dup(NULL, "n21"); - unittest(n21, "testcase setup failure %p\n", n21); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, n21); nchangeset = of_find_node_by_path("/testcase-data/changeset"); nremove = of_get_child_by_name(nchangeset, "node-remove"); - unittest(nremove, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nremove); ppadd = __of_prop_dup(&padd, GFP_KERNEL); - unittest(ppadd, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppadd); ppname_n1 = __of_prop_dup(&pname_n1, GFP_KERNEL); - unittest(ppname_n1, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppname_n1); ppname_n2 = __of_prop_dup(&pname_n2, GFP_KERNEL); - unittest(ppname_n2, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppname_n2); ppname_n21 = __of_prop_dup(&pname_n21, GFP_KERNEL); - unittest(ppname_n21, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppname_n21); ppupdate = __of_prop_dup(&pupdate, GFP_KERNEL); - unittest(ppupdate, "testcase setup failure\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppupdate); parent = nchangeset; n1->parent = parent; @@ -745,54 +838,72 @@ static void __init of_unittest_changeset(void) n21->parent = n2; ppremove = of_find_property(parent, "prop-remove", NULL); - unittest(ppremove, "failed to find removal prop"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ppremove); of_changeset_init(&chgset); - unittest(!of_changeset_attach_node(&chgset, n1), "fail attach n1\n"); - unittest(!of_changeset_add_property(&chgset, n1, ppname_n1), "fail add prop name\n"); - - unittest(!of_changeset_attach_node(&chgset, n2), "fail attach n2\n"); - unittest(!of_changeset_add_property(&chgset, n2, ppname_n2), "fail add prop name\n"); - - unittest(!of_changeset_detach_node(&chgset, nremove), "fail remove node\n"); - unittest(!of_changeset_add_property(&chgset, n21, ppname_n21), "fail add prop name\n"); - - unittest(!of_changeset_attach_node(&chgset, n21), "fail attach n21\n"); - - unittest(!of_changeset_add_property(&chgset, parent, ppadd), "fail add prop prop-add\n"); - unittest(!of_changeset_update_property(&chgset, parent, ppupdate), "fail update prop\n"); - unittest(!of_changeset_remove_property(&chgset, parent, ppremove), "fail remove prop\n"); - - unittest(!of_changeset_apply(&chgset), "apply failed\n"); + KUNIT_EXPECT_FALSE_MSG(test, of_changeset_attach_node(&chgset, n1), + "fail attach n1\n"); + KUNIT_EXPECT_FALSE_MSG( + test, of_changeset_add_property(&chgset, n1, ppname_n1), + "fail add prop name\n"); + + KUNIT_EXPECT_FALSE_MSG(test, of_changeset_attach_node(&chgset, n2), + "fail attach n2\n"); + KUNIT_EXPECT_FALSE_MSG( + test, of_changeset_add_property(&chgset, n2, ppname_n2), + "fail add prop name\n"); + + KUNIT_EXPECT_FALSE_MSG(test, of_changeset_detach_node(&chgset, nremove), + "fail remove node\n"); + KUNIT_EXPECT_FALSE_MSG( + test, of_changeset_add_property(&chgset, n21, ppname_n21), + "fail add prop name\n"); + + KUNIT_EXPECT_FALSE_MSG(test, of_changeset_attach_node(&chgset, n21), + "fail attach n21\n"); + + KUNIT_EXPECT_FALSE_MSG( + test, + of_changeset_add_property(&chgset, parent, ppadd), + "fail add prop prop-add\n"); + KUNIT_EXPECT_FALSE_MSG( + test, + of_changeset_update_property(&chgset, parent, ppupdate), + "fail update prop\n"); + KUNIT_EXPECT_FALSE_MSG( + test, + of_changeset_remove_property(&chgset, parent, ppremove), + "fail remove prop\n"); + + KUNIT_EXPECT_FALSE_MSG(test, of_changeset_apply(&chgset), + "apply failed\n"); of_node_put(nchangeset); /* Make sure node names are constructed correctly */ - unittest((np = of_find_node_by_path("/testcase-data/changeset/n2/n21")), - "'%pOF' not added\n", n21); + KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG( + test, + np = of_find_node_by_path("/testcase-data/changeset/n2/n21"), + "'%pOF' not added\n", n21); of_node_put(np); - unittest(!of_changeset_revert(&chgset), "revert failed\n"); + KUNIT_EXPECT_FALSE(test, of_changeset_revert(&chgset)); of_changeset_destroy(&chgset); #endif } -static void __init of_unittest_parse_interrupts(void) +static void of_unittest_parse_interrupts(struct kunit *test) { struct device_node *np; struct of_phandle_args args; int i, rc; - if (of_irq_workarounds & OF_IMAP_OLDWORLD_MAC) - return; + KUNIT_ASSERT_FALSE(test, of_irq_workarounds & OF_IMAP_OLDWORLD_MAC); np = of_find_node_by_path("/testcase-data/interrupts/interrupts0"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); for (i = 0; i < 4; i++) { bool passed = true; @@ -804,16 +915,15 @@ static void __init of_unittest_parse_interrupts(void) passed &= (args.args_count == 1); passed &= (args.args[0] == (i + 1)); - unittest(passed, "index %i - data error on node %pOF rc=%i\n", - i, args.np, rc); + KUNIT_EXPECT_TRUE_MSG( + test, passed, + "index %i - data error on node %pOF rc=%i\n", + i, args.np, rc); } of_node_put(np); np = of_find_node_by_path("/testcase-data/interrupts/interrupts1"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); for (i = 0; i < 4; i++) { bool passed = true; @@ -850,26 +960,24 @@ static void __init of_unittest_parse_interrupts(void) default: passed = false; } - unittest(passed, "index %i - data error on node %pOF rc=%i\n", - i, args.np, rc); + KUNIT_EXPECT_TRUE_MSG( + test, passed, + "index %i - data error on node %pOF rc=%i\n", + i, args.np, rc); } of_node_put(np); } -static void __init of_unittest_parse_interrupts_extended(void) +static void of_unittest_parse_interrupts_extended(struct kunit *test) { struct device_node *np; struct of_phandle_args args; int i, rc; - if (of_irq_workarounds & OF_IMAP_OLDWORLD_MAC) - return; + KUNIT_ASSERT_FALSE(test, of_irq_workarounds & OF_IMAP_OLDWORLD_MAC); np = of_find_node_by_path("/testcase-data/interrupts/interrupts-extended0"); - if (!np) { - pr_err("missing testcase data\n"); - return; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); for (i = 0; i < 7; i++) { bool passed = true; @@ -924,8 +1032,10 @@ static void __init of_unittest_parse_interrupts_extended(void) passed = false; } - unittest(passed, "index %i - data error on node %pOF rc=%i\n", - i, args.np, rc); + KUNIT_EXPECT_TRUE_MSG( + test, passed, + "index %i - data error on node %pOF rc=%i\n", + i, args.np, rc); } of_node_put(np); } @@ -965,7 +1075,7 @@ static struct { { .path = "/testcase-data/match-node/name9", .data = "K", }, }; -static void __init of_unittest_match_node(void) +static void of_unittest_match_node(struct kunit *test) { struct device_node *np; const struct of_device_id *match; @@ -973,26 +1083,19 @@ static void __init of_unittest_match_node(void) for (i = 0; i < ARRAY_SIZE(match_node_tests); i++) { np = of_find_node_by_path(match_node_tests[i].path); - if (!np) { - unittest(0, "missing testcase node %s\n", - match_node_tests[i].path); - continue; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); match = of_match_node(match_node_table, np); - if (!match) { - unittest(0, "%s didn't match anything\n", - match_node_tests[i].path); - continue; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL_MSG(test, np, + "%s didn't match anything", + match_node_tests[i].path); - if (strcmp(match->data, match_node_tests[i].data) != 0) { - unittest(0, "%s got wrong match. expected %s, got %s\n", - match_node_tests[i].path, match_node_tests[i].data, - (const char *)match->data); - continue; - } - unittest(1, "passed"); + KUNIT_EXPECT_STREQ_MSG( + test, + match->data, match_node_tests[i].data, + "%s got wrong match. expected %s, got %s\n", + match_node_tests[i].path, match_node_tests[i].data, + (const char *)match->data); } } @@ -1004,9 +1107,9 @@ static struct resource test_bus_res = { static const struct platform_device_info test_bus_info = { .name = "unittest-bus", }; -static void __init of_unittest_platform_populate(void) +static void of_unittest_platform_populate(struct kunit *test) { - int irq, rc; + int irq; struct device_node *np, *child, *grandchild; struct platform_device *pdev, *test_bus; const struct of_device_id match[] = { @@ -1020,32 +1123,27 @@ static void __init of_unittest_platform_populate(void) /* Test that a missing irq domain returns -EPROBE_DEFER */ np = of_find_node_by_path("/testcase-data/testcase-device1"); pdev = of_find_device_by_node(np); - unittest(pdev, "device 1 creation failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); if (!(of_irq_workarounds & OF_IMAP_OLDWORLD_MAC)) { irq = platform_get_irq(pdev, 0); - unittest(irq == -EPROBE_DEFER, - "device deferred probe failed - %d\n", irq); + KUNIT_ASSERT_EQ(test, irq, -EPROBE_DEFER); /* Test that a parsing failure does not return -EPROBE_DEFER */ np = of_find_node_by_path("/testcase-data/testcase-device2"); pdev = of_find_device_by_node(np); - unittest(pdev, "device 2 creation failed\n"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); irq = platform_get_irq(pdev, 0); - unittest(irq < 0 && irq != -EPROBE_DEFER, - "device parsing error failed - %d\n", irq); + KUNIT_ASSERT_TRUE_MSG(test, irq < 0 && irq != -EPROBE_DEFER, + "device parsing error failed - %d\n", + irq); } np = of_find_node_by_path("/testcase-data/platform-tests"); - unittest(np, "No testcase data in device tree\n"); - if (!np) - return; + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); test_bus = platform_device_register_full(&test_bus_info); - rc = PTR_ERR_OR_ZERO(test_bus); - unittest(!rc, "testbus registration failed; rc=%i\n", rc); - if (rc) - return; + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_bus); test_bus->dev.of_node = np; /* @@ -1060,17 +1158,19 @@ static void __init of_unittest_platform_populate(void) of_platform_populate(np, match, NULL, &test_bus->dev); for_each_child_of_node(np, child) { for_each_child_of_node(child, grandchild) - unittest(of_find_device_by_node(grandchild), - "Could not create device for node '%pOFn'\n", - grandchild); + KUNIT_EXPECT_TRUE_MSG( + test, of_find_device_by_node(grandchild), + "Could not create device for node '%pOFn'\n", + grandchild); } of_platform_depopulate(&test_bus->dev); for_each_child_of_node(np, child) { for_each_child_of_node(child, grandchild) - unittest(!of_find_device_by_node(grandchild), - "device didn't get destroyed '%pOFn'\n", - grandchild); + KUNIT_EXPECT_FALSE_MSG( + test, of_find_device_by_node(grandchild), + "device didn't get destroyed '%pOFn'\n", + grandchild); } platform_device_unregister(test_bus); @@ -1171,7 +1271,7 @@ static void attach_node_and_children(struct device_node *np) * unittest_data_add - Reads, copies data from * linked tree and attaches it to the live tree */ -static int __init unittest_data_add(void) +static int unittest_data_add(void) { void *unittest_data; struct device_node *unittest_data_node, *np; @@ -1242,7 +1342,7 @@ static int __init unittest_data_add(void) } #ifdef CONFIG_OF_OVERLAY -static int __init overlay_data_apply(const char *overlay_name, int *overlay_id); +static int overlay_data_apply(const char *overlay_name, int *overlay_id); static int unittest_probe(struct platform_device *pdev) { @@ -1471,172 +1571,146 @@ static void of_unittest_destroy_tracked_overlays(void) } while (defers > 0); } -static int __init of_unittest_apply_overlay(int overlay_nr, int *overlay_id) +static int of_unittest_apply_overlay(struct kunit *test, + int overlay_nr, + int *overlay_id) { const char *overlay_name; overlay_name = overlay_name_from_nr(overlay_nr); - if (!overlay_data_apply(overlay_name, overlay_id)) { - unittest(0, "could not apply overlay \"%s\"\n", - overlay_name); - return -EFAULT; - } + KUNIT_ASSERT_TRUE_MSG(test, + overlay_data_apply(overlay_name, overlay_id), + "could not apply overlay \"%s\"\n", overlay_name); of_unittest_track_overlay(*overlay_id); return 0; } /* apply an overlay while checking before and after states */ -static int __init of_unittest_apply_overlay_check(int overlay_nr, +static int of_unittest_apply_overlay_check(struct kunit *test, int overlay_nr, int unittest_nr, int before, int after, enum overlay_type ovtype) { int ret, ovcs_id; /* unittest device must not be in before state */ - if (of_unittest_device_exists(unittest_nr, ovtype) != before) { - unittest(0, "%s with device @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype), - !before ? "enabled" : "disabled"); - return -EINVAL; - } + KUNIT_ASSERT_EQ_MSG( + test, of_unittest_device_exists(unittest_nr, ovtype), before, + "%s with device @\"%s\" %s\n", overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype), + !before ? "enabled" : "disabled"); ovcs_id = 0; - ret = of_unittest_apply_overlay(overlay_nr, &ovcs_id); + ret = of_unittest_apply_overlay(test, overlay_nr, &ovcs_id); if (ret != 0) { - /* of_unittest_apply_overlay already called unittest() */ + /* of_unittest_apply_overlay already set expectation */ return ret; } /* unittest device must be to set to after state */ - if (of_unittest_device_exists(unittest_nr, ovtype) != after) { - unittest(0, "%s failed to create @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype), - !after ? "enabled" : "disabled"); - return -EINVAL; - } + KUNIT_ASSERT_EQ_MSG( + test, of_unittest_device_exists(unittest_nr, ovtype), after, + "%s failed to create @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype), + !after ? "enabled" : "disabled"); return 0; } /* apply an overlay and then revert it while checking before, after states */ -static int __init of_unittest_apply_revert_overlay_check(int overlay_nr, +static int of_unittest_apply_revert_overlay_check( + struct kunit *test, int overlay_nr, int unittest_nr, int before, int after, enum overlay_type ovtype) { int ret, ovcs_id; /* unittest device must be in before state */ - if (of_unittest_device_exists(unittest_nr, ovtype) != before) { - unittest(0, "%s with device @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype), - !before ? "enabled" : "disabled"); - return -EINVAL; - } + KUNIT_ASSERT_EQ_MSG( + test, of_unittest_device_exists(unittest_nr, ovtype), before, + "%s with device @\"%s\" %s\n", overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype), + !before ? "enabled" : "disabled"); /* apply the overlay */ ovcs_id = 0; - ret = of_unittest_apply_overlay(overlay_nr, &ovcs_id); + ret = of_unittest_apply_overlay(test, overlay_nr, &ovcs_id); if (ret != 0) { - /* of_unittest_apply_overlay already called unittest() */ + /* of_unittest_apply_overlay already set expectation. */ return ret; } /* unittest device must be in after state */ - if (of_unittest_device_exists(unittest_nr, ovtype) != after) { - unittest(0, "%s failed to create @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype), - !after ? "enabled" : "disabled"); - return -EINVAL; - } - - ret = of_overlay_remove(&ovcs_id); - if (ret != 0) { - unittest(0, "%s failed to be destroyed @\"%s\"\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype)); - return ret; - } + KUNIT_ASSERT_EQ_MSG( + test, of_unittest_device_exists(unittest_nr, ovtype), after, + "%s failed to create @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype), + !after ? "enabled" : "disabled"); + + KUNIT_ASSERT_EQ_MSG(test, of_overlay_remove(&ovcs_id), 0, + "%s failed to be destroyed @\"%s\"\n", + overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype)); /* unittest device must be again in before state */ - if (of_unittest_device_exists(unittest_nr, PDEV_OVERLAY) != before) { - unittest(0, "%s with device @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr), - unittest_path(unittest_nr, ovtype), - !before ? "enabled" : "disabled"); - return -EINVAL; - } + KUNIT_ASSERT_EQ_MSG( + test, + of_unittest_device_exists(unittest_nr, PDEV_OVERLAY), before, + "%s with device @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr), + unittest_path(unittest_nr, ovtype), + !before ? "enabled" : "disabled"); return 0; } /* test activation of device */ -static void __init of_unittest_overlay_0(void) +static void of_unittest_overlay_0(struct kunit *test) { /* device should enable */ - if (of_unittest_apply_overlay_check(0, 0, 0, 1, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 0); + of_unittest_apply_overlay_check(test, 0, 0, 0, 1, PDEV_OVERLAY); } /* test deactivation of device */ -static void __init of_unittest_overlay_1(void) +static void of_unittest_overlay_1(struct kunit *test) { /* device should disable */ - if (of_unittest_apply_overlay_check(1, 1, 1, 0, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 1); + of_unittest_apply_overlay_check(test, 1, 1, 1, 0, PDEV_OVERLAY); } /* test activation of device */ -static void __init of_unittest_overlay_2(void) +static void of_unittest_overlay_2(struct kunit *test) { /* device should enable */ - if (of_unittest_apply_overlay_check(2, 2, 0, 1, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 2); + of_unittest_apply_overlay_check(test, 2, 2, 0, 1, PDEV_OVERLAY); } /* test deactivation of device */ -static void __init of_unittest_overlay_3(void) +static void of_unittest_overlay_3(struct kunit *test) { /* device should disable */ - if (of_unittest_apply_overlay_check(3, 3, 1, 0, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 3); + of_unittest_apply_overlay_check(test, 3, 3, 1, 0, PDEV_OVERLAY); } /* test activation of a full device node */ -static void __init of_unittest_overlay_4(void) +static void of_unittest_overlay_4(struct kunit *test) { /* device should disable */ - if (of_unittest_apply_overlay_check(4, 4, 0, 1, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 4); + of_unittest_apply_overlay_check(test, 4, 4, 0, 1, PDEV_OVERLAY); } /* test overlay apply/revert sequence */ -static void __init of_unittest_overlay_5(void) +static void of_unittest_overlay_5(struct kunit *test) { /* device should disable */ - if (of_unittest_apply_revert_overlay_check(5, 5, 0, 1, PDEV_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 5); + of_unittest_apply_revert_overlay_check(test, 5, 5, 0, 1, PDEV_OVERLAY); } /* test overlay application in sequence */ -static void __init of_unittest_overlay_6(void) +static void of_unittest_overlay_6(struct kunit *test) { int i, ov_id[2], ovcs_id; int overlay_nr = 6, unittest_nr = 6; @@ -1645,74 +1719,67 @@ static void __init of_unittest_overlay_6(void) /* unittest device must be in before state */ for (i = 0; i < 2; i++) { - if (of_unittest_device_exists(unittest_nr + i, PDEV_OVERLAY) - != before) { - unittest(0, "%s with device @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr + i), - unittest_path(unittest_nr + i, - PDEV_OVERLAY), - !before ? "enabled" : "disabled"); - return; - } + KUNIT_ASSERT_EQ_MSG(test, + of_unittest_device_exists(unittest_nr + i, + PDEV_OVERLAY), + before, + "%s with device @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr + i), + unittest_path(unittest_nr + i, + PDEV_OVERLAY), + !before ? "enabled" : "disabled"); } /* apply the overlays */ for (i = 0; i < 2; i++) { - overlay_name = overlay_name_from_nr(overlay_nr + i); - if (!overlay_data_apply(overlay_name, &ovcs_id)) { - unittest(0, "could not apply overlay \"%s\"\n", - overlay_name); - return; - } + KUNIT_ASSERT_TRUE_MSG( + test, overlay_data_apply(overlay_name, &ovcs_id), + "could not apply overlay \"%s\"\n", overlay_name); ov_id[i] = ovcs_id; of_unittest_track_overlay(ov_id[i]); } for (i = 0; i < 2; i++) { /* unittest device must be in after state */ - if (of_unittest_device_exists(unittest_nr + i, PDEV_OVERLAY) - != after) { - unittest(0, "overlay @\"%s\" failed @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr + i), - unittest_path(unittest_nr + i, - PDEV_OVERLAY), - !after ? "enabled" : "disabled"); - return; - } + KUNIT_ASSERT_EQ_MSG(test, + of_unittest_device_exists(unittest_nr + i, + PDEV_OVERLAY), + after, + "overlay @\"%s\" failed @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr + i), + unittest_path(unittest_nr + i, + PDEV_OVERLAY), + !after ? "enabled" : "disabled"); } for (i = 1; i >= 0; i--) { ovcs_id = ov_id[i]; - if (of_overlay_remove(&ovcs_id)) { - unittest(0, "%s failed destroy @\"%s\"\n", - overlay_name_from_nr(overlay_nr + i), - unittest_path(unittest_nr + i, - PDEV_OVERLAY)); - return; - } + KUNIT_ASSERT_FALSE_MSG( + test, of_overlay_remove(&ovcs_id), + "%s failed destroy @\"%s\"\n", + overlay_name_from_nr(overlay_nr + i), + unittest_path(unittest_nr + i, PDEV_OVERLAY)); of_unittest_untrack_overlay(ov_id[i]); } for (i = 0; i < 2; i++) { /* unittest device must be again in before state */ - if (of_unittest_device_exists(unittest_nr + i, PDEV_OVERLAY) - != before) { - unittest(0, "%s with device @\"%s\" %s\n", - overlay_name_from_nr(overlay_nr + i), - unittest_path(unittest_nr + i, - PDEV_OVERLAY), - !before ? "enabled" : "disabled"); - return; - } + KUNIT_ASSERT_EQ_MSG(test, + of_unittest_device_exists(unittest_nr + i, + PDEV_OVERLAY), + before, + "%s with device @\"%s\" %s\n", + overlay_name_from_nr(overlay_nr + i), + unittest_path(unittest_nr + i, + PDEV_OVERLAY), + !before ? "enabled" : "disabled"); } - - unittest(1, "overlay test %d passed\n", 6); } /* test overlay application in sequence */ -static void __init of_unittest_overlay_8(void) +static void of_unittest_overlay_8(struct kunit *test) { int i, ov_id[2], ovcs_id; int overlay_nr = 8, unittest_nr = 8; @@ -1722,76 +1789,64 @@ static void __init of_unittest_overlay_8(void) /* apply the overlays */ for (i = 0; i < 2; i++) { - overlay_name = overlay_name_from_nr(overlay_nr + i); - if (!overlay_data_apply(overlay_name, &ovcs_id)) { - unittest(0, "could not apply overlay \"%s\"\n", - overlay_name); - return; - } + KUNIT_ASSERT_TRUE_MSG( + test, overlay_data_apply(overlay_name, &ovcs_id), + "could not apply overlay \"%s\"\n", overlay_name); ov_id[i] = ovcs_id; of_unittest_track_overlay(ov_id[i]); } /* now try to remove first overlay (it should fail) */ ovcs_id = ov_id[0]; - if (!of_overlay_remove(&ovcs_id)) { - unittest(0, "%s was destroyed @\"%s\"\n", - overlay_name_from_nr(overlay_nr + 0), - unittest_path(unittest_nr, - PDEV_OVERLAY)); - return; - } + KUNIT_ASSERT_TRUE_MSG( + test, of_overlay_remove(&ovcs_id), + "%s was destroyed @\"%s\"\n", + overlay_name_from_nr(overlay_nr + 0), + unittest_path(unittest_nr, PDEV_OVERLAY)); /* removing them in order should work */ for (i = 1; i >= 0; i--) { ovcs_id = ov_id[i]; - if (of_overlay_remove(&ovcs_id)) { - unittest(0, "%s not destroyed @\"%s\"\n", - overlay_name_from_nr(overlay_nr + i), - unittest_path(unittest_nr, - PDEV_OVERLAY)); - return; - } + KUNIT_ASSERT_FALSE_MSG( + test, of_overlay_remove(&ovcs_id), + "%s not destroyed @\"%s\"\n", + overlay_name_from_nr(overlay_nr + i), + unittest_path(unittest_nr, PDEV_OVERLAY)); of_unittest_untrack_overlay(ov_id[i]); } - - unittest(1, "overlay test %d passed\n", 8); } /* test insertion of a bus with parent devices */ -static void __init of_unittest_overlay_10(void) +static void of_unittest_overlay_10(struct kunit *test) { - int ret; char *child_path; /* device should disable */ - ret = of_unittest_apply_overlay_check(10, 10, 0, 1, PDEV_OVERLAY); - if (unittest(ret == 0, - "overlay test %d failed; overlay application\n", 10)) - return; + KUNIT_ASSERT_EQ_MSG( + test, + of_unittest_apply_overlay_check( + test, 10, 10, 0, 1, PDEV_OVERLAY), + 0, + "overlay test %d failed; overlay application\n", 10); child_path = kasprintf(GFP_KERNEL, "%s/test-unittest101", unittest_path(10, PDEV_OVERLAY)); - if (unittest(child_path, "overlay test %d failed; kasprintf\n", 10)) - return; + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, child_path); - ret = of_path_device_type_exists(child_path, PDEV_OVERLAY); + KUNIT_EXPECT_TRUE_MSG( + test, of_path_device_type_exists(child_path, PDEV_OVERLAY), + "overlay test %d failed; no child device\n", 10); kfree(child_path); - - unittest(ret, "overlay test %d failed; no child device\n", 10); } /* test insertion of a bus with parent devices (and revert) */ -static void __init of_unittest_overlay_11(void) +static void of_unittest_overlay_11(struct kunit *test) { - int ret; - /* device should disable */ - ret = of_unittest_apply_revert_overlay_check(11, 11, 0, 1, - PDEV_OVERLAY); - unittest(ret == 0, "overlay test %d failed; overlay apply\n", 11); + KUNIT_EXPECT_FALSE(test, of_unittest_apply_revert_overlay_check( + test, 11, 11, 0, 1, PDEV_OVERLAY)); } #if IS_BUILTIN(CONFIG_I2C) && IS_ENABLED(CONFIG_OF_OVERLAY) @@ -2013,25 +2068,18 @@ static struct i2c_driver unittest_i2c_mux_driver = { #endif -static int of_unittest_overlay_i2c_init(void) +static int of_unittest_overlay_i2c_init(struct kunit *test) { - int ret; - - ret = i2c_add_driver(&unittest_i2c_dev_driver); - if (unittest(ret == 0, - "could not register unittest i2c device driver\n")) - return ret; + KUNIT_ASSERT_EQ_MSG(test, i2c_add_driver(&unittest_i2c_dev_driver), 0, + "could not register unittest i2c device driver\n"); - ret = platform_driver_register(&unittest_i2c_bus_driver); - if (unittest(ret == 0, - "could not register unittest i2c bus driver\n")) - return ret; + KUNIT_ASSERT_EQ_MSG( + test, platform_driver_register(&unittest_i2c_bus_driver), 0, + "could not register unittest i2c bus driver\n"); #if IS_BUILTIN(CONFIG_I2C_MUX) - ret = i2c_add_driver(&unittest_i2c_mux_driver); - if (unittest(ret == 0, - "could not register unittest i2c mux driver\n")) - return ret; + KUNIT_ASSERT_EQ_MSG(test, i2c_add_driver(&unittest_i2c_mux_driver), 0, + "could not register unittest i2c mux driver\n"); #endif return 0; @@ -2046,101 +2094,85 @@ static void of_unittest_overlay_i2c_cleanup(void) i2c_del_driver(&unittest_i2c_dev_driver); } -static void __init of_unittest_overlay_i2c_12(void) +static void of_unittest_overlay_i2c_12(struct kunit *test) { /* device should enable */ - if (of_unittest_apply_overlay_check(12, 12, 0, 1, I2C_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 12); + of_unittest_apply_overlay_check(test, 12, 12, 0, 1, I2C_OVERLAY); } /* test deactivation of device */ -static void __init of_unittest_overlay_i2c_13(void) +static void of_unittest_overlay_i2c_13(struct kunit *test) { /* device should disable */ - if (of_unittest_apply_overlay_check(13, 13, 1, 0, I2C_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 13); + of_unittest_apply_overlay_check(test, 13, 13, 1, 0, I2C_OVERLAY); } /* just check for i2c mux existence */ -static void of_unittest_overlay_i2c_14(void) +static void of_unittest_overlay_i2c_14(struct kunit *test) { + KUNIT_SUCCEED(test); } -static void __init of_unittest_overlay_i2c_15(void) +static void of_unittest_overlay_i2c_15(struct kunit *test) { /* device should enable */ - if (of_unittest_apply_overlay_check(15, 15, 0, 1, I2C_OVERLAY)) - return; - - unittest(1, "overlay test %d passed\n", 15); + of_unittest_apply_overlay_check(test, 15, 15, 0, 1, I2C_OVERLAY); } #else -static inline void of_unittest_overlay_i2c_14(void) { } -static inline void of_unittest_overlay_i2c_15(void) { } +static inline void of_unittest_overlay_i2c_14(struct kunit *test) { } +static inline void of_unittest_overlay_i2c_15(struct kunit *test) { } #endif -static void __init of_unittest_overlay(void) +static void of_unittest_overlay(struct kunit *test) { struct device_node *bus_np = NULL; - if (platform_driver_register(&unittest_driver)) { - unittest(0, "could not register unittest driver\n"); - goto out; - } + KUNIT_ASSERT_FALSE_MSG(test, platform_driver_register(&unittest_driver), + "could not register unittest driver\n"); bus_np = of_find_node_by_path(bus_path); - if (bus_np == NULL) { - unittest(0, "could not find bus_path \"%s\"\n", bus_path); - goto out; - } + KUNIT_ASSERT_NOT_ERR_OR_NULL_MSG( + test, bus_np, "could not find bus_path \"%s\"\n", bus_path); - if (of_platform_default_populate(bus_np, NULL, NULL)) { - unittest(0, "could not populate bus @ \"%s\"\n", bus_path); - goto out; - } - - if (!of_unittest_device_exists(100, PDEV_OVERLAY)) { - unittest(0, "could not find unittest0 @ \"%s\"\n", - unittest_path(100, PDEV_OVERLAY)); - goto out; - } + KUNIT_ASSERT_FALSE_MSG( + test, of_platform_default_populate(bus_np, NULL, NULL), + "could not populate bus @ \"%s\"\n", bus_path); - if (of_unittest_device_exists(101, PDEV_OVERLAY)) { - unittest(0, "unittest1 @ \"%s\" should not exist\n", - unittest_path(101, PDEV_OVERLAY)); - goto out; - } + KUNIT_ASSERT_TRUE_MSG( + test, of_unittest_device_exists(100, PDEV_OVERLAY), + "could not find unittest0 @ \"%s\"\n", + unittest_path(100, PDEV_OVERLAY)); - unittest(1, "basic infrastructure of overlays passed"); + KUNIT_ASSERT_FALSE_MSG( + test, of_unittest_device_exists(101, PDEV_OVERLAY), + "unittest1 @ \"%s\" should not exist\n", + unittest_path(101, PDEV_OVERLAY)); /* tests in sequence */ - of_unittest_overlay_0(); - of_unittest_overlay_1(); - of_unittest_overlay_2(); - of_unittest_overlay_3(); - of_unittest_overlay_4(); - of_unittest_overlay_5(); - of_unittest_overlay_6(); - of_unittest_overlay_8(); - - of_unittest_overlay_10(); - of_unittest_overlay_11(); + of_unittest_overlay_0(test); + of_unittest_overlay_1(test); + of_unittest_overlay_2(test); + of_unittest_overlay_3(test); + of_unittest_overlay_4(test); + of_unittest_overlay_5(test); + of_unittest_overlay_6(test); + of_unittest_overlay_8(test); + + of_unittest_overlay_10(test); + of_unittest_overlay_11(test); #if IS_BUILTIN(CONFIG_I2C) - if (unittest(of_unittest_overlay_i2c_init() == 0, "i2c init failed\n")) - goto out; + KUNIT_ASSERT_EQ_MSG(test, of_unittest_overlay_i2c_init(test), 0, + "i2c init failed\n"); + goto out; - of_unittest_overlay_i2c_12(); - of_unittest_overlay_i2c_13(); - of_unittest_overlay_i2c_14(); - of_unittest_overlay_i2c_15(); + of_unittest_overlay_i2c_12(test); + of_unittest_overlay_i2c_13(test); + of_unittest_overlay_i2c_14(test); + of_unittest_overlay_i2c_15(test); of_unittest_overlay_i2c_cleanup(); #endif @@ -2152,7 +2184,7 @@ static void __init of_unittest_overlay(void) } #else -static inline void __init of_unittest_overlay(void) { } +static inline void of_unittest_overlay(struct kunit *test) { } #endif #ifdef CONFIG_OF_OVERLAY @@ -2313,7 +2345,7 @@ void __init unittest_unflatten_overlay_base(void) * * Return 0 on unexpected error. */ -static int __init overlay_data_apply(const char *overlay_name, int *overlay_id) +static int overlay_data_apply(const char *overlay_name, int *overlay_id) { struct overlay_info *info; int found = 0; @@ -2359,19 +2391,17 @@ static int __init overlay_data_apply(const char *overlay_name, int *overlay_id) * The first part of the function is _not_ normal overlay usage; it is * finishing splicing the base overlay device tree into the live tree. */ -static __init void of_unittest_overlay_high_level(void) +static void of_unittest_overlay_high_level(struct kunit *test) { struct device_node *last_sibling; struct device_node *np; struct device_node *of_symbols; - struct device_node *overlay_base_symbols; + struct device_node *overlay_base_symbols = 0; struct device_node **pprev; struct property *prop; - if (!overlay_base_root) { - unittest(0, "overlay_base_root not initialized\n"); - return; - } + KUNIT_ASSERT_TRUE_MSG(test, overlay_base_root, + "overlay_base_root not initialized\n"); /* * Could not fixup phandles in unittest_unflatten_overlay_base() @@ -2418,11 +2448,9 @@ static __init void of_unittest_overlay_high_level(void) for_each_child_of_node(overlay_base_root, np) { struct device_node *base_child; for_each_child_of_node(of_root, base_child) { - if (!strcmp(np->full_name, base_child->full_name)) { - unittest(0, "illegal node name in overlay_base %pOFn", - np); - return; - } + KUNIT_ASSERT_STRNEQ_MSG( + test, np->full_name, base_child->full_name, + "illegal node name in overlay_base %pOFn", np); } } @@ -2456,21 +2484,24 @@ static __init void of_unittest_overlay_high_level(void) new_prop = __of_prop_dup(prop, GFP_KERNEL); if (!new_prop) { - unittest(0, "__of_prop_dup() of '%s' from overlay_base node __symbols__", - prop->name); + KUNIT_FAIL(test, + "__of_prop_dup() of '%s' from overlay_base node __symbols__", + prop->name); goto err_unlock; } if (__of_add_property(of_symbols, new_prop)) { /* "name" auto-generated by unflatten */ if (!strcmp(new_prop->name, "name")) continue; - unittest(0, "duplicate property '%s' in overlay_base node __symbols__", - prop->name); + KUNIT_FAIL(test, + "duplicate property '%s' in overlay_base node __symbols__", + prop->name); goto err_unlock; } if (__of_add_property_sysfs(of_symbols, new_prop)) { - unittest(0, "unable to add property '%s' in overlay_base node __symbols__ to sysfs", - prop->name); + KUNIT_FAIL(test, + "unable to add property '%s' in overlay_base node __symbols__ to sysfs", + prop->name); goto err_unlock; } } @@ -2481,20 +2512,24 @@ static __init void of_unittest_overlay_high_level(void) /* now do the normal overlay usage test */ - unittest(overlay_data_apply("overlay", NULL), - "Adding overlay 'overlay' failed\n"); + KUNIT_EXPECT_TRUE_MSG(test, overlay_data_apply("overlay", NULL), + "Adding overlay 'overlay' failed\n"); - unittest(overlay_data_apply("overlay_bad_add_dup_node", NULL), - "Adding overlay 'overlay_bad_add_dup_node' failed\n"); + KUNIT_EXPECT_TRUE_MSG( + test, overlay_data_apply("overlay_bad_add_dup_node", NULL), + "Adding overlay 'overlay_bad_add_dup_node' failed\n"); - unittest(overlay_data_apply("overlay_bad_add_dup_prop", NULL), - "Adding overlay 'overlay_bad_add_dup_prop' failed\n"); + KUNIT_EXPECT_TRUE_MSG( + test, overlay_data_apply("overlay_bad_add_dup_prop", NULL), + "Adding overlay 'overlay_bad_add_dup_prop' failed\n"); - unittest(overlay_data_apply("overlay_bad_phandle", NULL), - "Adding overlay 'overlay_bad_phandle' failed\n"); + KUNIT_EXPECT_TRUE_MSG( + test, overlay_data_apply("overlay_bad_phandle", NULL), + "Adding overlay 'overlay_bad_phandle' failed\n"); - unittest(overlay_data_apply("overlay_bad_symbol", NULL), - "Adding overlay 'overlay_bad_symbol' failed\n"); + KUNIT_EXPECT_TRUE_MSG( + test, overlay_data_apply("overlay_bad_symbol", NULL), + "Adding overlay 'overlay_bad_symbol' failed\n"); return; @@ -2504,57 +2539,52 @@ static __init void of_unittest_overlay_high_level(void) #else -static inline __init void of_unittest_overlay_high_level(void) {} +static inline void of_unittest_overlay_high_level(struct kunit *test) {} #endif -static int __init of_unittest(void) +static int of_test_init(struct kunit *test) { - struct device_node *np; - int res; - /* adding data for unittest */ - res = unittest_data_add(); - if (res) - return res; + KUNIT_ASSERT_EQ(test, 0, unittest_data_add()); + if (!of_aliases) of_aliases = of_find_node_by_path("/aliases"); - np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); - if (!np) { - pr_info("No testcase data in device tree; not running tests\n"); - return 0; - } - of_node_put(np); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, of_find_node_by_path( + "/testcase-data/phandle-tests/consumer-a")); if (IS_ENABLED(CONFIG_UML)) unflatten_device_tree(); - pr_info("start of unittest - you will see error messages\n"); - of_unittest_check_tree_linkage(); - of_unittest_check_phandles(); - of_unittest_find_node_by_name(); - of_unittest_dynamic(); - of_unittest_parse_phandle_with_args(); - of_unittest_parse_phandle_with_args_map(); - of_unittest_printf(); - of_unittest_property_string(); - of_unittest_property_copy(); - of_unittest_changeset(); - of_unittest_parse_interrupts(); - of_unittest_parse_interrupts_extended(); - of_unittest_match_node(); - of_unittest_platform_populate(); - of_unittest_overlay(); + return 0; +} +static struct kunit_case of_test_cases[] = { + KUNIT_CASE(of_unittest_check_tree_linkage), + KUNIT_CASE(of_unittest_check_phandles), + KUNIT_CASE(of_unittest_find_node_by_name), + KUNIT_CASE(of_unittest_dynamic), + KUNIT_CASE(of_unittest_parse_phandle_with_args), + KUNIT_CASE(of_unittest_parse_phandle_with_args_map), + KUNIT_CASE(of_unittest_printf), + KUNIT_CASE(of_unittest_property_string), + KUNIT_CASE(of_unittest_property_copy), + KUNIT_CASE(of_unittest_changeset), + KUNIT_CASE(of_unittest_parse_interrupts), + KUNIT_CASE(of_unittest_parse_interrupts_extended), + KUNIT_CASE(of_unittest_match_node), + KUNIT_CASE(of_unittest_platform_populate), + KUNIT_CASE(of_unittest_overlay), /* Double check linkage after removing testcase data */ - of_unittest_check_tree_linkage(); - - of_unittest_overlay_high_level(); - - pr_info("end of unittest - %i passed, %i failed\n", - unittest_results.passed, unittest_results.failed); + KUNIT_CASE(of_unittest_check_tree_linkage), + KUNIT_CASE(of_unittest_overlay_high_level), + {}, +}; - return 0; -} -late_initcall(of_unittest); +static struct kunit_module of_test_module = { + .name = "of-test", + .init = of_test_init, + .test_cases = of_test_cases, +}; +module_test(of_test_module); From patchwork Thu Feb 14 21:37:28 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813891 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 6269D1390 for ; Thu, 14 Feb 2019 21:39:16 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id 4B7592E7C5 for ; Thu, 14 Feb 2019 21:39:16 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id 3E42E2E7D3; Thu, 14 Feb 2019 21:39:16 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id DD8842E7C5 for ; Thu, 14 Feb 2019 21:39:14 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id D60E8208AE341; Thu, 14 Feb 2019 13:39:14 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::849; helo=mail-qt1-x849.google.com; envelope-from=3aoblxa4kdeeeuhqgdqkljjlqvjrrjoh.frpolqx0-qyglppolvwv.34.ruj@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-qt1-x849.google.com (mail-qt1-x849.google.com [IPv6:2607:f8b0:4864:20::849]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 966D2208AE2B6 for ; Thu, 14 Feb 2019 13:39:13 -0800 (PST) Received: by mail-qt1-x849.google.com with SMTP id r24so7084551qtj.13 for ; Thu, 14 Feb 2019 13:39:13 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=oDZ4WgorEFwoYe2QxPD78+BUwrOWjIt9Bzd+4b24oMI=; b=qblGwoGOiS+OI5CPyqusqGzJ+qGLXGCdtyBGO2FtoiF/SJUJdVUbaVKV2bsughCpbc PD63MC07UR3NBXoEQdvCz35H0iXUm/nMCBYDgoBpuiFx80DmJwgK/RITNOeZnAsE9fT5 o0hPUYfFLQO1/gMtc0u2dCUUXEObD5pGPanvJdsA+VwgUedgN3Q67RPkDwa4U2xrBPtA DZeouLj5aIowgeDK5sq2vN5GO4m8D/wgfc2fqVWgwJZJjOYMCkZgkvz/18kuM087RpfK 18PvDOvaijrOVzrfiswesYD9TPeCqgyQzssq8foKOMyMGUqrXxNJ4TBmTPchuMWqspmS iddw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=oDZ4WgorEFwoYe2QxPD78+BUwrOWjIt9Bzd+4b24oMI=; b=cgq4PeRZR+JloYlCvn6NYRypspu5ii3Q/VBaPze33cORA+5M/tbKnq9GpGxcrl0YUO yZNELRWPZ0pw2n4I3jygQu90RL2+JbV6OPDtcoFEmyVRx67RrYEqn68m674A1SXMvjg1 JjijzKFxbMBYJBFqMxUYc9tD5U4ZKKfFVJFVLjtD+d1RBu3/2+k3Al/NIaaPOgVT5HMr 8nTDiCrPRFaHt68DZJvy1oWCY7gwtoL3VNmvwgzYQysk6zJ2CdWW8FrIsO8Ynw3Lq2ZA UawVe3DfvZ13JoUvSThwXMA8Pe+ABv49jZ1qCzwgcquvre1T0ZGTBsPVPyhMJTTylRk9 E4gg== X-Gm-Message-State: AHQUAubSk2Kqwds7zHAlt3//mVHA//NR1WupMy0+NAL8p0+o2wVYXl1V cqASwC5lnh9Bfbj5VSMY6E6uGLMKet3znIRSb6Ybrw== X-Google-Smtp-Source: AHgI3IYPu6bsykPuSX89ZU6mze0rS8YH0EYZCO4MJgFbfVl+39hYrOVO2YUbg/tIofHm8Z38vNUknLAw+QH3HEJLd8rYZw== X-Received: by 2002:ac8:9d:: with SMTP id c29mr3615586qtg.50.1550180352393; Thu, 14 Feb 2019 13:39:12 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:28 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-17-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 16/17] of: unittest: split out a couple of test cases from unittest From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Split out a couple of test cases that these features in base.c from the unittest.c monolith. The intention is that we will eventually split out all test cases and group them together based on what portion of device tree they test. Signed-off-by: Brendan Higgins --- drivers/of/Makefile | 2 +- drivers/of/base-test.c | 214 ++++++++++++++++++++++++ drivers/of/test-common.c | 175 ++++++++++++++++++++ drivers/of/test-common.h | 16 ++ drivers/of/unittest.c | 345 +-------------------------------------- 5 files changed, 407 insertions(+), 345 deletions(-) create mode 100644 drivers/of/base-test.c create mode 100644 drivers/of/test-common.c create mode 100644 drivers/of/test-common.h diff --git a/drivers/of/Makefile b/drivers/of/Makefile index 663a4af0cccd5..4a4bd527d586c 100644 --- a/drivers/of/Makefile +++ b/drivers/of/Makefile @@ -8,7 +8,7 @@ obj-$(CONFIG_OF_PROMTREE) += pdt.o obj-$(CONFIG_OF_ADDRESS) += address.o obj-$(CONFIG_OF_IRQ) += irq.o obj-$(CONFIG_OF_NET) += of_net.o -obj-$(CONFIG_OF_UNITTEST) += unittest.o +obj-$(CONFIG_OF_UNITTEST) += unittest.o base-test.o test-common.o obj-$(CONFIG_OF_MDIO) += of_mdio.o obj-$(CONFIG_OF_RESERVED_MEM) += of_reserved_mem.o obj-$(CONFIG_OF_RESOLVE) += resolver.o diff --git a/drivers/of/base-test.c b/drivers/of/base-test.c new file mode 100644 index 0000000000000..3d3f4f1b74800 --- /dev/null +++ b/drivers/of/base-test.c @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Unit tests for functions defined in base.c. + */ +#include + +#include + +#include "test-common.h" + +static void of_unittest_find_node_by_name(struct kunit *test) +{ + struct device_node *np; + const char *options, *name; + + np = of_find_node_by_path("/testcase-data"); + name = kasprintf(GFP_KERNEL, "%pOF", np); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, + "find /testcase-data failed\n"); + of_node_put(np); + kfree(name); + + /* Test if trailing '/' works */ + KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("/testcase-data/"), NULL, + "trailing '/' on /testcase-data/ should fail\n"); + + np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + name = kasprintf(GFP_KERNEL, "%pOF", np); + KUNIT_EXPECT_STREQ_MSG( + test, "/testcase-data/phandle-tests/consumer-a", name, + "find /testcase-data/phandle-tests/consumer-a failed\n"); + of_node_put(np); + kfree(name); + + np = of_find_node_by_path("testcase-alias"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + name = kasprintf(GFP_KERNEL, "%pOF", np); + KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, + "find testcase-alias failed\n"); + of_node_put(np); + kfree(name); + + /* Test if trailing '/' works on aliases */ + KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("testcase-alias/"), NULL, + "trailing '/' on testcase-alias/ should fail\n"); + + np = of_find_node_by_path("testcase-alias/phandle-tests/consumer-a"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + name = kasprintf(GFP_KERNEL, "%pOF", np); + KUNIT_EXPECT_STREQ_MSG( + test, "/testcase-data/phandle-tests/consumer-a", name, + "find testcase-alias/phandle-tests/consumer-a failed\n"); + of_node_put(np); + kfree(name); + + KUNIT_EXPECT_EQ_MSG( + test, + np = of_find_node_by_path("/testcase-data/missing-path"), NULL, + "non-existent path returned node %pOF\n", np); + of_node_put(np); + + KUNIT_EXPECT_EQ_MSG( + test, np = of_find_node_by_path("missing-alias"), NULL, + "non-existent alias returned node %pOF\n", np); + of_node_put(np); + + KUNIT_EXPECT_EQ_MSG( + test, + np = of_find_node_by_path("testcase-alias/missing-path"), NULL, + "non-existent alias with relative path returned node %pOF\n", + np); + of_node_put(np); + + np = of_find_node_opts_by_path("/testcase-data:testoption", &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "testoption", options, + "option path test failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("/testcase-data:test/option", &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, + "option path test, subcase #1 failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("/testcase-data/testcase-device1:test/option", &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, + "option path test, subcase #2 failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("/testcase-data:testoption", NULL); + KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, np, + "NULL option path test failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("testcase-alias:testaliasoption", + &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "testaliasoption", options, + "option alias path test failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("testcase-alias:test/alias/option", + &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_STREQ_MSG(test, "test/alias/option", options, + "option alias path test, subcase #1 failed\n"); + of_node_put(np); + + np = of_find_node_opts_by_path("testcase-alias:testaliasoption", NULL); + KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG( + test, np, "NULL option alias path test failed\n"); + of_node_put(np); + + options = "testoption"; + np = of_find_node_opts_by_path("testcase-alias", &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_EQ_MSG(test, options, NULL, + "option clearing test failed\n"); + of_node_put(np); + + options = "testoption"; + np = of_find_node_opts_by_path("/", &options); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + KUNIT_EXPECT_EQ_MSG(test, options, NULL, + "option clearing root node test failed\n"); + of_node_put(np); +} + +static void of_unittest_dynamic(struct kunit *test) +{ + struct device_node *np; + struct property *prop; + + np = of_find_node_by_path("/testcase-data"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); + + /* Array of 4 properties for the purpose of testing */ + prop = kcalloc(4, sizeof(*prop), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop); + + /* Add a new property - should pass*/ + prop->name = "new-property"; + prop->value = "new-property-data"; + prop->length = strlen(prop->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + "Adding a new property failed\n"); + + /* Try to add an existing property - should fail */ + prop++; + prop->name = "new-property"; + prop->value = "new-property-data-should-fail"; + prop->length = strlen(prop->value) + 1; + KUNIT_EXPECT_NE_MSG(test, of_add_property(np, prop), 0, + "Adding an existing property should have failed\n"); + + /* Try to modify an existing property - should pass */ + prop->value = "modify-property-data-should-pass"; + prop->length = strlen(prop->value) + 1; + KUNIT_EXPECT_EQ_MSG( + test, of_update_property(np, prop), 0, + "Updating an existing property should have passed\n"); + + /* Try to modify non-existent property - should pass*/ + prop++; + prop->name = "modify-property"; + prop->value = "modify-missing-property-data-should-pass"; + prop->length = strlen(prop->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop), 0, + "Updating a missing property should have passed\n"); + + /* Remove property - should pass */ + KUNIT_EXPECT_EQ_MSG(test, of_remove_property(np, prop), 0, + "Removing a property should have passed\n"); + + /* Adding very large property - should pass */ + prop++; + prop->name = "large-property-PAGE_SIZEx8"; + prop->length = PAGE_SIZE * 8; + prop->value = kzalloc(prop->length, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop->value); + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + "Adding a large property should have passed\n"); +} + +static int of_test_init(struct kunit *test) +{ + /* adding data for unittest */ + KUNIT_ASSERT_EQ(test, 0, unittest_data_add()); + + if (!of_aliases) + of_aliases = of_find_node_by_path("/aliases"); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, of_find_node_by_path( + "/testcase-data/phandle-tests/consumer-a")); + + return 0; +} + +static struct kunit_case of_test_cases[] = { + KUNIT_CASE(of_unittest_find_node_by_name), + KUNIT_CASE(of_unittest_dynamic), + {}, +}; + +static struct kunit_module of_test_module = { + .name = "of-base-test", + .init = of_test_init, + .test_cases = of_test_cases, +}; +module_test(of_test_module); diff --git a/drivers/of/test-common.c b/drivers/of/test-common.c new file mode 100644 index 0000000000000..4c9a5f3b82f7d --- /dev/null +++ b/drivers/of/test-common.c @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Common code to be used by unit tests. + */ +#include "test-common.h" + +#include +#include + +#include "of_private.h" + +/** + * update_node_properties - adds the properties + * of np into dup node (present in live tree) and + * updates parent of children of np to dup. + * + * @np: node whose properties are being added to the live tree + * @dup: node present in live tree to be updated + */ +static void update_node_properties(struct device_node *np, + struct device_node *dup) +{ + struct property *prop; + struct property *save_next; + struct device_node *child; + int ret; + + for_each_child_of_node(np, child) + child->parent = dup; + + /* + * "unittest internal error: unable to add testdata property" + * + * If this message reports a property in node '/__symbols__' then + * the respective unittest overlay contains a label that has the + * same name as a label in the live devicetree. The label will + * be in the live devicetree only if the devicetree source was + * compiled with the '-@' option. If you encounter this error, + * please consider renaming __all__ of the labels in the unittest + * overlay dts files with an odd prefix that is unlikely to be + * used in a real devicetree. + */ + + /* + * open code for_each_property_of_node() because of_add_property() + * sets prop->next to NULL + */ + for (prop = np->properties; prop != NULL; prop = save_next) { + save_next = prop->next; + ret = of_add_property(dup, prop); + if (ret) + pr_err("unittest internal error: unable to add testdata property %pOF/%s", + np, prop->name); + } +} + +/** + * attach_node_and_children - attaches nodes + * and its children to live tree + * + * @np: Node to attach to live tree + */ +static void attach_node_and_children(struct device_node *np) +{ + struct device_node *next, *dup, *child; + unsigned long flags; + const char *full_name; + + full_name = kasprintf(GFP_KERNEL, "%pOF", np); + + if (!strcmp(full_name, "/__local_fixups__") || + !strcmp(full_name, "/__fixups__")) + return; + + dup = of_find_node_by_path(full_name); + kfree(full_name); + if (dup) { + update_node_properties(np, dup); + return; + } + + child = np->child; + np->child = NULL; + + mutex_lock(&of_mutex); + raw_spin_lock_irqsave(&devtree_lock, flags); + np->sibling = np->parent->child; + np->parent->child = np; + of_node_clear_flag(np, OF_DETACHED); + raw_spin_unlock_irqrestore(&devtree_lock, flags); + + __of_attach_node_sysfs(np); + mutex_unlock(&of_mutex); + + while (child) { + next = child->sibling; + attach_node_and_children(child); + child = next; + } +} + +/** + * unittest_data_add - Reads, copies data from + * linked tree and attaches it to the live tree + */ +int unittest_data_add(void) +{ + void *unittest_data; + struct device_node *unittest_data_node, *np; + /* + * __dtb_testcases_begin[] and __dtb_testcases_end[] are magically + * created by cmd_dt_S_dtb in scripts/Makefile.lib + */ + extern uint8_t __dtb_testcases_begin[]; + extern uint8_t __dtb_testcases_end[]; + const int size = __dtb_testcases_end - __dtb_testcases_begin; + int rc; + + if (!size) { + pr_warn("%s: No testcase data to attach; not running tests\n", + __func__); + return -ENODATA; + } + + /* creating copy */ + unittest_data = kmemdup(__dtb_testcases_begin, size, GFP_KERNEL); + + if (!unittest_data) { + pr_warn("%s: Failed to allocate memory for unittest_data; " + "not running tests\n", __func__); + return -ENOMEM; + } + of_fdt_unflatten_tree(unittest_data, NULL, &unittest_data_node); + if (!unittest_data_node) { + pr_warn("%s: No tree to attach; not running tests\n", __func__); + return -ENODATA; + } + + /* + * This lock normally encloses of_resolve_phandles() + */ + of_overlay_mutex_lock(); + + rc = of_resolve_phandles(unittest_data_node); + if (rc) { + pr_err("%s: Failed to resolve phandles (rc=%i)\n", __func__, rc); + of_overlay_mutex_unlock(); + return -EINVAL; + } + + if (!of_root) { + of_root = unittest_data_node; + for_each_of_allnodes(np) + __of_attach_node_sysfs(np); + of_aliases = of_find_node_by_path("/aliases"); + of_chosen = of_find_node_by_path("/chosen"); + of_overlay_mutex_unlock(); + return 0; + } + + /* attach the sub-tree to live tree */ + np = unittest_data_node->child; + while (np) { + struct device_node *next = np->sibling; + + np->parent = of_root; + attach_node_and_children(np); + np = next; + } + + of_overlay_mutex_unlock(); + + return 0; +} + diff --git a/drivers/of/test-common.h b/drivers/of/test-common.h new file mode 100644 index 0000000000000..a35484406bbf1 --- /dev/null +++ b/drivers/of/test-common.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Common code to be used by unit tests. + */ +#ifndef _LINUX_OF_TEST_COMMON_H +#define _LINUX_OF_TEST_COMMON_H + +#include + +/** + * unittest_data_add - Reads, copies data from + * linked tree and attaches it to the live tree + */ +int unittest_data_add(void); + +#endif /* _LINUX_OF_TEST_COMMON_H */ diff --git a/drivers/of/unittest.c b/drivers/of/unittest.c index 96de69ccb3e63..05a2610d0be7f 100644 --- a/drivers/of/unittest.c +++ b/drivers/of/unittest.c @@ -29,184 +29,7 @@ #include #include "of_private.h" - -static void of_unittest_find_node_by_name(struct kunit *test) -{ - struct device_node *np; - const char *options, *name; - - np = of_find_node_by_path("/testcase-data"); - name = kasprintf(GFP_KERNEL, "%pOF", np); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, - "find /testcase-data failed\n"); - of_node_put(np); - kfree(name); - - /* Test if trailing '/' works */ - KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("/testcase-data/"), NULL, - "trailing '/' on /testcase-data/ should fail\n"); - - np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - name = kasprintf(GFP_KERNEL, "%pOF", np); - KUNIT_EXPECT_STREQ_MSG( - test, "/testcase-data/phandle-tests/consumer-a", name, - "find /testcase-data/phandle-tests/consumer-a failed\n"); - of_node_put(np); - kfree(name); - - np = of_find_node_by_path("testcase-alias"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - name = kasprintf(GFP_KERNEL, "%pOF", np); - KUNIT_EXPECT_STREQ_MSG(test, "/testcase-data", name, - "find testcase-alias failed\n"); - of_node_put(np); - kfree(name); - - /* Test if trailing '/' works on aliases */ - KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("testcase-alias/"), NULL, - "trailing '/' on testcase-alias/ should fail\n"); - - np = of_find_node_by_path("testcase-alias/phandle-tests/consumer-a"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - name = kasprintf(GFP_KERNEL, "%pOF", np); - KUNIT_EXPECT_STREQ_MSG( - test, "/testcase-data/phandle-tests/consumer-a", name, - "find testcase-alias/phandle-tests/consumer-a failed\n"); - of_node_put(np); - kfree(name); - - KUNIT_EXPECT_EQ_MSG( - test, - np = of_find_node_by_path("/testcase-data/missing-path"), NULL, - "non-existent path returned node %pOF\n", np); - of_node_put(np); - - KUNIT_EXPECT_EQ_MSG( - test, np = of_find_node_by_path("missing-alias"), NULL, - "non-existent alias returned node %pOF\n", np); - of_node_put(np); - - KUNIT_EXPECT_EQ_MSG( - test, - np = of_find_node_by_path("testcase-alias/missing-path"), NULL, - "non-existent alias with relative path returned node %pOF\n", - np); - of_node_put(np); - - np = of_find_node_opts_by_path("/testcase-data:testoption", &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "testoption", options, - "option path test failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("/testcase-data:test/option", &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, - "option path test, subcase #1 failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("/testcase-data/testcase-device1:test/option", &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, - "option path test, subcase #2 failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("/testcase-data:testoption", NULL); - KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, np, - "NULL option path test failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("testcase-alias:testaliasoption", - &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "testaliasoption", options, - "option alias path test failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("testcase-alias:test/alias/option", - &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_STREQ_MSG(test, "test/alias/option", options, - "option alias path test, subcase #1 failed\n"); - of_node_put(np); - - np = of_find_node_opts_by_path("testcase-alias:testaliasoption", NULL); - KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG( - test, np, "NULL option alias path test failed\n"); - of_node_put(np); - - options = "testoption"; - np = of_find_node_opts_by_path("testcase-alias", &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_EQ_MSG(test, options, NULL, - "option clearing test failed\n"); - of_node_put(np); - - options = "testoption"; - np = of_find_node_opts_by_path("/", &options); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - KUNIT_EXPECT_EQ_MSG(test, options, NULL, - "option clearing root node test failed\n"); - of_node_put(np); -} - -static void of_unittest_dynamic(struct kunit *test) -{ - struct device_node *np; - struct property *prop; - - np = of_find_node_by_path("/testcase-data"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); - - /* Array of 4 properties for the purpose of testing */ - prop = kcalloc(4, sizeof(*prop), GFP_KERNEL); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop); - - /* Add a new property - should pass*/ - prop->name = "new-property"; - prop->value = "new-property-data"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, - "Adding a new property failed\n"); - - /* Try to add an existing property - should fail */ - prop++; - prop->name = "new-property"; - prop->value = "new-property-data-should-fail"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_NE_MSG(test, of_add_property(np, prop), 0, - "Adding an existing property should have failed\n"); - - /* Try to modify an existing property - should pass */ - prop->value = "modify-property-data-should-pass"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG( - test, of_update_property(np, prop), 0, - "Updating an existing property should have passed\n"); - - /* Try to modify non-existent property - should pass*/ - prop++; - prop->name = "modify-property"; - prop->value = "modify-missing-property-data-should-pass"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop), 0, - "Updating a missing property should have passed\n"); - - /* Remove property - should pass */ - KUNIT_EXPECT_EQ_MSG(test, of_remove_property(np, prop), 0, - "Removing a property should have passed\n"); - - /* Adding very large property - should pass */ - prop++; - prop->name = "large-property-PAGE_SIZEx8"; - prop->length = PAGE_SIZE * 8; - prop->value = kzalloc(prop->length, GFP_KERNEL); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop->value); - KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, - "Adding a large property should have passed\n"); -} +#include "test-common.h" static int of_unittest_check_node_linkage(struct device_node *np) { @@ -1177,170 +1000,6 @@ static void of_unittest_platform_populate(struct kunit *test) of_node_put(np); } -/** - * update_node_properties - adds the properties - * of np into dup node (present in live tree) and - * updates parent of children of np to dup. - * - * @np: node whose properties are being added to the live tree - * @dup: node present in live tree to be updated - */ -static void update_node_properties(struct device_node *np, - struct device_node *dup) -{ - struct property *prop; - struct property *save_next; - struct device_node *child; - int ret; - - for_each_child_of_node(np, child) - child->parent = dup; - - /* - * "unittest internal error: unable to add testdata property" - * - * If this message reports a property in node '/__symbols__' then - * the respective unittest overlay contains a label that has the - * same name as a label in the live devicetree. The label will - * be in the live devicetree only if the devicetree source was - * compiled with the '-@' option. If you encounter this error, - * please consider renaming __all__ of the labels in the unittest - * overlay dts files with an odd prefix that is unlikely to be - * used in a real devicetree. - */ - - /* - * open code for_each_property_of_node() because of_add_property() - * sets prop->next to NULL - */ - for (prop = np->properties; prop != NULL; prop = save_next) { - save_next = prop->next; - ret = of_add_property(dup, prop); - if (ret) - pr_err("unittest internal error: unable to add testdata property %pOF/%s", - np, prop->name); - } -} - -/** - * attach_node_and_children - attaches nodes - * and its children to live tree - * - * @np: Node to attach to live tree - */ -static void attach_node_and_children(struct device_node *np) -{ - struct device_node *next, *dup, *child; - unsigned long flags; - const char *full_name; - - full_name = kasprintf(GFP_KERNEL, "%pOF", np); - - if (!strcmp(full_name, "/__local_fixups__") || - !strcmp(full_name, "/__fixups__")) - return; - - dup = of_find_node_by_path(full_name); - kfree(full_name); - if (dup) { - update_node_properties(np, dup); - return; - } - - child = np->child; - np->child = NULL; - - mutex_lock(&of_mutex); - raw_spin_lock_irqsave(&devtree_lock, flags); - np->sibling = np->parent->child; - np->parent->child = np; - of_node_clear_flag(np, OF_DETACHED); - raw_spin_unlock_irqrestore(&devtree_lock, flags); - - __of_attach_node_sysfs(np); - mutex_unlock(&of_mutex); - - while (child) { - next = child->sibling; - attach_node_and_children(child); - child = next; - } -} - -/** - * unittest_data_add - Reads, copies data from - * linked tree and attaches it to the live tree - */ -static int unittest_data_add(void) -{ - void *unittest_data; - struct device_node *unittest_data_node, *np; - /* - * __dtb_testcases_begin[] and __dtb_testcases_end[] are magically - * created by cmd_dt_S_dtb in scripts/Makefile.lib - */ - extern uint8_t __dtb_testcases_begin[]; - extern uint8_t __dtb_testcases_end[]; - const int size = __dtb_testcases_end - __dtb_testcases_begin; - int rc; - - if (!size) { - pr_warn("%s: No testcase data to attach; not running tests\n", - __func__); - return -ENODATA; - } - - /* creating copy */ - unittest_data = kmemdup(__dtb_testcases_begin, size, GFP_KERNEL); - - if (!unittest_data) { - pr_warn("%s: Failed to allocate memory for unittest_data; " - "not running tests\n", __func__); - return -ENOMEM; - } - of_fdt_unflatten_tree(unittest_data, NULL, &unittest_data_node); - if (!unittest_data_node) { - pr_warn("%s: No tree to attach; not running tests\n", __func__); - return -ENODATA; - } - - /* - * This lock normally encloses of_resolve_phandles() - */ - of_overlay_mutex_lock(); - - rc = of_resolve_phandles(unittest_data_node); - if (rc) { - pr_err("%s: Failed to resolve phandles (rc=%i)\n", __func__, rc); - of_overlay_mutex_unlock(); - return -EINVAL; - } - - if (!of_root) { - of_root = unittest_data_node; - for_each_of_allnodes(np) - __of_attach_node_sysfs(np); - of_aliases = of_find_node_by_path("/aliases"); - of_chosen = of_find_node_by_path("/chosen"); - of_overlay_mutex_unlock(); - return 0; - } - - /* attach the sub-tree to live tree */ - np = unittest_data_node->child; - while (np) { - struct device_node *next = np->sibling; - - np->parent = of_root; - attach_node_and_children(np); - np = next; - } - - of_overlay_mutex_unlock(); - - return 0; -} - #ifdef CONFIG_OF_OVERLAY static int overlay_data_apply(const char *overlay_name, int *overlay_id); @@ -2563,8 +2222,6 @@ static int of_test_init(struct kunit *test) static struct kunit_case of_test_cases[] = { KUNIT_CASE(of_unittest_check_tree_linkage), KUNIT_CASE(of_unittest_check_phandles), - KUNIT_CASE(of_unittest_find_node_by_name), - KUNIT_CASE(of_unittest_dynamic), KUNIT_CASE(of_unittest_parse_phandle_with_args), KUNIT_CASE(of_unittest_parse_phandle_with_args_map), KUNIT_CASE(of_unittest_printf), From patchwork Thu Feb 14 21:37:29 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Brendan Higgins X-Patchwork-Id: 10813895 Return-Path: Received: from mail.wl.linuxfoundation.org (pdx-wl-mail.web.codeaurora.org [172.30.200.125]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 114926C2 for ; Thu, 14 Feb 2019 21:39:18 +0000 (UTC) Received: from mail.wl.linuxfoundation.org (localhost [127.0.0.1]) by mail.wl.linuxfoundation.org (Postfix) with ESMTP id F0B642E7C5 for ; Thu, 14 Feb 2019 21:39:17 +0000 (UTC) Received: by mail.wl.linuxfoundation.org (Postfix, from userid 486) id E416D2E7D1; Thu, 14 Feb 2019 21:39:17 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on pdx-wl-mail.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-2.7 required=2.0 tests=BAYES_00,DKIM_ADSP_CUSTOM_MED, DKIM_INVALID,DKIM_SIGNED,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE autolearn=ham version=3.3.1 Received: from ml01.01.org (ml01.01.org [198.145.21.10]) (using TLSv1.2 with cipher DHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.wl.linuxfoundation.org (Postfix) with ESMTPS id 03F142E7C5 for ; Thu, 14 Feb 2019 21:39:17 +0000 (UTC) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id F307D208AE2DF; Thu, 14 Feb 2019 13:39:16 -0800 (PST) X-Original-To: linux-nvdimm@lists.01.org Delivered-To: linux-nvdimm@lists.01.org Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=2607:f8b0:4864:20::449; helo=mail-pf1-x449.google.com; envelope-from=3aublxa4kdemgwjsifsmnllnsxlttlqj.htrqnsz2-s0inrrqnxyx.56.twl@flex--brendanhiggins.bounces.google.com; receiver=linux-nvdimm@lists.01.org Received: from mail-pf1-x449.google.com (mail-pf1-x449.google.com [IPv6:2607:f8b0:4864:20::449]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 8BCF1208AE2C2 for ; Thu, 14 Feb 2019 13:39:15 -0800 (PST) Received: by mail-pf1-x449.google.com with SMTP id q21so5805803pfi.17 for ; Thu, 14 Feb 2019 13:39:15 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=date:in-reply-to:message-id:mime-version:references:subject:from:to :cc; bh=EAuQlf1fKXRek+1vtW1D4HQYVzdPlJLUWWIxe+MLs4w=; b=gaO4tGzoAhxmamwimIt681npqwCn41PFdIy95iypxUg8sj2H38nBXSN4IUAFgwKefW c8yt3imt0ooOa1vHgPwCgrV9xQwM/nPxgIstgz6hQwihG25kh89yZqhjArwl93vF9t4Z XbNJ5vBRBS9FNgaasqqCXzBy86L9E8rSTmuAkADlhAlOOkVtNsBvW6UCYwkr+HERQQUu kTFkQYp2qKtWOGSF8ZKPqI+E0KFAO5cWDzTI79j3wqeixWBsmECcLZwAWV1TslTD1w2u 0B4unWVRVU+ReqnTBUvL1kT8lMLOxQFQ42uzInjCAEpDAvBgsHv5el0qwY3II4hlod/I z43g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:in-reply-to:message-id:mime-version :references:subject:from:to:cc; bh=EAuQlf1fKXRek+1vtW1D4HQYVzdPlJLUWWIxe+MLs4w=; b=tPKgPAHres7icAEdHxjHg6KzEMcnh+YVj7g2AI1ImitR+EJ9R8l/UphZeT4+EG7p3u yMwS0Zlpe8VDxKyJSXxXRS7SUWQQLSpTMIe2qEV83xhADW3Vu39g5Nl9dlbC7OIhpirV +lv9gllI3xe3JFi91LWE6TRBJ843cEVkeJ+yW5FJ8DrXJjOSvF4utjipYY9MJA3uZdSf tfgaAob9hSCRu/sDbBYnel+MLNIwScF6AiSPao3p2AqExQO92tkq88cWOR5rneVz3WS9 0CQmBg3jIRFE7fz9p3Rl0C1lzEt8aFmB0dtZrLIvqKn19RSef77otD0eeL+OMpT8rXlK yAXQ== X-Gm-Message-State: AHQUAubOLEhlFuVpo4JgEmCNmv3lL6/iF+psaBhzD6/cdNZ2VZ1KD1ea UmJmwpZe5lR9OBH6uuv2v+E1Znbd77iDckTRIcXzDw== X-Google-Smtp-Source: AHgI3Ibnae4zxn6yqvd5d1Wz9RmY3yvhFLV+4L6cHJjvniZhExtOtNtBQER7ez2HMPW45KBTXN7/Wk8/T72shDqzp+UBSg== X-Received: by 2002:a17:902:b113:: with SMTP id q19mr1886341plr.33.1550180354890; Thu, 14 Feb 2019 13:39:14 -0800 (PST) Date: Thu, 14 Feb 2019 13:37:29 -0800 In-Reply-To: <20190214213729.21702-1-brendanhiggins@google.com> Message-Id: <20190214213729.21702-18-brendanhiggins@google.com> Mime-Version: 1.0 References: <20190214213729.21702-1-brendanhiggins@google.com> X-Mailer: git-send-email 2.21.0.rc0.258.g878e2cd30e-goog Subject: [RFC v4 17/17] of: unittest: split up some super large test cases From: Brendan Higgins To: keescook@google.com, mcgrof@kernel.org, shuah@kernel.org, robh@kernel.org, kieran.bingham@ideasonboard.com, frowand.list@gmail.com X-BeenThere: linux-nvdimm@lists.01.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: "Linux-nvdimm developer list." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: brakmo@fb.com, pmladek@suse.com, amir73il@gmail.com, Brendan Higgins , dri-devel@lists.freedesktop.org, Alexander.Levin@microsoft.com, linux-kselftest@vger.kernel.org, linux-nvdimm@lists.01.org, richard@nod.at, knut.omang@oracle.com, wfg@linux.intel.com, joel@jms.id.au, jdike@addtoit.com, dan.carpenter@oracle.com, devicetree@vger.kernel.org, Tim.Bird@sony.com, linux-um@lists.infradead.org, rostedt@goodmis.org, julia.lawall@lip6.fr, kunit-dev@googlegroups.com, gregkh@linuxfoundation.org, linux-kernel@vger.kernel.org, daniel@ffwll.ch, mpe@ellerman.id.au, joe@perches.com, khilman@baylibre.com Errors-To: linux-nvdimm-bounces@lists.01.org Sender: "Linux-nvdimm" X-Virus-Scanned: ClamAV using ClamSMTP Split up the super large test cases of_unittest_find_node_by_name and of_unittest_dynamic into properly sized and defined test cases. Signed-off-by: Brendan Higgins --- drivers/of/base-test.c | 297 ++++++++++++++++++++++++++++++++++------- 1 file changed, 249 insertions(+), 48 deletions(-) diff --git a/drivers/of/base-test.c b/drivers/of/base-test.c index 3d3f4f1b74800..7b44c967ed2fd 100644 --- a/drivers/of/base-test.c +++ b/drivers/of/base-test.c @@ -8,10 +8,10 @@ #include "test-common.h" -static void of_unittest_find_node_by_name(struct kunit *test) +static void of_test_find_node_by_name_basic(struct kunit *test) { struct device_node *np; - const char *options, *name; + const char *name; np = of_find_node_by_path("/testcase-data"); name = kasprintf(GFP_KERNEL, "%pOF", np); @@ -20,11 +20,21 @@ static void of_unittest_find_node_by_name(struct kunit *test) "find /testcase-data failed\n"); of_node_put(np); kfree(name); +} +static void of_test_find_node_by_name_trailing_slash(struct kunit *test) +{ /* Test if trailing '/' works */ KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("/testcase-data/"), NULL, "trailing '/' on /testcase-data/ should fail\n"); +} + +static void of_test_find_node_by_name_multiple_components(struct kunit *test) +{ + struct device_node *np; + const char *name; + np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); name = kasprintf(GFP_KERNEL, "%pOF", np); @@ -33,6 +43,12 @@ static void of_unittest_find_node_by_name(struct kunit *test) "find /testcase-data/phandle-tests/consumer-a failed\n"); of_node_put(np); kfree(name); +} + +static void of_test_find_node_by_name_with_alias(struct kunit *test) +{ + struct device_node *np; + const char *name; np = of_find_node_by_path("testcase-alias"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); @@ -41,10 +57,23 @@ static void of_unittest_find_node_by_name(struct kunit *test) "find testcase-alias failed\n"); of_node_put(np); kfree(name); +} +static void of_test_find_node_by_name_with_alias_and_slash(struct kunit *test) +{ /* Test if trailing '/' works on aliases */ KUNIT_EXPECT_EQ_MSG(test, of_find_node_by_path("testcase-alias/"), NULL, - "trailing '/' on testcase-alias/ should fail\n"); + "trailing '/' on testcase-alias/ should fail\n"); +} + +/* + * TODO(brendanhiggins@google.com): This looks like a duplicate of + * of_test_find_node_by_name_multiple_components + */ +static void of_test_find_node_by_name_multiple_components_2(struct kunit *test) +{ + struct device_node *np; + const char *name; np = of_find_node_by_path("testcase-alias/phandle-tests/consumer-a"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); @@ -54,17 +83,33 @@ static void of_unittest_find_node_by_name(struct kunit *test) "find testcase-alias/phandle-tests/consumer-a failed\n"); of_node_put(np); kfree(name); +} + +static void of_test_find_node_by_name_missing_path(struct kunit *test) +{ + struct device_node *np; KUNIT_EXPECT_EQ_MSG( test, np = of_find_node_by_path("/testcase-data/missing-path"), NULL, "non-existent path returned node %pOF\n", np); of_node_put(np); +} + +static void of_test_find_node_by_name_missing_alias(struct kunit *test) +{ + struct device_node *np; KUNIT_EXPECT_EQ_MSG( test, np = of_find_node_by_path("missing-alias"), NULL, "non-existent alias returned node %pOF\n", np); of_node_put(np); +} + +static void of_test_find_node_by_name_missing_alias_with_relative_path( + struct kunit *test) +{ + struct device_node *np; KUNIT_EXPECT_EQ_MSG( test, @@ -72,12 +117,24 @@ static void of_unittest_find_node_by_name(struct kunit *test) "non-existent alias with relative path returned node %pOF\n", np); of_node_put(np); +} + +static void of_test_find_node_by_name_with_option(struct kunit *test) +{ + struct device_node *np; + const char *options; np = of_find_node_opts_by_path("/testcase-data:testoption", &options); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); KUNIT_EXPECT_STREQ_MSG(test, "testoption", options, "option path test failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_with_option_and_slash(struct kunit *test) +{ + struct device_node *np; + const char *options; np = of_find_node_opts_by_path("/testcase-data:test/option", &options); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); @@ -90,11 +147,22 @@ static void of_unittest_find_node_by_name(struct kunit *test) KUNIT_EXPECT_STREQ_MSG(test, "test/option", options, "option path test, subcase #2 failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_with_null_option(struct kunit *test) +{ + struct device_node *np; np = of_find_node_opts_by_path("/testcase-data:testoption", NULL); KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG(test, np, "NULL option path test failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_with_option_alias(struct kunit *test) +{ + struct device_node *np; + const char *options; np = of_find_node_opts_by_path("testcase-alias:testaliasoption", &options); @@ -102,6 +170,13 @@ static void of_unittest_find_node_by_name(struct kunit *test) KUNIT_EXPECT_STREQ_MSG(test, "testaliasoption", options, "option alias path test failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_with_option_alias_and_slash( + struct kunit *test) +{ + struct device_node *np; + const char *options; np = of_find_node_opts_by_path("testcase-alias:test/alias/option", &options); @@ -109,11 +184,22 @@ static void of_unittest_find_node_by_name(struct kunit *test) KUNIT_EXPECT_STREQ_MSG(test, "test/alias/option", options, "option alias path test, subcase #1 failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_with_null_option_alias(struct kunit *test) +{ + struct device_node *np; np = of_find_node_opts_by_path("testcase-alias:testaliasoption", NULL); KUNIT_EXPECT_NOT_ERR_OR_NULL_MSG( test, np, "NULL option alias path test failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_option_clearing(struct kunit *test) +{ + struct device_node *np; + const char *options; options = "testoption"; np = of_find_node_opts_by_path("testcase-alias", &options); @@ -121,6 +207,12 @@ static void of_unittest_find_node_by_name(struct kunit *test) KUNIT_EXPECT_EQ_MSG(test, options, NULL, "option clearing test failed\n"); of_node_put(np); +} + +static void of_test_find_node_by_name_option_clearing_root(struct kunit *test) +{ + struct device_node *np; + const char *options; options = "testoption"; np = of_find_node_opts_by_path("/", &options); @@ -130,65 +222,147 @@ static void of_unittest_find_node_by_name(struct kunit *test) of_node_put(np); } -static void of_unittest_dynamic(struct kunit *test) +static int of_test_find_node_by_name_init(struct kunit *test) { + /* adding data for unittest */ + KUNIT_ASSERT_EQ(test, 0, unittest_data_add()); + + if (!of_aliases) + of_aliases = of_find_node_by_path("/aliases"); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, of_find_node_by_path( + "/testcase-data/phandle-tests/consumer-a")); + + return 0; +} + +static struct kunit_case of_test_find_node_by_name_cases[] = { + KUNIT_CASE(of_test_find_node_by_name_basic), + KUNIT_CASE(of_test_find_node_by_name_trailing_slash), + KUNIT_CASE(of_test_find_node_by_name_multiple_components), + KUNIT_CASE(of_test_find_node_by_name_with_alias), + KUNIT_CASE(of_test_find_node_by_name_with_alias_and_slash), + KUNIT_CASE(of_test_find_node_by_name_multiple_components_2), + KUNIT_CASE(of_test_find_node_by_name_missing_path), + KUNIT_CASE(of_test_find_node_by_name_missing_alias), + KUNIT_CASE(of_test_find_node_by_name_missing_alias_with_relative_path), + KUNIT_CASE(of_test_find_node_by_name_with_option), + KUNIT_CASE(of_test_find_node_by_name_with_option_and_slash), + KUNIT_CASE(of_test_find_node_by_name_with_null_option), + KUNIT_CASE(of_test_find_node_by_name_with_option_alias), + KUNIT_CASE(of_test_find_node_by_name_with_option_alias_and_slash), + KUNIT_CASE(of_test_find_node_by_name_with_null_option_alias), + KUNIT_CASE(of_test_find_node_by_name_option_clearing), + KUNIT_CASE(of_test_find_node_by_name_option_clearing_root), + {}, +}; + +static struct kunit_module of_test_find_node_by_name_module = { + .name = "of-test-find-node-by-name", + .init = of_test_find_node_by_name_init, + .test_cases = of_test_find_node_by_name_cases, +}; +module_test(of_test_find_node_by_name_module); + +struct of_test_dynamic_context { struct device_node *np; - struct property *prop; + struct property *prop0; + struct property *prop1; +}; - np = of_find_node_by_path("/testcase-data"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, np); +static void of_test_dynamic_basic(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + struct property *prop0 = ctx->prop0; - /* Array of 4 properties for the purpose of testing */ - prop = kcalloc(4, sizeof(*prop), GFP_KERNEL); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop); + /* Add a new property - should pass*/ + prop0->name = "new-property"; + prop0->value = "new-property-data"; + prop0->length = strlen(prop0->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop0), 0, + "Adding a new property failed\n"); + + /* Test that we can remove a property */ + KUNIT_EXPECT_EQ(test, of_remove_property(np, prop0), 0); +} + +static void of_test_dynamic_add_existing_property(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + struct property *prop0 = ctx->prop0, *prop1 = ctx->prop1; /* Add a new property - should pass*/ - prop->name = "new-property"; - prop->value = "new-property-data"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + prop0->name = "new-property"; + prop0->value = "new-property-data"; + prop0->length = strlen(prop0->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop0), 0, "Adding a new property failed\n"); /* Try to add an existing property - should fail */ - prop++; - prop->name = "new-property"; - prop->value = "new-property-data-should-fail"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_NE_MSG(test, of_add_property(np, prop), 0, + prop1->name = "new-property"; + prop1->value = "new-property-data-should-fail"; + prop1->length = strlen(prop1->value) + 1; + KUNIT_EXPECT_NE_MSG(test, of_add_property(np, prop1), 0, "Adding an existing property should have failed\n"); +} + +static void of_test_dynamic_modify_existing_property(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + struct property *prop0 = ctx->prop0, *prop1 = ctx->prop1; + + /* Add a new property - should pass*/ + prop0->name = "new-property"; + prop0->value = "new-property-data"; + prop0->length = strlen(prop0->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop0), 0, + "Adding a new property failed\n"); /* Try to modify an existing property - should pass */ - prop->value = "modify-property-data-should-pass"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG( - test, of_update_property(np, prop), 0, - "Updating an existing property should have passed\n"); + prop1->name = "new-property"; + prop1->value = "modify-property-data-should-pass"; + prop1->length = strlen(prop1->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop1), 0, + "Updating an existing property should have passed\n"); +} + +static void of_test_dynamic_modify_non_existent_property(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + struct property *prop0 = ctx->prop0; /* Try to modify non-existent property - should pass*/ - prop++; - prop->name = "modify-property"; - prop->value = "modify-missing-property-data-should-pass"; - prop->length = strlen(prop->value) + 1; - KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop), 0, + prop0->name = "modify-property"; + prop0->value = "modify-missing-property-data-should-pass"; + prop0->length = strlen(prop0->value) + 1; + KUNIT_EXPECT_EQ_MSG(test, of_update_property(np, prop0), 0, "Updating a missing property should have passed\n"); +} - /* Remove property - should pass */ - KUNIT_EXPECT_EQ_MSG(test, of_remove_property(np, prop), 0, - "Removing a property should have passed\n"); +static void of_test_dynamic_large_property(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + struct property *prop0 = ctx->prop0; /* Adding very large property - should pass */ - prop++; - prop->name = "large-property-PAGE_SIZEx8"; - prop->length = PAGE_SIZE * 8; - prop->value = kzalloc(prop->length, GFP_KERNEL); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop->value); - KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop), 0, + prop0->name = "large-property-PAGE_SIZEx8"; + prop0->length = PAGE_SIZE * 8; + prop0->value = kunit_kzalloc(test, prop0->length, GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, prop0->value); + + KUNIT_EXPECT_EQ_MSG(test, of_add_property(np, prop0), 0, "Adding a large property should have passed\n"); } -static int of_test_init(struct kunit *test) +static int of_test_dynamic_init(struct kunit *test) { - /* adding data for unittest */ + struct of_test_dynamic_context *ctx; + KUNIT_ASSERT_EQ(test, 0, unittest_data_add()); if (!of_aliases) @@ -197,18 +371,45 @@ static int of_test_init(struct kunit *test) KUNIT_ASSERT_NOT_ERR_OR_NULL(test, of_find_node_by_path( "/testcase-data/phandle-tests/consumer-a")); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); + test->priv = ctx; + + ctx->np = of_find_node_by_path("/testcase-data"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->np); + + ctx->prop0 = kunit_kzalloc(test, sizeof(*ctx->prop0), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->prop0); + + ctx->prop1 = kunit_kzalloc(test, sizeof(*ctx->prop1), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->prop1); + return 0; } -static struct kunit_case of_test_cases[] = { - KUNIT_CASE(of_unittest_find_node_by_name), - KUNIT_CASE(of_unittest_dynamic), +static void of_test_dynamic_exit(struct kunit *test) +{ + struct of_test_dynamic_context *ctx = test->priv; + struct device_node *np = ctx->np; + + of_remove_property(np, ctx->prop0); + of_remove_property(np, ctx->prop1); + of_node_put(np); +} + +static struct kunit_case of_test_dynamic_cases[] = { + KUNIT_CASE(of_test_dynamic_basic), + KUNIT_CASE(of_test_dynamic_add_existing_property), + KUNIT_CASE(of_test_dynamic_modify_existing_property), + KUNIT_CASE(of_test_dynamic_modify_non_existent_property), + KUNIT_CASE(of_test_dynamic_large_property), {}, }; -static struct kunit_module of_test_module = { - .name = "of-base-test", - .init = of_test_init, - .test_cases = of_test_cases, +static struct kunit_module of_test_dynamic_module = { + .name = "of-dynamic-test", + .init = of_test_dynamic_init, + .exit = of_test_dynamic_exit, + .test_cases = of_test_dynamic_cases, }; -module_test(of_test_module); +module_test(of_test_dynamic_module);