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