From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qt1-f202.google.com (mail-qt1-f202.google.com [209.85.160.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 36DAD2FD7CB for ; Fri, 15 Aug 2025 10:36:12 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254173; cv=none; b=ZyNhzbHSmOOSYU+7cGmQ9BPZQCnHGB/KnBwhszVTgj4ob4Em+bAvdLe3HXl6UJ+k58Kf5zEBW2IS+LV6UYdyla55BhNlS5WUTZlEb2D3eiRKK41XHPLYPq1aOD/dNiEwLaMdfryGZyZ9S41s5dzzMhJmclB1pFCF4wYBpVMfpYw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254173; c=relaxed/simple; bh=PXQaTPzfeZfmaVn+8SVNIYBwLVe02DdrsG9PDJmT+1o=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=gl1biz3WjXTIe5ereYS+QAdTi3/5PTNS6xD6xgTusf0oY4pFIMw1hb2YHeeJgUJ/QAXoPTwK1kdgnfIBV2k0Fj57kUORJyHXVZOx96ld8D4z+D3DvZ78FjUXRDhOabbXYr7sstD2Uiyq+q67HLrpFjSQNagvnp9jWBfNLwYc9qE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=yQXlADGI; arc=none smtp.client-ip=209.85.160.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="yQXlADGI" Received: by mail-qt1-f202.google.com with SMTP id d75a77b69052e-4b109c5457cso48071521cf.3 for ; Fri, 15 Aug 2025 03:36:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254171; x=1755858971; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=9cK185h9gxNmOTBKXZc10qbmIH62I7BV6bECtC8O9ek=; b=yQXlADGIZBWVHcOurm+jLTaWrRQr8hjvlpxHup6Rr1/1m+Hzkg3V0LRSvWx567rfZ/ iwWNlZwqrAW6NXzcyJh6Iek2A5nO53f4TH/w0UX/Ap2Dk8GNGqh68GP+gFnyEJm7UzWA rsd1bwAfwtLMuY1Jpus9Qjk22mj5eeyOJw8JoLGIXmu2uXMUyddQbA1fNxoE2/xE2VkX Rf7J7FApC6uK1+z+WtL6kaC+3FAWActotW0+m/yWhQ+U5/PoMo1g+YV6qaB6E6oK2ZK5 HEhqa+xEy5vlGb+9rUf0nFc0tEQ1Ud0biNkU7gJps+uWZiw5OBopim/FyOL6hNqrXyU3 beKw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254171; x=1755858971; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=9cK185h9gxNmOTBKXZc10qbmIH62I7BV6bECtC8O9ek=; b=iNHfwx8XJbxqW6FpttdbtDiDFv6PQG3hZgzH4XQTY+52BQhQCrSZxsoT95Hn4rnU3D ogzfVXHrKSr0SWNgmAdcKEtI5F1ukKvojzfz86DiKPH/c/iWNDiNtaGp9zpXMtX8ga96 TW3xEV62DzKC+NSrwN5ulJweJDjS45n2dqQn3uOSZE9uZNwp//zTwmI/qdHHbK7JQI40 5ivLoxUGUETBYV2Y4TcUzUnsb3xLp1Y8RL4cOvlio5FNSghv94/8I5iAFXUdD27Z3Dmi a3dXVQMMlN7NOPxIFjdFo8eU1wnqhU+n3tra3DjmKqS5/GFC+swGcq3CnfUiSFyXHh8M OfdQ== X-Forwarded-Encrypted: i=1; AJvYcCVvLAHWaLLpm7eXzGpnp5bf1OJPPnjFLv/urOXyuxX10g1l9skW1979M9M7u9uaJrl4h5NvZaGEmINZ6xI=@vger.kernel.org X-Gm-Message-State: AOJu0YzE3DrEHtb1A2g9zUfxR3gNYzP+KM6hxiK/WIFLIcWkpLk4yVqJ zqSJDL3+fNI1GjvU+dMvebh+h59Xc9mwU6pNzvm/B/XO6G6u9XB28A1mM4Sv8BFzcWnkm4gHi7N l9bVp8gTdLNc34g== X-Google-Smtp-Source: AGHT+IEaT0Jnn5or3jfzn5ggHOZAVAIlHTvGeOhQZuo5gK5kIbPKro1ACE25ujkZ3EehfX1NVXCYKKGDM6Qxbg== X-Received: from qtbih9.prod.google.com ([2002:a05:622a:6a89:b0:4b0:9663:7cc6]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:a05:622a:1b12:b0:4b0:616f:919b with SMTP id d75a77b69052e-4b11e21e941mr15083281cf.39.1755254171112; Fri, 15 Aug 2025 03:36:11 -0700 (PDT) Date: Fri, 15 Aug 2025 10:35:58 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-2-marievic@google.com> Subject: [PATCH v3 1/7] kunit: Add parent kunit for parameterized test context From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Currently, KUnit parameterized tests lack a mechanism to share resources across parameter runs because the same `struct kunit` instance is cleaned up and reused for each run. This patch introduces parameterized test context, enabling test users to share resources between parameter runs. It also allows setting up resources that need to be available for all parameter runs only once, which is helpful in cases where setup is expensive. To establish a parameterized test context, this patch adds a parent pointer field to `struct kunit`. This allows resources added to the parent `struct kunit` to be shared and accessible across all parameter runs. In kunit_run_tests(), the default `struct kunit` created is now designated to act as the parameterized test context whenever a test is parameterized. Subsequently, a new `struct kunit` is made for each parameter run, and its parent pointer is set to the `struct kunit` that holds the parameterized test context. Reviewed-by: David Gow Reviewed-by: Rae Moar Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-2-marievic@google.co= m/ - Commit message formatting. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-2-marievic@google.co= m/ - Descriptions of the parent pointer in `struct kunit` were changed to be more general, as it could be used to share resources not only between parameter runs but also between test cases in the future. - When printing parameter descriptions using test.param_index was changed to param_test.param_index. - kunit_cleanup(&test) in kunit_run_tests() was moved inside the parameterized test check. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- include/kunit/test.h | 8 ++++++-- lib/kunit/test.c | 34 ++++++++++++++++++++-------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/include/kunit/test.h b/include/kunit/test.h index 39c768f87dc9..b47b9a3102f3 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -268,14 +268,18 @@ struct kunit_suite_set { * * @priv: for user to store arbitrary data. Commonly used to pass data * created in the init function (see &struct kunit_suite). + * @parent: reference to the parent context of type struct kunit that can + * be used for storing shared resources. * * 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. + * indirectly via public functions; the two exceptions are @priv and @pare= nt + * which can be used by the test writer to store arbitrary data and access= the + * parent context, respectively. */ struct kunit { void *priv; + struct kunit *parent; =20 /* private: internal use only. */ const char *name; /* Read only after initialization! */ diff --git a/lib/kunit/test.c b/lib/kunit/test.c index f3c6b11f12b8..14a8bd846939 100644 --- a/lib/kunit/test.c +++ b/lib/kunit/test.c @@ -647,6 +647,7 @@ int kunit_run_tests(struct kunit_suite *suite) struct kunit_case *test_case; struct kunit_result_stats suite_stats =3D { 0 }; struct kunit_result_stats total_stats =3D { 0 }; + const void *curr_param; =20 /* Taint the kernel so we know we've run tests. */ add_taint(TAINT_TEST, LOCKDEP_STILL_OK); @@ -679,37 +680,42 @@ int kunit_run_tests(struct kunit_suite *suite) } else { /* Get initial param. */ param_desc[0] =3D '\0'; - test.param_value =3D test_case->generate_params(NULL, param_desc); + /* TODO: Make generate_params try-catch */ + curr_param =3D test_case->generate_params(NULL, param_desc); test_case->status =3D KUNIT_SKIPPED; kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT "KTAP version 1\n"); kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT "# Subtest: %s", test_case->name); =20 - while (test.param_value) { - kunit_run_case_catch_errors(suite, test_case, &test); + while (curr_param) { + struct kunit param_test =3D { + .param_value =3D curr_param, + .param_index =3D ++test.param_index, + .parent =3D &test, + }; + kunit_init_test(¶m_test, test_case->name, test_case->log); + kunit_run_case_catch_errors(suite, test_case, ¶m_test); =20 if (param_desc[0] =3D=3D '\0') { snprintf(param_desc, sizeof(param_desc), - "param-%d", test.param_index); + "param-%d", param_test.param_index); } =20 - kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE_PARAM, - test.status, - test.param_index + 1, + kunit_print_ok_not_ok(¶m_test, KUNIT_LEVEL_CASE_PARAM, + param_test.status, + param_test.param_index, param_desc, - test.status_comment); + param_test.status_comment); =20 - kunit_update_stats(¶m_stats, test.status); + kunit_update_stats(¶m_stats, param_test.status); =20 /* Get next param. */ param_desc[0] =3D '\0'; - test.param_value =3D test_case->generate_params(test.param_value, para= m_desc); - test.param_index++; - test.status =3D KUNIT_SUCCESS; - test.status_comment[0] =3D '\0'; - test.priv =3D NULL; + curr_param =3D test_case->generate_params(curr_param, param_desc); } + /* TODO: Put this kunit_cleanup into a try-catch. */ + kunit_cleanup(&test); } =20 kunit_print_attr((void *)test_case, true, KUNIT_LEVEL_CASE); --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qt1-f201.google.com (mail-qt1-f201.google.com [209.85.160.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CD9E32FB968 for ; Fri, 15 Aug 2025 10:36:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254176; cv=none; b=HH6FgMxmw31qgOB88Uk3BUJfjyXkjjgr7N79htHpbBGjLY4YBsfnJQYsCBb71PIS6KbVoQUH5Q81eQSZHwNrQOqTHvcQeU6KUtcDGbZagPi2/bCU4iZJ1AvLLkxWIVXAV+EVKF/7W6xeFCjAPnk3eLNhNFe2mcGzH93zHXirXWw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254176; c=relaxed/simple; bh=3lqLcAlnGNm9Cy16wVeQlJtJEhmkTlJXot2uNYK7MOQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=DVXLa5XH7576LJ+lAYV/JwD3+JghRQzyZ4nyxrjA4Zsionau/402BvMwsMyRvOXQCBgQSMvzVnBZDCv8yT4HiLyTcUF0/c9dxVMP3+pYcfRjHRxp6y8gkm9qomOJTFPKAoLyWA8Drveg+//XRADc+Q7OYr5XFWEc7SOf7b8IjlI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=a+l3p7+8; arc=none smtp.client-ip=209.85.160.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="a+l3p7+8" Received: by mail-qt1-f201.google.com with SMTP id d75a77b69052e-4b109c382aaso54348141cf.3 for ; Fri, 15 Aug 2025 03:36:14 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254174; x=1755858974; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=sAGiMmlsvvRAyIRtfIkliO7s5pzV7dahw9GOcGCzEKA=; b=a+l3p7+8rIyOIui7IfHgcyahzv8uM/BLyUAK8ieTaxnlpGzl39W8PZWeJHHdZJHjpZ 3Vjjtz/e81VeZXnSPhTlpZW/XIeI73Yj/ReJWJ0c2UwWUnybY/irKeexdkGOF5FHHoNb AgtnXUPXQx5QQWg36w84MpmqkDokIpTszIKsJ6754lxUFQPJ1yxX78txvgXhiWxfPvbE JXXWENzY1tiMu8eNj5HYbGdZi3yuQTYyBsyKEmaS6BsjPCaVFogD+HEPxvXym2aah5en RE9SxoVNl21u7iZH1teW+MmdZ6O68IPYvUet5jY0g/d3/GWDhhm0hLfTgrb5m5LhtSxt Sy6g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254174; x=1755858974; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=sAGiMmlsvvRAyIRtfIkliO7s5pzV7dahw9GOcGCzEKA=; b=sVMNv34bSz6lVgzNFWsh94F+FgfazUvsi9tYSNmw4q9zKRF9BeQajD8YNRDgq005yq DYfYmLje0w57GCJQ9YEiI6NFAS15czmwm+IYDahlFtMoLndBpWMGzpFerUV3b6zqqdfc /GYmpFbmhbJentlauE+Uyvb7QwOciz4GDbV24J79xTfxcJsUvF56DWkXQZdhZ0lCiq7Q J31cd87bNyGQBmWaq1CyW0uumMwiVkYmxTSyVpShP0MLIc7X9xhK15qOXauT0HDofRBj /ZXNBiM8IFzsnaNM6riFkJW2tPcasz7wrDSM7qmZYYFCMRpENrLkWyQchlQTf3hfzXM8 WV3A== X-Forwarded-Encrypted: i=1; AJvYcCUBPGNFGWBLR0pwGpNpTtGAFuiRa5qiRD/OisU9fqFm5jzIvefOqymm/hQPiSbxwxopAmV62okL2W6F3Fw=@vger.kernel.org X-Gm-Message-State: AOJu0YzNwl5Dmb9PXCNht2tZnJr+48weXmr/7K3mAU6ycFueECxvxjLM AMUjTHFz+S+m/drZEod0OPiTR+8mkkwy82lXL86Ks7nt/FtUuajawDjOgcrnrrMkmzyr1zwOzIE LvNdeJF2Gfd75Iw== X-Google-Smtp-Source: AGHT+IHSVv7xHpU+Q0K/EeYyGEApkzk4giTDGbZ8lKVWGiJHgmFp5Hi5KpmylCxkoZzIsi7d4UYcfQKbguUZug== X-Received: from qth25.prod.google.com ([2002:a05:622a:9019:b0:4af:205f:b347]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:a05:622a:19a7:b0:4b0:6f65:4622 with SMTP id d75a77b69052e-4b11e100b18mr13704771cf.2.1755254173610; Fri, 15 Aug 2025 03:36:13 -0700 (PDT) Date: Fri, 15 Aug 2025 10:35:59 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-3-marievic@google.com> Subject: [PATCH v3 2/7] kunit: Introduce param_init/exit for parameterized test context management From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add (*param_init) and (*param_exit) function pointers to `struct kunit_case`. Users will be able to set them via the new KUNIT_CASE_PARAM_WITH_INIT() macro. param_init/exit will be invoked by kunit_run_tests() once before and once after the parameterized test, respectively. They will receive the `struct kunit` that holds the parameterized test context; facilitating init and exit for shared state. This patch also sets param_init/exit to None in rust/kernel/kunit.rs. Reviewed-by: Rae Moar Signed-off-by: Marie Zhussupova Reviewed-by: David Gow --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-3-marievic@google.co= m/ - kunit_init_parent_param_test() now sets both the `struct kunit_case` and the `struct kunit` statuses as failed if the parameterized test init failed. The failure message was also changed to include the failure code, mirroring the kunit_suite init failure message. - A check for parameter init failure was added in kunit_run_tests(). So, if the init failed, the framework will skip the parameter runs and update the param_test statistics to count that failure. - Commit message formatting. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-3-marievic@google.co= m/ - param init/exit were set to None in rust/kernel/kunit.rs to fix the Rust breakage. - The name of __kunit_init_parent_test was changed to kunit_init_parent_param_test and its call was changed to happen only if the test is parameterized. - The param_exit call was also moved inside the check for if the test is parameterized. - KUNIT_CASE_PARAM_WITH_INIT() macro logic was change to not automatically set generate_params() to KUnit's built-in generator function. Instead, the test user will be asked to provide it themselves. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- include/kunit/test.h | 25 +++++++++++++++++++++++++ lib/kunit/test.c | 27 ++++++++++++++++++++++++++- rust/kernel/kunit.rs | 4 ++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/include/kunit/test.h b/include/kunit/test.h index b47b9a3102f3..d2e1b986b161 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -92,6 +92,8 @@ struct kunit_attributes { * @name: the name of the test case. * @generate_params: the generator function for parameterized tests. * @attr: the attributes associated with the test + * @param_init: The init function to run before a parameterized test. + * @param_exit: The exit function to run after a parameterized test. * * A test case is a function with the signature, * ``void (*)(struct kunit *)`` @@ -128,6 +130,8 @@ struct kunit_case { const char *name; const void* (*generate_params)(const void *prev, char *desc); struct kunit_attributes attr; + int (*param_init)(struct kunit *test); + void (*param_exit)(struct kunit *test); =20 /* private: internal use only. */ enum kunit_status status; @@ -218,6 +222,27 @@ static inline char *kunit_status_to_ok_not_ok(enum kun= it_status status) .generate_params =3D gen_params, \ .attr =3D attributes, .module_name =3D KBUILD_MODNAME} =20 +/** + * KUNIT_CASE_PARAM_WITH_INIT - Define a parameterized KUnit test case wit= h custom + * param_init() and param_exit() functions. + * @test_name: The function implementing the test case. + * @gen_params: The function to generate parameters for the test case. + * @init: A reference to the param_init() function to run before a paramet= erized test. + * @exit: A reference to the param_exit() function to run after a paramete= rized test. + * + * Provides the option to register param_init() and param_exit() functions. + * param_init/exit will be passed the parameterized test context and run o= nce + * before and once after the parameterized test. The init function can be = used + * to add resources to share between parameter runs, and any other setup l= ogic. + * The exit function can be used to clean up resources that were not manag= ed by + * the parameterized test, and any other teardown logic. + */ +#define KUNIT_CASE_PARAM_WITH_INIT(test_name, gen_params, init, exit) \ + { .run_case =3D test_name, .name =3D #test_name, \ + .generate_params =3D gen_params, \ + .param_init =3D init, .param_exit =3D exit, \ + .module_name =3D KBUILD_MODNAME} + /** * struct kunit_suite - describes a related collection of &struct kunit_ca= se * diff --git a/lib/kunit/test.c b/lib/kunit/test.c index 14a8bd846939..917df2e1688d 100644 --- a/lib/kunit/test.c +++ b/lib/kunit/test.c @@ -641,6 +641,20 @@ static void kunit_accumulate_stats(struct kunit_result= _stats *total, total->total +=3D add.total; } =20 +static void kunit_init_parent_param_test(struct kunit_case *test_case, str= uct kunit *test) +{ + if (test_case->param_init) { + int err =3D test_case->param_init(test); + + if (err) { + kunit_err(test_case, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT + "# failed to initialize parent parameter test (%d)", err); + test->status =3D KUNIT_FAILURE; + test_case->status =3D KUNIT_FAILURE; + } + } +} + int kunit_run_tests(struct kunit_suite *suite) { char param_desc[KUNIT_PARAM_DESC_SIZE]; @@ -678,6 +692,11 @@ int kunit_run_tests(struct kunit_suite *suite) kunit_run_case_catch_errors(suite, test_case, &test); kunit_update_stats(¶m_stats, test.status); } else { + kunit_init_parent_param_test(test_case, &test); + if (test_case->status =3D=3D KUNIT_FAILURE) { + kunit_update_stats(¶m_stats, test.status); + goto test_case_end; + } /* Get initial param. */ param_desc[0] =3D '\0'; /* TODO: Make generate_params try-catch */ @@ -714,10 +733,16 @@ int kunit_run_tests(struct kunit_suite *suite) param_desc[0] =3D '\0'; curr_param =3D test_case->generate_params(curr_param, param_desc); } + /* + * TODO: Put into a try catch. Since we don't need suite->exit + * for it we can't reuse kunit_try_run_cleanup for this yet. + */ + if (test_case->param_exit) + test_case->param_exit(&test); /* TODO: Put this kunit_cleanup into a try-catch. */ kunit_cleanup(&test); } - +test_case_end: kunit_print_attr((void *)test_case, true, KUNIT_LEVEL_CASE); =20 kunit_print_test_stats(&test, param_stats); diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 4b8cdcb21e77..cda64574b44d 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -207,6 +207,8 @@ pub const fn kunit_case( status: kernel::bindings::kunit_status_KUNIT_SUCCESS, module_name: core::ptr::null_mut(), log: core::ptr::null_mut(), + param_init: None, + param_exit: None, } } =20 @@ -226,6 +228,8 @@ pub const fn kunit_case_null() -> kernel::bindings::kun= it_case { status: kernel::bindings::kunit_status_KUNIT_SUCCESS, module_name: core::ptr::null_mut(), log: core::ptr::null_mut(), + param_init: None, + param_exit: None, } } =20 --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qt1-f201.google.com (mail-qt1-f201.google.com [209.85.160.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0CC9B2FFDF0 for ; Fri, 15 Aug 2025 10:36:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254178; cv=none; b=sp3z3NaODgBNLWxXyU0bdmOUeKhbbQZxLUmQaCo3JwX82NgVMi7UPYu2ZTJJX6r3GzBkLvmN41LiRCOdbnZJmSAP1/5dCks6ahMAVei61zki3C8RE2BfARVJBtt4aQT0LfZCQo2pqxhC/mXV9TBH5OEtUgGx8Vau5gMj+bvMwrA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254178; c=relaxed/simple; bh=WzKOwOZ/Egx5fUkYaQAlnWSmFemcKYO4P0JLz87ddqU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=LCe3zCZyrdYm4rQQbT2MNbsJJcFfAjtjdYniRLJmb7APFQJ6uE5ddr6dHV/e/oTTarqdW6ONqisYPkiymbgaclWVcoj/xxscwTvSEw+slC4AkMnd1r2J8HL0KWKHnjKj5UGoBdcn5FhGnIqdNTkrLVNI4uWPjq5mJNwQwnz24L8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=4Ez2DVcu; arc=none smtp.client-ip=209.85.160.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="4Ez2DVcu" Received: by mail-qt1-f201.google.com with SMTP id d75a77b69052e-4b109c7ad98so66618051cf.3 for ; Fri, 15 Aug 2025 03:36:16 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254176; x=1755858976; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=BONUnu1NKFOsWRPuaKEG6QiZAgg+IitETz5ddIXNoOc=; b=4Ez2DVcuEWrpsowGNCWBVt9dRxfLT62JSIVYnlhNQjBTdOZBISyTZeqDTXJHg+1c4S uR8c7yoZ1915bCNdGRswr7ztbq1lEfnUpHvYDBNAITFFKhVCBLpL5mQO1TgV6tZCYjjD Tjs1aL+0JK/eQNtWKkSCCD5pl3iZa1DIj7Itvv7XzRYSOTmbTB7kreVL+jhuStGlM4No G5LaRKN5kz2Jebma7dW/SDQxEG8def2Pd3ZDdJ3c3q9IySrO3EWVjzBT7xyVuvCyjcrF Gd1ohlkEfxv1QWVeBxcA+XZsGN59p8aImaAaIcBs5yVDVO/lZXmMZL98CDI93NdZ+XlC dttA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254176; x=1755858976; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=BONUnu1NKFOsWRPuaKEG6QiZAgg+IitETz5ddIXNoOc=; b=NTGGSHpKccBbE9sqlACQPRiyIjr2v9d9yMXUWiRQIqm3MFae6ajmqisCUcY8ndRmGp 9r9C9uFCML43h3NmXmfRPILY4cn6M9htN5a46YrxHqlReTAdLBBy+nmoGn+RdrsJUt5G mitSIxCmXk0JEV6NfTUVk3T2zHTk2iUXYAOXcs61r2Ct2e6y7yw3d30fOnJptauHd4AX O1ICYwiSB1bff+Rbb1WQUySNK5wL9s9nb4Npw3o5FzvNNYlvKsuCD5R+NcsJRkpw1Um/ dEjMCnVtTknxD3X6fkAQy6vkgULERpdA6lQJj2gAdTa1oWE8aDnRJGshUnDKC+fn5Jec c+Lw== X-Forwarded-Encrypted: i=1; AJvYcCVstK3ZyVvDGjM08sBIXJ4YHNA/W67IDqaMMVu502fRB6Jtm2bdJ7iMm2tYMbQJmTeAze79aXIs2T5U8/M=@vger.kernel.org X-Gm-Message-State: AOJu0YxyQbiHg1DasNB6MvrSLKYupuNx160MU+JEYfquKh+v07zQpesq gPS6rEjFN8LB70HrxjpkEwocDZC+OoVEdX0XFs3AkchYTT3qjj6Ba0XB7IUcitwVzgNhm7TJgQf 4XHFKjvHC/LA8LA== X-Google-Smtp-Source: AGHT+IEcA9mV3vSJ0s1QyQh2RxJ/dCmFXZLqK+CHWderFPKfVsCVEdy6IgdXgjKdrlUhFX5Rm47QMzQ9n3WdHQ== X-Received: from qtbih3.prod.google.com ([2002:a05:622a:6a83:b0:4ae:75d2:c21]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:ac8:590a:0:b0:4b0:8057:1de9 with SMTP id d75a77b69052e-4b11e125b21mr15990631cf.3.1755254175914; Fri, 15 Aug 2025 03:36:15 -0700 (PDT) Date: Fri, 15 Aug 2025 10:36:00 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-4-marievic@google.com> Subject: [PATCH v3 3/7] kunit: Pass parameterized test context to generate_params() From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" To enable more complex parameterized testing scenarios, the generate_params() function needs additional context beyond just the previously generated parameter. This patch modifies the generate_params() function signature to include an extra `struct kunit *test` argument, giving test users access to the parameterized test context when generating parameters. The `struct kunit *test` argument was added as the first parameter to the function signature as it aligns with the convention of other KUnit functions that accept `struct kunit *test` first. This also mirrors the "this" or "self" reference found in object-oriented programming languages. This patch also modifies xe_pci_live_device_gen_param() in xe_pci.c and nthreads_gen_params() in kcsan_test.c to reflect this signature change. Reviewed-by: David Gow Reviewed-by: Rae Moar Acked-by: Marco Elver Acked-by: Rodrigo Vivi Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-4-marievic@google.co= m/ - Commit message formatting. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-4-marievic@google.co= m/ https://lore.kernel.org/all/20250729193647.3410634-5-marievic@google.co= m/ https://lore.kernel.org/all/20250729193647.3410634-6-marievic@google.co= m/ - generate_params signature changes in xe_pci.c and kcsan_test.c were squashed into a single patch to avoid in-between breakages in the series. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- drivers/gpu/drm/xe/tests/xe_pci.c | 2 +- include/kunit/test.h | 9 ++++++--- kernel/kcsan/kcsan_test.c | 2 +- lib/kunit/test.c | 5 +++-- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/xe/tests/xe_pci.c b/drivers/gpu/drm/xe/tests/x= e_pci.c index 1d3e2e50c355..62c016e84227 100644 --- a/drivers/gpu/drm/xe/tests/xe_pci.c +++ b/drivers/gpu/drm/xe/tests/xe_pci.c @@ -129,7 +129,7 @@ EXPORT_SYMBOL_IF_KUNIT(xe_pci_fake_device_init); * Return: pointer to the next &struct xe_device ready to be used as a par= ameter * or NULL if there are no more Xe devices on the system. */ -const void *xe_pci_live_device_gen_param(const void *prev, char *desc) +const void *xe_pci_live_device_gen_param(struct kunit *test, const void *p= rev, char *desc) { const struct xe_device *xe =3D prev; struct device *dev =3D xe ? xe->drm.dev : NULL; diff --git a/include/kunit/test.h b/include/kunit/test.h index d2e1b986b161..b527189d2d1c 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -128,7 +128,8 @@ struct kunit_attributes { struct kunit_case { void (*run_case)(struct kunit *test); const char *name; - const void* (*generate_params)(const void *prev, char *desc); + const void* (*generate_params)(struct kunit *test, + const void *prev, char *desc); struct kunit_attributes attr; int (*param_init)(struct kunit *test); void (*param_exit)(struct kunit *test); @@ -1691,7 +1692,8 @@ do { \ * Define function @name_gen_params which uses @array to generate paramete= rs. */ #define KUNIT_ARRAY_PARAM(name, array, get_desc) \ - static const void *name##_gen_params(const void *prev, char *desc) \ + static const void *name##_gen_params(struct kunit *test, \ + const void *prev, char *desc) \ { \ typeof((array)[0]) *__next =3D prev ? ((typeof(__next)) prev) + 1 : (arr= ay); \ if (__next - (array) < ARRAY_SIZE((array))) { \ @@ -1712,7 +1714,8 @@ do { \ * Define function @name_gen_params which uses @array to generate paramete= rs. */ #define KUNIT_ARRAY_PARAM_DESC(name, array, desc_member) \ - static const void *name##_gen_params(const void *prev, char *desc) \ + static const void *name##_gen_params(struct kunit *test, \ + const void *prev, char *desc) \ { \ typeof((array)[0]) *__next =3D prev ? ((typeof(__next)) prev) + 1 : (arr= ay); \ if (__next - (array) < ARRAY_SIZE((array))) { \ diff --git a/kernel/kcsan/kcsan_test.c b/kernel/kcsan/kcsan_test.c index c2871180edcc..fc76648525ac 100644 --- a/kernel/kcsan/kcsan_test.c +++ b/kernel/kcsan/kcsan_test.c @@ -1383,7 +1383,7 @@ static void test_atomic_builtins_missing_barrier(stru= ct kunit *test) * The thread counts are chosen to cover potentially interesting boundarie= s and * corner cases (2 to 5), and then stress the system with larger counts. */ -static const void *nthreads_gen_params(const void *prev, char *desc) +static const void *nthreads_gen_params(struct kunit *test, const void *pre= v, char *desc) { long nthreads =3D (long)prev; =20 diff --git a/lib/kunit/test.c b/lib/kunit/test.c index 917df2e1688d..ac8fa8941a6a 100644 --- a/lib/kunit/test.c +++ b/lib/kunit/test.c @@ -700,7 +700,7 @@ int kunit_run_tests(struct kunit_suite *suite) /* Get initial param. */ param_desc[0] =3D '\0'; /* TODO: Make generate_params try-catch */ - curr_param =3D test_case->generate_params(NULL, param_desc); + curr_param =3D test_case->generate_params(&test, NULL, param_desc); test_case->status =3D KUNIT_SKIPPED; kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT "KTAP version 1\n"); @@ -731,7 +731,8 @@ int kunit_run_tests(struct kunit_suite *suite) =20 /* Get next param. */ param_desc[0] =3D '\0'; - curr_param =3D test_case->generate_params(curr_param, param_desc); + curr_param =3D test_case->generate_params(&test, curr_param, + param_desc); } /* * TODO: Put into a try catch. Since we don't need suite->exit --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-vs1-f74.google.com (mail-vs1-f74.google.com [209.85.217.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 478C43002B7 for ; Fri, 15 Aug 2025 10:36:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.217.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254181; cv=none; b=nfyHGFd8ljZ8z77zUHL0WGERUQeDZ3MQ3b9gEfeBvzxXKodLhKm7YuiI4Gc2nIarFwu6Z/Cy2ASDYQC153Wy9dH7BmMneM/efNHUVuwVFuLW4y740caO6fbafyA9uJdkEVbR/+2wdpRQL99pfP8IIYnEYUKHwGLRIV6KqXVzIdA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254181; c=relaxed/simple; bh=JgV5MD2yabq4D6asDj0fi2EiUnADMV9HImtsW8SGMGs=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=j7t/AH+UDaKIyQr2we2F0MCFEOP+NA5xUrP3Jy4UXBJu3KOrfg482VRT4un39bvPYDlNfslKgWIsdxB+DI4lttOK13/WtB0xuHm5M34TTqOuUaoDIg0tQQcY+XZMnhM9Lbz9TqzqeT3x8VGZdKD5z0nW/42Ugdom15dA2xuf/EA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=vM/oqIEP; arc=none smtp.client-ip=209.85.217.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="vM/oqIEP" Received: by mail-vs1-f74.google.com with SMTP id ada2fe7eead31-50f85ea631bso3288637137.0 for ; Fri, 15 Aug 2025 03:36:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254178; x=1755858978; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=EbtD+Xjrb63N9PWKLbZO8o0el647SMdtXD5thCMFX0c=; b=vM/oqIEPaTjj6TkkZ7bQarOIJhUlUuNFwdTdnpFBHaDrxUmlz7fABisEJuGL7iUJP0 C1C+1GfctmxGGsOB77ounvybHNChit/GU0Tk4RIAnL0wLuDh86yF+wvejmZTXjuvf9oP UExOxRXwRUT+HwFdv6MfWDaooKxVzm4z+QJvMlUZNgFnPYtnbb/CsEQvK14kkWK1P98q 7QVrT7Aw0J3PBZaPa+x1eKrBG+siBZOgTvbMwbkEz13o7K6zSmLuVYCt3gaflaHq41w+ FvwXf0OCXpcmh1W4wnDmWa864+E7rShdaZSTbvxuibUGrvtOPyhZ8ZveiMLmv2NzMFTD J3sw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254178; x=1755858978; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=EbtD+Xjrb63N9PWKLbZO8o0el647SMdtXD5thCMFX0c=; b=dPEw9gss9ya7oB8ym4zFUUeBn03dNx1G67m00uVnbab5IOLzTqEjAaG8q6YDZ1JXho 516vFheKH+MLP8GntgeO5CaB3iha2Sui0/D9mbVyJ3jz8BR1TYHdCxijZYK6wY2Ou/b0 OAKvrey/Fk7ujodyE9etV5qLyO3K0O8IV/mAfkhqKMqSd6v6T3dkr3KJBLSqLADsRetp H9BN/0HlEgsGiqXOPvZlEGBiwtje6pPSJSFelmFmc7KvY86VRQMA5fkSssEQkgCFf6fT rSzW9gTh0xgmxJOouSXcbKF18bEYhPFzShe9eGMrniekdlkzGg9N4BhvLsdJadOyqcih v9Mw== X-Forwarded-Encrypted: i=1; AJvYcCVwLdWgmOcBJM4NKYWxINwqL2wbwYpN/EOMoYTlOGtdzVmOetJE8hHoPduDFSGvIep9nUHv7ZLm3iL6PDk=@vger.kernel.org X-Gm-Message-State: AOJu0Yw2q9QrmOXUMJP0Gesupz9IlQzimy4Zf21ptQxjpEpjEuTZkv+v 0O+NV6ys7H59iUZzhJutk/bB/EyyqTGJMBrnsrwwVgwqUdbIJtCxs4/ND8NH+K8Q+1txiE0UPtu 8GyyGvPidTTVH6Q== X-Google-Smtp-Source: AGHT+IHZIGI9cChSQ6YXS3ZOKII47oT6XYVnPvPtuMz5HTh9l2QXTiLwtNtgFQGsGTPjcNZzVesvUe6veRlW7A== X-Received: from vsp19-n2.prod.google.com ([2002:a05:6102:40d3:20b0:512:29bc:e5ed]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6102:6cc:b0:4e5:f673:7da4 with SMTP id ada2fe7eead31-5126b10f139mr343801137.8.1755254178131; Fri, 15 Aug 2025 03:36:18 -0700 (PDT) Date: Fri, 15 Aug 2025 10:36:01 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-5-marievic@google.com> Subject: [PATCH v3 4/7] kunit: Enable direct registration of parameter arrays to a KUnit test From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" KUnit parameterized tests currently support two primary methods f or getting parameters: 1. Defining custom logic within a generate_params() function. 2. Using the KUNIT_ARRAY_PARAM() and KUNIT_ARRAY_PARAM_DESC() macros with a pre-defined static array and passing the created *_gen_params() to KUNIT_CASE_PARAM(). These methods present limitations when dealing with dynamically generated parameter arrays, or in scenarios where populating parameters sequentially via generate_params() is inefficient or overly complex. This patch addresses these limitations by adding a new `params_array` field to `struct kunit`, of the type `kunit_params`. The `struct kunit_params` is designed to store the parameter array itself, along with essential metadata including the parameter count, parameter size, and a get_description() function for providing custom descriptions for individual parameters. The `params_array` field can be populated by calling the new kunit_register_params_array() macro from within a param_init() function. This will register the array as part of the parameterized test context. The user will then need to pass kunit_array_gen_params() to the KUNIT_CASE_PARAM_WITH_INIT() macro as the generator function, if not providing their own. kunit_array_gen_params() is a KUnit helper that will use the registered array to generate parameters. The arrays passed to KUNIT_ARRAY_PARAM(,DESC) will also be registered to the parameterized test context for consistency as well as for higher availability of the parameter count that will be used for outputting a KTAP test plan for a parameterized test. This modification provides greater flexibility to the KUnit framework, allowing testers to easily register and utilize both dynamic and static parameter arrays. Reviewed-by: David Gow Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-5-marievic@google.co= m/ - Commit message formatting. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-7-marievic@google.co= m/ - If the parameter count is available for a parameterized test, the kunit_run_tests() function will now output the KTAP test plan for it. - The name of the struct kunit_params field in struct kunit was changed from params_data to params_array. This name change better reflects its purpose, which is to encapsulate both the parameter array and its associated metadata. - The name of `kunit_get_next_param_and_desc` was changed to `kunit_array_gen_params` to make it simpler and to better fit its purpose of being KUnit's built-in generator function that uses arrays to generate parameters. - The signature of get_description() in `struct params_array` was changed to accept the parameterized test context, as well. This way test users can potentially use information available in the parameterized test context, such as the parameterized test name for setting the parameter description= s. - The type of `num_params` in `struct params_array` was changed from int to size_t for better handling of the array size. - The name of __kunit_init_params() was changed to be kunit_init_params(). Logic that sets the get_description() function pointer to NULL was also added in there. - `kunit_array_gen_params` is now exported to make it available to use with modules. - Instead of allowing NULL to be passed in as the parameter generator function in the KUNIT_CASE_PARAM_WITH_INIT macro, users will now be asked to provide `kunit_array_gen_params` as the generator function. This will ensure that a parameterized test remains defined by the existence of a parameter generation function. - KUNIT_ARRAY_PARAM(,DESC) will now additionally register the passed in arr= ay in struct kunit_params. This will make things more consistent i.e. if a parameter array is available then the struct kunit_params field in parent struct kunit is populated. Additionally, this will increase the availability of the KTAP test plan. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- include/kunit/test.h | 65 ++++++++++++++++++++++++++++++++++++++++---- lib/kunit/test.c | 30 ++++++++++++++++++++ 2 files changed, 89 insertions(+), 6 deletions(-) diff --git a/include/kunit/test.h b/include/kunit/test.h index b527189d2d1c..8cc9614a88d5 100644 --- a/include/kunit/test.h +++ b/include/kunit/test.h @@ -234,9 +234,13 @@ static inline char *kunit_status_to_ok_not_ok(enum kun= it_status status) * Provides the option to register param_init() and param_exit() functions. * param_init/exit will be passed the parameterized test context and run o= nce * before and once after the parameterized test. The init function can be = used - * to add resources to share between parameter runs, and any other setup l= ogic. - * The exit function can be used to clean up resources that were not manag= ed by - * the parameterized test, and any other teardown logic. + * to add resources to share between parameter runs, pass parameter arrays, + * and any other setup logic. The exit function can be used to clean up re= sources + * that were not managed by the parameterized test, and any other teardown= logic. + * + * Note: If you are registering a parameter array in param_init() with + * kunit_register_param_array() then you need to pass kunit_array_gen_para= ms() + * to this as the generator function. */ #define KUNIT_CASE_PARAM_WITH_INIT(test_name, gen_params, init, exit) \ { .run_case =3D test_name, .name =3D #test_name, \ @@ -289,6 +293,20 @@ struct kunit_suite_set { struct kunit_suite * const *end; }; =20 +/* Stores the pointer to the parameter array and its metadata. */ +struct kunit_params { + /* + * Reference to the parameter array for a parameterized test. This + * is NULL if a parameter array wasn't directly passed to the + * parameterized test context struct kunit via kunit_register_params_arra= y(). + */ + const void *params; + /* Reference to a function that gets the description of a parameter. */ + void (*get_description)(struct kunit *test, const void *param, char *desc= ); + size_t num_params; + size_t elem_size; +}; + /** * struct kunit - represents a running instance of a test. * @@ -296,16 +314,18 @@ struct kunit_suite_set { * created in the init function (see &struct kunit_suite). * @parent: reference to the parent context of type struct kunit that can * be used for storing shared resources. + * @params_array: for storing the parameter array. * * 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 two exceptions are @priv and @pare= nt - * which can be used by the test writer to store arbitrary data and access= the - * parent context, respectively. + * indirectly via public functions; the exceptions are @priv, @parent and + * @params_array which can be used by the test writer to store arbitrary d= ata, + * access the parent context, and to store the parameter array, respective= ly. */ struct kunit { void *priv; struct kunit *parent; + struct kunit_params params_array; =20 /* private: internal use only. */ const char *name; /* Read only after initialization! */ @@ -376,6 +396,8 @@ void kunit_exec_list_tests(struct kunit_suite_set *suit= e_set, bool include_attr) struct kunit_suite_set kunit_merge_suite_sets(struct kunit_suite_set init_= suite_set, struct kunit_suite_set suite_set); =20 +const void *kunit_array_gen_params(struct kunit *test, const void *prev, c= har *desc); + #if IS_BUILTIN(CONFIG_KUNIT) int kunit_run_all_tests(void); #else @@ -1696,6 +1718,8 @@ do { \ const void *prev, char *desc) \ { \ typeof((array)[0]) *__next =3D prev ? ((typeof(__next)) prev) + 1 : (arr= ay); \ + if (!prev) \ + kunit_register_params_array(test, array, ARRAY_SIZE(array), NULL); \ if (__next - (array) < ARRAY_SIZE((array))) { \ void (*__get_desc)(typeof(__next), char *) =3D get_desc; \ if (__get_desc) \ @@ -1718,6 +1742,8 @@ do { \ const void *prev, char *desc) \ { \ typeof((array)[0]) *__next =3D prev ? ((typeof(__next)) prev) + 1 : (arr= ay); \ + if (!prev) \ + kunit_register_params_array(test, array, ARRAY_SIZE(array), NULL); \ if (__next - (array) < ARRAY_SIZE((array))) { \ strscpy(desc, __next->desc_member, KUNIT_PARAM_DESC_SIZE); \ return __next; \ @@ -1725,6 +1751,33 @@ do { \ return NULL; \ } =20 +/** + * kunit_register_params_array() - Register parameter array for a KUnit te= st. + * @test: The KUnit test structure to which parameters will be added. + * @array: An array of test parameters. + * @param_count: Number of parameters. + * @get_desc: Function that generates a string description for a given par= ameter + * element. + * + * This macro initializes the @test's parameter array data, storing inform= ation + * including the parameter array, its count, the element size, and the par= ameter + * description function within `test->params_array`. + * + * Note: If using this macro in param_init(), kunit_array_gen_params() + * will then need to be manually provided as the parameter generator funct= ion to + * KUNIT_CASE_PARAM_WITH_INIT(). kunit_array_gen_params() is a KUnit + * function that uses the registered array to generate parameters + */ +#define kunit_register_params_array(test, array, param_count, get_desc) = \ + do { \ + struct kunit *_test =3D (test); \ + const typeof((array)[0]) * _params_ptr =3D &(array)[0]; \ + _test->params_array.params =3D _params_ptr; \ + _test->params_array.num_params =3D (param_count); \ + _test->params_array.elem_size =3D sizeof(*_params_ptr); \ + _test->params_array.get_description =3D (get_desc); \ + } while (0) + // TODO(dlatypov@google.com): consider eventually migrating users to expli= citly // include resource.h themselves if they need it. #include diff --git a/lib/kunit/test.c b/lib/kunit/test.c index ac8fa8941a6a..ce4bb93f09f4 100644 --- a/lib/kunit/test.c +++ b/lib/kunit/test.c @@ -337,6 +337,14 @@ void __kunit_do_failed_assertion(struct kunit *test, } EXPORT_SYMBOL_GPL(__kunit_do_failed_assertion); =20 +static void kunit_init_params(struct kunit *test) +{ + test->params_array.params =3D NULL; + test->params_array.get_description =3D NULL; + test->params_array.num_params =3D 0; + test->params_array.elem_size =3D 0; +} + void kunit_init_test(struct kunit *test, const char *name, struct string_s= tream *log) { spin_lock_init(&test->lock); @@ -347,6 +355,7 @@ void kunit_init_test(struct kunit *test, const char *na= me, struct string_stream string_stream_clear(log); test->status =3D KUNIT_SUCCESS; test->status_comment[0] =3D '\0'; + kunit_init_params(test); } EXPORT_SYMBOL_GPL(kunit_init_test); =20 @@ -641,6 +650,23 @@ static void kunit_accumulate_stats(struct kunit_result= _stats *total, total->total +=3D add.total; } =20 +const void *kunit_array_gen_params(struct kunit *test, const void *prev, c= har *desc) +{ + struct kunit_params *params_arr =3D &test->params_array; + const void *param; + + if (test->param_index < params_arr->num_params) { + param =3D (char *)params_arr->params + + test->param_index * params_arr->elem_size; + + if (params_arr->get_description) + params_arr->get_description(test, param, desc); + return param; + } + return NULL; +} +EXPORT_SYMBOL_GPL(kunit_array_gen_params); + static void kunit_init_parent_param_test(struct kunit_case *test_case, str= uct kunit *test) { if (test_case->param_init) { @@ -706,6 +732,10 @@ int kunit_run_tests(struct kunit_suite *suite) "KTAP version 1\n"); kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT "# Subtest: %s", test_case->name); + if (test.params_array.params) + kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT + KUNIT_SUBTEST_INDENT "1..%zd\n", + test.params_array.num_params); =20 while (curr_param) { struct kunit param_test =3D { --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qv1-f74.google.com (mail-qv1-f74.google.com [209.85.219.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7A7012FF17A for ; Fri, 15 Aug 2025 10:36:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254184; cv=none; b=uliEWllaJgo3ubcGKq2H95mTrOThdz3tAejYCcgpL1F2zyMCUjJbbqhRWq1ITegvc1qt0u4stAOTPEFNGvjO4uUgzi6Hjl56Q703EpmToUIseW323pR+vpirOTJEW4zQ9wVVcWickFQa9jnnLmfA2vraop6C7F8A0XDQgSaqOtQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254184; c=relaxed/simple; bh=rk+rv+DubkiOdslbaKlZTWR/6LAnBWqdq0f9LEpQipU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Lhr0pupQnNjprqrfRGlWwyjCaE/e7i+8C9rc86g8Lic0zjH2NGgRM2Zqxm4kUunOOgwhOiJCTdyKzcHZkbvH9hKRdECiYGg1AlDWyynSdFjH01mljICxcA172OJIm6u/tiRqmx0Ys2kdzjdWZq8aw3FACkcBZrEsSW/Gci8nhB4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=QK22E6bD; arc=none smtp.client-ip=209.85.219.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="QK22E6bD" Received: by mail-qv1-f74.google.com with SMTP id 6a1803df08f44-70a9f636685so56948316d6.3 for ; Fri, 15 Aug 2025 03:36:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254181; x=1755858981; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=RNyqlzYzn7jh+8CRt3OEjX2dauCV97Pxa7UQdJrgoqo=; b=QK22E6bD9dWS3MUFM1hkEvXeczPuyvsjYUPVMlVFPCAlLPEVgt+oteLFHvu22feJ+S YBaJfcPhz4wp8in4dS1LEsn0dU1luWGYtZvxw4DKbgyTtzjhSJXxGpXF1I/+hXVugQ1B wFnc+4VTHRng91N9y6bkIZA4cOCk+Oqoot89cyM+FeSg3jMIyaTpxzo1e7sGg6Rgm0Z0 qI2Qk51OKN7EieHlbuI0Vpdfm91ggTtkxAs7gmsINqW9RrTlG5UejcVFwFL+yHsjmUNb p0m/TNTEaZeJN4F7croBw3+/Z9AbefFWeq2m2pV9nfTRiGal3jfgZTH1e+SifDi1Ncx9 yGwA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254181; x=1755858981; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=RNyqlzYzn7jh+8CRt3OEjX2dauCV97Pxa7UQdJrgoqo=; b=IH1z6j/75PwFXtw1cWw4JAbiRnXWnL7ZEAsj3AUtcvOu4ZlE5ke6/EXZg8SQ95Wfcr RSXCUkML9BZ7lIugw4slcfUNoBkYsVEpucspNvgbaBjPEfsK4So0062J5mWK3A6AMgda 0rdhuG87JJDvfLA1R3WratQT0C7CjQ7Yjq1ZrUo9T7BCrwozqKaYIod1nupyxUAqmCO+ uEbhG7uonZIbQHm8dsBVPpm8Mlk903FtY/b4Ud6x6KLNnlNYFwFcF8GCuXQZgGISQ55w 79e4KtHUdu3PY5HlgFQAV2XstjG7O5CgFdTHoOEJthvqsQYp3I0xU8viRjjvw32vDL5a +AuA== X-Forwarded-Encrypted: i=1; AJvYcCUiK4158cUgSnXadXAEHZuU4ewIgumfQUpynSG8gFavYe/Im0SiEuPe4u4rZyGKOZ3aqRfOMGy76Wlzle8=@vger.kernel.org X-Gm-Message-State: AOJu0Ywk57OWhVaEU4HIZh3AqDm720/F6MZeQSY2JaI6VtEZ+/k3Kmhs JxQOdExekGvimVZC6exV8/sSuSZ/fNCH27RScKbHpcSoYgJQWxm2DtapGE3xBJCQCZmOeWw4fOx /U2POwK2n0ZkhCw== X-Google-Smtp-Source: AGHT+IE4pytpja7qv/dmXwoEtBCdtldEAT6l81LHSN6OYwd1hu8zWD0dEYjSqzYdvp2zQ1dRCnAG8StquQ7H/Q== X-Received: from qvbqh9.prod.google.com ([2002:a05:6214:4c09:b0:709:2a7e:b05]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6214:27ef:b0:707:6977:aa77 with SMTP id 6a1803df08f44-70ba7c1d3bfmr12153106d6.33.1755254181483; Fri, 15 Aug 2025 03:36:21 -0700 (PDT) Date: Fri, 15 Aug 2025 10:36:02 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-6-marievic@google.com> Subject: [PATCH v3 5/7] kunit: Add example parameterized test with shared resource management using the Resource API From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add example_params_test_with_init() to illustrate how to manage shared resources across a parameterized KUnit test. This example showcases the use of the new param_init() function and its registration to a test using the KUNIT_CASE_PARAM_WITH_INIT() macro. Additionally, the test demonstrates how to directly pass a parameter array to the parameterized test context via kunit_register_params_array() and leveraging the Resource API for shared resource management. Reviewed-by: Rae Moar Reviewed-by: David Gow Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-6-marievic@google.co= m/ - Code comment edits. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-8-marievic@google.co= m/ - kunit_array_gen_params() is now explicitly passed to KUNIT_CASE_PARAM_WITH_INIT() to be consistent with a parameterized test being defined by the existence of the generate_params() function. - The comments were edited to be more concise. - The patch header was changed to reflect that this example test's intent is more aligned with showcasing using the Resource API for shared resource management. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- lib/kunit/kunit-example-test.c | 113 +++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/lib/kunit/kunit-example-test.c b/lib/kunit/kunit-example-test.c index 3056d6bc705d..3e858367be01 100644 --- a/lib/kunit/kunit-example-test.c +++ b/lib/kunit/kunit-example-test.c @@ -277,6 +277,117 @@ static void example_slow_test(struct kunit *test) KUNIT_EXPECT_EQ(test, 1 + 1, 2); } =20 +/* + * This custom function allocates memory and sets the information we want + * stored in the kunit_resource->data field. + */ +static int example_resource_init(struct kunit_resource *res, void *context) +{ + int *info =3D kmalloc(sizeof(*info), GFP_KERNEL); + + if (!info) + return -ENOMEM; + *info =3D *(int *)context; + res->data =3D info; + return 0; +} + +/* + * This function deallocates memory for the kunit_resource->data field. + */ +static void example_resource_free(struct kunit_resource *res) +{ + kfree(res->data); +} + +/* + * This match function is invoked by kunit_find_resource() to locate + * a test resource based on certain criteria. + */ +static bool example_resource_alloc_match(struct kunit *test, + struct kunit_resource *res, + void *match_data) +{ + return res->data && res->free =3D=3D example_resource_free; +} + +/* + * This is an example of a function that provides a description for each o= f the + * parameters in a parameterized test. + */ +static void example_param_array_get_desc(struct kunit *test, const void *p= , char *desc) +{ + const struct example_param *param =3D p; + + snprintf(desc, KUNIT_PARAM_DESC_SIZE, + "example check if %d is less than or equal to 3", param->value); +} + +/* + * This function gets passed in the parameterized test context i.e. the + * struct kunit belonging to the parameterized test. You can use this func= tion + * to add resources you want shared across the whole parameterized test or + * for additional setup. + */ +static int example_param_init(struct kunit *test) +{ + int ctx =3D 3; /* Data to be stored. */ + size_t arr_size =3D ARRAY_SIZE(example_params_array); + + /* + * This allocates a struct kunit_resource, sets its data field to + * ctx, and adds it to the struct kunit's resources list. Note that + * this is parameterized test managed. So, it doesn't need to have + * a custom exit function to deallocation as it will get cleaned up at + * the end of the parameterized test. + */ + void *data =3D kunit_alloc_resource(test, example_resource_init, example_= resource_free, + GFP_KERNEL, &ctx); + + if (!data) + return -ENOMEM; + /* + * Pass the parameter array information to the parameterized test context + * struct kunit. Note that you will need to provide kunit_array_gen_param= s() + * as the generator function to KUNIT_CASE_PARAM_WITH_INIT() when registe= ring + * a parameter array this route. + */ + kunit_register_params_array(test, example_params_array, arr_size, + example_param_array_get_desc); + return 0; +} + +/* + * This is an example of a test that uses shared resources available in the + * parameterized test context. + */ +static void example_params_test_with_init(struct kunit *test) +{ + int threshold; + struct kunit_resource *res; + const struct example_param *param =3D test->param_value; + + /* By design, param pointer will not be NULL. */ + KUNIT_ASSERT_NOT_NULL(test, param); + + /* + * Here we pass test->parent to search for shared resources in the + * parameterized test context. + */ + res =3D kunit_find_resource(test->parent, example_resource_alloc_match, N= ULL); + + KUNIT_ASSERT_NOT_NULL(test, res); + + /* Since kunit_resource->data is a void pointer we need to typecast it. */ + threshold =3D *((int *)res->data); + + /* Assert that the parameter is less than or equal to a certain threshold= . */ + KUNIT_ASSERT_LE(test, param->value, threshold); + + /* This decreases the reference count after calling kunit_find_resource()= . */ + kunit_put_resource(res); +} + /* * Here we make a list of all the test cases we want to add to the test su= ite * below. @@ -296,6 +407,8 @@ static struct kunit_case example_test_cases[] =3D { KUNIT_CASE(example_static_stub_using_fn_ptr_test), KUNIT_CASE(example_priv_test), KUNIT_CASE_PARAM(example_params_test, example_gen_params), + KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_gen= _params, + example_param_init, NULL), KUNIT_CASE_SLOW(example_slow_test), {} }; --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qv1-f74.google.com (mail-qv1-f74.google.com [209.85.219.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CEFE530100D for ; Fri, 15 Aug 2025 10:36:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254186; cv=none; b=CdEiihJf1B1lWv4F0dnvLQJu984907XnfkG36Hyw1Mli6A4Xy8GD1d8cb7gEtZiVK+rIUwH+Iy8l8hbYOg3S0EggocpOU08sTmLESacUMld1Sk6fqolsHvvqa1LccAX8U2R7BS2NHyNYGxy16e2V2XuDwE9d2+vDsoav1/R5TLs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254186; c=relaxed/simple; bh=y/T3DmcVT74O6iwGf31QFTMGNpni6MOPhIo+k/vGZkg=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=MOJg86UZ/OT4s+LiUmQ10v1bClWjU4R+0Rtv93B4EvoLsehE36BGV9P4bucq32gdkJJkKZSoslroUy4dlj7U0ZAfpx5uZ0R/aZABB+4myWduFd/V0LX4mxUbibuvQ7NVOqFNSSftOaDqjcyRpV+WJajfZPeI4ORR8xN7l5SXK78= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=BpbvAaW6; arc=none smtp.client-ip=209.85.219.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="BpbvAaW6" Received: by mail-qv1-f74.google.com with SMTP id 6a1803df08f44-70a928282a3so59356346d6.1 for ; Fri, 15 Aug 2025 03:36:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254184; x=1755858984; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=N5BvlszSrzL55yCb3EusIjjVMhIlB9YqkU/uZs3QISs=; b=BpbvAaW6Of0aNAJygv2xM+4PEqR6A71UC2EwecnYwfiP8O6cS/cXMPrZM80VtFwBY1 y90hESSlkF+AePaWDEDcUtD9HqV8PigIZti9Va5ncjblAOzIegEu5wpzzxj/IdoV/74A MYucU/vRZhD7GRN3DHKpc384/YQgnKEZLi+6uSnuWftjkIJuQnKKmQLxMyhBQBy2NYzH k44D/6T9w5mT1lrB0moqjWeuPeLw8+5SY3Q1HkSIH/8UV4+AYnHo/HodsJY4MAn7UFrE wQVavskV/5F4Vj+11C+LAz2IwxMW2RoW8UqBASu1NamW/snB8kV+QYYQHNo/TeaMVbs7 xfGw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254184; x=1755858984; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=N5BvlszSrzL55yCb3EusIjjVMhIlB9YqkU/uZs3QISs=; b=lHMAy+Ju5QDgpGqCjY0eNLLkDx8hpjjaOp9wTxrBNRKOw8y3kbxzyNpr1dvvlrEV8a eydXI2zQN24bvXtXrDD17NYNSizSMHKOD7uLVDQdvVt5a3StwpPKL+MkNnmgAVb8uc+P HMtuRU69UkSuPY/RaiBnELiG/qz1bmWxHbqWk6VYmXEvtkEttZnND+zej4dMOsm2tcwu B50ANnjh0w1ny9kzfQEA5/AfI0ShUAsVf+Qgmc0H/LP5JAd2WmtY8PsYOSrotx57tssj chfeG8HGz7DlAKluqvxJx/T4ubRzdLYU8GHZajpO/9LXzHqvBhxnMZNcMQadHIJ+KSHe M+pg== X-Forwarded-Encrypted: i=1; AJvYcCVpN3R2lqk/Ue6Yw1F4vb2ytuFdwhhsxS1WvT9BZfcRkhiGBkdDmiFYiMcNR/qT4OPfmkScs0uDImslSZQ=@vger.kernel.org X-Gm-Message-State: AOJu0YxUm2PsrVvRq5nZVru/lObQfQ3GpnE/vkxpeMfLw4FVNW4xyuK0 CgC9UbrhF/CBcDlT75VJO1aBX7WxSExB4BNYWN5/eNzZwOUJSxQzaj89ayPRY2sQTOa4T+Mp6w7 +GSOUupBhRMp5BQ== X-Google-Smtp-Source: AGHT+IGnnHUHbdjLOOep4HUpewOyAiINeFc8kVXHQi8CqQJ4jl62kvVZarAxkLdpSI1LuPZggZfoYq5jLJl6Ew== X-Received: from qvbfo14.prod.google.com ([2002:ad4:5f0e:0:b0:709:b8bf:588f]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6214:1c85:b0:709:e492:e0da with SMTP id 6a1803df08f44-70ba7cb68c6mr14801986d6.49.1755254183707; Fri, 15 Aug 2025 03:36:23 -0700 (PDT) Date: Fri, 15 Aug 2025 10:36:03 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-7-marievic@google.com> Subject: [PATCH v3 6/7] kunit: Add example parameterized test with direct dynamic parameter array setup From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce example_params_test_with_init_dynamic_arr(). This new KUnit test demonstrates directly assigning a dynamic parameter array, using the kunit_register_params_array() macro, to a parameterized test context. It highlights the use of param_init() and param_exit() for initialization and exit of a parameterized test, and their registration to the test case with KUNIT_CASE_PARAM_WITH_INIT(). Reviewed-by: Rae Moar Reviewed-by: David Gow Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-7-marievic@google.co= m/ - No changes. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-9-marievic@google.co= m/ - kunit_array_gen_params() is now explicitly passed to KUNIT_CASE_PARAM_WITH_INIT() to be consistent with the parameterized test being defined by the existence of the generate_params() function. - param_init() was changed to output a log at the start of a parameterized test. - The parameter array was changed to be allocated using kunit_kmalloc_array= (), a KUnit memory allocation API, as that would be the preferred/easier meth= od. To still demonstrate a use of param_exit(), it now outputs a log at the e= nd of the parameterized test. - The comments and the commit message were changed to reflect the parameterized testing terminology. See the patch series cover letter change log for the definitions. --- lib/kunit/kunit-example-test.c | 104 +++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/lib/kunit/kunit-example-test.c b/lib/kunit/kunit-example-test.c index 3e858367be01..9452b163956f 100644 --- a/lib/kunit/kunit-example-test.c +++ b/lib/kunit/kunit-example-test.c @@ -388,6 +388,107 @@ static void example_params_test_with_init(struct kuni= t *test) kunit_put_resource(res); } =20 +/* + * Helper function to create a parameter array of Fibonacci numbers. This = example + * highlights a parameter generation scenario that is: + * 1. Not feasible to fully pre-generate at compile time. + * 2. Challenging to implement with a standard generate_params() function, + * as it only provides the previous parameter, while Fibonacci requires + * access to two preceding values for calculation. + */ +static void *make_fibonacci_params(struct kunit *test, size_t seq_size) +{ + int *seq; + + if (seq_size <=3D 0) + return NULL; + /* + * Using kunit_kmalloc_array here ties the lifetime of the array to + * the parameterized test i.e. it will get automatically cleaned up + * by KUnit after the parameterized test finishes. + */ + seq =3D kunit_kmalloc_array(test, seq_size, sizeof(int), GFP_KERNEL); + + if (!seq) + return NULL; + if (seq_size >=3D 1) + seq[0] =3D 0; + if (seq_size >=3D 2) + seq[1] =3D 1; + for (int i =3D 2; i < seq_size; i++) + seq[i] =3D seq[i - 1] + seq[i - 2]; + return seq; +} + +/* + * This is an example of a function that provides a description for each o= f the + * parameters. + */ +static void example_param_dynamic_arr_get_desc(struct kunit *test, const v= oid *p, char *desc) +{ + const int *fib_num =3D p; + + snprintf(desc, KUNIT_PARAM_DESC_SIZE, "fibonacci param: %d", *fib_num); +} + +/* + * Example of a parameterized test param_init() function that registers a = dynamic + * array of parameters. + */ +static int example_param_init_dynamic_arr(struct kunit *test) +{ + size_t seq_size; + int *fibonacci_params; + + kunit_info(test, "initializing parameterized test\n"); + + seq_size =3D 6; + fibonacci_params =3D make_fibonacci_params(test, seq_size); + + if (!fibonacci_params) + return -ENOMEM; + + /* + * Passes the dynamic parameter array information to the parameterized te= st + * context struct kunit. The array and its metadata will be stored in + * test->parent->params_array. The array itself will be located in + * params_data.params. + * + * Note that you will need to pass kunit_array_gen_params() as the + * generator function to KUNIT_CASE_PARAM_WITH_INIT() when registering + * a parameter array this route. + */ + kunit_register_params_array(test, fibonacci_params, seq_size, + example_param_dynamic_arr_get_desc); + return 0; +} + +/* + * Example of a parameterized test param_exit() function that outputs a log + * at the end of the parameterized test. It could also be used for any oth= er + * teardown logic. + */ +static void example_param_exit_dynamic_arr(struct kunit *test) +{ + kunit_info(test, "exiting parameterized test\n"); +} + +/* + * Example of test that uses the registered dynamic array to perform asser= tions + * and expectations. + */ +static void example_params_test_with_init_dynamic_arr(struct kunit *test) +{ + const int *param =3D test->param_value; + int param_val; + + /* By design, param pointer will not be NULL. */ + KUNIT_ASSERT_NOT_NULL(test, param); + + param_val =3D *param; + KUNIT_EXPECT_EQ(test, param_val - param_val, 0); +} + /* * Here we make a list of all the test cases we want to add to the test su= ite * below. @@ -409,6 +510,9 @@ static struct kunit_case example_test_cases[] =3D { KUNIT_CASE_PARAM(example_params_test, example_gen_params), KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_gen= _params, example_param_init, NULL), + KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr, + kunit_array_gen_params, example_param_init_dynamic_arr, + example_param_exit_dynamic_arr), KUNIT_CASE_SLOW(example_slow_test), {} }; --=20 2.51.0.rc1.167.g924127e9c0-goog From nobody Sat Oct 4 14:14:57 2025 Received: from mail-qt1-f201.google.com (mail-qt1-f201.google.com [209.85.160.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 48C54301466 for ; Fri, 15 Aug 2025 10:36:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254190; cv=none; b=RqbkCi58ApTOwGJNb1QCTpqTmTblI6cnkEKt6PiBFniYQQajYrluZuhp1vF3wmKmhhgHlPb6TsniNfJNycboYSGXxXLbzeO+uYa3dvTYeAfTWngKpKfHmrSnvMYEpM8TgPJ8fvN7sxut3S4VRgnFD4OpJtMziL7H3TDOBIhe0dk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755254190; c=relaxed/simple; bh=vYll5e1IgogjjJeaX95KDrXLkmeeg9LXiiZmSqOila0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=lxrodbSxoMkJcIkmhbJEnLfAOdcXRT+EaOmI3Iogk0uQtTPtS4EcSUcntdl+fdZE6BvGt3QIzQvdXyeo4o4J+vpKIYrlBbareu8igTGqwyCypFHlKnn6Kq1GRgj4OussCWiugXlfNbtskqNXgDbkVulIh8FKRAz0AIKvAfM4ESc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=oQdMVrPM; arc=none smtp.client-ip=209.85.160.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--marievic.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="oQdMVrPM" Received: by mail-qt1-f201.google.com with SMTP id d75a77b69052e-4b109919a51so75863291cf.0 for ; Fri, 15 Aug 2025 03:36:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1755254186; x=1755858986; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=z5VWtmN7wXdBM8xUp2T3Z+kcllw5mJ+rBSS+cDWhsio=; b=oQdMVrPMOQqYQSPWhOTM7Cm3C8fDjeiuOt/QRqDLPvCIrzApf8O65DAZX13EMarzNr uW6PM/ot7gJbVaFGNpJ+PL18RImDvVRWG7lAuPAi3cAsU0Cbe6QOKxD3sw/p7lM/XYb8 xVrK6UXkPBM58Kc7tZda/DQTZP1B66UbqeLEWtnYhzs9Eop4n2GYtWjD9g8L0IQ2m/nj cx0xKCW+9Hyd7ZZX1ZzLtFyhC+hjqYlC+qp1AD4R9F+bPIzLBpXcMKkMqLfIoNCo+91O dYu+TEtK5iNY35wE+Q58PSDdV+sSEtJUBSBlchL+eQDr8SBWpMWTvbs6PpDlCkEK1unq ZYgw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755254186; x=1755858986; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=z5VWtmN7wXdBM8xUp2T3Z+kcllw5mJ+rBSS+cDWhsio=; b=JbcPE6whFCOfQuMyMFW0X/RIhY0k+73ek+3C5bDhe8QI5/cCV4r2gFHnbjjJa38nJR 00ZFBI1kRet/a00fmce+XP3kgT5qqE5Sq/aaesJgQ2WGRhlxq3owZXeUlvKzNSxMWnUf PTK3tGUHEuU8xivXQWKBwj0iA0V53Eqd7LXHsBbq0xXNmxYWYd1Zhi9HSkpaP3rwG7j1 3yzffBQR1Qyzl2RyMCKsp2Oih/TddulS+0rnCIQ+nv4tIIENvpB6de4lg0B68cBNfHAt RxKJg35v9CUgFQ8qDFmiV07OKEqAcUHL3z29Z3o+3i0raYA4uZDKCY6iB1SRvxy1Scv3 8bdQ== X-Forwarded-Encrypted: i=1; AJvYcCUvl8CTaPNpkUVzQlO9CCcG0bheVF6tkiA/6gWyw7iI7xyaCWAVvOX9ju/GQ0Q2OiQSMAtGdQs4/uLC4PE=@vger.kernel.org X-Gm-Message-State: AOJu0Yw6OJoITcl0O2g0KX6XLOSHm4f6PtJl4RRj8sZDtx4Qbg8jzo+d UDQ6zkqiBRW1El1/tVpxqVXMWLMXAeSN9qdayr3RNVer/WOfNHMK7gmq7k/YwdJrRU3nyiq4Qgn ovllDq1dpJ7p7Xg== X-Google-Smtp-Source: AGHT+IHgIvS5m7zsnvhrNu/79S0fJFF/LuP+mjcMqGvy+8kFhDJtAPX7/Z1TX1Wulq+yqxrCu+LJEZ/7E0YjeQ== X-Received: from qtny22.prod.google.com ([2002:ac8:5256:0:b0:4b0:77f6:dd7f]) (user=marievic job=prod-delivery.src-stubby-dispatcher) by 2002:ac8:7dcc:0:b0:4af:1837:778e with SMTP id d75a77b69052e-4b11e2a24demr15608461cf.31.1755254186232; Fri, 15 Aug 2025 03:36:26 -0700 (PDT) Date: Fri, 15 Aug 2025 10:36:04 +0000 In-Reply-To: <20250815103604.3857930-1-marievic@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250815103604.3857930-1-marievic@google.com> X-Mailer: git-send-email 2.51.0.rc1.167.g924127e9c0-goog Message-ID: <20250815103604.3857930-8-marievic@google.com> Subject: [PATCH v3 7/7] Documentation: kunit: Document new parameterized test features From: Marie Zhussupova To: rmoar@google.com, davidgow@google.com, shuah@kernel.org, brendan.higgins@linux.dev Cc: mark.rutland@arm.com, elver@google.com, dvyukov@google.com, lucas.demarchi@intel.com, thomas.hellstrom@linux.intel.com, rodrigo.vivi@intel.com, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, kasan-dev@googlegroups.com, intel-xe@lists.freedesktop.org, dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, Marie Zhussupova Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch updates the KUnit docs to show how to use the new parameterized test context to share resources between parameter runs. It documents and show examples of different ways the test user can pass parameter arrays to a parameterized test. Finally, it specifies the parameterized testing terminology. Reviewed-by: Rae Moar Reviewed-by: David Gow Signed-off-by: Marie Zhussupova --- Changes in v3: v2: https://lore.kernel.org/all/20250811221739.2694336-8-marievic@google.co= m/ - Parameterized test terminology was made more concise. - Introduction now includes more background information on the generate_params() function. - Minor wording edits for conciseness. - Code line number references were removed as they could quickly go out of date. Changes in v2: v1: https://lore.kernel.org/all/20250729193647.3410634-10-marievic@google.c= om/ - The documentation was updated to establish the parameterized testing terminology and reflect all the patch series changes. - The references to other parts of the KUnit Documentation were not changed from being "Documentation/dev-tools/kunit/api/test.rst" to ":ref:`kunit-resource`" links as originally planned. This is because the existing way shows up as a link to a webpage and it would be hard for people reading the documentation as an .rst file to find the referred section without having the file path. - The code examples were made more concise. - Minor edits to titles and formatting. --- Documentation/dev-tools/kunit/usage.rst | 342 +++++++++++++++++++++++- 1 file changed, 337 insertions(+), 5 deletions(-) diff --git a/Documentation/dev-tools/kunit/usage.rst b/Documentation/dev-to= ols/kunit/usage.rst index 066ecda1dd98..ebd06f5ea455 100644 --- a/Documentation/dev-tools/kunit/usage.rst +++ b/Documentation/dev-tools/kunit/usage.rst @@ -542,11 +542,31 @@ There is more boilerplate code involved, but it can: Parameterized Testing ~~~~~~~~~~~~~~~~~~~~~ =20 -The table-driven testing pattern is common enough that KUnit has special -support for it. +To run a test case against multiple inputs, KUnit provides a parameterized +testing framework. This feature formalizes and extends the concept of +table-driven tests discussed previously. =20 -By reusing the same ``cases`` array from above, we can write the test as a -"parameterized test" with the following. +A KUnit test is determined to be parameterized if a parameter generator fu= nction +is provided when registering the test case. A test user can either write t= heir +own generator function or use one that is provided by KUnit. The generator +function is stored in ``kunit_case->generate_params`` and can be set usin= g the +macros described in the section below. + +To establish the terminology, a "parameterized test" is a test which is run +multiple times (once per "parameter" or "parameter run"). Each parameter r= un has +both its own independent ``struct kunit`` (the "parameter run context") and +access to a shared parent ``struct kunit`` (the "parameterized test contex= t"). + +Passing Parameters to a Test +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +There are three ways to provide the parameters to a test: + +Array Parameter Macros: + + KUnit provides special support for the common table-driven testing patt= ern. + By applying either ``KUNIT_ARRAY_PARAM`` or ``KUNIT_ARRAY_PARAM_DESC`` = to the + ``cases`` array from the previous section, we can create a parameterize= d test + as shown below: =20 .. code-block:: c =20 @@ -555,7 +575,7 @@ By reusing the same ``cases`` array from above, we can = write the test as a const char *str; const char *sha1; }; - const struct sha1_test_case cases[] =3D { + static const struct sha1_test_case cases[] =3D { { .str =3D "hello world", .sha1 =3D "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", @@ -590,6 +610,318 @@ By reusing the same ``cases`` array from above, we ca= n write the test as a {} }; =20 +Custom Parameter Generator Function: + + The generator function is responsible for generating parameters one-by-= one + and has the following signature: + ``const void* (*)(struct kunit *test, const void *prev, char *desc)``. + You can pass the generator function to the ``KUNIT_CASE_PARAM`` + or ``KUNIT_CASE_PARAM_WITH_INIT`` macros. + + The function receives the previously generated parameter as the ``prev`= ` argument + (which is ``NULL`` on the first call) and can also access the parameter= ized + test context passed as the ``test`` argument. KUnit calls this function + repeatedly until it returns ``NULL``, which signifies that a parameteri= zed + test ended. + + Below is an example of how it works: + +.. code-block:: c + + #define MAX_TEST_BUFFER_SIZE 8 + + // Example generator function. It produces a sequence of buffer sizes that + // are powers of two, starting at 1 (e.g., 1, 2, 4, 8). + static const void *buffer_size_gen_params(struct kunit *test, const void = *prev, char *desc) + { + long prev_buffer_size =3D (long)prev; + long next_buffer_size =3D 1; // Start with an initial size of 1. + + // Stop generating parameters if the limit is reached or exceeded. + if (prev_buffer_size >=3D MAX_TEST_BUFFER_SIZE) + return NULL; + + // For subsequent calls, calculate the next size by doubling the previou= s one. + if (prev) + next_buffer_size =3D prev_buffer_size << 1; + + return (void *)next_buffer_size; + } + + // Simple test to validate that kunit_kzalloc provides zeroed memory. + static void buffer_zero_test(struct kunit *test) + { + long buffer_size =3D (long)test->param_value; + // Use kunit_kzalloc to allocate a zero-initialized buffer. This makes t= he + // memory "parameter run managed," meaning it's automatically cleaned up= at + // the end of each parameter run. + int *buf =3D kunit_kzalloc(test, buffer_size * sizeof(int), GFP_KERNEL); + + // Ensure the allocation was successful. + KUNIT_ASSERT_NOT_NULL(test, buf); + + // Loop through the buffer and confirm every element is zero. + for (int i =3D 0; i < buffer_size; i++) + KUNIT_EXPECT_EQ(test, buf[i], 0); + } + + static struct kunit_case buffer_test_cases[] =3D { + KUNIT_CASE_PARAM(buffer_zero_test, buffer_size_gen_params), + {} + }; + +Runtime Parameter Array Registration in the Init Function: + + For scenarios where you might need to initialize a parameterized test, = you + can directly register a parameter array to the parameterized test conte= xt. + + To do this, you must pass the parameterized test context, the array its= elf, + the array size, and a ``get_description()`` function to the + ``kunit_register_params_array()`` macro. This macro populates + ``struct kunit_params`` within the parameterized test context, effectiv= ely + storing a parameter array object. The ``get_description()`` function wi= ll + be used for populating parameter descriptions and has the following sig= nature: + ``void (*)(struct kunit *test, const void *param, char *desc)``. Note t= hat it + also has access to the parameterized test context. + + .. important:: + When using this way to register a parameter array, you will need = to + manually pass ``kunit_array_gen_params()`` as the generator funct= ion to + ``KUNIT_CASE_PARAM_WITH_INIT``. ``kunit_array_gen_params()`` is a= KUnit + helper that will use the registered array to generate the paramet= ers. + + If needed, instead of passing the KUnit helper, you can also pass your + own custom generator function that utilizes the parameter array. To + access the parameter array from within the parameter generator + function use ``test->params_array.params``. + + The ``kunit_register_params_array()`` macro should be called within a + ``param_init()`` function that initializes the parameterized test and h= as + the following signature ``int (*)(struct kunit *test)``. For a detailed + explanation of this mechanism please refer to the "Adding Shared Resour= ces" + section that is after this one. This method supports registering both + dynamically built and static parameter arrays. + + The code snippet below shows the ``example_param_init_dynamic_arr`` tes= t that + utilizes ``make_fibonacci_params()`` to create a dynamic array, which i= s then + registered using ``kunit_register_params_array()``. To see the full code + please refer to lib/kunit/kunit-example-test.c. + +.. code-block:: c + + /* + * Example of a parameterized test param_init() function that registers a = dynamic + * array of parameters. + */ + static int example_param_init_dynamic_arr(struct kunit *test) + { + size_t seq_size; + int *fibonacci_params; + + kunit_info(test, "initializing parameterized test\n"); + + seq_size =3D 6; + fibonacci_params =3D make_fibonacci_params(test, seq_size); + if (!fibonacci_params) + return -ENOMEM; + /* + * Passes the dynamic parameter array information to the parameterized te= st + * context struct kunit. The array and its metadata will be stored in + * test->parent->params_array. The array itself will be located in + * params_data.params. + */ + kunit_register_params_array(test, fibonacci_params, seq_size, + example_param_dynamic_arr_get_desc); + return 0; + } + + static struct kunit_case example_test_cases[] =3D { + /* + * Note how we pass kunit_array_gen_params() to use the array we + * registered in example_param_init_dynamic_arr() to generate + * parameters. + */ + KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_dynamic_arr, + kunit_array_gen_params, + example_param_init_dynamic_arr, + example_param_exit_dynamic_arr), + {} + }; + +Adding Shared Resources +^^^^^^^^^^^^^^^^^^^^^^^ +All parameter runs in this framework hold a reference to the parameterized= test +context, which can be accessed using the parent ``struct kunit`` pointer. = The +parameterized test context is not used to execute any test logic itself; i= nstead, +it serves as a container for shared resources. + +It's possible to add resources to share between parameter runs within a +parameterized test by using ``KUNIT_CASE_PARAM_WITH_INIT``, to which you p= ass +custom ``param_init()`` and ``param_exit()`` functions. These functions ru= n once +before and once after the parameterized test, respectively. + +The ``param_init()`` function, with the signature ``int (*)(struct kunit *= test)``, +can be used for adding resources to the ``resources`` or ``priv`` fields of +the parameterized test context, registering the parameter array, and any o= ther +initialization logic. + +The ``param_exit()`` function, with the signature ``void (*)(struct kunit = *test)``, +can be used to release any resources that were not parameterized test mana= ged (i.e. +not automatically cleaned up after the parameterized test ends) and for an= y other +exit logic. + +Both ``param_init()`` and ``param_exit()`` are passed the parameterized te= st +context behind the scenes. However, the test case function receives the pa= rameter +run context. Therefore, to manage and access shared resources from within = a test +case function, you must use ``test->parent``. + +For instance, finding a shared resource allocated by the Resource API requ= ires +passing ``test->parent`` to ``kunit_find_resource()``. This principle exte= nds to +all other APIs that might be used in the test case function, including +``kunit_kzalloc()``, ``kunit_kmalloc_array()``, and others (see +Documentation/dev-tools/kunit/api/test.rst and the +Documentation/dev-tools/kunit/api/resource.rst). + +.. note:: + The ``suite->init()`` function, which executes before each parameter ru= n, + receives the parameter run context. Therefore, any resources set up in + ``suite->init()`` are cleaned up after each parameter run. + +The code below shows how you can add the shared resources. Note that this = code +utilizes the Resource API, which you can read more about here: +Documentation/dev-tools/kunit/api/resource.rst. To see the full version of= this +code please refer to lib/kunit/kunit-example-test.c. + +.. code-block:: c + + static int example_resource_init(struct kunit_resource *res, void *contex= t) + { + ... /* Code that allocates memory and stores context in res->data. */ + } + + /* This function deallocates memory for the kunit_resource->data field. */ + static void example_resource_free(struct kunit_resource *res) + { + kfree(res->data); + } + + /* This match function locates a test resource based on defined criteria.= */ + static bool example_resource_alloc_match(struct kunit *test, struct kunit= _resource *res, + void *match_data) + { + return res->data && res->free =3D=3D example_resource_free; + } + + /* Function to initialize the parameterized test. */ + static int example_param_init(struct kunit *test) + { + int ctx =3D 3; /* Data to be stored. */ + void *data =3D kunit_alloc_resource(test, example_resource_init, + example_resource_free, + GFP_KERNEL, &ctx); + if (!data) + return -ENOMEM; + kunit_register_params_array(test, example_params_array, + ARRAY_SIZE(example_params_array)); + return 0; + } + + /* Example test that uses shared resources in test->resources. */ + static void example_params_test_with_init(struct kunit *test) + { + int threshold; + const struct example_param *param =3D test->param_value; + /* Here we pass test->parent to access the parameterized test context. = */ + struct kunit_resource *res =3D kunit_find_resource(test->parent, + example_resource_alloc_match, + NULL); + + threshold =3D *((int *)res->data); + KUNIT_ASSERT_LE(test, param->value, threshold); + kunit_put_resource(res); + } + + static struct kunit_case example_test_cases[] =3D { + KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init, kunit_array_ge= n_params, + example_param_init, NULL), + {} + }; + +As an alternative to using the KUnit Resource API for sharing resources, y= ou can +place them in ``test->parent->priv``. This serves as a more lightweight me= thod +for resource storage, best for scenarios where complex resource management= is +not required. + +As stated previously ``param_init()`` and ``param_exit()`` get the paramet= erized +test context. So, you can directly use ``test->priv`` within ``param_init/= exit`` +to manage shared resources. However, from within the test case function, y= ou must +navigate up to the parent ``struct kunit`` i.e. the parameterized test con= text. +Therefore, you need to use ``test->parent->priv`` to access those same +resources. + +The resources placed in ``test->parent->priv`` will need to be allocated in +memory to persist across the parameter runs. If memory is allocated using = the +KUnit memory allocation APIs (described more in the "Allocating Memory" se= ction +below), you won't need to worry about deallocation. The APIs will make the= memory +parameterized test 'managed', ensuring that it will automatically get clea= ned up +after the parameterized test concludes. + +The code below demonstrates example usage of the ``priv`` field for shared +resources: + +.. code-block:: c + + static const struct example_param { + int value; + } example_params_array[] =3D { + { .value =3D 3, }, + { .value =3D 2, }, + { .value =3D 1, }, + { .value =3D 0, }, + }; + + /* Initialize the parameterized test context. */ + static int example_param_init_priv(struct kunit *test) + { + int ctx =3D 3; /* Data to be stored. */ + int arr_size =3D ARRAY_SIZE(example_params_array); + + /* + * Allocate memory using kunit_kzalloc(). Since the `param_init` + * function receives the parameterized test context, this memory + * allocation will be scoped to the lifetime of the parameterized test. + */ + test->priv =3D kunit_kzalloc(test, sizeof(int), GFP_KERNEL); + + /* Assign the context value to test->priv.*/ + *((int *)test->priv) =3D ctx; + + /* Register the parameter array. */ + kunit_register_params_array(test, example_params_array, arr_size, NULL); + return 0; + } + + static void example_params_test_with_init_priv(struct kunit *test) + { + int threshold; + const struct example_param *param =3D test->param_value; + + /* By design, test->parent will not be NULL. */ + KUNIT_ASSERT_NOT_NULL(test, test->parent); + + /* Here we use test->parent->priv to access the shared resource. */ + threshold =3D *(int *)test->parent->priv; + + KUNIT_ASSERT_LE(test, param->value, threshold); + } + + static struct kunit_case example_tests[] =3D { + KUNIT_CASE_PARAM_WITH_INIT(example_params_test_with_init_priv, + kunit_array_gen_params, + example_param_init_priv, NULL), + {} + }; + Allocating Memory ----------------- =20 --=20 2.51.0.rc1.167.g924127e9c0-goog