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