1#!/usr/bin/env python3
2# Copyright (c) 2024 Intel Corporation
3#
4# SPDX-License-Identifier: Apache-2.0
5"""
6Blackbox tests for twister's command line functions related to saving and loading a testlist.
7"""
8
9import importlib
10import mock
11import os
12import pytest
13import sys
14import json
15
16# pylint: disable=no-name-in-module
17from conftest import ZEPHYR_BASE, TEST_DATA, testsuite_filename_mock, clear_log_in_test
18from twisterlib.testplan import TestPlan
19
20
21class TestTestlist:
22    @classmethod
23    def setup_class(cls):
24        apath = os.path.join(ZEPHYR_BASE, 'scripts', 'twister')
25        cls.loader = importlib.machinery.SourceFileLoader('__main__', apath)
26        cls.spec = importlib.util.spec_from_loader(cls.loader.name, cls.loader)
27        cls.twister_module = importlib.util.module_from_spec(cls.spec)
28
29    @classmethod
30    def teardown_class(cls):
31        pass
32
33    @mock.patch.object(TestPlan, 'TESTSUITE_FILENAME', testsuite_filename_mock)
34    def test_save_tests(self, out_path):
35        test_platforms = ['qemu_x86', 'intel_adl_crb']
36        path = os.path.join(TEST_DATA, 'tests', 'dummy', 'agnostic')
37        saved_tests_file_path = os.path.realpath(os.path.join(out_path, '..', 'saved-tests.json'))
38        args = ['-i', '--outdir', out_path, '-T', path, '-y'] + \
39               ['--save-tests', saved_tests_file_path] + \
40               [val for pair in zip(
41                   ['-p'] * len(test_platforms), test_platforms
42               ) for val in pair]
43
44        # Save agnostics tests
45        with mock.patch.object(sys, 'argv', [sys.argv[0]] + args), \
46                pytest.raises(SystemExit) as sys_exit:
47            self.loader.exec_module(self.twister_module)
48
49        assert str(sys_exit.value) == '0'
50
51        clear_log_in_test()
52
53        # Load all
54        path = os.path.join(TEST_DATA, 'tests', 'dummy')
55        args = ['-i', '--outdir', out_path, '-T', path, '-y'] + \
56               ['--load-tests', saved_tests_file_path] + \
57               [val for pair in zip(
58                   ['-p'] * len(test_platforms), test_platforms
59               ) for val in pair]
60
61        with mock.patch.object(sys, 'argv', [sys.argv[0]] + args), \
62                pytest.raises(SystemExit) as sys_exit:
63            self.loader.exec_module(self.twister_module)
64
65        assert str(sys_exit.value) == '0'
66
67        with open(os.path.join(out_path, 'testplan.json')) as f:
68            j = json.load(f)
69        filtered_j = [
70           (ts['platform'], ts['name'], tc['identifier']) \
71               for ts in j['testsuites'] \
72               for tc in ts['testcases'] if 'reason' not in tc
73        ]
74
75        assert len(filtered_j) == 6
76