Skip to contentSkip to conversation

test: Add support for passing arguments to C unit tests

PATCH In review Simon Glass 2 participants 18 messages Apr 12 – Jun 14

lore
Share & tools
lore
#0 lore raw

v2 cover test: Add support for passing arguments to C unit tests

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

- Python lacks access to things like return codes and has to scan the console output to figure out what happened
- Python lacks access to internal state, so it cannot directly check the result of an operation
- Python is ~100x slower due to console interaction, etc.
- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

This series adds infrastructure for passing typed, runtime arguments from Python to C unit tests, using a name=value format on the ut command line.

The series includes:

- Regex assertion helpers for matching variable output in tests

- A private buffer in unit_test_state for test-local temporary data

- Argument-type definitions (string, integer, boolean) with optional flags and default values

- A new UNIT_TEST_ARGS() macro for declaring tests with typed arguments

- Argument parsing in the test framework, accepting name=value format

- Updates to the ut command to pass arguments through to tests

- Type-checked accessor macros ut_str(), ut_int(), and ut_bool() with bounds validation

- Tests for the argument feature covering type checking, optional arguments, and argument-parsing failures

- Documentation for the test-parameter feature

- C-based filesystem tests as an example of the hybrid approach, with Python wrappers that pass filesystem type, image path, and expected MD5 values to the C tests

Note: This series depends on:

https://patchwork.ozlabs.org/project/uboot/list/?series=496972

Changes in v2:
- Correct double signoff

Simon Glass (12):
test: Add ut_asserteq_regex() for regex pattern matching
test: Add a helper to check the next line against a regex
test: Add a private buffer for tests
test: Add argument-type definitions
test: Add a macro to declare unit tests with arguments
test: Add support for passing arguments to C tests
test: Enhance the ut command to pass test arguments
test: Add type-checked argument accessor functions
test: Add tests for unit-test arguments
test: Add documentation for the test framework
test: fs: add C-based filesystem tests
test: fs: Update Python tests to call C implementations

 arch/sandbox/cpu/spl.c              |   3 +-
 doc/develop/tests_writing.rst       | 169 ++++++++++++
 doc/usage/cmd/ut.rst                |  18 +-
 include/test/fs.h                   |  39 +++
 include/test/test.h                 | 107 ++++++++
 include/test/ut.h                   | 123 ++++++++-
 test/Makefile                       |   1 +
 test/cmd_ut.c                       |  32 ++-
 test/common/Makefile                |   1 +
 test/common/test_args.c             | 176 ++++++++++++
 test/fs/Makefile                    |   3 +
 test/fs/fs_basic.c                  | 407 ++++++++++++++++++++++++++++
 test/py/tests/test_fs/conftest.py   |   4 +-
 test/py/tests/test_fs/test_basic.py | 346 +++++++----------------
 test/test-main.c                    | 170 +++++++++++-
 test/ut.c                           | 117 ++++++++
 16 files changed, 1437 insertions(+), 279 deletions(-)
 create mode 100644 include/test/fs.h
 create mode 100644 test/common/test_args.c
 create mode 100644 test/fs/Makefile
 create mode 100644 test/fs/fs_basic.c
Signature · 4 lines
2.43.0

base-commit: e2fa3e570f83ab0f9ce667ddaec9dc738bcf05b9
branch: testa-us2
#1 lore raw

PATCH v2 1/12 test: Add ut_asserteq_regex() for regex pattern matching

Add a new assertion macro ut_asserteq_regex() that checks if a string matches a regular expression pattern using the SLRE library.

This is useful for tests where exact string-matching is difficult, such as when output contains line numbers or other variable content.

Use a helper function ut_check_regex() to avoid including slre.h in the header.

---

(no changes since v1)

 include/test/ut.h | 36 +++++++++++++++++++++++++++++-------
 test/ut.c         | 30 ++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+), 7 deletions(-)
include/test/ut.h +29 -7
index 6510c35997f..cda15f3a7a9 100644
@@ -13,6 +13,9 @@
 #include <linux/err.h>
 #include <test/test.h>
 
+/* Size of error buffer for ut_check_regex() */
+#define UT_REGEX_ERR_SIZE	256
+
 struct unit_test_state;
 
 /**
@@ -41,6 +44,16 @@ void ut_failf(struct unit_test_state *uts, const char *fname, int line,
 	      const char *func, const char *cond, const char *fmt, ...)
 			__attribute__ ((format (__printf__, 6, 7)));
 
+/**
+ * ut_check_regex() - Check if a string matches a regex pattern
+ *
+ * @pattern: Regular expression pattern
+ * @str: String to match against
+ * @err: Buffer to hold error message on failure (UT_REGEX_ERR_SIZE bytes)
+ * Return: 0 if match, -EINVAL if pattern is invalid, -ENOENT if no match
+ */
+int ut_check_regex(const char *pattern, const char *str, char *err);
+
 /**
  * ut_check_console_line() - Check the next console line against expectations
  *
@@ -264,13 +277,22 @@ int ut_check_console_dump(struct unit_test_state *uts, int total_bytes);
 	__ret;								\
 })
 
-/**
- * ut_asserteq_mem() - Assert that two memory areas are equal
- *
- * @expr1:	expected value
- * @expr2:	actual value
- * @len:	length of the memory areas
- */
+/* Assert that a string matches a regex pattern */
+#define ut_asserteq_regex(pattern, str) ({				\
+	const char *_pattern = (pattern), *_str = (str);		\
+	char _err[UT_REGEX_ERR_SIZE];					\
+	int __ret = 0;							\
+									\
+	__ret = ut_check_regex(_pattern, _str, _err);			\
+	if (__ret) {							\
+		ut_failf(uts, __FILE__, __LINE__, __func__,		\
+			 #pattern " matches " #str, "%s", _err);	\
+		return CMD_RET_FAILURE;					\
+	}								\
+	__ret;								\
+})
+
+/* Assert that two memory areas are equal */
 #define ut_asserteq_mem(expr1, expr2, len) ({				\
 	const u8 *_val1 = (u8 *)(expr1), *_val2 = (u8 *)(expr2);	\
 	const uint __len = len;						\
test/ut.c +30 -0
index a16fdfb3a93..b4f2a8bf40f 100644
@@ -6,7 +6,10 @@
  */
 
 #include <console.h>
+#include <errno.h>
 #include <malloc.h>
+#include <slre.h>
+#include <vsprintf.h>
 #ifdef CONFIG_SANDBOX
 #include <asm/state.h>
 #endif
@@ -38,6 +41,33 @@ void ut_failf(struct unit_test_state *uts, const char *fname, int line,
 	uts->cur.fail_count++;
 }
 
