blob: 1e919f7bb514199230cc0b1ec444c7dd4b577781 [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
Tao Baofc7e0e02018-02-13 13:54:02 -080028
29import common
Tao Bao04e1f012018-02-04 12:13:35 -080030
Tao Bao898a9242018-10-18 14:51:27 -070031# Some test runner doesn't like outputs from stderr.
32logging.basicConfig(stream=sys.stdout)
33
Tao Bao82490d32019-04-09 00:12:30 -070034# Use ANDROID_BUILD_TOP as an indicator to tell if the needed tools (e.g.
35# avbtool, mke2fs) are available while running the tests. Not having the var or
36# having empty string means we can't run the tests that require external tools.
37EXTERNAL_TOOLS_UNAVAILABLE = not os.environ.get("ANDROID_BUILD_TOP")
38
39
40def SkipIfExternalToolsUnavailable():
41 """Decorator function that allows skipping tests per tools availability."""
42 if EXTERNAL_TOOLS_UNAVAILABLE:
43 return unittest.skip('External tools unavailable')
44 return lambda func: func
45
Tao Bao04e1f012018-02-04 12:13:35 -080046
47def get_testdata_dir():
48 """Returns the testdata dir, in relative to the script dir."""
49 # The script dir is the one we want, which could be different from pwd.
50 current_dir = os.path.dirname(os.path.realpath(__file__))
51 return os.path.join(current_dir, 'testdata')
Tao Baofc7e0e02018-02-13 13:54:02 -080052
53
Tao Bao3bf8c652018-03-16 12:59:42 -070054def get_search_path():
55 """Returns the search path that has 'framework/signapk.jar' under."""
Tao Bao30e31142019-04-09 00:12:30 -070056
57 def signapk_exists(path):
58 signapk_path = os.path.realpath(
59 os.path.join(path, 'framework', 'signapk.jar'))
60 return os.path.exists(signapk_path)
61
62 # Try with ANDROID_BUILD_TOP first.
63 full_path = os.path.realpath(os.path.join(
64 os.environ.get('ANDROID_BUILD_TOP', ''), 'out', 'host', 'linux-x86'))
65 if signapk_exists(full_path):
66 return full_path
67
68 # Otherwise try going with relative pathes.
Tao Bao3bf8c652018-03-16 12:59:42 -070069 current_dir = os.path.dirname(os.path.realpath(__file__))
70 for path in (
71 # In relative to 'build/make/tools/releasetools' in the Android source.
72 ['..'] * 4 + ['out', 'host', 'linux-x86'],
73 # Or running the script unpacked from otatools.zip.
74 ['..']):
75 full_path = os.path.realpath(os.path.join(current_dir, *path))
Tao Bao30e31142019-04-09 00:12:30 -070076 if signapk_exists(full_path):
Tao Bao3bf8c652018-03-16 12:59:42 -070077 return full_path
78 return None
79
80
Tao Baofc7e0e02018-02-13 13:54:02 -080081def construct_sparse_image(chunks):
82 """Returns a sparse image file constructed from the given chunks.
83
84 From system/core/libsparse/sparse_format.h.
85 typedef struct sparse_header {
86 __le32 magic; // 0xed26ff3a
87 __le16 major_version; // (0x1) - reject images with higher major versions
88 __le16 minor_version; // (0x0) - allow images with higer minor versions
89 __le16 file_hdr_sz; // 28 bytes for first revision of the file format
90 __le16 chunk_hdr_sz; // 12 bytes for first revision of the file format
91 __le32 blk_sz; // block size in bytes, must be a multiple of 4 (4096)
92 __le32 total_blks; // total blocks in the non-sparse output image
93 __le32 total_chunks; // total chunks in the sparse input image
94 __le32 image_checksum; // CRC32 checksum of the original data, counting
95 // "don't care" as 0. Standard 802.3 polynomial,
96 // use a Public Domain table implementation
97 } sparse_header_t;
98
99 typedef struct chunk_header {
100 __le16 chunk_type; // 0xCAC1 -> raw; 0xCAC2 -> fill;
101 // 0xCAC3 -> don't care
102 __le16 reserved1;
103 __le32 chunk_sz; // in blocks in output image
104 __le32 total_sz; // in bytes of chunk input file including chunk header
105 // and data
106 } chunk_header_t;
107
108 Args:
109 chunks: A list of chunks to be written. Each entry should be a tuple of
110 (chunk_type, block_number).
111
112 Returns:
113 Filename of the created sparse image.
114 """
115 SPARSE_HEADER_MAGIC = 0xED26FF3A
116 SPARSE_HEADER_FORMAT = "<I4H4I"
117 CHUNK_HEADER_FORMAT = "<2H2I"
118
119 sparse_image = common.MakeTempFile(prefix='sparse-', suffix='.img')
120 with open(sparse_image, 'wb') as fp:
121 fp.write(struct.pack(
122 SPARSE_HEADER_FORMAT, SPARSE_HEADER_MAGIC, 1, 0, 28, 12, 4096,
123 sum(chunk[1] for chunk in chunks),
124 len(chunks), 0))
125
126 for chunk in chunks:
127 data_size = 0
128 if chunk[0] == 0xCAC1:
129 data_size = 4096 * chunk[1]
130 elif chunk[0] == 0xCAC2:
131 data_size = 4
132 elif chunk[0] == 0xCAC3:
133 pass
134 else:
135 assert False, "Unsupported chunk type: {}".format(chunk[0])
136
137 fp.write(struct.pack(
138 CHUNK_HEADER_FORMAT, chunk[0], 0, chunk[1], data_size + 12))
139 if data_size != 0:
140 fp.write(os.urandom(data_size))
141
142 return sparse_image
Tao Bao65b94e92018-10-11 21:57:26 -0700143
144
145class ReleaseToolsTestCase(unittest.TestCase):
146 """A common base class for all the releasetools unittests."""
147
148 def tearDown(self):
149 common.Cleanup()
Tao Bao30e31142019-04-09 00:12:30 -0700150
151
152if __name__ == '__main__':
153 testsuite = unittest.TestLoader().discover(
154 os.path.dirname(os.path.realpath(__file__)))
155 # atest needs a verbosity level of >= 2 to correctly parse the result.
156 unittest.TextTestRunner(verbosity=2).run(testsuite)