summaryrefslogtreecommitdiff
path: root/harnesses/host_controller/console_test.py
blob: bd4906ad18e64d3818e874d18c1be018cf69bcc1 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python
#
# Copyright (C) 2017 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
import unittest

try:
    from unittest import mock
except ImportError:
    import mock

try:
    import StringIO as string_io_module
except ImportError:
    import io as string_io_module

from host_controller.build import build_flasher
from host_controller.tfc import command_task
from host_controller.tfc import device_info
from host_controller import common
from host_controller import console


class ConsoleTest(unittest.TestCase):
    """A test for console.Console.

    Attribute:
        _out_file: The console output buffer.
        _host_controller: A mock tfc_host_controller.HostController.
        _build_provider_pab: A mock build_provider_pab.BuildProviderPAB.
        _tfc_client: A mock tfc_client.TfcClient.
        _vti_client A mock vti_endpoint_client.VtiEndpointClient.
        _console: The console being tested.
    """
    _DEVICES = [
        device_info.DeviceInfo(
            device_serial="ABC001",
            run_target="sailfish",
            state="Available",
            build_id="111111",
            sdk_version="27")
    ]
    _TASKS = [
        command_task.CommandTask(
            request_id="1",
            task_id="1-0",
            command_id="2",
            command_line="vts -m SampleShellTest",
            device_serials=["ABC001"])
    ]

    def setUp(self):
        """Creates the console."""
        self._out_file = string_io_module.StringIO()
        self._host_controller = mock.Mock()
        self._build_provider_pab = mock.Mock()
        self._tfc_client = mock.Mock()
        self._vti_client = mock.Mock()
        self._console = console.Console(
            self._vti_client,
            self._tfc_client,
            self._build_provider_pab, [self._host_controller],
            None,
            out_file=self._out_file)
        self._console.device_image_info = {}

    def tearDown(self):
        """Closes the output file."""
        self._out_file.close()

    def _IssueCommand(self, command_line):
        """Issues a command in the console.

        Args:
            command_line: A string, the input to the console.

        Returns:
            A string, the output of the console.
        """
        out_position = self._out_file.tell()
        self._console.onecmd(command_line)
        self._out_file.seek(out_position)
        return self._out_file.read()

    def testLease(self):
        """Tests the lease command."""
        self._host_controller.LeaseCommandTasks.return_value = self._TASKS
        output = self._IssueCommand("lease")
        expected = (
            "request_id  command_id  task_id  device_serials  command_line          \n"
            "1           2           1-0      ABC001          vts -m SampleShellTest\n"
        )
        self.assertEqual(expected, output)
        output = self._IssueCommand("lease --host 0")
        self.assertEqual(expected, output)

    def testRequest(self):
        """Tests the request command."""
        user = "user0"
        cluster = "cluster0"
        run_target = "sailfish"
        command_line = "vts -m SampleShellTest"
        self._IssueCommand("request --user %s --cluster %s --run-target %s "
                           "-- %s" % (user, cluster, run_target, command_line))
        req = self._tfc_client.NewRequest.call_args[0][0]
        self.assertEqual(user, req.user)
        self.assertEqual(cluster, req.cluster)
        self.assertEqual(run_target, req.run_target)
        self.assertEqual(command_line, req.command_line)

    def testListHosts(self):
        """Tests the list command."""
        self._host_controller.hostname = "host0"
        output = self._IssueCommand("list hosts")
        self.assertEqual("index  name\n" "[  0]  host0\n", output)

    def testListDevices(self):
        """Tests the list command."""
        self._host_controller.ListDevices.return_value = self._DEVICES
        self._host_controller.hostname = "host0"
        output = self._IssueCommand("list devices")
        expected = (
            "[  0]  host0\n"
            "device_serial  state      run_target  build_id  sdk_version  stub\n"
            "ABC001         Available  sailfish    111111    27               \n"
        )
        self.assertEqual(expected, output)
        output = self._IssueCommand("list devices --host 0")
        self.assertEqual(expected, output)

    def testWrongHostIndex(self):
        """Tests host index out of range."""
        output = self._IssueCommand("list devices --host 1")
        expected = "IndexError: "
        self.assertTrue(output.startswith(expected))
        output = self._IssueCommand("lease --host 1")
        self.assertTrue(output.startswith(expected))

    @mock.patch('host_controller.build.build_flasher.BuildFlasher')
    def testFetchPOSTAndFlash(self, mock_class):
        """Tests fetching from pab and flashing."""
        self._build_provider_pab.GetArtifact.return_value = ({
            "system.img":
            "/mock/system.img",
            "odm.img":
            "/mock/odm.img"
        }, {}, {
            "build_id":
            "build_id"
        }, {})
        self._build_provider_pab.GetFetchedArtifactType.return_value = common._ARTIFACT_TYPE_DEVICE
        self._IssueCommand(
            "fetch --branch=aosp-master-ndk --target=darwin_mac "
            "--account_id=100621237 "
            "--artifact_name=foo-{build_id}.tar.bz2 --method=POST")
        self._build_provider_pab.GetArtifact.assert_called_with(
            account_id='100621237',
            branch='aosp-master-ndk',
            target='darwin_mac',
            artifact_name='foo-{build_id}.tar.bz2',
            build_id='latest',
            method='POST',
            full_device_images=False)
        self.assertEqual(self._console.device_image_info, {
            "system.img": "/mock/system.img",
            "odm.img": "/mock/odm.img"
        })

        flasher = mock.Mock()
        mock_class.return_value = flasher
        self._IssueCommand("flash --current system=system.img odm=odm.img")
        flasher.Flash.assert_called_with({
            "system": "/mock/system.img",
            "odm": "/mock/odm.img"
        }, False)

    def testFetchAndEnvironment(self):
        """Tests fetching from pab and check stored os environment"""
        build_id_return = "4328532"
        target_return = "darwin_mac"
        expected_fetch_info = {"build_id": build_id_return}

        self._build_provider_pab.GetArtifact.return_value = ({
            "system.img":
            "/mock/system.img",
            "odm.img":
            "/mock/odm.img"
        }, {}, expected_fetch_info, {})
        self._IssueCommand(
            "fetch --branch=aosp-master-ndk --target=%s "
            "--account_id=100621237 "
            "--artifact_name=foo-{id}.tar.bz2 --method=POST" % target_return)
        self._build_provider_pab.GetArtifact.assert_called_with(
            account_id='100621237',
            branch='aosp-master-ndk',
            target='darwin_mac',
            artifact_name='foo-{id}.tar.bz2',
            build_id='latest',
            full_device_images=False,
            method='POST')

        expected = expected_fetch_info["build_id"]
        self.assertEqual(build_id_return, expected)

    @mock.patch('host_controller.build.build_flasher.BuildFlasher')
    def testFlashGSI(self, mock_class):
        flasher = mock.Mock()
        mock_class.return_value = flasher
        self._IssueCommand("flash --gsi=system.img")
        flasher.FlashGSI.assert_called_with(
            'system.img', None, skip_vbmeta=False)

    @mock.patch('host_controller.build.build_flasher.BuildFlasher')
    def testFlashGSIWithVbmeta(self, mock_class):
        flasher = mock.Mock()
        mock_class.return_value = flasher
        self._IssueCommand("flash --gsi=system.img --vbmeta=vbmeta.img")
        flasher.FlashGSI.assert_called_with(
            'system.img', 'vbmeta.img', skip_vbmeta=False)

    @mock.patch('host_controller.build.build_flasher.BuildFlasher')
    def testFlashall(self, mock_class):
        flasher = mock.Mock()
        mock_class.return_value = flasher
        self._IssueCommand("flash --build_dir=path/to/dir/")
        flasher.Flashall.assert_called_with('path/to/dir/')

    @mock.patch('host_controller.command_processor.command_flash.importlib')
    @mock.patch('host_controller.command_processor.command_flash.issubclass')
    def testImportFlasher(self, mock_issubclass, mock_importlib):
        mock_issubclass.return_value = True
        flasher_module = mock.Mock()
        flasher = mock.Mock()
        mock_importlib.import_module.return_value = flasher_module
        flasher_module.Flasher.return_value = flasher
        self._IssueCommand("flash --serial ABC001 "
                           "--flasher_type test.flasher.Flasher "
                           "--flasher_path /test/flasher "
                           "-- --unit test")
        mock_issubclass.assert_called_once_with(flasher_module.Flasher,
                                                build_flasher.BuildFlasher)
        mock_importlib.import_module.assert_called_with("test.flasher")
        flasher_module.Flasher.assert_called_with("ABC001", "/test/flasher")
        flasher.Flash.assert_called_with({}, {}, "--unit", "test")
        flasher.WaitForDevice.assert_called_with()


if __name__ == "__main__":
    unittest.main()