+int ut_check_regex(const char *pattern, const char *str, char *err)
+{
+	struct slre slre;
+
+	if (!pattern || !str) {
+		snprintf(err, UT_REGEX_ERR_SIZE,
+			 "NULL value: pattern=%s, str=%s",
+			 pattern ? pattern : "(null)",
+			 str ? str : "(null)");
+		return -EINVAL;
+	}
+
+	if (!slre_compile(&slre, pattern)) {
+		snprintf(err, UT_REGEX_ERR_SIZE,
+			 "Invalid regex '%s': %s", pattern, slre.err_str);
+		return -EINVAL;
+	}
+
+	if (!slre_match(&slre, str, strlen(str), NULL)) {
+		snprintf(err, UT_REGEX_ERR_SIZE,
+			 "No match: pattern '%s', str '%s'", pattern, str);
+		return -ENOENT;
+	}
+
+	return 0;
+}
+
 ulong ut_check_free(void)
 {
 	struct mallinfo info = mallinfo();
Signature · 1 line
2.43.0
#2 lore raw

PATCH v2 2/12 test: Add a helper to check the next line against a regex

In reply to Simon Glass

Add a new ut_assert_nextline_regex() macro and ut_check_console_line_regex() helper to check console output against a regex pattern. This is useful when the exact output varies (e.g., file paths or line numbers in error messages).

---

(no changes since v1)

 include/test/ut.h | 33 +++++++++++++++++++++++++++++----
 test/ut.c         | 21 +++++++++++++++++++++
 2 files changed, 50 insertions(+), 4 deletions(-)
include/test/ut.h +29 -4
index cda15f3a7a9..8f0e69a7734 100644
@@ -87,6 +87,20 @@ int ut_check_console_line(struct unit_test_state *uts, const char *fmt, ...)
 int ut_check_console_linen(struct unit_test_state *uts, const char *fmt, ...)
 			__attribute__ ((format (__printf__, 2, 3)));
 
+/**
+ * ut_check_console_line_regex() - Check the next console line against a regex
+ *
+ * This checks the next line of console output against a regex pattern.
+ *
+ * After the function returns, uts->expect_str holds the regex pattern and
+ * uts->actual_str holds the actual string read from the console.
+ *
+ * @uts: Test state
+ * @regex: Regular expression pattern to match against
+ * Return: 0 if OK, other value on error
+ */
+int ut_check_console_line_regex(struct unit_test_state *uts, const char *regex);
+
 /**
  * ut_check_skipline() - Check that the next console line exists and skip it
  *
@@ -451,10 +465,21 @@ int ut_check_console_dump(struct unit_test_state *uts, int total_bytes);
 	__ret;								\
 })
 
-/**
- * ut_assert_skipline() - Assert that there is a 'next' console output line,
- *			  and skip it
- */
+/* Assert that the next console output line matches a regex pattern */
+#define ut_assert_nextline_regex(pattern) ({				\
+	int __ret = 0;							\
+									\
+	if (ut_check_console_line_regex(uts, pattern)) {		\
+		ut_failf(uts, __FILE__, __LINE__, __func__,		\
+			 "console regex",				\
+			 "\nExpected regex '%s',\n         got '%s'",	\
+			 uts->expect_str, uts->actual_str);		\
+		return CMD_RET_FAILURE;					\
+	}								\
+	__ret;								\
+})
+
+/* Assert that there is a 'next' console output line, and skip it */
 #define ut_assert_skipline() ({						\
 	int __ret = 0;							\
 									\
test/ut.c +21 -0
index b4f2a8bf40f..b0cc0f3e8ff 100644
@@ -139,6 +139,27 @@ int ut_check_console_linen(struct unit_test_state *uts, const char *fmt, ...)
 		       strlen(uts->expect_str));
 }
 
