blob: 919c193955350453f05e2f9af6081d12a0566b69 [file] [log] [blame]
Luca Farsib9c54642024-08-13 17:16:33 -07001# Copyright 2024, 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
15"""Tests for optimized_targets.py"""
16
17import json
18import logging
19import os
20import pathlib
21import re
22import unittest
23from unittest import mock
24import optimized_targets
25from build_context import BuildContext
26from pyfakefs import fake_filesystem_unittest
27
28
29class GeneralTestsOptimizerTest(fake_filesystem_unittest.TestCase):
30
31 def setUp(self):
32 self.setUpPyfakefs()
33
34 os_environ_patcher = mock.patch.dict('os.environ', {})
35 self.addCleanup(os_environ_patcher.stop)
36 self.mock_os_environ = os_environ_patcher.start()
37
38 self._setup_working_build_env()
39 self._write_change_info_file()
40 test_mapping_dir = pathlib.Path('/project/path/file/path')
41 test_mapping_dir.mkdir(parents=True)
42 self._write_test_mapping_file()
43
44 def _setup_working_build_env(self):
45 self.change_info_file = pathlib.Path('/tmp/change_info')
46
47 self.mock_os_environ.update({
48 'CHANGE_INFO': str(self.change_info_file),
49 })
50
51 def test_general_tests_optimized(self):
52 optimizer = self._create_general_tests_optimizer()
53
54 build_targets = optimizer.get_build_targets()
55
56 expected_build_targets = set(
57 optimized_targets.GeneralTestsOptimizer._REQUIRED_MODULES
58 )
59 expected_build_targets.add('test_mapping_module')
60
61 self.assertSetEqual(build_targets, expected_build_targets)
62
63 def test_no_change_info_no_optimization(self):
64 del os.environ['CHANGE_INFO']
65
66 optimizer = self._create_general_tests_optimizer()
67
68 build_targets = optimizer.get_build_targets()
69
70 self.assertSetEqual(build_targets, {'general-tests'})
71
72 def test_mapping_groups_unused_module_not_built(self):
73 test_context = self._create_test_context()
74 test_context['testInfos'][0]['extraOptions'] = [
75 {
76 'key': 'additional-files-filter',
77 'values': ['general-tests.zip'],
78 },
79 {
80 'key': 'test-mapping-test-group',
81 'values': ['unused-test-mapping-group'],
82 },
83 ]
84 optimizer = self._create_general_tests_optimizer(
85 build_context=self._create_build_context(test_context=test_context)
86 )
87
88 build_targets = optimizer.get_build_targets()
89
90 expected_build_targets = set(
91 optimized_targets.GeneralTestsOptimizer._REQUIRED_MODULES
92 )
93 self.assertSetEqual(build_targets, expected_build_targets)
94
95 def test_general_tests_used_by_non_test_mapping_test_no_optimization(self):
96 test_context = self._create_test_context()
97 test_context['testInfos'][0]['extraOptions'] = [{
98 'key': 'additional-files-filter',
99 'values': ['general-tests.zip'],
100 }]
101 optimizer = self._create_general_tests_optimizer(
102 build_context=self._create_build_context(test_context=test_context)
103 )
104
105 build_targets = optimizer.get_build_targets()
106
107 self.assertSetEqual(build_targets, {'general-tests'})
108
109 def test_malformed_change_info_raises(self):
110 with open(self.change_info_file, 'w') as f:
111 f.write('not change info')
112
113 optimizer = self._create_general_tests_optimizer()
114
115 with self.assertRaises(json.decoder.JSONDecodeError):
116 build_targets = optimizer.get_build_targets()
117
118 def test_malformed_test_mapping_raises(self):
119 with open('/project/path/file/path/TEST_MAPPING', 'w') as f:
120 f.write('not test mapping')
121
122 optimizer = self._create_general_tests_optimizer()
123
124 with self.assertRaises(json.decoder.JSONDecodeError):
125 build_targets = optimizer.get_build_targets()
126
127 def _write_change_info_file(self):
128 change_info_contents = {
129 'changes': [{
130 'projectPath': '/project/path',
131 'revisions': [{
132 'fileInfos': [{
133 'path': 'file/path/file_name',
134 }],
135 }],
136 }]
137 }
138
139 with open(self.change_info_file, 'w') as f:
140 json.dump(change_info_contents, f)
141
142 def _write_test_mapping_file(self):
143 test_mapping_contents = {
144 'test-mapping-group': [
145 {
146 'name': 'test_mapping_module',
147 },
148 ],
149 }
150
151 with open('/project/path/file/path/TEST_MAPPING', 'w') as f:
152 json.dump(test_mapping_contents, f)
153
154 def _create_general_tests_optimizer(
155 self, build_context: BuildContext = None
156 ):
157 if not build_context:
158 build_context = self._create_build_context()
159 return optimized_targets.GeneralTestsOptimizer(
160 'general-tests', build_context, None
161 )
162
163 def _create_build_context(
164 self,
165 general_tests_optimized: bool = True,
166 test_context: dict[str, any] = None,
167 ) -> BuildContext:
168 if not test_context:
169 test_context = self._create_test_context()
170 build_context_dict = {}
171 build_context_dict['enabledBuildFeatures'] = [{'name': 'optimized_build'}]
172 if general_tests_optimized:
173 build_context_dict['enabledBuildFeatures'].append({'name': 'general_tests_optimized'})
174 build_context_dict['testContext'] = test_context
175 return BuildContext(build_context_dict)
176
177 def _create_test_context(self):
178 return {
179 'testInfos': [
180 {
181 'name': 'atp_test',
182 'target': 'test_target',
183 'branch': 'branch',
184 'extraOptions': [
185 {
186 'key': 'additional-files-filter',
187 'values': ['general-tests.zip'],
188 },
189 {
190 'key': 'test-mapping-test-group',
191 'values': ['test-mapping-group'],
192 },
193 ],
194 'command': '/tf/command',
195 'extraBuildTargets': [
196 'extra_build_target',
197 ],
198 },
199 ],
200 }
201
202
203if __name__ == '__main__':
204 # Setup logging to be silent so unit tests can pass through TF.
205 logging.disable(logging.ERROR)
206 unittest.main()