Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

kunit: make KUNIT_EXPECT_STREQ() quote values, don't print literals

Before:
> Expected str == "world", but
> str == hello
> "world" == world

After:
> Expected str == "world", but
> str == "hello"
<we don't need to tell the user that "world" == "world">

Note: like the literal ellision for integers, this doesn't handle the
case of
KUNIT_EXPECT_STREQ(test, "hello", "world")
since we don't expect it to realistically happen in checked in tests.
(If you really wanted a test to fail, KUNIT_FAIL("msg") exists)

In that case, you'd get:
> Expected "hello" == "world", but
<output for next failure>

Signed-off-by: Daniel Latypov <dlatypov@google.com>
Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

authored by

Daniel Latypov and committed by
Shuah Khan
acd97625 2f9f21cd

+24 -6
+24 -6
lib/kunit/assert.c
··· 163 163 } 164 164 EXPORT_SYMBOL_GPL(kunit_binary_ptr_assert_format); 165 165 166 + /* Checks if KUNIT_EXPECT_STREQ() args were string literals. 167 + * Note: `text` will have ""s where as `value` will not. 168 + */ 169 + static bool is_str_literal(const char *text, const char *value) 170 + { 171 + int len; 172 + 173 + len = strlen(text); 174 + if (len < 2) 175 + return false; 176 + if (text[0] != '\"' || text[len - 1] != '\"') 177 + return false; 178 + 179 + return strncmp(text + 1, value, len - 2) == 0; 180 + } 181 + 166 182 void kunit_binary_str_assert_format(const struct kunit_assert *assert, 167 183 struct string_stream *stream) 168 184 { ··· 193 177 binary_assert->left_text, 194 178 binary_assert->operation, 195 179 binary_assert->right_text); 196 - string_stream_add(stream, KUNIT_SUBSUBTEST_INDENT "%s == %s\n", 197 - binary_assert->left_text, 198 - binary_assert->left_value); 199 - string_stream_add(stream, KUNIT_SUBSUBTEST_INDENT "%s == %s", 200 - binary_assert->right_text, 201 - binary_assert->right_value); 180 + if (!is_str_literal(binary_assert->left_text, binary_assert->left_value)) 181 + string_stream_add(stream, KUNIT_SUBSUBTEST_INDENT "%s == \"%s\"\n", 182 + binary_assert->left_text, 183 + binary_assert->left_value); 184 + if (!is_str_literal(binary_assert->right_text, binary_assert->right_value)) 185 + string_stream_add(stream, KUNIT_SUBSUBTEST_INDENT "%s == \"%s\"", 186 + binary_assert->right_text, 187 + binary_assert->right_value); 202 188 kunit_assert_print_msg(assert, stream); 203 189 } 204 190 EXPORT_SYMBOL_GPL(kunit_binary_str_assert_format);