xref: /linux/lib/kunit/string-stream-test.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KUnit test for struct string_stream.
4  *
5  * Copyright (C) 2019, Google LLC.
6  * Author: Brendan Higgins <brendanhiggins@google.com>
7  */
8 
9 #include <kunit/static_stub.h>
10 #include <kunit/test.h>
11 #include <linux/ktime.h>
12 #include <linux/prandom.h>
13 #include <linux/slab.h>
14 #include <linux/timekeeping.h>
15 
16 #include "string-stream.h"
17 
18 struct string_stream_test_priv {
19 	/* For testing resource-managed free. */
20 	struct string_stream *expected_free_stream;
21 	bool stream_was_freed;
22 	bool stream_free_again;
23 };
24 
25 /* Avoids a cast warning if kfree() is passed direct to kunit_add_action(). */
26 KUNIT_DEFINE_ACTION_WRAPPER(kfree_wrapper, kfree, const void *);
27 
28 /* Avoids a cast warning if string_stream_destroy() is passed direct to kunit_add_action(). */
29 KUNIT_DEFINE_ACTION_WRAPPER(cleanup_raw_stream, string_stream_destroy, struct string_stream *);
30 
31 static char *get_concatenated_string(struct kunit *test, struct string_stream *stream)
32 {
33 	char *str = string_stream_get_string(stream);
34 
35 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, str);
36 	kunit_add_action(test, kfree_wrapper, (void *)str);
37 
38 	return str;
39 }
40 
41 /* Managed string_stream object is initialized correctly. */
42 static void string_stream_managed_init_test(struct kunit *test)
43 {
44 	struct string_stream *stream;
45 
46 	/* Resource-managed initialization. */
47 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
48 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
49 
50 	KUNIT_EXPECT_EQ(test, stream->length, 0);
51 	KUNIT_EXPECT_TRUE(test, list_empty(&stream->fragments));
52 	KUNIT_EXPECT_TRUE(test, (stream->gfp == GFP_KERNEL));
53 	KUNIT_EXPECT_FALSE(test, stream->append_newlines);
54 	KUNIT_EXPECT_TRUE(test, string_stream_is_empty(stream));
55 }
56 
57 /* Unmanaged string_stream object is initialized correctly. */
58 static void string_stream_unmanaged_init_test(struct kunit *test)
59 {
60 	struct string_stream *stream;
61 
62 	stream = alloc_string_stream(GFP_KERNEL);
63 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
64 	kunit_add_action(test, cleanup_raw_stream, stream);
65 
66 	KUNIT_EXPECT_EQ(test, stream->length, 0);
67 	KUNIT_EXPECT_TRUE(test, list_empty(&stream->fragments));
68 	KUNIT_EXPECT_TRUE(test, (stream->gfp == GFP_KERNEL));
69 	KUNIT_EXPECT_FALSE(test, stream->append_newlines);
70 
71 	KUNIT_EXPECT_TRUE(test, string_stream_is_empty(stream));
72 }
73 
74 static void string_stream_destroy_stub(struct string_stream *stream)
75 {
76 	struct kunit *fake_test = kunit_get_current_test();
77 	struct string_stream_test_priv *priv = fake_test->priv;
78 
79 	/* The kunit could own string_streams other than the one we are testing. */
80 	if (stream == priv->expected_free_stream) {
81 		if (priv->stream_was_freed)
82 			priv->stream_free_again = true;
83 		else
84 			priv->stream_was_freed = true;
85 	}
86 
87 	/*
88 	 * Calling string_stream_destroy() will only call this function again
89 	 * because the redirection stub is still active.
90 	 * Avoid calling deactivate_static_stub() or changing current->kunit_test
91 	 * during cleanup.
92 	 */
93 	string_stream_clear(stream);
94 	kfree(stream);
95 }
96 
97 /* kunit_free_string_stream() calls string_stream_desrtoy() */
98 static void string_stream_managed_free_test(struct kunit *test)
99 {
100 	struct string_stream_test_priv *priv = test->priv;
101 
102 	priv->expected_free_stream = NULL;
103 	priv->stream_was_freed = false;
104 	priv->stream_free_again = false;
105 
106 	kunit_activate_static_stub(test,
107 				   string_stream_destroy,
108 				   string_stream_destroy_stub);
109 
110 	priv->expected_free_stream = kunit_alloc_string_stream(test, GFP_KERNEL);
111 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, priv->expected_free_stream);
112 
113 	/* This should call the stub function. */
114 	kunit_free_string_stream(test, priv->expected_free_stream);
115 
116 	KUNIT_EXPECT_TRUE(test, priv->stream_was_freed);
117 	KUNIT_EXPECT_FALSE(test, priv->stream_free_again);
118 }
119 
120 /* string_stream object is freed when test is cleaned up. */
121 static void string_stream_resource_free_test(struct kunit *test)
122 {
123 	struct string_stream_test_priv *priv = test->priv;
124 	struct kunit *fake_test;
125 
126 	fake_test = kunit_kzalloc(test, sizeof(*fake_test), GFP_KERNEL);
127 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, fake_test);
128 
129 	kunit_init_test(fake_test, "string_stream_fake_test", NULL);
130 	fake_test->priv = priv;
131 
132 	/*
133 	 * Activate stub before creating string_stream so the
134 	 * string_stream will be cleaned up first.
135 	 */
136 	priv->expected_free_stream = NULL;
137 	priv->stream_was_freed = false;
138 	priv->stream_free_again = false;
139 
140 	kunit_activate_static_stub(fake_test,
141 				   string_stream_destroy,
142 				   string_stream_destroy_stub);
143 
144 	priv->expected_free_stream = kunit_alloc_string_stream(fake_test, GFP_KERNEL);
145 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, priv->expected_free_stream);
146 
147 	/* Set current->kunit_test to fake_test so the static stub will be called. */
148 	current->kunit_test = fake_test;
149 
150 	/* Cleanup test - the stub function should be called */
151 	kunit_cleanup(fake_test);
152 
153 	/* Set current->kunit_test back to current test. */
154 	current->kunit_test = test;
155 
156 	KUNIT_EXPECT_TRUE(test, priv->stream_was_freed);
157 	KUNIT_EXPECT_FALSE(test, priv->stream_free_again);
158 }
159 
160 /*
161  * Add a series of lines to a string_stream. Check that all lines
162  * appear in the correct order and no characters are dropped.
163  */
164 static void string_stream_line_add_test(struct kunit *test)
165 {
166 	struct string_stream *stream;
167 	char line[60];
168 	char *concat_string, *pos, *string_end;
169 	size_t len, total_len;
170 	int num_lines, i;
171 
172 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
173 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
174 
175 	/* Add series of sequence numbered lines */
176 	total_len = 0;
177 	for (i = 0; i < 100; ++i) {
178 		len = snprintf(line, sizeof(line),
179 			"The quick brown fox jumps over the lazy penguin %d\n", i);
180 
181 		/* Sanity-check that our test string isn't truncated */
182 		KUNIT_ASSERT_LT(test, len, sizeof(line));
183 
184 		string_stream_add(stream, line);
185 		total_len += len;
186 	}
187 	num_lines = i;
188 
189 	concat_string = get_concatenated_string(test, stream);
190 	KUNIT_EXPECT_NOT_ERR_OR_NULL(test, concat_string);
191 	KUNIT_EXPECT_EQ(test, strlen(concat_string), total_len);
192 
193 	/*
194 	 * Split the concatenated string at the newlines and check that
195 	 * all the original added strings are present.
196 	 */
197 	pos = concat_string;
198 	for (i = 0; i < num_lines; ++i) {
199 		string_end = strchr(pos, '\n');
200 		KUNIT_EXPECT_NOT_NULL(test, string_end);
201 
202 		/* Convert to NULL-terminated string */
203 		*string_end = '\0';
204 
205 		snprintf(line, sizeof(line),
206 			 "The quick brown fox jumps over the lazy penguin %d", i);
207 		KUNIT_EXPECT_STREQ(test, pos, line);
208 
209 		pos = string_end + 1;
210 	}
211 
212 	/* There shouldn't be any more data after this */
213 	KUNIT_EXPECT_EQ(test, strlen(pos), 0);
214 }
215 
216 /* Add a series of lines of variable length to a string_stream. */
217 static void string_stream_variable_length_line_test(struct kunit *test)
218 {
219 	static const char line[] =
220 		"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
221 		" 0123456789!$%^&*()_-+={}[]:;@'~#<>,.?/|";
222 	struct string_stream *stream;
223 	struct rnd_state rnd;
224 	char *concat_string, *pos, *string_end;
225 	size_t offset, total_len;
226 	int num_lines, i;
227 
228 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
229 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
230 
231 	/*
232 	 * Log many lines of varying lengths until we have created
233 	 * many fragments.
234 	 * The "randomness" must be repeatable.
235 	 */
236 	prandom_seed_state(&rnd, 3141592653589793238ULL);
237 	total_len = 0;
238 	for (i = 0; i < 100; ++i) {
239 		offset = prandom_u32_state(&rnd) % (sizeof(line) - 1);
240 		string_stream_add(stream, "%s\n", &line[offset]);
241 		total_len += sizeof(line) - offset;
242 	}
243 	num_lines = i;
244 
245 	concat_string = get_concatenated_string(test, stream);
246 	KUNIT_EXPECT_NOT_ERR_OR_NULL(test, concat_string);
247 	KUNIT_EXPECT_EQ(test, strlen(concat_string), total_len);
248 
249 	/*
250 	 * Split the concatenated string at the newlines and check that
251 	 * all the original added strings are present.
252 	 */
253 	prandom_seed_state(&rnd, 3141592653589793238ULL);
254 	pos = concat_string;
255 	for (i = 0; i < num_lines; ++i) {
256 		string_end = strchr(pos, '\n');
257 		KUNIT_EXPECT_NOT_NULL(test, string_end);
258 
259 		/* Convert to NULL-terminated string */
260 		*string_end = '\0';
261 
262 		offset = prandom_u32_state(&rnd) % (sizeof(line) - 1);
263 		KUNIT_EXPECT_STREQ(test, pos, &line[offset]);
264 
265 		pos = string_end + 1;
266 	}
267 
268 	/* There shouldn't be any more data after this */
269 	KUNIT_EXPECT_EQ(test, strlen(pos), 0);
270 }
271 
272 /* Appending the content of one string stream to another. */
273 static void string_stream_append_test(struct kunit *test)
274 {
275 	static const char * const strings_1[] = {
276 		"one", "two", "three", "four", "five", "six",
277 		"seven", "eight", "nine", "ten",
278 	};
279 	static const char * const strings_2[] = {
280 		"Apple", "Pear", "Orange", "Banana", "Grape", "Apricot",
281 	};
282 	struct string_stream *stream_1, *stream_2;
283 	const char *stream1_content_before_append, *stream_2_content;
284 	char *combined_content;
285 	size_t combined_length;
286 	int i;
287 
288 	stream_1 = kunit_alloc_string_stream(test, GFP_KERNEL);
289 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_1);
290 
291 	stream_2 = kunit_alloc_string_stream(test, GFP_KERNEL);
292 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_2);
293 
294 	/* Append content of empty stream to empty stream */
295 	string_stream_append(stream_1, stream_2);
296 	KUNIT_EXPECT_EQ(test, strlen(get_concatenated_string(test, stream_1)), 0);
297 
298 	/* Add some data to stream_1 */
299 	for (i = 0; i < ARRAY_SIZE(strings_1); ++i)
300 		string_stream_add(stream_1, "%s\n", strings_1[i]);
301 
302 	stream1_content_before_append = get_concatenated_string(test, stream_1);
303 
304 	/* Append content of empty stream to non-empty stream */
305 	string_stream_append(stream_1, stream_2);
306 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream_1),
307 			   stream1_content_before_append);
308 
309 	/* Add some data to stream_2 */
310 	for (i = 0; i < ARRAY_SIZE(strings_2); ++i)
311 		string_stream_add(stream_2, "%s\n", strings_2[i]);
312 
313 	/* Append content of non-empty stream to non-empty stream */
314 	string_stream_append(stream_1, stream_2);
315 
316 	/*
317 	 * End result should be the original content of stream_1 plus
318 	 * the content of stream_2.
319 	 */
320 	stream_2_content = get_concatenated_string(test, stream_2);
321 	combined_length = strlen(stream1_content_before_append) + strlen(stream_2_content);
322 	combined_length++; /* for terminating \0 */
323 	combined_content = kunit_kmalloc(test, combined_length, GFP_KERNEL);
324 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, combined_content);
325 	snprintf(combined_content, combined_length, "%s%s",
326 		 stream1_content_before_append, stream_2_content);
327 
328 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream_1), combined_content);
329 
330 	/* Append content of non-empty stream to empty stream */
331 	kunit_free_string_stream(test, stream_1);
332 
333 	stream_1 = kunit_alloc_string_stream(test, GFP_KERNEL);
334 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_1);
335 
336 	string_stream_append(stream_1, stream_2);
337 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream_1), stream_2_content);
338 }
339 
340 /* Appending the content of one string stream to one with auto-newlining. */
341 static void string_stream_append_auto_newline_test(struct kunit *test)
342 {
343 	struct string_stream *stream_1, *stream_2;
344 
345 	/* Stream 1 has newline appending enabled */
346 	stream_1 = kunit_alloc_string_stream(test, GFP_KERNEL);
347 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_1);
348 	string_stream_set_append_newlines(stream_1, true);
349 	KUNIT_EXPECT_TRUE(test, stream_1->append_newlines);
350 
351 	/* Stream 2 does not append newlines */
352 	stream_2 = kunit_alloc_string_stream(test, GFP_KERNEL);
353 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_2);
354 
355 	/* Appending a stream with a newline should not add another newline */
356 	string_stream_add(stream_1, "Original string\n");
357 	string_stream_add(stream_2, "Appended content\n");
358 	string_stream_add(stream_2, "More stuff\n");
359 	string_stream_append(stream_1, stream_2);
360 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream_1),
361 			   "Original string\nAppended content\nMore stuff\n");
362 
363 	kunit_free_string_stream(test, stream_2);
364 	stream_2 = kunit_alloc_string_stream(test, GFP_KERNEL);
365 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream_2);
366 
367 	/*
368 	 * Appending a stream without newline should add a final newline.
369 	 * The appended string_stream is treated as a single string so newlines
370 	 * should not be inserted between fragments.
371 	 */
372 	string_stream_add(stream_2, "Another");
373 	string_stream_add(stream_2, "And again");
374 	string_stream_append(stream_1, stream_2);
375 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream_1),
376 			   "Original string\nAppended content\nMore stuff\nAnotherAnd again\n");
377 }
378 
379 /* Adding an empty string should not create a fragment. */
380 static void string_stream_append_empty_string_test(struct kunit *test)
381 {
382 	struct string_stream *stream;
383 	int original_frag_count;
384 
385 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
386 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
387 
388 	/* Formatted empty string */
389 	string_stream_add(stream, "%s", "");
390 	KUNIT_EXPECT_TRUE(test, string_stream_is_empty(stream));
391 	KUNIT_EXPECT_TRUE(test, list_empty(&stream->fragments));
392 
393 	/* Adding an empty string to a non-empty stream */
394 	string_stream_add(stream, "Add this line");
395 	original_frag_count = list_count_nodes(&stream->fragments);
396 
397 	string_stream_add(stream, "%s", "");
398 	KUNIT_EXPECT_EQ(test, list_count_nodes(&stream->fragments), original_frag_count);
399 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream), "Add this line");
400 }
401 
402 /* Adding strings without automatic newline appending */
403 static void string_stream_no_auto_newline_test(struct kunit *test)
404 {
405 	struct string_stream *stream;
406 
407 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
408 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
409 
410 	/*
411 	 * Add some strings with and without newlines. All formatted newlines
412 	 * should be preserved. It should not add any extra newlines.
413 	 */
414 	string_stream_add(stream, "One");
415 	string_stream_add(stream, "Two\n");
416 	string_stream_add(stream, "%s\n", "Three");
417 	string_stream_add(stream, "%s", "Four\n");
418 	string_stream_add(stream, "Five\n%s", "Six");
419 	string_stream_add(stream, "Seven\n\n");
420 	string_stream_add(stream, "Eight");
421 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream),
422 			   "OneTwo\nThree\nFour\nFive\nSixSeven\n\nEight");
423 }
424 
425 /* Adding strings with automatic newline appending */
426 static void string_stream_auto_newline_test(struct kunit *test)
427 {
428 	struct string_stream *stream;
429 
430 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
431 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
432 
433 	string_stream_set_append_newlines(stream, true);
434 	KUNIT_EXPECT_TRUE(test, stream->append_newlines);
435 
436 	/*
437 	 * Add some strings with and without newlines. Newlines should
438 	 * be appended to lines that do not end with \n, but newlines
439 	 * resulting from the formatting should not be changed.
440 	 */
441 	string_stream_add(stream, "One");
442 	string_stream_add(stream, "Two\n");
443 	string_stream_add(stream, "%s\n", "Three");
444 	string_stream_add(stream, "%s", "Four\n");
445 	string_stream_add(stream, "Five\n%s", "Six");
446 	string_stream_add(stream, "Seven\n\n");
447 	string_stream_add(stream, "Eight");
448 	KUNIT_EXPECT_STREQ(test, get_concatenated_string(test, stream),
449 			   "One\nTwo\nThree\nFour\nFive\nSix\nSeven\n\nEight\n");
450 }
451 
452 /*
453  * This doesn't actually "test" anything. It reports time taken
454  * and memory used for logging a large number of lines.
455  */
456 static void string_stream_performance_test(struct kunit *test)
457 {
458 	struct string_stream_fragment *frag_container;
459 	struct string_stream *stream;
460 	char test_line[101];
461 	ktime_t start_time, end_time;
462 	size_t len, bytes_requested, actual_bytes_used, total_string_length;
463 	int offset, i;
464 
465 	stream = kunit_alloc_string_stream(test, GFP_KERNEL);
466 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, stream);
467 
468 	memset(test_line, 'x', sizeof(test_line) - 1);
469 	test_line[sizeof(test_line) - 1] = '\0';
470 
471 	start_time = ktime_get();
472 	for (i = 0; i < 10000; i++) {
473 		offset = i % (sizeof(test_line) - 1);
474 		string_stream_add(stream, "%s: %d\n", &test_line[offset], i);
475 	}
476 	end_time = ktime_get();
477 
478 	/*
479 	 * Calculate memory used. This doesn't include invisible
480 	 * overhead due to kernel allocator fragment size rounding.
481 	 */
482 	bytes_requested = sizeof(*stream);
483 	actual_bytes_used = ksize(stream);
484 	total_string_length = 0;
485 
486 	list_for_each_entry(frag_container, &stream->fragments, node) {
487 		bytes_requested += sizeof(*frag_container);
488 		actual_bytes_used += ksize(frag_container);
489 
490 		len = strlen(frag_container->fragment);
491 		total_string_length += len;
492 		bytes_requested += len + 1; /* +1 for '\0' */
493 		actual_bytes_used += ksize(frag_container->fragment);
494 	}
495 
496 	kunit_info(test, "Time elapsed:           %lld us\n",
497 		   ktime_us_delta(end_time, start_time));
498 	kunit_info(test, "Total string length:    %zu\n", total_string_length);
499 	kunit_info(test, "Bytes requested:        %zu\n", bytes_requested);
500 	kunit_info(test, "Actual bytes allocated: %zu\n", actual_bytes_used);
501 }
502 
503 static int string_stream_test_init(struct kunit *test)
504 {
505 	struct string_stream_test_priv *priv;
506 
507 	priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL);
508 	if (!priv)
509 		return -ENOMEM;
510 
511 	test->priv = priv;
512 
513 	return 0;
514 }
515 
516 static struct kunit_case string_stream_test_cases[] = {
517 	KUNIT_CASE(string_stream_managed_init_test),
518 	KUNIT_CASE(string_stream_unmanaged_init_test),
519 	KUNIT_CASE(string_stream_managed_free_test),
520 	KUNIT_CASE(string_stream_resource_free_test),
521 	KUNIT_CASE(string_stream_line_add_test),
522 	KUNIT_CASE(string_stream_variable_length_line_test),
523 	KUNIT_CASE(string_stream_append_test),
524 	KUNIT_CASE(string_stream_append_auto_newline_test),
525 	KUNIT_CASE(string_stream_append_empty_string_test),
526 	KUNIT_CASE(string_stream_no_auto_newline_test),
527 	KUNIT_CASE(string_stream_auto_newline_test),
528 	KUNIT_CASE(string_stream_performance_test),
529 	{}
530 };
531 
532 static struct kunit_suite string_stream_test_suite = {
533 	.name = "string-stream-test",
534 	.test_cases = string_stream_test_cases,
535 	.init = string_stream_test_init,
536 };
537 kunit_test_suites(&string_stream_test_suite);
538