xref: /linux/tools/testing/kunit/kunit_tool_test.py (revision 85aff81b0dba7c42d226d9f7c11c4d30a7906878)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3#
4# A collection of tests for tools/testing/kunit/kunit.py
5#
6# Copyright (C) 2019, Google LLC.
7# Author: Brendan Higgins <brendanhiggins@google.com>
8
9import unittest
10from unittest import mock
11
12import tempfile, shutil # Handling test_tmpdir
13
14import itertools
15import json
16import os
17import signal
18import subprocess
19from typing import Iterable
20
21import kunit_config
22import kunit_parser
23import kunit_kernel
24import kunit_json
25import kunit
26from kunit_printer import stdout
27
28test_tmpdir = ''
29abs_test_data_dir = ''
30
31def setUpModule():
32	global test_tmpdir, abs_test_data_dir
33	test_tmpdir = tempfile.mkdtemp()
34	abs_test_data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'test_data'))
35
36def tearDownModule():
37	shutil.rmtree(test_tmpdir)
38
39def test_data_path(path):
40	return os.path.join(abs_test_data_dir, path)
41
42class KconfigTest(unittest.TestCase):
43
44	def test_is_subset_of(self):
45		kconfig0 = kunit_config.Kconfig()
46		self.assertTrue(kconfig0.is_subset_of(kconfig0))
47
48		kconfig1 = kunit_config.Kconfig()
49		kconfig1.add_entry('TEST', 'y')
50		self.assertTrue(kconfig1.is_subset_of(kconfig1))
51		self.assertTrue(kconfig0.is_subset_of(kconfig1))
52		self.assertFalse(kconfig1.is_subset_of(kconfig0))
53
54	def test_read_from_file(self):
55		kconfig_path = test_data_path('test_read_from_file.kconfig')
56
57		kconfig = kunit_config.parse_file(kconfig_path)
58
59		expected_kconfig = kunit_config.Kconfig()
60		expected_kconfig.add_entry('UML', 'y')
61		expected_kconfig.add_entry('MMU', 'y')
62		expected_kconfig.add_entry('TEST', 'y')
63		expected_kconfig.add_entry('EXAMPLE_TEST', 'y')
64		expected_kconfig.add_entry('MK8', 'n')
65
66		self.assertEqual(kconfig, expected_kconfig)
67
68	def test_write_to_file(self):
69		kconfig_path = os.path.join(test_tmpdir, '.config')
70
71		expected_kconfig = kunit_config.Kconfig()
72		expected_kconfig.add_entry('UML', 'y')
73		expected_kconfig.add_entry('MMU', 'y')
74		expected_kconfig.add_entry('TEST', 'y')
75		expected_kconfig.add_entry('EXAMPLE_TEST', 'y')
76		expected_kconfig.add_entry('MK8', 'n')
77
78		expected_kconfig.write_to_file(kconfig_path)
79
80		actual_kconfig = kunit_config.parse_file(kconfig_path)
81		self.assertEqual(actual_kconfig, expected_kconfig)
82
83class KUnitParserTest(unittest.TestCase):
84	def setUp(self):
85		self.print_mock = mock.patch('kunit_printer.Printer.print').start()
86		self.addCleanup(mock.patch.stopall)
87
88	def noPrintCallContains(self, substr: str):
89		for call in self.print_mock.mock_calls:
90			self.assertNotIn(substr, call.args[0])
91
92	def assertContains(self, needle: str, haystack: kunit_parser.LineStream):
93		# Clone the iterator so we can print the contents on failure.
94		copy, backup = itertools.tee(haystack)
95		for line in copy:
96			if needle in line:
97				return
98		raise AssertionError(f'"{needle}" not found in {list(backup)}!')
99
100	def test_output_isolated_correctly(self):
101		log_path = test_data_path('test_output_isolated_correctly.log')
102		with open(log_path) as file:
103			result = kunit_parser.extract_tap_lines(file.readlines())
104		self.assertContains('TAP version 14', result)
105		self.assertContains('# Subtest: example', result)
106		self.assertContains('1..2', result)
107		self.assertContains('ok 1 - example_simple_test', result)
108		self.assertContains('ok 2 - example_mock_test', result)
109		self.assertContains('ok 1 - example', result)
110
111	def test_output_with_prefix_isolated_correctly(self):
112		log_path = test_data_path('test_pound_sign.log')
113		with open(log_path) as file:
114			result = kunit_parser.extract_tap_lines(file.readlines())
115		self.assertContains('TAP version 14', result)
116		self.assertContains('# Subtest: kunit-resource-test', result)
117		self.assertContains('1..5', result)
118		self.assertContains('ok 1 - kunit_resource_test_init_resources', result)
119		self.assertContains('ok 2 - kunit_resource_test_alloc_resource', result)
120		self.assertContains('ok 3 - kunit_resource_test_destroy_resource', result)
121		self.assertContains('foo bar 	#', result)
122		self.assertContains('ok 4 - kunit_resource_test_cleanup_resources', result)
123		self.assertContains('ok 5 - kunit_resource_test_proper_free_ordering', result)
124		self.assertContains('ok 1 - kunit-resource-test', result)
125		self.assertContains('foo bar 	# non-kunit output', result)
126		self.assertContains('# Subtest: kunit-try-catch-test', result)
127		self.assertContains('1..2', result)
128		self.assertContains('ok 1 - kunit_test_try_catch_successful_try_no_catch',
129				    result)
130		self.assertContains('ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch',
131				    result)
132		self.assertContains('ok 2 - kunit-try-catch-test', result)
133		self.assertContains('# Subtest: string-stream-test', result)
134		self.assertContains('1..3', result)
135		self.assertContains('ok 1 - string_stream_test_empty_on_creation', result)
136		self.assertContains('ok 2 - string_stream_test_not_empty_after_add', result)
137		self.assertContains('ok 3 - string_stream_test_get_string', result)
138		self.assertContains('ok 3 - string-stream-test', result)
139
140	def test_parse_successful_test_log(self):
141		all_passed_log = test_data_path('test_is_test_passed-all_passed.log')
142		with open(all_passed_log) as file:
143			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
144		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
145		self.assertEqual(result.counts.errors, 0)
146
147	def test_parse_successful_nested_tests_log(self):
148		all_passed_log = test_data_path('test_is_test_passed-all_passed_nested.log')
149		with open(all_passed_log) as file:
150			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
151		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
152		self.assertEqual(result.counts.errors, 0)
153
154	def test_kselftest_nested(self):
155		kselftest_log = test_data_path('test_is_test_passed-kselftest.log')
156		with open(kselftest_log) as file:
157			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
158		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
159		self.assertEqual(result.counts.errors, 0)
160
161	def test_parse_failed_test_log(self):
162		failed_log = test_data_path('test_is_test_passed-failure.log')
163		with open(failed_log) as file:
164			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
165		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
166		self.assertEqual(result.counts.errors, 0)
167
168	def test_parse_failed_nested_tests_log(self):
169		nested_log = test_data_path('test_is_test_passed-failure-nested.log')
170		with open(nested_log) as file:
171			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
172		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
173		self.assertEqual(result.counts.failed, 2)
174		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[0].status)
175		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.subtests[0].subtests[0].status)
176		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[1].status)
177		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[1].subtests[0].status)
178
179	def test_no_header(self):
180		empty_log = test_data_path('test_is_test_passed-no_tests_run_no_header.log')
181		with open(empty_log) as file:
182			result = kunit_parser.parse_run_tests(
183				kunit_parser.extract_tap_lines(file.readlines()), stdout)
184		self.assertEqual(0, len(result.subtests))
185		self.assertEqual(kunit_parser.TestStatus.FAILURE_TO_PARSE_TESTS, result.status)
186		self.assertEqual(result.counts.errors, 1)
187
188	def test_missing_test_plan(self):
189		missing_plan_log = test_data_path('test_is_test_passed-'
190			'missing_plan.log')
191		with open(missing_plan_log) as file:
192			result = kunit_parser.parse_run_tests(
193				kunit_parser.extract_tap_lines(
194				file.readlines()), stdout)
195		# A missing test plan is not an error.
196		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=10, errors=0))
197		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
198
199	def test_no_tests(self):
200		header_log = test_data_path('test_is_test_passed-no_tests_run_with_header.log')
201		with open(header_log) as file:
202			result = kunit_parser.parse_run_tests(
203				kunit_parser.extract_tap_lines(file.readlines()), stdout)
204		self.assertEqual(0, len(result.subtests))
205		self.assertEqual(kunit_parser.TestStatus.NO_TESTS, result.status)
206		self.assertEqual(result.counts.errors, 1)
207
208	def test_no_tests_no_plan(self):
209		no_plan_log = test_data_path('test_is_test_passed-no_tests_no_plan.log')
210		with open(no_plan_log) as file:
211			result = kunit_parser.parse_run_tests(
212				kunit_parser.extract_tap_lines(file.readlines()), stdout)
213		self.assertEqual(0, len(result.subtests[0].subtests[0].subtests))
214		self.assertEqual(
215			kunit_parser.TestStatus.NO_TESTS,
216			result.subtests[0].subtests[0].status)
217		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=1, errors=1))
218
219
220	def test_no_kunit_output(self):
221		crash_log = test_data_path('test_insufficient_memory.log')
222		print_mock = mock.patch('kunit_printer.Printer.print').start()
223		with open(crash_log) as file:
224			result = kunit_parser.parse_run_tests(
225				kunit_parser.extract_tap_lines(file.readlines()), stdout)
226		print_mock.assert_any_call(StrContains('Could not find any KTAP output.'))
227		print_mock.stop()
228		self.assertEqual(0, len(result.subtests))
229		self.assertEqual(result.counts.errors, 1)
230
231	def test_skipped_test(self):
232		skipped_log = test_data_path('test_skip_tests.log')
233		with open(skipped_log) as file:
234			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
235
236		# A skipped test does not fail the whole suite.
237		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
238		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=4, skipped=1))
239
240	def test_skipped_all_tests(self):
241		skipped_log = test_data_path('test_skip_all_tests.log')
242		with open(skipped_log) as file:
243			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
244
245		self.assertEqual(kunit_parser.TestStatus.SKIPPED, result.status)
246		self.assertEqual(result.counts, kunit_parser.TestCounts(skipped=5))
247
248	def test_ignores_hyphen(self):
249		hyphen_log = test_data_path('test_strip_hyphen.log')
250		with open(hyphen_log) as file:
251			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
252
253		# A skipped test does not fail the whole suite.
254		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
255		self.assertEqual(
256			"sysctl_test",
257			result.subtests[0].name)
258		self.assertEqual(
259			"example",
260			result.subtests[1].name)
261
262	def test_ignores_prefix_printk_time(self):
263		prefix_log = test_data_path('test_config_printk_time.log')
264		with open(prefix_log) as file:
265			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
266		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
267		self.assertEqual('kunit-resource-test', result.subtests[0].name)
268		self.assertEqual(result.counts.errors, 0)
269
270	def test_ignores_multiple_prefixes(self):
271		prefix_log = test_data_path('test_multiple_prefixes.log')
272		with open(prefix_log) as file:
273			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
274		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
275		self.assertEqual('kunit-resource-test', result.subtests[0].name)
276		self.assertEqual(result.counts.errors, 0)
277
278	def test_prefix_mixed_kernel_output(self):
279		mixed_prefix_log = test_data_path('test_interrupted_tap_output.log')
280		with open(mixed_prefix_log) as file:
281			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
282		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
283		self.assertEqual('kunit-resource-test', result.subtests[0].name)
284		self.assertEqual(result.counts.errors, 0)
285
286	def test_prefix_poundsign(self):
287		pound_log = test_data_path('test_pound_sign.log')
288		with open(pound_log) as file:
289			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
290		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
291		self.assertEqual('kunit-resource-test', result.subtests[0].name)
292		self.assertEqual(result.counts.errors, 0)
293
294	def test_kernel_panic_end(self):
295		panic_log = test_data_path('test_kernel_panic_interrupt.log')
296		with open(panic_log) as file:
297			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
298		self.assertEqual(kunit_parser.TestStatus.TEST_CRASHED, result.status)
299		self.assertEqual('kunit-resource-test', result.subtests[0].name)
300		self.assertGreaterEqual(result.counts.errors, 1)
301
302	def test_pound_no_prefix(self):
303		pound_log = test_data_path('test_pound_no_prefix.log')
304		with open(pound_log) as file:
305			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
306		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
307		self.assertEqual('kunit-resource-test', result.subtests[0].name)
308		self.assertEqual(result.counts.errors, 0)
309
310	def test_summarize_failures(self):
311		output = """
312		KTAP version 1
313		1..2
314			# Subtest: all_failed_suite
315			1..2
316			not ok 1 - test1
317			not ok 2 - test2
318		not ok 1 - all_failed_suite
319			# Subtest: some_failed_suite
320			1..2
321			ok 1 - test1
322			not ok 2 - test2
323		not ok 1 - some_failed_suite
324		"""
325		result = kunit_parser.parse_run_tests(output.splitlines(), stdout)
326		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
327
328		self.assertEqual(kunit_parser._summarize_failed_tests(result),
329			'Failures: all_failed_suite, some_failed_suite.test2')
330
331	def test_ktap_format(self):
332		ktap_log = test_data_path('test_parse_ktap_output.log')
333		with open(ktap_log) as file:
334			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
335		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=3))
336		self.assertEqual('suite', result.subtests[0].name)
337		self.assertEqual('case_1', result.subtests[0].subtests[0].name)
338		self.assertEqual('case_2', result.subtests[0].subtests[1].name)
339
340	def test_parse_subtest_header(self):
341		ktap_log = test_data_path('test_parse_subtest_header.log')
342		with open(ktap_log) as file:
343			kunit_parser.parse_run_tests(file.readlines(), stdout)
344		self.print_mock.assert_any_call(StrContains('suite (1 subtest)'))
345
346	def test_parse_attributes(self):
347		ktap_log = test_data_path('test_parse_attributes.log')
348		with open(ktap_log) as file:
349			result = kunit_parser.parse_run_tests(file.readlines(), stdout)
350
351		# Test should pass with no errors
352		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=1, errors=0))
353		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
354
355		# Ensure suite header is parsed correctly
356		self.print_mock.assert_any_call(StrContains('suite (1 subtest)'))
357
358		# Ensure attributes in correct test log
359		self.assertContains('# module: example', result.subtests[0].log)
360		self.assertContains('# test.speed: slow', result.subtests[0].subtests[0].log)
361
362	def test_show_test_output_on_failure(self):
363		output = """
364		KTAP version 1
365		1..1
366		  Test output.
367		    Indented more.
368		not ok 1 test1
369		"""
370		result = kunit_parser.parse_run_tests(output.splitlines(), stdout)
371		self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
372
373		self.print_mock.assert_any_call(StrContains('Test output.'))
374		self.print_mock.assert_any_call(StrContains('  Indented more.'))
375		self.noPrintCallContains('not ok 1 test1')
376
377	def test_parse_late_test_plan(self):
378		output = """
379		TAP version 13
380		ok 4 test4
381		1..4
382		"""
383		result = kunit_parser.parse_run_tests(output.splitlines(), stdout)
384		# Missing test results after test plan should alert a suspected test crash.
385		self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
386		self.assertEqual(result.counts, kunit_parser.TestCounts(passed=1, errors=2))
387
388def line_stream_from_strs(strs: Iterable[str]) -> kunit_parser.LineStream:
389	return kunit_parser.LineStream(enumerate(strs, start=1))
390
391class LineStreamTest(unittest.TestCase):
392
393	def test_basic(self):
394		stream = line_stream_from_strs(['hello', 'world'])
395
396		self.assertTrue(stream, msg='Should be more input')
397		self.assertEqual(stream.line_number(), 1)
398		self.assertEqual(stream.peek(), 'hello')
399		self.assertEqual(stream.pop(), 'hello')
400
401		self.assertTrue(stream, msg='Should be more input')
402		self.assertEqual(stream.line_number(), 2)
403		self.assertEqual(stream.peek(), 'world')
404		self.assertEqual(stream.pop(), 'world')
405
406		self.assertFalse(stream, msg='Should be no more input')
407		with self.assertRaisesRegex(ValueError, 'LineStream: going past EOF'):
408			stream.pop()
409
410	def test_is_lazy(self):
411		called_times = 0
412		def generator():
413			nonlocal called_times
414			for _ in range(1,5):
415				called_times += 1
416				yield called_times, str(called_times)
417
418		stream = kunit_parser.LineStream(generator())
419		self.assertEqual(called_times, 0)
420
421		self.assertEqual(stream.pop(), '1')
422		self.assertEqual(called_times, 1)
423
424		self.assertEqual(stream.pop(), '2')
425		self.assertEqual(called_times, 2)
426
427class LinuxSourceTreeTest(unittest.TestCase):
428
429	def setUp(self):
430		mock.patch.object(signal, 'signal').start()
431		self.addCleanup(mock.patch.stopall)
432
433	def test_invalid_kunitconfig(self):
434		with self.assertRaisesRegex(kunit_kernel.ConfigError, 'nonexistent.* does not exist'):
435			kunit_kernel.LinuxSourceTree('', kunitconfig_paths=['/nonexistent_file'])
436
437	def test_valid_kunitconfig(self):
438		with tempfile.NamedTemporaryFile('wt') as kunitconfig:
439			kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[kunitconfig.name])
440
441	def test_dir_kunitconfig(self):
442		with tempfile.TemporaryDirectory('') as dir:
443			with open(os.path.join(dir, '.kunitconfig'), 'w'):
444				pass
445			kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir])
446
447	def test_multiple_kunitconfig(self):
448		want_kconfig = kunit_config.Kconfig()
449		want_kconfig.add_entry('KUNIT', 'y')
450		want_kconfig.add_entry('KUNIT_TEST', 'm')
451
452		with tempfile.TemporaryDirectory('') as dir:
453			other = os.path.join(dir, 'otherkunitconfig')
454			with open(os.path.join(dir, '.kunitconfig'), 'w') as f:
455				f.write('CONFIG_KUNIT=y')
456			with open(other, 'w') as f:
457				f.write('CONFIG_KUNIT_TEST=m')
458				pass
459
460			tree = kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir, other])
461			self.assertTrue(want_kconfig.is_subset_of(tree._kconfig), msg=tree._kconfig)
462
463
464	def test_multiple_kunitconfig_invalid(self):
465		with tempfile.TemporaryDirectory('') as dir:
466			other = os.path.join(dir, 'otherkunitconfig')
467			with open(os.path.join(dir, '.kunitconfig'), 'w') as f:
468				f.write('CONFIG_KUNIT=y')
469			with open(other, 'w') as f:
470				f.write('CONFIG_KUNIT=m')
471
472			with self.assertRaisesRegex(kunit_kernel.ConfigError, '(?s)Multiple values.*CONFIG_KUNIT'):
473				kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir, other])
474
475
476	def test_kconfig_add(self):
477		want_kconfig = kunit_config.Kconfig()
478		want_kconfig.add_entry('NOT_REAL', 'y')
479
480		tree = kunit_kernel.LinuxSourceTree('', kconfig_add=['CONFIG_NOT_REAL=y'])
481		self.assertTrue(want_kconfig.is_subset_of(tree._kconfig), msg=tree._kconfig)
482
483	def test_invalid_arch(self):
484		with self.assertRaisesRegex(kunit_kernel.ConfigError, 'not a valid arch, options are.*x86_64'):
485			kunit_kernel.LinuxSourceTree('', arch='invalid')
486
487	def test_run_kernel_hits_exception(self):
488		def fake_start(unused_args, unused_build_dir):
489			return subprocess.Popen(['echo "hi\nbye"'], shell=True, text=True, stdout=subprocess.PIPE)
490
491		with tempfile.TemporaryDirectory('') as build_dir:
492			tree = kunit_kernel.LinuxSourceTree(build_dir)
493			mock.patch.object(tree._ops, 'start', side_effect=fake_start).start()
494
495			with self.assertRaises(ValueError):
496				for line in tree.run_kernel(build_dir=build_dir):
497					self.assertEqual(line, 'hi\n')
498					raise ValueError('uh oh, did not read all output')
499
500			with open(kunit_kernel.get_outfile_path(build_dir), 'rt') as outfile:
501				self.assertEqual(outfile.read(), 'hi\nbye\n', msg='Missing some output')
502
503	def test_build_reconfig_no_config(self):
504		with tempfile.TemporaryDirectory('') as build_dir:
505			with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
506				f.write('CONFIG_KUNIT=y')
507
508			tree = kunit_kernel.LinuxSourceTree(build_dir)
509			# Stub out the source tree operations, so we don't have
510			# the defaults for any given architecture get in the
511			# way.
512			tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
513			mock_build_config = mock.patch.object(tree, 'build_config').start()
514
515			# Should generate the .config
516			self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
517			mock_build_config.assert_called_once_with(build_dir, [])
518
519	def test_build_reconfig_existing_config(self):
520		with tempfile.TemporaryDirectory('') as build_dir:
521			# Existing .config is a superset, should not touch it
522			with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
523				f.write('CONFIG_KUNIT=y')
524			with open(kunit_kernel.get_old_kunitconfig_path(build_dir), 'w') as f:
525				f.write('CONFIG_KUNIT=y')
526			with open(kunit_kernel.get_kconfig_path(build_dir), 'w') as f:
527				f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
528
529			tree = kunit_kernel.LinuxSourceTree(build_dir)
530			# Stub out the source tree operations, so we don't have
531			# the defaults for any given architecture get in the
532			# way.
533			tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
534			mock_build_config = mock.patch.object(tree, 'build_config').start()
535
536			self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
537			self.assertEqual(mock_build_config.call_count, 0)
538
539	def test_build_reconfig_remove_option(self):
540		with tempfile.TemporaryDirectory('') as build_dir:
541			# We removed CONFIG_KUNIT_TEST=y from our .kunitconfig...
542			with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
543				f.write('CONFIG_KUNIT=y')
544			with open(kunit_kernel.get_old_kunitconfig_path(build_dir), 'w') as f:
545				f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
546			with open(kunit_kernel.get_kconfig_path(build_dir), 'w') as f:
547				f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
548
549			tree = kunit_kernel.LinuxSourceTree(build_dir)
550			# Stub out the source tree operations, so we don't have
551			# the defaults for any given architecture get in the
552			# way.
553			tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
554			mock_build_config = mock.patch.object(tree, 'build_config').start()
555
556			# ... so we should trigger a call to build_config()
557			self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
558			mock_build_config.assert_called_once_with(build_dir, [])
559
560	# TODO: add more test cases.
561
562
563class KUnitJsonTest(unittest.TestCase):
564	def setUp(self):
565		self.print_mock = mock.patch('kunit_printer.Printer.print').start()
566		self.addCleanup(mock.patch.stopall)
567
568	def _json_for(self, log_file):
569		with open(test_data_path(log_file)) as file:
570			test_result = kunit_parser.parse_run_tests(file, stdout)
571			json_obj = kunit_json.get_json_result(
572				test=test_result,
573				metadata=kunit_json.Metadata())
574		return json.loads(json_obj)
575
576	def test_failed_test_json(self):
577		result = self._json_for('test_is_test_passed-failure.log')
578		self.assertEqual(
579			{'name': 'example_simple_test', 'status': 'FAIL'},
580			result["sub_groups"][1]["test_cases"][0])
581
582	def test_crashed_test_json(self):
583		result = self._json_for('test_kernel_panic_interrupt.log')
584		self.assertEqual(
585			{'name': '', 'status': 'ERROR'},
586			result["sub_groups"][2]["test_cases"][1])
587
588	def test_skipped_test_json(self):
589		result = self._json_for('test_skip_tests.log')
590		self.assertEqual(
591			{'name': 'example_skip_test', 'status': 'SKIP'},
592			result["sub_groups"][1]["test_cases"][1])
593
594	def test_no_tests_json(self):
595		result = self._json_for('test_is_test_passed-no_tests_run_with_header.log')
596		self.assertEqual(0, len(result['sub_groups']))
597
598	def test_nested_json(self):
599		result = self._json_for('test_is_test_passed-all_passed_nested.log')
600		self.assertEqual(
601			{'name': 'example_simple_test', 'status': 'PASS'},
602			result["sub_groups"][0]["sub_groups"][0]["test_cases"][0])
603
604class StrContains(str):
605	def __eq__(self, other):
606		return self in other
607
608class KUnitMainTest(unittest.TestCase):
609	def setUp(self):
610		path = test_data_path('test_is_test_passed-all_passed.log')
611		with open(path) as file:
612			all_passed_log = file.readlines()
613
614		self.print_mock = mock.patch('kunit_printer.Printer.print').start()
615		mock.patch.dict(os.environ, clear=True).start()
616		self.addCleanup(mock.patch.stopall)
617
618		self.mock_linux_init = mock.patch.object(kunit_kernel, 'LinuxSourceTree').start()
619		self.linux_source_mock = self.mock_linux_init.return_value
620		self.linux_source_mock.build_reconfig.return_value = True
621		self.linux_source_mock.build_kernel.return_value = True
622		self.linux_source_mock.run_kernel.return_value = all_passed_log
623
624	def test_config_passes_args_pass(self):
625		kunit.main(['config', '--build_dir=.kunit'])
626		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
627		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
628
629	def test_build_passes_args_pass(self):
630		kunit.main(['build'])
631		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
632		self.linux_source_mock.build_kernel.assert_called_once_with(kunit.get_default_jobs(), '.kunit', None)
633		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
634
635	def test_exec_passes_args_pass(self):
636		kunit.main(['exec'])
637		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 0)
638		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
639		self.linux_source_mock.run_kernel.assert_called_once_with(
640			args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
641		self.print_mock.assert_any_call(StrContains('Testing complete.'))
642
643	def test_run_passes_args_pass(self):
644		kunit.main(['run'])
645		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
646		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
647		self.linux_source_mock.run_kernel.assert_called_once_with(
648			args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
649		self.print_mock.assert_any_call(StrContains('Testing complete.'))
650
651	def test_exec_passes_args_fail(self):
652		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
653		with self.assertRaises(SystemExit) as e:
654			kunit.main(['exec'])
655		self.assertEqual(e.exception.code, 1)
656
657	def test_run_passes_args_fail(self):
658		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
659		with self.assertRaises(SystemExit) as e:
660			kunit.main(['run'])
661		self.assertEqual(e.exception.code, 1)
662		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
663		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
664		self.print_mock.assert_any_call(StrContains('Could not find any KTAP output.'))
665
666	def test_exec_no_tests(self):
667		self.linux_source_mock.run_kernel = mock.Mock(return_value=['TAP version 14', '1..0'])
668		with self.assertRaises(SystemExit) as e:
669			kunit.main(['run'])
670		self.assertEqual(e.exception.code, 1)
671		self.linux_source_mock.run_kernel.assert_called_once_with(
672			args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
673		self.print_mock.assert_any_call(StrContains(' 0 tests run!'))
674
675	def test_exec_raw_output(self):
676		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
677		kunit.main(['exec', '--raw_output'])
678		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
679		for call in self.print_mock.call_args_list:
680			self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
681			self.assertNotEqual(call, mock.call(StrContains(' 0 tests run!')))
682
683	def test_run_raw_output(self):
684		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
685		kunit.main(['run', '--raw_output'])
686		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
687		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
688		for call in self.print_mock.call_args_list:
689			self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
690			self.assertNotEqual(call, mock.call(StrContains(' 0 tests run!')))
691
692	def test_run_raw_output_kunit(self):
693		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
694		kunit.main(['run', '--raw_output=kunit'])
695		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
696		self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
697		for call in self.print_mock.call_args_list:
698			self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
699			self.assertNotEqual(call, mock.call(StrContains(' 0 tests run')))
700
701	def test_run_raw_output_invalid(self):
702		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
703		with self.assertRaises(SystemExit) as e:
704			kunit.main(['run', '--raw_output=invalid'])
705		self.assertNotEqual(e.exception.code, 0)
706
707	def test_run_raw_output_does_not_take_positional_args(self):
708		# --raw_output is a string flag, but we don't want it to consume
709		# any positional arguments, only ones after an '='
710		self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
711		kunit.main(['run', '--raw_output', 'filter_glob'])
712		self.linux_source_mock.run_kernel.assert_called_once_with(
713			args=None, build_dir='.kunit', filter_glob='filter_glob', filter='', filter_action=None, timeout=300)
714
715	def test_exec_timeout(self):
716		timeout = 3453
717		kunit.main(['exec', '--timeout', str(timeout)])
718		self.linux_source_mock.run_kernel.assert_called_once_with(
719			args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=timeout)
720		self.print_mock.assert_any_call(StrContains('Testing complete.'))
721
722	def test_run_timeout(self):
723		timeout = 3453
724		kunit.main(['run', '--timeout', str(timeout)])
725		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
726		self.linux_source_mock.run_kernel.assert_called_once_with(
727			args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=timeout)
728		self.print_mock.assert_any_call(StrContains('Testing complete.'))
729
730	def test_run_builddir(self):
731		build_dir = '.kunit'
732		kunit.main(['run', '--build_dir=.kunit'])
733		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
734		self.linux_source_mock.run_kernel.assert_called_once_with(
735			args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
736		self.print_mock.assert_any_call(StrContains('Testing complete.'))
737
738	@mock.patch.dict(os.environ, {'KBUILD_OUTPUT': '/tmp'})
739	def test_run_builddir_from_env(self):
740		build_dir = '/tmp/.kunit'
741		kunit.main(['run'])
742		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
743		self.linux_source_mock.run_kernel.assert_called_once_with(
744			args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
745		self.print_mock.assert_any_call(StrContains('Testing complete.'))
746
747	@mock.patch.dict(os.environ, {'KBUILD_OUTPUT': '/tmp'})
748	def test_run_builddir_override(self):
749		build_dir = '.kunit'
750		kunit.main(['run', '--build_dir=.kunit'])
751		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
752		self.linux_source_mock.run_kernel.assert_called_once_with(
753			args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
754		self.print_mock.assert_any_call(StrContains('Testing complete.'))
755
756	def test_config_builddir(self):
757		build_dir = '.kunit'
758		kunit.main(['config', '--build_dir', build_dir])
759		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
760
761	def test_build_builddir(self):
762		build_dir = '.kunit'
763		jobs = kunit.get_default_jobs()
764		kunit.main(['build', '--build_dir', build_dir])
765		self.linux_source_mock.build_kernel.assert_called_once_with(jobs, build_dir, None)
766
767	def test_exec_builddir(self):
768		build_dir = '.kunit'
769		kunit.main(['exec', '--build_dir', build_dir])
770		self.linux_source_mock.run_kernel.assert_called_once_with(
771			args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
772		self.print_mock.assert_any_call(StrContains('Testing complete.'))
773
774	def test_run_kunitconfig(self):
775		kunit.main(['run', '--kunitconfig=mykunitconfig'])
776		# Just verify that we parsed and initialized it correctly here.
777		self.mock_linux_init.assert_called_once_with('.kunit',
778						kunitconfig_paths=['mykunitconfig'],
779						kconfig_add=None,
780						arch='um',
781						cross_compile=None,
782						qemu_config_path=None,
783						extra_qemu_args=[])
784
785	def test_config_kunitconfig(self):
786		kunit.main(['config', '--kunitconfig=mykunitconfig'])
787		# Just verify that we parsed and initialized it correctly here.
788		self.mock_linux_init.assert_called_once_with('.kunit',
789						kunitconfig_paths=['mykunitconfig'],
790						kconfig_add=None,
791						arch='um',
792						cross_compile=None,
793						qemu_config_path=None,
794						extra_qemu_args=[])
795
796	def test_config_alltests(self):
797		kunit.main(['config', '--kunitconfig=mykunitconfig', '--alltests'])
798		# Just verify that we parsed and initialized it correctly here.
799		self.mock_linux_init.assert_called_once_with('.kunit',
800						kunitconfig_paths=[kunit_kernel.ALL_TESTS_CONFIG_PATH, 'mykunitconfig'],
801						kconfig_add=None,
802						arch='um',
803						cross_compile=None,
804						qemu_config_path=None,
805						extra_qemu_args=[])
806
807
808	@mock.patch.object(kunit_kernel, 'LinuxSourceTree')
809	def test_run_multiple_kunitconfig(self, mock_linux_init):
810		mock_linux_init.return_value = self.linux_source_mock
811		kunit.main(['run', '--kunitconfig=mykunitconfig', '--kunitconfig=other'])
812		# Just verify that we parsed and initialized it correctly here.
813		mock_linux_init.assert_called_once_with('.kunit',
814							kunitconfig_paths=['mykunitconfig', 'other'],
815							kconfig_add=None,
816							arch='um',
817							cross_compile=None,
818							qemu_config_path=None,
819							extra_qemu_args=[])
820
821	def test_run_kconfig_add(self):
822		kunit.main(['run', '--kconfig_add=CONFIG_KASAN=y', '--kconfig_add=CONFIG_KCSAN=y'])
823		# Just verify that we parsed and initialized it correctly here.
824		self.mock_linux_init.assert_called_once_with('.kunit',
825						kunitconfig_paths=[],
826						kconfig_add=['CONFIG_KASAN=y', 'CONFIG_KCSAN=y'],
827						arch='um',
828						cross_compile=None,
829						qemu_config_path=None,
830						extra_qemu_args=[])
831
832	def test_run_qemu_args(self):
833		kunit.main(['run', '--arch=x86_64', '--qemu_args', '-m 2048'])
834		# Just verify that we parsed and initialized it correctly here.
835		self.mock_linux_init.assert_called_once_with('.kunit',
836						kunitconfig_paths=[],
837						kconfig_add=None,
838						arch='x86_64',
839						cross_compile=None,
840						qemu_config_path=None,
841						extra_qemu_args=['-m', '2048'])
842
843	def test_run_kernel_args(self):
844		kunit.main(['run', '--kernel_args=a=1', '--kernel_args=b=2'])
845		self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
846		self.linux_source_mock.run_kernel.assert_called_once_with(
847		      args=['a=1','b=2'], build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
848		self.print_mock.assert_any_call(StrContains('Testing complete.'))
849
850	def test_list_tests(self):
851		want = ['suite.test1', 'suite.test2', 'suite2.test1']
852		self.linux_source_mock.run_kernel.return_value = ['TAP version 14', 'init: random output'] + want
853
854		got = kunit._list_tests(self.linux_source_mock,
855				     kunit.KunitExecRequest(None, None, False, False, '.kunit', 300, 'suite*', '', None, None, 'suite', False, False))
856		self.assertEqual(got, want)
857		# Should respect the user's filter glob when listing tests.
858		self.linux_source_mock.run_kernel.assert_called_once_with(
859			args=['kunit.action=list'], build_dir='.kunit', filter_glob='suite*', filter='', filter_action=None, timeout=300)
860
861	@mock.patch.object(kunit, '_list_tests')
862	def test_run_isolated_by_suite(self, mock_tests):
863		mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1']
864		kunit.main(['exec', '--run_isolated=suite', 'suite*.test*'])
865
866		# Should respect the user's filter glob when listing tests.
867		mock_tests.assert_called_once_with(mock.ANY,
868				     kunit.KunitExecRequest(None, None, False, False, '.kunit', 300, 'suite*.test*', '', None, None, 'suite', False, False))
869		self.linux_source_mock.run_kernel.assert_has_calls([
870			mock.call(args=None, build_dir='.kunit', filter_glob='suite.test*', filter='', filter_action=None, timeout=300),
871			mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test*', filter='', filter_action=None, timeout=300),
872		])
873
874	@mock.patch.object(kunit, '_list_tests')
875	def test_run_isolated_by_test(self, mock_tests):
876		mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1']
877		kunit.main(['exec', '--run_isolated=test', 'suite*'])
878
879		# Should respect the user's filter glob when listing tests.
880		mock_tests.assert_called_once_with(mock.ANY,
881				     kunit.KunitExecRequest(None, None, False, False, '.kunit', 300, 'suite*', '', None, None, 'test', False, False))
882		self.linux_source_mock.run_kernel.assert_has_calls([
883			mock.call(args=None, build_dir='.kunit', filter_glob='suite.test1', filter='', filter_action=None, timeout=300),
884			mock.call(args=None, build_dir='.kunit', filter_glob='suite.test2', filter='', filter_action=None, timeout=300),
885			mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test1', filter='', filter_action=None, timeout=300),
886		])
887
888if __name__ == '__main__':
889	unittest.main()
890