blob: 65092d84def64975d909705f5ca86562d4c66915 [file] [log] [blame]
Tao Bao30e31142019-04-09 00:12:30 -07001#!/usr/bin/env python
Tao Bao04e1f012018-02-04 12:13:35 -08002#
3# Copyright (C) 2018 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
18"""
19Utils for running unittests.
20"""
21
Tao Bao898a9242018-10-18 14:51:27 -070022import logging
Tao Baofc7e0e02018-02-13 13:54:02 -080023import os
Tao Bao04e1f012018-02-04 12:13:35 -080024import os.path
Tao Baofc7e0e02018-02-13 13:54:02 -080025import struct
Tao Bao898a9242018-10-18 14:51:27 -070026import sys
Tao Bao65b94e92018-10-11 21:57:26 -070027import unittest
Kelvin Zhangcff4d762020-07-29 16:37:51 -040028import zipfile
Tao Baofc7e0e02018-02-13 13:54:02 -080029
30import common
Tao Bao04e1f012018-02-04 12:13:35 -080031
Tao Bao898a9242018-10-18 14:51:27 -070032# Some test runner doesn't like outputs from stderr.
33logging.basicConfig(stream=sys.stdout)
34
Tao Bao82490d32019-04-09 00:12:30 -070035# Use ANDROID_BUILD_TOP as an indicator to tell if the needed tools (e.g.
Tao Bao7d223c62019-08-01 12:12:59 -070036# avbtool, mke2fs) are available while running the tests, unless
37# FORCE_RUN_RELEASETOOLS is set to '1'. Not having the required vars means we
38# can't run the tests that require external tools.
39EXTERNAL_TOOLS_UNAVAILABLE = (
40 not os.environ.get('ANDROID_BUILD_TOP') and
41 os.environ.get('FORCE_RUN_RELEASETOOLS') != '1')
Tao Bao82490d32019-04-09 00:12:30 -070042
43
44def SkipIfExternalToolsUnavailable():
45 """Decorator function that allows skipping tests per tools availability."""
46 if EXTERNAL_TOOLS_UNAVAILABLE:
47 return unittest.skip('External tools unavailable')
48 return lambda func: func
49
Tao Bao04e1f012018-02-04 12:13:35 -080050
51def get_testdata_dir():
52 """Returns the testdata dir, in relative to the script dir."""
53 # The script dir is the one we want, which could be different from pwd.
54 current_dir = os.path.dirname(os.path.realpath(__file__))
55 return os.path.join(current_dir, 'testdata')
Tao Baofc7e0e02018-02-13 13:54:02 -080056
57
Tao Bao3bf8c652018-03-16 12:59:42 -070058def get_search_path():
59 """Returns the search path that has 'framework/signapk.jar' under."""
Tao Bao30e31142019-04-09 00:12:30 -070060
61 def signapk_exists(path):
62 signapk_path = os.path.realpath(
63 os.path.join(path, 'framework', 'signapk.jar'))
64 return os.path.exists(signapk_path)
65
66 # Try with ANDROID_BUILD_TOP first.
67 full_path = os.path.realpath(os.path.join(
68 os.environ.get('ANDROID_BUILD_TOP', ''), 'out', 'host', 'linux-x86'))
69 if signapk_exists(full_path):
70 return full_path
71
72 # Otherwise try going with relative pathes.
Tao Bao3bf8c652018-03-16 12:59:42 -070073 current_dir = os.path.dirname(os.path.realpath(__file__))
74 for path in (
75 # In relative to 'build/make/tools/releasetools' in the Android source.
76 ['..'] * 4 + ['out', 'host', 'linux-x86'],
77 # Or running the script unpacked from otatools.zip.
78 ['..']):
79 full_path = os.path.realpath(os.path.join(current_dir, *path))
Tao Bao30e31142019-04-09 00:12:30 -070080 if signapk_exists(full_path):
Tao Bao3bf8c652018-03-16 12:59:42 -070081 return full_path
82 return None
83
84
Tao Baofc7e0e02018-02-13 13:54:02 -080085def construct_sparse_image(chunks):
86 """Returns a sparse image file constructed from the given chunks.
87
88 From system/core/libsparse/sparse_format.h.
89 typedef struct sparse_header {
90 __le32 magic; // 0xed26ff3a
91 __le16 major_version; // (0x1) - reject images with higher major versions
92 __le16 minor_version; // (0x0) - allow images with higer minor versions
93 __le16 file_hdr_sz; // 28 bytes for first revision of the file format
94 __le16 chunk_hdr_sz; // 12 bytes for first revision of the file format
95 __le32 blk_sz; // block size in bytes, must be a multiple of 4 (4096)
96 __le32 total_blks; // total blocks in the non-sparse output image
97 __le32 total_chunks; // total chunks in the sparse input image
98 __le32 image_checksum; // CRC32 checksum of the original data, counting
99 // "don't care" as 0. Standard 802.3 polynomial,
100 // use a Public Domain table implementation
101 } sparse_header_t;
102
103 typedef struct chunk_header {
104 __le16 chunk_type; // 0xCAC1 -> raw; 0xCAC2 -> fill;
105 // 0xCAC3 -> don't care
106 __le16 reserved1;
107 __le32 chunk_sz; // in blocks in output image
108 __le32 total_sz; // in bytes of chunk input file including chunk header
109 // and data
110 } chunk_header_t;
111
112 Args:
113 chunks: A list of chunks to be written. Each entry should be a tuple of
114 (chunk_type, block_number).
115
116 Returns:
117 Filename of the created sparse image.
118 """
119 SPARSE_HEADER_MAGIC = 0xED26FF3A
120 SPARSE_HEADER_FORMAT = "<I4H4I"
121 CHUNK_HEADER_FORMAT = "<2H2I"
122
123 sparse_image = common.MakeTempFile(prefix='sparse-', suffix='.img')
124 with open(sparse_image, 'wb') as fp:
125 fp.write(struct.pack(
126 SPARSE_HEADER_FORMAT, SPARSE_HEADER_MAGIC, 1, 0, 28, 12, 4096,
127 sum(chunk[1] for chunk in chunks),
128 len(chunks), 0))
129
130 for chunk in chunks:
131 data_size = 0
132 if chunk[0] == 0xCAC1:
133 data_size = 4096 * chunk[1]
134 elif chunk[0] == 0xCAC2:
135 data_size = 4
136 elif chunk[0] == 0xCAC3:
137 pass
138 else:
139 assert False, "Unsupported chunk type: {}".format(chunk[0])
140
141 fp.write(struct.pack(
142 CHUNK_HEADER_FORMAT, chunk[0], 0, chunk[1], data_size + 12))
143 if data_size != 0:
144 fp.write(os.urandom(data_size))
145
146 return sparse_image
Tao Bao65b94e92018-10-11 21:57:26 -0700147
148
Tao Baoe1148042019-10-07 20:00:34 -0700149class MockScriptWriter(object):
150 """A class that mocks edify_generator.EdifyGenerator.
151
152 It simply pushes the incoming arguments onto script stack, which is to assert
153 the calls to EdifyGenerator functions.
154 """
155
156 def __init__(self, enable_comments=False):
157 self.lines = []
158 self.enable_comments = enable_comments
159
160 def Mount(self, *args):
161 self.lines.append(('Mount',) + args)
162
163 def AssertDevice(self, *args):
164 self.lines.append(('AssertDevice',) + args)
165
166 def AssertOemProperty(self, *args):
167 self.lines.append(('AssertOemProperty',) + args)
168
169 def AssertFingerprintOrThumbprint(self, *args):
170 self.lines.append(('AssertFingerprintOrThumbprint',) + args)
171
172 def AssertSomeFingerprint(self, *args):
173 self.lines.append(('AssertSomeFingerprint',) + args)
174
175 def AssertSomeThumbprint(self, *args):
176 self.lines.append(('AssertSomeThumbprint',) + args)
177
178 def Comment(self, comment):
179 if not self.enable_comments:
180 return
181 self.lines.append('# {}'.format(comment))
182
183 def AppendExtra(self, extra):
184 self.lines.append(extra)
185
186 def __str__(self):
187 return '\n'.join(self.lines)
188
189
Tao Bao65b94e92018-10-11 21:57:26 -0700190class ReleaseToolsTestCase(unittest.TestCase):
191 """A common base class for all the releasetools unittests."""
192
193 def tearDown(self):
194 common.Cleanup()
Tao Bao30e31142019-04-09 00:12:30 -0700195
Kelvin Zhangcff4d762020-07-29 16:37:51 -0400196class PropertyFilesTestCase(ReleaseToolsTestCase):
197
198 @staticmethod
199 def construct_zip_package(entries):
200 zip_file = common.MakeTempFile(suffix='.zip')
201 with zipfile.ZipFile(zip_file, 'w') as zip_fp:
202 for entry in entries:
203 zip_fp.writestr(
204 entry,
205 entry.replace('.', '-').upper(),
206 zipfile.ZIP_STORED)
207 return zip_file
208
209 @staticmethod
210 def _parse_property_files_string(data):
211 result = {}
212 for token in data.split(','):
213 name, info = token.split(':', 1)
214 result[name] = info
215 return result
216
217 def setUp(self):
218 common.OPTIONS.no_signing = False
219
220 def _verify_entries(self, input_file, tokens, entries):
221 for entry in entries:
222 offset, size = map(int, tokens[entry].split(':'))
223 with open(input_file, 'rb') as input_fp:
224 input_fp.seek(offset)
225 if entry == 'metadata':
226 expected = b'META-INF/COM/ANDROID/METADATA'
227 else:
228 expected = entry.replace('.', '-').upper().encode()
229 self.assertEqual(expected, input_fp.read(size))
230
Tao Bao30e31142019-04-09 00:12:30 -0700231
232if __name__ == '__main__':
233 testsuite = unittest.TestLoader().discover(
234 os.path.dirname(os.path.realpath(__file__)))
235 # atest needs a verbosity level of >= 2 to correctly parse the result.
236 unittest.TextTestRunner(verbosity=2).run(testsuite)