1# Copyright 2018 - The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Tests for create_common."""
15
16import os
17import unittest
18
19import mock
20
21from acloud import errors
22from acloud.create import create_common
23from acloud.internal.lib import android_build_client
24from acloud.internal.lib import auth
25from acloud.internal.lib import driver_test_lib
26from acloud.internal.lib import utils
27
28
29class FakeZipFile(object):
30    """Fake implementation of ZipFile()"""
31
32    # pylint: disable=invalid-name,unused-argument,no-self-use
33    def write(self, filename, arcname=None, compress_type=None):
34        """Fake write method."""
35        return
36
37    # pylint: disable=invalid-name,no-self-use
38    def close(self):
39        """Fake close method."""
40        return
41
42
43# pylint: disable=invalid-name,protected-access
44class CreateCommonTest(driver_test_lib.BaseDriverTest):
45    """Test create_common functions."""
46
47    # pylint: disable=protected-access
48    def testProcessHWPropertyWithInvalidArgs(self):
49        """Test ParseHWPropertyArgs with invalid args."""
50        # Checking wrong property value.
51        args_str = "cpu:3,disk:"
52        with self.assertRaises(errors.MalformedDictStringError):
53            create_common.ParseHWPropertyArgs(args_str)
54
55        # Checking wrong property format.
56        args_str = "cpu:3,disk"
57        with self.assertRaises(errors.MalformedDictStringError):
58            create_common.ParseHWPropertyArgs(args_str)
59
60    def testParseHWPropertyStr(self):
61        """Test ParseHWPropertyArgs."""
62        expected_dict = {"cpu": "2", "resolution": "1080x1920", "dpi": "240",
63                         "memory": "4g", "disk": "4g"}
64        args_str = "cpu:2,resolution:1080x1920,dpi:240,memory:4g,disk:4g"
65        result_dict = create_common.ParseHWPropertyArgs(args_str)
66        self.assertTrue(expected_dict == result_dict)
67
68    def testGetCvdHostPackage(self):
69        """test GetCvdHostPackage."""
70        # Can't find the cvd host package
71        with mock.patch("os.path.exists") as exists:
72            exists.return_value = False
73            self.assertRaises(
74                errors.GetCvdLocalHostPackageError,
75                create_common.GetCvdHostPackage)
76
77        self.Patch(os.environ, "get", return_value="/fake_dir2")
78        self.Patch(utils, "GetDistDir", return_value="/fake_dir1")
79        # First path is host out dir, 2nd path is dist dir.
80        self.Patch(os.path, "exists",
81                   side_effect=[False, True])
82
83        # Find cvd host in dist dir.
84        self.assertEqual(
85            create_common.GetCvdHostPackage(),
86            "/fake_dir1/cvd-host_package.tar.gz")
87
88        # Find cvd host in host out dir.
89        self.Patch(os.environ, "get", return_value="/fake_dir2")
90        self.Patch(utils, "GetDistDir", return_value=None)
91        with mock.patch("os.path.exists") as exists:
92            exists.return_value = True
93            self.assertEqual(
94                create_common.GetCvdHostPackage(),
95                "/fake_dir2/cvd-host_package.tar.gz")
96
97    @mock.patch.object(utils, "Decompress")
98    def testDownloadRemoteArtifact(self, mock_decompress):
99        """Test Download cuttlefish package."""
100        mock_build_client = mock.MagicMock()
101        self.Patch(
102            android_build_client,
103            "AndroidBuildClient",
104            return_value=mock_build_client)
105        self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock())
106        avd_spec = mock.MagicMock()
107        avd_spec.cfg = mock.MagicMock()
108        avd_spec.remote_image = {"build_target" : "aosp_cf_x86_phone-userdebug",
109                                 "build_id": "1234"}
110        build_id = "1234"
111        build_target = "aosp_cf_x86_phone-userdebug"
112        checkfile1 = "aosp_cf_x86_phone-img-1234.zip"
113        checkfile2 = "cvd-host_package.tar.gz"
114        extract_path = "/tmp/1234"
115
116        create_common.DownloadRemoteArtifact(
117            avd_spec.cfg,
118            avd_spec.remote_image["build_target"],
119            avd_spec.remote_image["build_id"],
120            checkfile1,
121            extract_path,
122            decompress=True)
123
124        self.assertEqual(mock_build_client.DownloadArtifact.call_count, 1)
125        mock_build_client.DownloadArtifact.assert_called_once_with(
126            build_target,
127            build_id,
128            checkfile1,
129            "%s/%s" % (extract_path, checkfile1))
130        self.assertEqual(mock_decompress.call_count, 1)
131
132        mock_decompress.call_count = 0
133        mock_build_client.DownloadArtifact.call_count = 0
134        create_common.DownloadRemoteArtifact(
135            avd_spec.cfg,
136            avd_spec.remote_image["build_target"],
137            avd_spec.remote_image["build_id"],
138            checkfile2,
139            extract_path)
140
141        self.assertEqual(mock_build_client.DownloadArtifact.call_count, 1)
142        mock_build_client.DownloadArtifact.assert_called_once_with(
143            build_target,
144            build_id,
145            checkfile2,
146            "%s/%s" % (extract_path, checkfile2))
147        self.assertEqual(mock_decompress.call_count, 0)
148
149
150if __name__ == "__main__":
151    unittest.main()
152