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