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 collections 17import os 18import shutil 19import tempfile 20import unittest 21 22from unittest import mock 23 24from acloud import errors 25from acloud.create import create_common 26from acloud.internal.lib import android_build_client 27from acloud.internal.lib import auth 28from acloud.internal.lib import driver_test_lib 29from acloud.internal.lib import utils 30 31 32ExtraFile = collections.namedtuple("ExtraFile", ["source", "target"]) 33 34 35class FakeZipFile: 36 """Fake implementation of ZipFile()""" 37 38 # pylint: disable=invalid-name,unused-argument,no-self-use 39 def write(self, filename, arcname=None, compress_type=None): 40 """Fake write method.""" 41 return 42 43 # pylint: disable=invalid-name,no-self-use 44 def close(self): 45 """Fake close method.""" 46 return 47 48 49# pylint: disable=invalid-name,protected-access 50class CreateCommonTest(driver_test_lib.BaseDriverTest): 51 """Test create_common functions.""" 52 53 # pylint: disable=protected-access 54 def testProcessHWPropertyWithInvalidArgs(self): 55 """Test ParseKeyValuePairArgs with invalid args.""" 56 # Checking wrong property value. 57 args_str = "cpu:3,disk:" 58 with self.assertRaises(errors.MalformedDictStringError): 59 create_common.ParseKeyValuePairArgs(args_str) 60 61 # Checking wrong property format. 62 args_str = "cpu:3,disk" 63 with self.assertRaises(errors.MalformedDictStringError): 64 create_common.ParseKeyValuePairArgs(args_str) 65 66 def testParseHWPropertyStr(self): 67 """Test ParseKeyValuePairArgs.""" 68 expected_dict = {"cpu": "2", "resolution": "1080x1920", "dpi": "240", 69 "memory": "4g", "disk": "4g"} 70 args_str = "cpu:2,resolution:1080x1920,dpi:240,memory:4g,disk:4g" 71 result_dict = create_common.ParseKeyValuePairArgs(args_str) 72 self.assertTrue(expected_dict == result_dict) 73 74 def testGetNonEmptyEnvVars(self): 75 """Test GetNonEmptyEnvVars.""" 76 with mock.patch.dict("acloud.internal.lib.utils.os.environ", 77 {"A": "", "B": "b"}, 78 clear=True): 79 self.assertEqual( 80 ["b"], create_common.GetNonEmptyEnvVars("A", "B", "C")) 81 82 def testParseExtraFilesArgs(self): 83 """Test ParseExtraFilesArgs.""" 84 expected_result = [ExtraFile(source="local_path", target="gce_path")] 85 files_info = ["local_path,gce_path"] 86 self.assertEqual(expected_result, 87 create_common.ParseExtraFilesArgs(files_info)) 88 89 # Test multiple files 90 expected_result = [ExtraFile(source="local_path1", target="gce_path1"), 91 ExtraFile(source="local_path2", target="gce_path2")] 92 files_info = ["local_path1,gce_path1", 93 "local_path2,gce_path2"] 94 self.assertEqual(expected_result, 95 create_common.ParseExtraFilesArgs(files_info)) 96 97 # Test wrong file info format. 98 files_info = ["local_path"] 99 with self.assertRaises(errors.MalformedDictStringError): 100 create_common.ParseExtraFilesArgs(files_info) 101 102 def testGetCvdHostPackage(self): 103 """test GetCvdHostPackage.""" 104 # Can't find the cvd host package 105 with mock.patch("os.path.exists") as exists: 106 exists.return_value = False 107 self.assertRaises( 108 errors.GetCvdLocalHostPackageError, 109 create_common.GetCvdHostPackage) 110 111 self.Patch(os.environ, "get", return_value="/fake_dir2") 112 self.Patch(utils, "GetDistDir", return_value="/fake_dir1") 113 self.Patch(os.path, "exists", 114 side_effect=lambda path: 115 path == "/fake_dir1/cvd-host_package.tar.gz") 116 117 # Find cvd host in dist dir. 118 self.assertEqual( 119 create_common.GetCvdHostPackage(), 120 "/fake_dir1/cvd-host_package.tar.gz") 121 122 # Find cvd host in host out dir. 123 self.Patch(os.environ, "get", return_value="/fake_dir2") 124 self.Patch(utils, "GetDistDir", return_value=None) 125 with mock.patch("os.path.exists") as exists: 126 exists.side_effect = lambda path: \ 127 path == "/fake_dir2/cvd-host_package.tar.gz" 128 self.assertEqual( 129 create_common.GetCvdHostPackage(), 130 "/fake_dir2/cvd-host_package.tar.gz") 131 with mock.patch("os.path.exists") as exists: 132 exists.side_effect = lambda path: \ 133 path == "/fake_dir2/cvd-host_package" 134 self.assertEqual( 135 create_common.GetCvdHostPackage(), 136 "/fake_dir2/cvd-host_package") 137 138 # Find cvd host in specified path. 139 package_path = "/tool_dir/cvd-host_package.tar.gz" 140 self.Patch(utils, "GetDistDir", return_value=None) 141 with mock.patch("os.path.exists") as exists: 142 exists.return_value = True 143 self.assertEqual( 144 create_common.GetCvdHostPackage(package_path), 145 "/tool_dir/cvd-host_package.tar.gz") 146 147 @mock.patch("acloud.create.create_common.os.path.isfile", 148 side_effect=lambda path: path == "/dir/name") 149 @mock.patch("acloud.create.create_common.os.path.isdir", 150 side_effect=lambda path: path == "/dir") 151 @mock.patch("acloud.create.create_common.os.listdir", 152 return_value=["name", "name2"]) 153 def testFindLocalImage(self, _mock_listdir, _mock_isdir, _mock_isfile): 154 """Test FindLocalImage.""" 155 self.assertEqual( 156 "/dir/name", 157 create_common.FindLocalImage("/test/../dir/name", "not_exist")) 158 159 self.assertEqual("/dir/name", 160 create_common.FindLocalImage("/dir/", "name")) 161 162 163 self.assertIsNone(create_common.FindLocalImage("/dir", "not_exist", 164 raise_error=False)) 165 with self.assertRaises(errors.GetLocalImageError): 166 create_common.FindLocalImage("/dir", "not_exist") 167 168 with self.assertRaises(errors.GetLocalImageError): 169 create_common.FindLocalImage("/dir", "name.?", raise_error=False) 170 171 def testFindBootImage(self): 172 """Test FindBootImage.""" 173 with tempfile.TemporaryDirectory() as temp_dir: 174 with self.assertRaises(errors.GetLocalImageError): 175 create_common.FindBootImage(temp_dir) 176 177 boot_image_path = os.path.join(temp_dir, "boot.img") 178 self.CreateFile(boot_image_path, b"invalid") 179 with self.assertRaises(errors.GetLocalImageError): 180 create_common.FindBootImage(temp_dir) 181 os.remove(boot_image_path) 182 183 boot_image_path = os.path.join(temp_dir, "boot.img") 184 self.CreateFile(boot_image_path, b"ANDROID!") 185 self.assertEqual(boot_image_path, 186 create_common.FindBootImage(temp_dir)) 187 os.remove(boot_image_path) 188 189 boot_image_path = os.path.join(temp_dir, "boot-5.10.img") 190 self.CreateFile(boot_image_path, b"ANDROID!") 191 self.assertEqual(boot_image_path, 192 create_common.FindBootImage(temp_dir)) 193 194 @mock.patch.object(utils, "Decompress") 195 def testDownloadRemoteArtifact(self, mock_decompress): 196 """Test Download cuttlefish package.""" 197 mock_build_client = mock.MagicMock() 198 self.Patch( 199 android_build_client, 200 "AndroidBuildClient", 201 return_value=mock_build_client) 202 self.Patch(auth, "CreateCredentials", return_value=mock.MagicMock()) 203 avd_spec = mock.MagicMock() 204 avd_spec.cfg = mock.MagicMock() 205 avd_spec.remote_image = {"build_target" : "aosp_cf_x86_64_phone-userdebug", 206 "build_id": "1234"} 207 build_id = "1234" 208 build_target = "aosp_cf_x86_64_phone-userdebug" 209 checkfile1 = "aosp_cf_x86_phone-img-1234.zip" 210 checkfile2 = "cvd-host_package.tar.gz" 211 extract_path = "/tmp/1234" 212 213 create_common.DownloadRemoteArtifact( 214 avd_spec.cfg, 215 avd_spec.remote_image["build_target"], 216 avd_spec.remote_image["build_id"], 217 checkfile1, 218 extract_path, 219 decompress=True) 220 221 self.assertEqual(mock_build_client.DownloadArtifact.call_count, 1) 222 mock_build_client.DownloadArtifact.assert_called_once_with( 223 build_target, 224 build_id, 225 checkfile1, 226 "%s/%s" % (extract_path, checkfile1)) 227 self.assertEqual(mock_decompress.call_count, 1) 228 229 mock_decompress.call_count = 0 230 mock_build_client.DownloadArtifact.call_count = 0 231 create_common.DownloadRemoteArtifact( 232 avd_spec.cfg, 233 avd_spec.remote_image["build_target"], 234 avd_spec.remote_image["build_id"], 235 checkfile2, 236 extract_path) 237 238 self.assertEqual(mock_build_client.DownloadArtifact.call_count, 1) 239 mock_build_client.DownloadArtifact.assert_called_once_with( 240 build_target, 241 build_id, 242 checkfile2, 243 "%s/%s" % (extract_path, checkfile2)) 244 self.assertEqual(mock_decompress.call_count, 0) 245 246 def testPrepareLocalInstanceDir(self): 247 """test PrepareLocalInstanceDir.""" 248 temp_dir = tempfile.mkdtemp() 249 try: 250 cvd_home_dir = os.path.join(temp_dir, "local-instance-1") 251 mock_avd_spec = mock.Mock(local_instance_dir=None) 252 create_common.PrepareLocalInstanceDir(cvd_home_dir, mock_avd_spec) 253 self.assertTrue(os.path.isdir(cvd_home_dir) and 254 not os.path.islink(cvd_home_dir)) 255 256 link_target_dir = os.path.join(temp_dir, "cvd_home") 257 os.mkdir(link_target_dir) 258 mock_avd_spec.local_instance_dir = link_target_dir 259 create_common.PrepareLocalInstanceDir(cvd_home_dir, mock_avd_spec) 260 self.assertTrue(os.path.islink(cvd_home_dir) and 261 os.path.samefile(cvd_home_dir, link_target_dir)) 262 finally: 263 shutil.rmtree(temp_dir) 264 265 266if __name__ == "__main__": 267 unittest.main() 268