blob: ccd97a938d7e1be3b7bc5c4cfcd97565d9c7f4e9 [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
Tianjiea2076132020-08-19 17:25:32 -070025import re
Tao Baofc7e0e02018-02-13 13:54:02 -080026import struct
Tao Bao898a9242018-10-18 14:51:27 -070027import sys
Tao Bao65b94e92018-10-11 21:57:26 -070028import unittest
Kelvin Zhangcff4d762020-07-29 16:37:51 -040029import zipfile
Tao Baofc7e0e02018-02-13 13:54:02 -080030
31import common
Tao Bao04e1f012018-02-04 12:13:35 -080032
Tao Bao898a9242018-10-18 14:51:27 -070033# Some test runner doesn't like outputs from stderr.
34logging.basicConfig(stream=sys.stdout)
35
Tao Bao82490d32019-04-09 00:12:30 -070036# Use ANDROID_BUILD_TOP as an indicator to tell if the needed tools (e.g.
Tao Bao7d223c62019-08-01 12:12:59 -070037# avbtool, mke2fs) are available while running the tests, unless
38# FORCE_RUN_RELEASETOOLS is set to '1'. Not having the required vars means we
39# can't run the tests that require external tools.
40EXTERNAL_TOOLS_UNAVAILABLE = (
41 not os.environ.get('ANDROID_BUILD_TOP') and
42 os.environ.get('FORCE_RUN_RELEASETOOLS') != '1')
Tao Bao82490d32019-04-09 00:12:30 -070043
44
45def SkipIfExternalToolsUnavailable():
46 """Decorator function that allows skipping tests per tools availability."""
47 if EXTERNAL_TOOLS_UNAVAILABLE:
48 return unittest.skip('External tools unavailable')
49 return lambda func: func
50
Tao Bao04e1f012018-02-04 12:13:35 -080051
52def get_testdata_dir():
53 """Returns the testdata dir, in relative to the script dir."""
54 # The script dir is the one we want, which could be different from pwd.
55 current_dir = os.path.dirname(os.path.realpath(__file__))
56 return os.path.join(current_dir, 'testdata')
Tao Baofc7e0e02018-02-13 13:54:02 -080057
58
Tao Bao3bf8c652018-03-16 12:59:42 -070059def get_search_path():
60 """Returns the search path that has 'framework/signapk.jar' under."""
Tao Bao30e31142019-04-09 00:12:30 -070061
62 def signapk_exists(path):
63 signapk_path = os.path.realpath(
64 os.path.join(path, 'framework', 'signapk.jar'))
65 return os.path.exists(signapk_path)
66
67 # Try with ANDROID_BUILD_TOP first.
68 full_path = os.path.realpath(os.path.join(
69 os.environ.get('ANDROID_BUILD_TOP', ''), 'out', 'host', 'linux-x86'))
70 if signapk_exists(full_path):
71 return full_path
72
73 # Otherwise try going with relative pathes.
Tao Bao3bf8c652018-03-16 12:59:42 -070074 current_dir = os.path.dirname(os.path.realpath(__file__))
75 for path in (
76 # In relative to 'build/make/tools/releasetools' in the Android source.
77 ['..'] * 4 + ['out', 'host', 'linux-x86'],
78 # Or running the script unpacked from otatools.zip.
79 ['..']):
80 full_path = os.path.realpath(os.path.join(current_dir, *path))
Tao Bao30e31142019-04-09 00:12:30 -070081 if signapk_exists(full_path):
Tao Bao3bf8c652018-03-16 12:59:42 -070082 return full_path
83 return None
84
85
Tao Baofc7e0e02018-02-13 13:54:02 -080086def construct_sparse_image(chunks):
87 """Returns a sparse image file constructed from the given chunks.
88
89 From system/core/libsparse/sparse_format.h.
90 typedef struct sparse_header {
91 __le32 magic; // 0xed26ff3a
92 __le16 major_version; // (0x1) - reject images with higher major versions
93 __le16 minor_version; // (0x0) - allow images with higer minor versions
94 __le16 file_hdr_sz; // 28 bytes for first revision of the file format
95 __le16 chunk_hdr_sz; // 12 bytes for first revision of the file format
96 __le32 blk_sz; // block size in bytes, must be a multiple of 4 (4096)
97 __le32 total_blks; // total blocks in the non-sparse output image
98 __le32 total_chunks; // total chunks in the sparse input image
99 __le32 image_checksum; // CRC32 checksum of the original data, counting
100 // "don't care" as 0. Standard 802.3 polynomial,
101 // use a Public Domain table implementation
102 } sparse_header_t;
103
104 typedef struct chunk_header {
105 __le16 chunk_type; // 0xCAC1 -> raw; 0xCAC2 -> fill;
106 // 0xCAC3 -> don't care
107 __le16 reserved1;
108 __le32 chunk_sz; // in blocks in output image
109 __le32 total_sz; // in bytes of chunk input file including chunk header
110 // and data
111 } chunk_header_t;
112
113 Args:
114 chunks: A list of chunks to be written. Each entry should be a tuple of
115 (chunk_type, block_number).
116
117 Returns:
118 Filename of the created sparse image.
119 """
120 SPARSE_HEADER_MAGIC = 0xED26FF3A
121 SPARSE_HEADER_FORMAT = "<I4H4I"
122 CHUNK_HEADER_FORMAT = "<2H2I"
123
124 sparse_image = common.MakeTempFile(prefix='sparse-', suffix='.img')
125 with open(sparse_image, 'wb') as fp:
126 fp.write(struct.pack(
127 SPARSE_HEADER_FORMAT, SPARSE_HEADER_MAGIC, 1, 0, 28, 12, 4096,
128 sum(chunk[1] for chunk in chunks),
129 len(chunks), 0))
130
131 for chunk in chunks:
132 data_size = 0
133 if chunk[0] == 0xCAC1:
134 data_size = 4096 * chunk[1]
135 elif chunk[0] == 0xCAC2:
136 data_size = 4
137 elif chunk[0] == 0xCAC3:
138 pass
139 else:
140 assert False, "Unsupported chunk type: {}".format(chunk[0])
141
142 fp.write(struct.pack(
143 CHUNK_HEADER_FORMAT, chunk[0], 0, chunk[1], data_size + 12))
144 if data_size != 0:
145 fp.write(os.urandom(data_size))
146
147 return sparse_image
Tao Bao65b94e92018-10-11 21:57:26 -0700148
149
Tao Baoe1148042019-10-07 20:00:34 -0700150class MockScriptWriter(object):
151 """A class that mocks edify_generator.EdifyGenerator.
152
153 It simply pushes the incoming arguments onto script stack, which is to assert
154 the calls to EdifyGenerator functions.
155 """
156
157 def __init__(self, enable_comments=False):
158 self.lines = []
159 self.enable_comments = enable_comments
160
161 def Mount(self, *args):
162 self.lines.append(('Mount',) + args)
163
164 def AssertDevice(self, *args):
165 self.lines.append(('AssertDevice',) + args)
166
167 def AssertOemProperty(self, *args):
168 self.lines.append(('AssertOemProperty',) + args)
169
170 def AssertFingerprintOrThumbprint(self, *args):
171 self.lines.append(('AssertFingerprintOrThumbprint',) + args)
172
173 def AssertSomeFingerprint(self, *args):
174 self.lines.append(('AssertSomeFingerprint',) + args)
175
176 def AssertSomeThumbprint(self, *args):
177 self.lines.append(('AssertSomeThumbprint',) + args)
178
179 def Comment(self, comment):
180 if not self.enable_comments:
181 return
182 self.lines.append('# {}'.format(comment))
183
184 def AppendExtra(self, extra):
185 self.lines.append(extra)
186
187 def __str__(self):
188 return '\n'.join(self.lines)
189
190
Tao Bao65b94e92018-10-11 21:57:26 -0700191class ReleaseToolsTestCase(unittest.TestCase):
192 """A common base class for all the releasetools unittests."""
193
194 def tearDown(self):
195 common.Cleanup()
Tao Bao30e31142019-04-09 00:12:30 -0700196
Kelvin Zhangcff4d762020-07-29 16:37:51 -0400197class PropertyFilesTestCase(ReleaseToolsTestCase):
198
199 @staticmethod
200 def construct_zip_package(entries):
201 zip_file = common.MakeTempFile(suffix='.zip')
Kelvin Zhang928c2342020-09-22 16:15:57 -0400202 with zipfile.ZipFile(zip_file, 'w', allowZip64=True) as zip_fp:
Kelvin Zhangcff4d762020-07-29 16:37:51 -0400203 for entry in entries:
204 zip_fp.writestr(
205 entry,
206 entry.replace('.', '-').upper(),
207 zipfile.ZIP_STORED)
208 return zip_file
209
210 @staticmethod
211 def _parse_property_files_string(data):
212 result = {}
213 for token in data.split(','):
214 name, info = token.split(':', 1)
215 result[name] = info
216 return result
217
218 def setUp(self):
219 common.OPTIONS.no_signing = False
220
221 def _verify_entries(self, input_file, tokens, entries):
222 for entry in entries:
223 offset, size = map(int, tokens[entry].split(':'))
224 with open(input_file, 'rb') as input_fp:
225 input_fp.seek(offset)
226 if entry == 'metadata':
227 expected = b'META-INF/COM/ANDROID/METADATA'
Tianjiea2076132020-08-19 17:25:32 -0700228 elif entry == 'metadata.pb':
229 expected = b'META-INF/COM/ANDROID/METADATA-PB'
Kelvin Zhangcff4d762020-07-29 16:37:51 -0400230 else:
231 expected = entry.replace('.', '-').upper().encode()
232 self.assertEqual(expected, input_fp.read(size))
233
Tao Bao30e31142019-04-09 00:12:30 -0700234
235if __name__ == '__main__':
Tianjiea2076132020-08-19 17:25:32 -0700236 # We only want to run tests from the top level directory. Unfortunately the
237 # pattern option of unittest.discover, internally using fnmatch, doesn't
238 # provide a good API to filter the test files based on directory. So we do an
239 # os walk and load them manually.
240 test_modules = []
241 base_path = os.path.dirname(os.path.realpath(__file__))
242 for dirpath, _, files in os.walk(base_path):
243 for fn in files:
244 if dirpath == base_path and re.match('test_.*\\.py$', fn):
245 test_modules.append(fn[:-3])
246
247 test_suite = unittest.TestLoader().loadTestsFromNames(test_modules)
248
Tao Bao30e31142019-04-09 00:12:30 -0700249 # atest needs a verbosity level of >= 2 to correctly parse the result.
Tianjiea2076132020-08-19 17:25:32 -0700250 unittest.TextTestRunner(verbosity=2).run(test_suite)