aboutsummaryrefslogtreecommitdiff
path: root/lava_dispatcher/test/test_lavashell.py
blob: 2e402890cac283a5a4d1b139cdcfe5d3b8bd56f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# Copyright (C) 2014 Linaro Limited
#
# Author: Neil Williams <neil.williams@linaro.org>
#
# This file is part of LAVA Dispatcher.
#
# LAVA Dispatcher is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LAVA Dispatcher is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along
# with this program; if not, see <http://www.gnu.org/licenses>.

import os
import yaml
import datetime
from lava_dispatcher.action import Action, Pipeline
from lava_common.timeout import Timeout
from lava_common.exceptions import (
    InfrastructureError,
    JobError,
)
from lava_dispatcher.parser import JobParser
from lava_dispatcher.device import NewDevice
from lava_dispatcher.actions.deploy.testdef import get_test_action_namespaces
from lava_dispatcher.test.utils import DummyLogger
from lava_dispatcher.job import Job
from lava_dispatcher.protocols.multinode import MultinodeProtocol
from lava_dispatcher.protocols.vland import VlandProtocol
from lava_dispatcher.test.test_basic import Factory, StdoutTestCase
from lava_dispatcher.actions.test.shell import TestShellRetry, TestShellAction


# pylint: disable=duplicate-code,too-few-public-methods


class TestDefinitionHandlers(StdoutTestCase):  # pylint: disable=too-many-public-methods

    def setUp(self):
        super().setUp()
        self.factory = Factory()
        self.job = self.factory.create_kvm_job('sample_jobs/kvm.yaml')

    def test_testshell(self):
        testshell = None
        for action in self.job.pipeline.actions:
            self.assertIsNotNone(action.name)
            if isinstance(action, TestShellRetry):
                testshell = action.pipeline.actions[0]
                break
        self.assertIsInstance(testshell, TestShellAction)
        self.assertTrue(testshell.valid)

        if 'timeout' in testshell.parameters:
            time_int = Timeout.parse(testshell.parameters['timeout'])
        else:
            time_int = Timeout.default_duration()
        self.assertEqual(
            datetime.timedelta(seconds=time_int).total_seconds(),
            testshell.timeout.duration
        )

    def test_missing_handler(self):
        (rendered, _) = self.factory.create_device('kvm01.jinja2')
        device = NewDevice(yaml.load(rendered))
        kvm_yaml = os.path.join(os.path.dirname(__file__), 'sample_jobs/kvm.yaml')
        parser = JobParser()
        with open(kvm_yaml) as sample_job_data:
            data = yaml.load(sample_job_data)
        data['actions'][2]['test']['definitions'][0]['from'] = 'unusable-handler'
        try:
            job = parser.parse(yaml.dump(data), device, 4212, None, "")
            job.logger = DummyLogger()
        except JobError:
            pass
        except Exception as exc:  # pylint: disable=broad-except
            self.fail(exc)
        else:
            self.fail('JobError not raised')

    def test_eventpatterns(self):
        testshell = None
        for action in self.job.pipeline.actions:
            self.assertIsNotNone(action.name)
            if isinstance(action, TestShellRetry):
                testshell = action.pipeline.actions[0]
                break
        self.assertTrue(testshell.valid)
        self.assertFalse(testshell.check_patterns('exit', None, ''))
        self.assertRaises(InfrastructureError, testshell.check_patterns, 'eof', None, '')
        self.assertTrue(testshell.check_patterns('timeout', None, ''))


class X86Factory(Factory):

    def create_x86_job(self, filename, device):
        return self.create_job(device, filename)


class TestMultiNodeOverlay(StdoutTestCase):  # pylint: disable=too-many-public-methods

    def setUp(self):
        super().setUp()
        factory = X86Factory()
        self.server_job = factory.create_x86_job('sample_jobs/test_action-1.yaml', 'lng-generator-01.jinja2')
        self.client_job = factory.create_x86_job('sample_jobs/test_action-2.yaml', 'lng-generator-02.jinja2')

    def test_action_namespaces(self):
        self.assertIsNotNone(self.server_job)
        self.assertIsNotNone(self.client_job)
        deploy_server = [action for action in self.server_job.pipeline.actions if action.name == 'tftp-deploy'][0]
        self.assertIn(MultinodeProtocol.name, deploy_server.parameters.keys())
        self.assertIn(VlandProtocol.name, deploy_server.parameters.keys())
        self.assertEqual(['common'], get_test_action_namespaces(self.server_job.parameters))
        namespace = self.server_job.parameters.get('namespace')
        self.assertIsNone(namespace)
        namespace = self.client_job.parameters.get('namespace')
        self.assertIsNone(namespace)
        deploy_client = [action for action in self.client_job.pipeline.actions if action.name == 'tftp-deploy'][0]
        self.assertIn(MultinodeProtocol.name, deploy_client.parameters.keys())
        self.assertIn(VlandProtocol.name, deploy_client.parameters.keys())
        key_list = []
        for block in self.client_job.parameters['actions']:
            key_list.extend(block.keys())
        self.assertEqual(key_list, ['deploy', 'boot', 'test'])  # order is important
        self.assertEqual(['common'], get_test_action_namespaces(self.client_job.parameters))
        key_list = []
        for block in self.server_job.parameters['actions']:
            key_list.extend(block.keys())
        self.assertEqual(key_list, ['deploy', 'boot', 'test'])  # order is important


class TestShellResults(StdoutTestCase):   # pylint: disable=too-many-public-methods

    class FakeJob(Job):
        pass

    class FakeDeploy:
        """
        Derived from object, *not* Deployment as this confuses python -m unittest discover
        - leads to the FakeDeploy being called instead.
        """
        def __init__(self, parent):
            self.__parameters__ = {}
            self.pipeline = parent
            self.job = parent.job
            self.action = TestShellResults.FakeAction()

    class FakePipeline(Pipeline):

        def __init__(self, parent=None, job=None):
            super().__init__(parent, job)

    class FakeAction(Action):
        """
        Isolated Action which can be used to generate artificial exceptions.
        """

        name = "fake-action"
        description = "fake, do not use outside unit tests"
        summary = "fake action for unit tests"

        def __init__(self):
            super().__init__()
            self.count = 1

        def run(self, connection, max_end_time):
            self.count += 1
            raise JobError("fake error")