1#!/usr/bin/env python
2#
3# Copyright 2016 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Tests for acloud.public.device_driver."""
18
19import uuid
20
21import unittest
22import mock
23
24from acloud.internal.lib import auth
25from acloud.internal.lib import android_build_client
26from acloud.internal.lib import android_compute_client
27from acloud.internal.lib import driver_test_lib
28from acloud.internal.lib import gstorage_client
29from acloud.internal.lib import ssh
30from acloud.public import device_driver
31
32
33def _CreateCfg():
34    """A helper method that creates a mock configuration object."""
35    cfg = mock.MagicMock()
36    cfg.service_account_name = "fake@service.com"
37    cfg.service_account_private_key_path = "/fake/path/to/key"
38    cfg.zone = "fake_zone"
39    cfg.disk_image_name = "fake_image.tar.gz"
40    cfg.disk_image_mime_type = "fake/type"
41    cfg.storage_bucket_name = "fake_bucket"
42    cfg.extra_data_disk_size_gb = 4
43    cfg.precreated_data_image_map = {
44        4: "extradisk-image-4gb",
45        10: "extradisk-image-10gb"
46    }
47    cfg.extra_scopes = None
48    cfg.ssh_private_key_path = ""
49    cfg.ssh_public_key_path = ""
50
51    return cfg
52
53
54class DeviceDriverTest(driver_test_lib.BaseDriverTest):
55    """Test device_driver."""
56
57    def setUp(self):
58        """Set up the test."""
59        super(DeviceDriverTest, self).setUp()
60        self.build_client = mock.MagicMock()
61        self.Patch(android_build_client, "AndroidBuildClient",
62                   return_value=self.build_client)
63        self.storage_client = mock.MagicMock()
64        self.Patch(
65            gstorage_client, "StorageClient", return_value=self.storage_client)
66        self.compute_client = mock.MagicMock()
67        self.Patch(
68            android_compute_client,
69            "AndroidComputeClient",
70            return_value=self.compute_client)
71        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())
72        self.fake_avd_spec = mock.MagicMock()
73        self.fake_avd_spec.unlock_screen = False
74        self.fake_avd_spec.client_adb_port = 1234
75
76    def testCreateGCETypeAVD(self):
77        """Test CreateGCETypeAVD."""
78        cfg = _CreateCfg()
79        fake_gs_url = "fake_gs_url"
80        fake_ip = ssh.IP(external="140.1.1.1", internal="10.1.1.1")
81        fake_instance = "fake-instance"
82        fake_image = "fake-image"
83        fake_build_target = "fake_target"
84        fake_build_id = "12345"
85
86        # Mock uuid
87        fake_uuid = mock.MagicMock(hex="1234")
88        self.Patch(uuid, "uuid4", return_value=fake_uuid)
89        fake_gs_object = fake_uuid.hex + "-" + cfg.disk_image_name
90        self.storage_client.GetUrl.return_value = fake_gs_url
91
92        # Mock compute client methods
93        disk_name = "extradisk-image-4gb"
94        self.compute_client.GetInstanceIP.return_value = fake_ip
95        self.compute_client.GenerateImageName.return_value = fake_image
96        self.compute_client.GenerateInstanceName.return_value = fake_instance
97        self.compute_client.GetDataDiskName.return_value = disk_name
98
99        # Verify
100        report = device_driver.CreateGCETypeAVD(
101            cfg, fake_build_target, fake_build_id, avd_spec=self.fake_avd_spec)
102        self.build_client.CopyTo.assert_called_with(
103            fake_build_target, fake_build_id, artifact_name=cfg.disk_image_name,
104            destination_bucket=cfg.storage_bucket_name,
105            destination_path=fake_gs_object)
106        self.compute_client.CreateImage.assert_called_with(
107            image_name=fake_image, source_uri=fake_gs_url)
108        self.compute_client.CreateInstance.assert_called_with(
109            instance=fake_instance,
110            image_name=fake_image,
111            extra_disk_name=disk_name,
112            avd_spec=self.fake_avd_spec,
113            extra_scopes=None)
114        self.compute_client.DeleteImage.assert_called_with(fake_image)
115        self.storage_client.Delete(cfg.storage_bucket_name, fake_gs_object)
116
117        self.assertEqual(
118            report.data,
119            {
120                "devices": [
121                    {
122                        "instance_name": fake_instance,
123                        "ip": fake_ip.external,
124                    },
125                ],
126            }
127        )
128        self.assertEqual(report.command, "create")
129        self.assertEqual(report.status, "SUCCESS")
130
131    # pylint: disable=invalid-name
132    def testCreateGCETypeAVDInternalIP(self):
133        """Test CreateGCETypeAVD with internal IP."""
134        cfg = _CreateCfg()
135        fake_ip = ssh.IP(external="140.1.1.1", internal="10.1.1.1")
136        fake_instance = "fake-instance"
137        fake_build_target = "fake_target"
138        fake_build_id = "12345"
139
140        self.compute_client.GetInstanceIP.return_value = fake_ip
141        self.compute_client.GenerateInstanceName.return_value = fake_instance
142
143        report = device_driver.CreateGCETypeAVD(
144            cfg, fake_build_target, fake_build_id, report_internal_ip=True,
145            avd_spec=self.fake_avd_spec)
146
147        self.assertEqual(
148            report.data,
149            {
150                "devices": [
151                    {
152                        "instance_name": fake_instance,
153                        "ip": fake_ip.internal,
154                    },
155                ],
156            }
157        )
158
159    def testDeleteAndroidVirtualDevices(self):
160        """Test DeleteAndroidVirtualDevices."""
161        cfg = _CreateCfg()
162        instance_names = ["fake-instance-1", "fake-instance-2"]
163        self.compute_client.GetZonesByInstances.return_value = (
164            {cfg.zone: instance_names})
165        self.compute_client.DeleteInstances.return_value = (instance_names, [],
166                                                            [])
167        report = device_driver.DeleteAndroidVirtualDevices(cfg, instance_names)
168        self.compute_client.DeleteInstances.assert_called_once_with(
169            instance_names, cfg.zone)
170        self.assertEqual(report.data, {
171            "deleted": [
172                {
173                    "name": instance_names[0],
174                    "type": "instance",
175                },
176                {
177                    "name": instance_names[1],
178                    "type": "instance",
179                },
180            ],
181        })
182        self.assertEqual(report.command, "delete")
183        self.assertEqual(report.status, "SUCCESS")
184
185
186if __name__ == "__main__":
187    unittest.main()
188