+int ut_check_console_line_regex(struct unit_test_state *uts, const char *regex)
+{
+	char err[UT_REGEX_ERR_SIZE];
+	int len;
+	int ret;
+
+	len = strlcpy(uts->expect_str, regex, sizeof(uts->expect_str));
+	if (len >= sizeof(uts->expect_str)) {
+		ut_fail(uts, __FILE__, __LINE__, __func__,
+			"unit_test_state->expect_str too small");
+		return -EOVERFLOW;
+	}
+	ret = readline_check(uts);
+	if (ret == -ENOENT)
+		return 1;
+
+	ret = ut_check_regex(regex, uts->actual_str, err);
+
+	return ret;
+}
+
 int ut_check_skipline(struct unit_test_state *uts)
 {
 	int ret;
Signature · 1 line
2.43.0
#3 lore raw

PATCH v2 3/12 test: Add a private buffer for tests

In reply to Simon Glass

From: Simon Glass <[email protected]>

Add a priv[] buffer to struct unit_test_state that tests can use for their own data. This avoids the need to allocate memory or use global variables for test-specific state.

---

(no changes since v1)

 include/test/test.h | 4 ++++
 1 file changed, 4 insertions(+)
include/test/test.h +4 -0
index 0f2b68a5dee..f8a80a88959 100644
@@ -9,6 +9,8 @@
 #include <malloc.h>
 #include <linux/bitops.h>
 
+#define UT_PRIV_SIZE	256
+
 /**
  * struct ut_stats - Statistics about tests run
  *
@@ -53,6 +55,7 @@ struct ut_stats {
  * @old_bloblist: stores the old gd->bloblist pointer
  * @expect_str: Temporary string used to hold expected string value
  * @actual_str: Temporary string used to hold actual string value
+ * @priv: Private data for tests to use as needed
  */
 struct unit_test_state {
 	struct ut_stats cur;
@@ -78,6 +81,7 @@ struct unit_test_state {
 	void *old_bloblist;
 	char expect_str[512];
 	char actual_str[512];
+	char priv[UT_PRIV_SIZE];
 };
 
 /* Test flags for each test */
Signature · 1 line
2.43.0
#4 lore raw

PATCH v2 4/12 test: Add argument-type definitions

In reply to Simon Glass

Add types for declaring and storing unit test arguments:
- enum ut_arg_type: INT, BOOL, STR types
- enum ut_arg_flags: OPTIONAL flag for non-required args
- struct ut_arg_def: declares expected args with defaults
- struct ut_arg: holds parsed argument values

This prepares for passing key=value arguments to tests via the 'ut' command instead of needing to use environment variables.

---

(no changes since v1)

 include/test/test.h | 65 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 65 insertions(+)
include/test/test.h +65 -0
index f8a80a88959..c9b56c66eae 100644
@@ -29,6 +29,40 @@ struct ut_stats {
 	ulong duration_ms;
 };
 
+/**
+ * enum ut_arg_type - Type of a unit test argument
+ *
+ * @UT_ARG_INT: Integer argument (hex with 0x prefix, or decimal) -> vint
+ * @UT_ARG_BOOL: Boolean argument (0 or 1) -> vbool
+ * @UT_ARG_STR: String argument -> vstr
+ */
+enum ut_arg_type {
+	UT_ARG_INT,
+	UT_ARG_BOOL,
+	UT_ARG_STR,
+};
+
+/**
+ * struct ut_arg - Parsed unit test argument value
+ *
+ * Holds the parsed value of an argument after command-line processing.
+ *
+ * @name: Name of the argument (points to ut_arg_def.name)
+ * @type: Type of the argument
+ * @vint: Integer value (when type is UT_ARG_INT)
+ * @vbool: Boolean value (when type is UT_ARG_BOOL)
+ * @vstr: String value (when type is UT_ARG_STR, points into argv)
+ */
+struct ut_arg {
+	const char *name;
+	enum ut_arg_type type;
+	union {
+		long vint;
+		bool vbool;
+		const char *vstr;
+	};
+};
+
 /*
  * struct unit_test_state - Entire state of test system
  *
@@ -108,6 +142,37 @@ enum ut_flags {
 	UTF_UNINIT	= BIT(13),	/* test uninits a suite */
 };
 
+/**
+ * enum ut_arg_flags - Flags for unit test arguments
+ *
+ * @UT_ARGF_OPTIONAL: Argument is optional; use default value if not provided
+ */
+enum ut_arg_flags {
+	UT_ARGF_OPTIONAL	= BIT(0),
+};
+
+/**
+ * struct ut_arg_def - Definition of a unit test argument
+ *
+ * Declares an expected argument for a test, including its name, type,
+ * whether it is optional, and its default value.
+ *
+ * @name: Name of the argument (used in key=value matching)
+ * @type: Type of the argument (int, bool, or string)
+ * @flags: Argument flags (e.g., UT_ARGF_OPTIONAL)
+ * @def: Default value (used when argument is optional and not provided)
+ */
+struct ut_arg_def {
+	const char *name;
+	enum ut_arg_type type;
+	int flags;
+	union {
+		long vint;
+		bool vbool;
+		const char *vstr;
+	} def;
+};
+
 /**
  * struct unit_test - Information about a unit test
  *
Signature · 1 line
2.43.0
#5 lore raw

PATCH v2 5/12 test: Add a macro to declare unit tests with arguments

In reply to Simon Glass

Add a UNIT_TEST_ARGS() macro to declare and register a test with inline argument definitions. The variadic arguments use struct ut_arg_def and a NULL terminator is added automatically to the list.

Example usage:
static int my_test(struct unit_test_state *uts) { ... } UNIT_TEST_ARGS(my_test, UTF_CONSOLE, my_suite,

      { "path", UT_ARG_STR },
      { "count", UT_ARG_INT, UT_ARGF_OPTIONAL, { .vint = 10 } });

---

(no changes since v1)

 include/test/test.h | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
include/test/test.h +31 -0
index c9b56c66eae..cdd19392844 100644
@@ -49,6 +49,7 @@ enum ut_arg_type {
  *
  * @name: Name of the argument (points to ut_arg_def.name)
  * @type: Type of the argument
+ * @provided: true if value was provided on command line
  * @vint: Integer value (when type is UT_ARG_INT)
  * @vbool: Boolean value (when type is UT_ARG_BOOL)
  * @vstr: String value (when type is UT_ARG_STR, points into argv)
@@ -56,6 +57,7 @@ enum ut_arg_type {
 struct ut_arg {
 	const char *name;
 	enum ut_arg_type type;
+	bool provided;
 	union {
 		long vint;
 		bool vbool;
@@ -179,12 +181,14 @@ struct ut_arg_def {
  * @name: Name of test
  * @func: Function to call to perform test
  * @flags: Flags indicated pre-conditions for test
+ * @arg_defs: Argument definitions (NULL-terminated array), or NULL
  */
 struct unit_test {
 	const char *file;
 	const char *name;
 	int (*func)(struct unit_test_state *state);
 	int flags;
+	const struct ut_arg_def *arg_defs;
 };
 
 /**
@@ -236,6 +240,33 @@ struct unit_test {
 		.func = _name,						\
 	}
 
+/**
+ * UNIT_TEST_ARGS() - create unit test entry with inline argument definitions
+ *
+ * Like UNIT_TEST() but allows specifying argument definitions inline.
+ * The variadic arguments are struct ut_arg_def initializers. The NULL
+ * terminator is added automatically by the macro.
+ *
+ * Example:
+ *   UNIT_TEST_ARGS(my_test, UTF_CONSOLE, my_suite,
+ *       { "path", UT_ARG_STR },
+ *       { "count", UT_ARG_INT, UT_ARGF_OPTIONAL, { .vint = 10 } });
+ *
+ * @_name:	Test function name
+ * @_flags:	Test flags (see enum ut_flags)
+ * @_suite:	Test suite name
+ * @...:	Argument definitions (struct ut_arg_def initializers)
+ */
+#define UNIT_TEST_ARGS(_name, _flags, _suite, ...)			\
+	static const struct ut_arg_def _name##_args[] = { __VA_ARGS__, { NULL } }; \
+	ll_entry_declare(struct unit_test, _name, ut_ ## _suite) = {	\
+		.file = __FILE__,					\
+		.name = #_name,						\
+		.flags = _flags,					\
+		.func = _name,						\
+		.arg_defs = _name##_args,				\
+	}
+
 /* Get the start of a list of unit tests for a particular suite */
 #define UNIT_TEST_SUITE_START(_suite) \
 	ll_entry_start(struct unit_test, ut_ ## _suite)
Signature · 1 line
2.43.0
#6 lore raw

PATCH v2 6/12 test: Add support for passing arguments to C tests

In reply to Simon Glass

Add support for passing key=value arguments to unit tests. The test framework parses arguments based on definitions provided by each test and makes them available via uts->args[]

For now the 'ut' command does not support this new feature.

---

(no changes since v1)

 arch/sandbox/cpu/spl.c |   3 +-
 include/test/test.h    |   5 ++
 include/test/ut.h      |   4 +-
 test/cmd_ut.c          |   3 +-
 test/test-main.c       | 169 ++++++++++++++++++++++++++++++++++++++++-
 5 files changed, 177 insertions(+), 7 deletions(-)
arch/sandbox/cpu/spl.c +2 -1
index 7ee4975523e..162b678314e 100644
@@ -152,7 +152,8 @@ void spl_board_init(void)
 
 		ut_init_state(&uts);
 		ret = ut_run_list(&uts, "spl", NULL, tests, count,
-				  state->select_unittests, 1, false, NULL);
+				  state->select_unittests, 1, false, NULL,
+				  0, NULL);
 		ut_report(&uts.cur, 1);
 		ut_uninit_state(&uts);
 		/* continue execution into U-Boot */
include/test/test.h +5 -0
index cdd19392844..bd47025ce50 100644
@@ -9,6 +9,7 @@
 #include <malloc.h>
 #include <linux/bitops.h>
 
+#define UT_MAX_ARGS	8
 #define UT_PRIV_SIZE	256
 
 /**
@@ -92,6 +93,8 @@ struct ut_arg {
  * @expect_str: Temporary string used to hold expected string value
  * @actual_str: Temporary string used to hold actual string value
  * @priv: Private data for tests to use as needed
+ * @args: Parsed argument values for current test
+ * @arg_count: Number of parsed arguments
  */
 struct unit_test_state {
 	struct ut_stats cur;
@@ -118,6 +121,8 @@ struct unit_test_state {
 	char expect_str[512];
 	char actual_str[512];
 	char priv[UT_PRIV_SIZE];
+	struct ut_arg args[UT_MAX_ARGS];
+	int arg_count;
 };
 
 /* Test flags for each test */
include/test/ut.h +3 -1
index 8f0e69a7734..1c4ee390fd8 100644
@@ -675,12 +675,14 @@ void ut_uninit_state(struct unit_test_state *uts);
  * name is the name of the test to run. This is used to find which test causes
  * another test to fail. If the one test fails, testing stops immediately.
  * Pass NULL to disable this
+ * @argc: Number of test arguments (key=value pairs), 0 if none
+ * @argv: Test argument array, NULL if none
  * Return: 0 if all tests passed, -1 if any failed
  */
 int ut_run_list(struct unit_test_state *uts, const char *category,
 		const char *prefix, struct unit_test *tests, int count,
 		const char *select_name, int runs_per_test, bool force_run,
-		const char *test_insert);
+		const char *test_insert, int argc, char *const argv[]);
 
 /**
  * ut_report() - Report stats on a test run
test/cmd_ut.c +2 -1
index 44e5fdfdaa6..7304c32bec5 100644
@@ -130,7 +130,8 @@ static int run_suite(struct unit_test_state *uts, struct suite *ste,
 	snprintf(prefix, sizeof(prefix), "%s_test_", ste->name);
 
 	ret = ut_run_list(uts, ste->name, prefix, ste->start, n_ents,
-			  select_name, runs_per_test, force_run, test_insert);
+			  select_name, runs_per_test, force_run, test_insert,
+			  0, NULL);
 
 	return ret;
 }
test/test-main.c +165 -4

211 lines not on this page · raw message

Signature · 1 line
2.43.0
#7 lore raw

PATCH v2 7/12 test: Enhance the ut command to pass test arguments

In reply to Simon Glass

Update the ut command to permit passing arguments to tests.

Usage: ut -f fs test_name key1=value1 key2=value2

---

(no changes since v1)

 doc/usage/cmd/ut.rst | 11 ++++++++++-
 test/cmd_ut.c        | 29 ++++++++++++++++++++---------
 2 files changed, 30 insertions(+), 10 deletions(-)
doc/usage/cmd/ut.rst +10 -1
index 1acf3126680..d8c3cbf496c 100644
@@ -11,7 +11,7 @@ Synopsis
 
 ::
 
-    ut [-r<runs>] [-f] [-I<n>:<one_test>] [-r<n>] [<suite> | 'all' [<test>]]
+    ut [-r<runs>] [-f] [-I<n>:<one_test>] [<suite> | all [<test>]] [<args>...]
     ut [-s] info
 
 Description
@@ -37,6 +37,11 @@ test
     causes another test to fail. If the one test fails, testing stops
     immediately.
 
+args
+    Optional arguments to pass to the test, in `name=value` format. These are
+    used by tests declared with `UNIT_TEST_ARGS()` which define expected
+    argument names and types.
+
 Typically the command is run on :ref:`arch/sandbox/sandbox:sandbox` since it
 includes a near-complete set of emulators, no code-size limits, many CONFIG
 options enabled and runs easily in CI without needing QEMU. It is also possible
@@ -201,3 +206,7 @@ Run a selection of three suites::
     Tests run: 10, 12 ms, average: 1 ms, failures: 0
     Suites run: 3, total tests run: 37, 26 ms, average: 0 ms, failures: 0
     Average test time: 0 ms, worst case 'mem' took 1 ms
+
+Run a test with arguments (used by tests declared with UNIT_TEST_ARGS)::
+
+    => ut -f fs fs_test_ls_norun fs_type=ext4 fs_image=/tmp/img small=1MB.file
test/cmd_ut.c +20 -9
index 7304c32bec5..9d36bd5dc87 100644
@@ -30,7 +30,7 @@ struct suite {
 
 static int do_ut_all(struct unit_test_state *uts, const char *select_name,
 		     int runs_per_test, bool force_run,
-		     const char *test_insert);
+		     const char *test_insert, int argc, char *const argv[]);
 
 static int do_ut_info(bool show_suites);
 
@@ -120,7 +120,7 @@ static bool has_tests(struct suite *ste)
 /** run_suite() - Run a suite of tests */
 static int run_suite(struct unit_test_state *uts, struct suite *ste,
 		     const char *select_name, int runs_per_test, bool force_run,
-		     const char *test_insert)
+		     const char *test_insert, int argc, char *const argv[])
 {
 	int n_ents = ste->end - ste->start;
 	char prefix[30];
@@ -131,7 +131,7 @@ static int run_suite(struct unit_test_state *uts, struct suite *ste,
 
 	ret = ut_run_list(uts, ste->name, prefix, ste->start, n_ents,
 			  select_name, runs_per_test, force_run, test_insert,
-			  0, NULL);
+			  argc, argv);
 
 	return ret;
 }
@@ -167,7 +167,8 @@ static void update_stats(struct unit_test_state *uts, const struct suite *ste)
 }
 
 static int do_ut_all(struct unit_test_state *uts, const char *select_name,
-		     int runs_per_test, bool force_run, const char *test_insert)
+		     int runs_per_test, bool force_run, const char *test_insert,
+		     int argc, char *const argv[])
 {
 	int i;
 	int retval;
@@ -179,7 +180,7 @@ static int do_ut_all(struct unit_test_state *uts, const char *select_name,
 		if (has_tests(ste)) {
 			printf("----Running %s tests----\n", ste->name);
 			retval = run_suite(uts, ste, select_name, runs_per_test,
-					   force_run, test_insert);
+					   force_run, test_insert, argc, argv);
 			if (!any_fail)
 				any_fail = retval;
 			update_stats(uts, ste);
@@ -244,6 +245,8 @@ static struct suite *find_suite(const char *name)
 static int do_ut(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
 {
 	const char *test_insert = NULL, *select_name;
+	int test_argc;
+	char *const *test_argv;
 	struct unit_test_state uts;
 	bool show_suites = false;
 	bool force_run = false;
@@ -285,9 +288,14 @@ static int do_ut(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
 	ut_init_state(&uts);
 	name = argv[0];
 	select_name = cmd_arg1(argc, argv);
+
+	/* Test arguments are after suite name and test name */
+	test_argc = argc > 2 ? argc - 2 : 0;
+	test_argv = argc > 2 ? argv + 2 : NULL;
+
 	if (!strcmp(name, "all")) {
 		ret = do_ut_all(&uts, select_name, runs_per_text, force_run,
-				test_insert);
+				test_insert, test_argc, test_argv);
 	} else if (!strcmp(name, "info")) {
 		ret = do_ut_info(show_suites);
 	} else {
@@ -306,7 +314,8 @@ static int do_ut(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
 			}
 
 			ret = run_suite(&uts, ste, select_name, runs_per_text,
-					force_run, test_insert);
+					force_run, test_insert, test_argc,
+					test_argv);
 			if (!any_fail)
 				any_fail = ret;
 			update_stats(&uts, ste);
@@ -322,12 +331,14 @@ static int do_ut(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
 }
 
 U_BOOT_LONGHELP(ut,
-	"[-rs] [-f] [-I<n>:<one_test>][<suites>] - run unit tests\n"
+	"[-rs] [-f] [-I<n>:<one_test>] <suite> [<test> [<args>...]] - run unit tests\n"
 	"   -r<runs>   Number of times to run each test\n"
 	"   -f         Force 'manual' tests to run as well\n"
 	"   -I         Test to run after <n> other tests have run\n"
 	"   -s         Show all suites with ut info\n"
-	"   <suites>   Comma-separated list of suites to run\n"
+	"   <suite>    Test suite to run (or comma-separated list)\n"
+	"   <test>     Specific test to run (optional)\n"
+	"   <args>     Test arguments as key=value pairs (optional)\n"
 	"\n"
 	"Options for <suite>:\n"
 	"all       - execute all enabled tests\n"
Signature · 1 line
2.43.0
#8 lore raw

PATCH v2 8/12 test: Add type-checked argument accessor functions

In reply to Simon Glass

Add ut_get_str(), ut_get_int(), and ut_get_bool() functions with corresponding ut_str(), ut_int(), and ut_bool() macros for accessing test arguments with type checking.

These functions check that the argument index is within bounds and the type matches what was requested.

The first failure for a test is reported via ut_failf() which should make it fairly easy to debug the test.

---

(no changes since v1)

 include/test/test.h |  2 ++
 include/test/ut.h   | 50 ++++++++++++++++++++++++++++++++++
 test/test-main.c    |  1 +
 test/ut.c           | 66 +++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 119 insertions(+)
include/test/test.h +2 -0
index bd47025ce50..f435d6f8c6a 100644
@@ -95,6 +95,7 @@ struct ut_arg {
  * @priv: Private data for tests to use as needed
  * @args: Parsed argument values for current test
  * @arg_count: Number of parsed arguments
+ * @arg_error: Set if ut_str/int/bool() detects a type mismatch
  */
 struct unit_test_state {
 	struct ut_stats cur;
@@ -123,6 +124,7 @@ struct unit_test_state {
 	char priv[UT_PRIV_SIZE];
 	struct ut_arg args[UT_MAX_ARGS];
 	int arg_count;
+	bool arg_error;
 };
 
 /* Test flags for each test */
include/test/ut.h +50 -0

54 lines not on this page · raw message

test/test-main.c +1 -0
index 9d8ab794db8..9fc4bca8e20 100644
@@ -636,6 +636,7 @@ static int ut_run_test(struct unit_test_state *uts, struct unit_test *test,
 	if (ret)
 		return ret;
 
+	uts->arg_error = false;
 	ret = test->func(uts);
 	if (ret == -EAGAIN)
 		skip_test(uts);
test/ut.c +66 -0

69 lines not on this page · raw message

Signature · 1 line
2.43.0
#9 lore raw

PATCH v2 9/12 test: Add tests for unit-test arguments

In reply to Simon Glass

Add a set of tests to check the behaviour of test arguments and the ut command. This includes failure cases, where the wrong type or a non-existent argument is requested.

---

(no changes since v1)

 test/common/Makefile    |   1 +
 test/common/test_args.c | 176 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 177 insertions(+)
 create mode 100644 test/common/test_args.c
test/common/Makefile +1 -0
index baefc7b3622..bfeb29346f5 100644
@@ -11,3 +11,4 @@ obj-$(CONFIG_CYCLIC) += cyclic.o
 obj-$(CONFIG_EVENT_DYNAMIC) += event.o
 obj-y += cread.o
 obj-$(CONFIG_$(PHASE_)CMDLINE) += print.o
+obj-$(CONFIG_$(PHASE_)CMDLINE) += test_args.o
test/common/test_args.c new file +176 -0

176 lines not on this page · raw message

Signature · 1 line
2.43.0
#10 lore raw

PATCH v2 10/12 test: Add documentation for the test framework

In reply to Simon Glass

Add documentation for test assertions, the private buffer, and test parameters. This covers the available ut_assert*() macros, console output checks, memory helpers, and how to pass typed arguments from Python to C tests.

---

(no changes since v1)

 doc/develop/tests_writing.rst | 169 ++++++++++++++++++++++++++++++++++
 doc/usage/cmd/ut.rst          |  11 ++-
 2 files changed, 178 insertions(+), 2 deletions(-)
doc/develop/tests_writing.rst +169 -0
index 1a020caa411..40192f9db30 100644
@@ -101,6 +101,47 @@ constructs, in this case to check that the expected things happened in the
 Python test.
 
 
+Passing arguments to C tests
+----------------------------
+
+Sometimes a C test needs parameters from Python, such as filenames or expected
+values that are generated at runtime. The test-argument feature allows this.
+
+Use the `UNIT_TEST_ARGS` macro to declare a test with arguments::
+
+   static int my_test_norun(struct unit_test_state *uts)
+   {
+      const char *filename = ut_str(0);
+      int count = ut_int(1);
+
+      /* test code using filename and count */
+
+      return 0;
+   }
+   UNIT_TEST_ARGS(my_test_norun, UTF_CONSOLE | UTF_MANUAL, my_suite,
+                  { "filename", UT_ARG_STR },
+                  { "count", UT_ARG_INT });
+
+Each argument definition specifies a name and type:
+
+- `UT_ARG_STR` - string argument, accessed via `ut_str(n)`
+- `UT_ARG_INT` - integer argument, accessed via `ut_int(n)`
+- `UT_ARG_BOOL` - boolean argument, accessed via `ut_bool(n)`
+  (use `1` for true, any other value for false)
+
+Arguments are passed on the command line in `name=value` format::
+
+   ut -f my_suite my_test_norun filename=/path/to/file count=42
+
+From Python, you can call the test like this::
+
+   cmd = f'ut -f my_suite my_test_norun filename={filepath} count={count}'
+   ubman.run_command(cmd)
+
+This approach combines Python's flexibility for setup (creating files,
+generating values) with C's speed and debuggability for the actual test logic.
+
+
 How slow are Python tests?
 --------------------------
 
@@ -384,6 +425,134 @@ existing suite or creating a new one.
 An example SPL test is spl_test_load().
 
 
+.. _tests_writing_assertions:
+
+Assertions
+----------
+
+The test framework provides various assertion macros, defined in
+``include/test/ut.h``. All of these return from the test function on failure,
+unless ``uts->soft_fail`` is set.
+
+Basic assertions
+~~~~~~~~~~~~~~~~
+
+ut_assert(cond)
+    Assert that a condition is non-zero (true)
+
+ut_assertf(cond, fmt, args...)
+    Assert that a condition is non-zero, with a printf() message on failure
+
+ut_assertok(cond)
+    Assert that an operation succeeds (returns 0)
+
+ut_reportf(fmt, args...)
+    Report a failure with a printf() message (always fails)
+
+Value comparisons
+~~~~~~~~~~~~~~~~~
+
+ut_asserteq(expr1, expr2)
+    Assert that two int expressions are equal
+
+ut_asserteq_64(expr1, expr2)
+    Assert that two 64-bit expressions are equal
+
+ut_asserteq_str(expr1, expr2)
+    Assert that two strings are equal
+
+ut_asserteq_strn(expr1, expr2)
+    Assert that two strings are equal, up to the length of the first
+
+ut_asserteq_mem(expr1, expr2, len)
+    Assert that two memory areas are equal
+
+ut_asserteq_ptr(expr1, expr2)
+    Assert that two pointers are equal
+
+ut_asserteq_addr(expr1, expr2)
+    Assert that two addresses (converted from pointers via map_to_sysmem())
+    are equal
+
+ut_asserteq_regex(pattern, str)
+    Assert that a string matches a regular expression pattern. Uses the SLRE
+    library for regex matching. Useful when exact matching is fragile, e.g.
+    when output contains line numbers or variable content.
+
+Pointer assertions
+~~~~~~~~~~~~~~~~~~
+
+ut_assertnull(expr)
+    Assert that a pointer is NULL
+
+ut_assertnonnull(expr)
+    Assert that a pointer is not NULL
+
+ut_assertok_ptr(expr)
+    Assert that a pointer is not an error pointer (checked with IS_ERR())
+
+Console output assertions
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+These are used to check console output when ``UTF_CONSOLE`` flag is set.
+
+ut_assert_nextline(fmt, args...)
+    Assert that the next console output line matches the format string
+
+ut_assert_nextlinen(fmt, args...)
+    Assert that the next console output line matches up to the format
+    string length
+
+ut_assert_nextline_regex(pattern)
+    Assert that the next console output line matches a regex pattern
+
+ut_assert_nextline_empty()
+    Assert that the next console output line is empty
+
+ut_assert_skipline()
+    Assert that there is a next console output line, and skip it
+
+ut_assert_skip_to_line(fmt, args...)
+    Skip console output until a matching line is found
+
+ut_assert_skip_to_linen(fmt, args...)
+    Skip console output until a partial match is found (compares up to the
+    format-string length)
+
+ut_assert_console_end()
+    Assert that there is no more console output
+
+ut_assert_nextlines_are_dump(total_bytes)
+    Assert that the next lines are a print_buffer() hex dump of the specified
+    size
+
+Memory helpers
+~~~~~~~~~~~~~~
+
+These help check for memory leaks:
+
+ut_check_free()
+    Return the number of bytes free in the malloc() pool
+
+ut_check_delta(last)
+    Return the change in free memory since ``last`` was obtained from
+    ``ut_check_free()``. A positive value means more memory has been allocated.
+
+Private buffer
+~~~~~~~~~~~~~~
+
+Each test has access to a private buffer ``uts->priv`` (256 bytes) for temporary
+data. This avoids the need to allocate memory or use global variables::
+
+   static int my_test(struct unit_test_state *uts)
+   {
+      snprintf(uts->priv, sizeof(uts->priv), "/%s", filename);
+      /* use uts->priv as a path string */
+
+      return 0;
+   }
+
+
 Writing Python tests
 --------------------
 
doc/usage/cmd/ut.rst +9 -2
index d8c3cbf496c..a26ee6ad7de 100644
@@ -11,7 +11,7 @@ Synopsis
 
 ::
 
-    ut [-r<runs>] [-f] [-I<n>:<one_test>] [<suite> | all [<test>]] [<args>...]
+    ut [-r<runs>] [-f] [-R] [-I<n>:<one_test>] [<suite> | all [<test>]] [<args>...]
     ut [-s] info
 
 Description
@@ -37,10 +37,17 @@ test
     causes another test to fail. If the one test fails, testing stops
     immediately.
 
+-R
+    Preserve console recording on test failure. Normally when a test fails,
+    console recording is disabled so error messages go directly to output.
+    This flag keeps recording enabled, which is useful when testing the test
+    framework itself.
+
 args
     Optional arguments to pass to the test, in `name=value` format. These are
     used by tests declared with `UNIT_TEST_ARGS()` which define expected
-    argument names and types.
+    argument names and types. See :ref:`develop/tests_writing:passing arguments
+    to c tests` for details.
 
 Typically the command is run on :ref:`arch/sandbox/sandbox:sandbox` since it
 includes a near-complete set of emulators, no code-size limits, many CONFIG
Signature · 1 line
2.43.0
#11 lore raw

PATCH v2 11/12 test: fs: add C-based filesystem tests

In reply to Simon Glass

Add C implementations of filesystem tests that can be called via the 'ut fs' command. These tests use UTF_MANUAL flag since they require external setup, i.e. creation of filesystem images.

This covers the existing TestFsBasic tests.

The tests use typed arguments (fs_type, fs_image, md5 values) passed via the command line.

Add a few helpers to make the code easier to read.

---

(no changes since v1)

 include/test/fs.h  |  39 +++++
 test/Makefile      |   1 +
 test/cmd_ut.c      |   2 +
 test/fs/Makefile   |   3 +
 test/fs/fs_basic.c | 407 +++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 452 insertions(+)
 create mode 100644 include/test/fs.h
 create mode 100644 test/fs/Makefile
 create mode 100644 test/fs/fs_basic.c
include/test/fs.h new file +39 -0
new file mode 100644
index 00000000000..7fdb8d70451
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * Copyright 2026 Canonical Ltd
+ */
+
+#ifndef __TEST_FS_H
+#define __TEST_FS_H
+
+#include <test/test.h>
+#include <test/ut.h>
+
+/**
+ * FS_TEST() - Define a new filesystem test
+ *
+ * @name:	Name of test function
+ * @flags:	Flags for the test (see enum ut_flags)
+ */
+#define FS_TEST(_name, _flags)	UNIT_TEST(_name, UTF_DM | (_flags), fs)
+
+/**
+ * FS_TEST_ARGS() - Define a filesystem test with inline arguments
+ *
+ * Like FS_TEST() but for tests that take arguments.
+ * The test can access arguments via uts->args[].
+ * The NULL terminator is added automatically.
+ *
+ * Example:
+ *   FS_TEST_ARGS(my_test, UTF_MANUAL,
+ *       { "fs_type", UT_ARG_STR },
+ *       { "fs_image", UT_ARG_STR });
+ *
+ * @name:	Name of test function
+ * @flags:	Flags for the test (see enum ut_flags)
+ * @...:	Argument definitions (struct ut_arg_def initializers)
+ */
+#define FS_TEST_ARGS(_name, _flags, ...) \
+	UNIT_TEST_ARGS(_name, UTF_DM | (_flags), fs, __VA_ARGS__)
+
+#endif /* __TEST_FS_H */
test/Makefile +1 -0
index 5676bd35963..02ded045995 100644
@@ -22,6 +22,7 @@ obj-y += boot/
 obj-y += common/
 obj-$(CONFIG_UT_ENV) += env/
 obj-$(CONFIG_UT_FDT_OVERLAY) += fdt_overlay/
+obj-$(CONFIG_SANDBOX) += fs/
 obj-y += log/
 else
 obj-$(CONFIG_SPL_UT_LOAD) += image/
test/cmd_ut.c +2 -0
index 9d36bd5dc87..827fcbc9fcb 100644
@@ -60,6 +60,7 @@ SUITE_DECL(exit);
 SUITE_DECL(fdt);
 SUITE_DECL(fdt_overlay);
 SUITE_DECL(font);
+SUITE_DECL(fs);
 SUITE_DECL(hush);
 SUITE_DECL(lib);
 SUITE_DECL(loadm);
@@ -87,6 +88,7 @@ static struct suite suites[] = {
 	SUITE(fdt, "fdt command"),
 	SUITE(fdt_overlay, "device tree overlays"),
 	SUITE(font, "font command"),
+	SUITE(fs, "filesystem tests"),
 	SUITE(hush, "hush behaviour"),
 	SUITE(lib, "library functions"),
 	SUITE(loadm, "loadm command parameters and loading memory blob"),
test/fs/Makefile new file +3 -0
new file mode 100644
index 00000000000..5899be8e667
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0+
+
+obj-y += fs_basic.o
test/fs/fs_basic.c new file +407 -0

407 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw

PATCH v2 12/12 test: fs: Update Python tests to call C implementations

In reply to Simon Glass

Update test_basic.py to call the new C-based filesystem tests via the 'ut' command. This allows tests to run more directly, calling the actual FS layer, without having to go through the command interface and worrying about which filesystem command to use.

---

(no changes since v1)

 test/py/tests/test_fs/conftest.py   |   4 +-
 test/py/tests/test_fs/test_basic.py | 346 ++++++++--------------------
 2 files changed, 98 insertions(+), 252 deletions(-)
test/py/tests/test_fs/conftest.py +1 -3
index 0205048e73a..5fc796097e3 100644
@@ -198,8 +198,6 @@ def fs_obj_basic(request, u_boot_config):
         volume file name and  a list of MD5 hashes.
     """
     fs_type = request.param
-    fs_cmd_prefix = fstype_to_prefix(fs_type)
-    fs_cmd_write = 'save' if fs_type == 'fs_generic' or fs_type == 'exfat' else 'write'
     fs_img = ''
 
     fs_ubtype = fstype_to_ubname(fs_type)
@@ -289,7 +287,7 @@ def fs_obj_basic(request, u_boot_config):
         pytest.skip('Setup failed for filesystem: ' + fs_type + '. {}'.format(err))
         return
     else:
-        yield [fs_ubtype, fs_cmd_prefix, fs_cmd_write, fs_img, md5val]
+        yield [fs_ubtype, fs_img, md5val]
     finally:
         call('rm -rf %s' % scratch_dir, shell=True)
         call('rm -f %s' % fs_img, shell=True)
test/py/tests/test_fs/test_basic.py +97 -249

395 lines not on this page · raw message

Signature · 1 line
2.43.0
#13 lore raw
In reply to Simon Glass
Quoted 52 lines · Simon Glass

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

- Python lacks access to things like return codes and has to scan the console output to figure out what happened
- Python lacks access to internal state, so it cannot directly check the result of an operation
- Python is ~100x slower due to console interaction, etc.
- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

This series adds infrastructure for passing typed, runtime arguments from Python to C unit tests, using a name=value format on the ut command line.

The series includes:

- Regex assertion helpers for matching variable output in tests

- A private buffer in unit_test_state for test-local temporary data

- Argument-type definitions (string, integer, boolean) with optional flags and default values

- A new UNIT_TEST_ARGS() macro for declaring tests with typed arguments

- Argument parsing in the test framework, accepting name=value format

- Updates to the ut command to pass arguments through to tests

- Type-checked accessor macros ut_str(), ut_int(), and ut_bool() with bounds validation

- Tests for the argument feature covering type checking, optional arguments, and argument-parsing failures

- Documentation for the test-parameter feature

- C-based filesystem tests as an example of the hybrid approach, with Python wrappers that pass filesystem type, image path, and expected MD5 values to the C tests

Quoted 6 lines

Note: This series depends on:

   https://patchwork.ozlabs.org/project/uboot/list/?series=496972

Changes in v2:
- Correct double signoff

Reposting a series this large, on the weekend, the day after v1, because you made a trivial mistake is bad form. You should just acknowledge that in the cover letter and wait for feedback.

And since I'm seeing over 100 emails from you this weekend, this matters.

Signature · 1 line
Tom
#14 lore raw

Hi Tom,

Quoted 57 lines · Tom Rini
Quoted 54 lines · Simon Glass

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

- Python lacks access to things like return codes and has to scan the console output to figure out what happened
- Python lacks access to internal state, so it cannot directly check the result of an operation
- Python is ~100x slower due to console interaction, etc.
- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

This series adds infrastructure for passing typed, runtime arguments from Python to C unit tests, using a name=value format on the ut command line.

The series includes:

- Regex assertion helpers for matching variable output in tests

- A private buffer in unit_test_state for test-local temporary data

- Argument-type definitions (string, integer, boolean) with optional flags and default values

- A new UNIT_TEST_ARGS() macro for declaring tests with typed arguments

- Argument parsing in the test framework, accepting name=value format

- Updates to the ut command to pass arguments through to tests

- Type-checked accessor macros ut_str(), ut_int(), and ut_bool() with bounds validation

- Tests for the argument feature covering type checking, optional arguments, and argument-parsing failures

- Documentation for the test-parameter feature

- C-based filesystem tests as an example of the hybrid approach, with Python wrappers that pass filesystem type, image path, and expected MD5 values to the C tests

Note: This series depends on:

Quoted 8 lines
Quoted 4 lines
   https://patchwork.ozlabs.org/project/uboot/list/?series=496972

Changes in v2:
- Correct double signoff

Reposting a series this large, on the weekend, the day after v1, because you made a trivial mistake is bad form. You should just acknowledge that in the cover letter and wait for feedback.

OK I'll do that if I make this mistake again.

Quoted 2 lines

And since I'm seeing over 100 emails from you this weekend, this matters.

Yes, I was trying to catch up on various things.

Regards,
Simon

#15 lore raw
In reply to Simon Glass
Quoted 8 lines · Simon Glass

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

You still need to work on explaining your changes in a positive manner.

Quoted 2 lines

- Python lacks access to things like return codes and has to scan the console output to figure out what happened

Pro: Python exercises things the way users exercise them and so exposes deficiencies in our user interface as well, when applicable.

Quoted 2 lines

- Python lacks access to internal state, so it cannot directly check the result of an operation

It's unclear when that is, or is not a problem and when tests that do check intermediate state are providing value.

Quoted 1 line

- Python is ~100x slower due to console interaction, etc.

Again, maybe you should go back to your suggestion of several years ago to see about addressing that, as the tests themselves are not slow, it's the pipe? Our brave new AI powered world runs on Python handing stuff off and getting it back super quickly.

Quoted 5 lines

- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

All things that may or may not be problems for other people, or are intentional choices as they again test the system the way it's used. Using gdb attached to u-boot in the other terminal where you're running breaking things sounds like a reasonable debug path to me. And having unit tests calling in to functions is why today we have a lot of things not marked as "static" and so not being optimized as well as they could by the compiler, which is its own set of trade-offs and not an automatic good thing and design win.

[snip]

Quoted 1 line
 16 files changed, 1437 insertions(+), 279 deletions(-)

All of which is to say, you need to explain yourself in a positive, not negative or oppositional way. Otherwise this reads like "I don't like what we do now, here's a bunch of change to what I like instead".

Signature · 1 line
Tom
#16 lore raw

Hi Tom,

Quoted 47 lines · Tom Rini
Quoted 8 lines · Simon Glass

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

You still need to work on explaining your changes in a positive manner.

Quoted 2 lines

- Python lacks access to things like return codes and has to scan the console output to figure out what happened

Pro: Python exercises things the way users exercise them and so exposes deficiencies in our user interface as well, when applicable.

Quoted 2 lines

- Python lacks access to internal state, so it cannot directly check the result of an operation

It's unclear when that is, or is not a problem and when tests that do check intermediate state are providing value.

Quoted 1 line

- Python is ~100x slower due to console interaction, etc.

Again, maybe you should go back to your suggestion of several years ago to see about addressing that, as the tests themselves are not slow, it's the pipe? Our brave new AI powered world runs on Python handing stuff off and getting it back super quickly.

Quoted 5 lines

- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

All things that may or may not be problems for other people, or are intentional choices as they again test the system the way it's used. Using gdb attached to u-boot in the other terminal where you're running breaking things sounds like a reasonable debug path to me. And having unit tests calling in to functions is why today we have a lot of things not marked as "static" and so not being optimized as well as they could by the compiler, which is its own set of trade-offs and not an automatic good thing and design win.

Quoted 6 lines

[snip]

Quoted 1 line
 16 files changed, 1437 insertions(+), 279 deletions(-)

All of which is to say, you need to explain yourself in a positive, not negative or oppositional way. Otherwise this reads like "I don't like what we do now, here's a bunch of change to what I like instead".

Just to check, is this a discussion and you would like me to reply with more details about the benefits of C over Python in particular circumstances? Or are you wanting the cover-letter rewritten. Or is this just a NAK?

I did some work on using a socket to talk to sandbox (it is faster and also avoids some of the confusion as to what state sandbox is in without having to rely on looking at console output). But I never quite finished it. The other option (which we briefly discussed years ago) would be to build U-Boot as a Python module. I haven't tried that at all, but it's an idea.

I am well aware of the tradeoffs between Python and C, so I am not advocating one over the other in all cases. I use gdb a lot with the pytests - e.g. hunting down memory leaks recent. Really I just want them to coexist better - i.e. improving the sandbox pattern where Python sets something up and then C runs it.

- Simon

#17 lore raw

Hi Tom,

Quoted 70 lines · Simon Glass

Hi Tom,

Quoted 47 lines · Tom Rini
Quoted 8 lines · Simon Glass

Some tests have two parts: a Python test which handles setup, such as creating filesystem images or configuring the environment, and a C test which does the bulk of the work including assertions. At present there is no way to pass information between these two parts, so things like paths and device names must be hard-coded in the C test.

This tends to make people write tests in Python, but this is not ideal for several reasons:

You still need to work on explaining your changes in a positive manner.

Quoted 2 lines

- Python lacks access to things like return codes and has to scan the console output to figure out what happened

Pro: Python exercises things the way users exercise them and so exposes deficiencies in our user interface as well, when applicable.

Quoted 2 lines

- Python lacks access to internal state, so it cannot directly check the result of an operation

It's unclear when that is, or is not a problem and when tests that do check intermediate state are providing value.

Quoted 1 line

- Python is ~100x slower due to console interaction, etc.

Again, maybe you should go back to your suggestion of several years ago to see about addressing that, as the tests themselves are not slow, it's the pipe? Our brave new AI powered world runs on Python handing stuff off and getting it back super quickly.

Quoted 5 lines

- C tests can be stepped through in gdb, which is much harder with Python driving the console
- C tests can exercise internal APIs directly (e.g. fs_read(), fs_size()) rather than going through the command layer, so they test more precisely what they intend to

All things that may or may not be problems for other people, or are intentional choices as they again test the system the way it's used. Using gdb attached to u-boot in the other terminal where you're running breaking things sounds like a reasonable debug path to me. And having unit tests calling in to functions is why today we have a lot of things not marked as "static" and so not being optimized as well as they could by the compiler, which is its own set of trade-offs and not an automatic good thing and design win.

Quoted 6 lines

[snip]

Quoted 1 line
 16 files changed, 1437 insertions(+), 279 deletions(-)

All of which is to say, you need to explain yourself in a positive, not negative or oppositional way. Otherwise this reads like "I don't like what we do now, here's a bunch of change to what I like instead".

Just to check, is this a discussion and you would like me to reply with more details about the benefits of C over Python in particular circumstances? Or are you wanting the cover-letter rewritten. Or is this just a NAK?

I did some work on using a socket to talk to sandbox (it is faster and also avoids some of the confusion as to what state sandbox is in without having to rely on looking at console output). But I never quite finished it. The other option (which we briefly discussed years ago) would be to build U-Boot as a Python module. I haven't tried that at all, but it's an idea.

Quoted 6 lines

I am well aware of the tradeoffs between Python and C, so I am not advocating one over the other in all cases. I use gdb a lot with the pytests - e.g. hunting down memory leaks recent. Really I just want them to coexist better - i.e. improving the sandbox pattern where Python sets something up and then C runs it.

I see that this series is marked 'deferred'. Does that mean rejected, or is there something you are waiting on. I believe this (or something like it) is an important new feature for testing.

Regards,
SImon