summaryrefslogtreecommitdiff
path: root/init/init_ddk_test.py
blob: 6fdc436a06025d1790b68a9948b1370e80a39b71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# Copyright (C) 2024 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for init_ddk.py"""

import logging
import pathlib
import tempfile
from typing import Any

from absl.testing import absltest
from absl.testing import parameterized
import init_ddk

# pylint: disable=protected-access


def join(*args: Any) -> str:
    return "\n".join([*args])


_HELLO_WORLD = "Hello World!"


class KleafProjectSetterTest(parameterized.TestCase):

    @parameterized.named_parameters([
        (
            "Empty",
            "",
            join(
                init_ddk._FILE_MARKER_BEGIN,
                _HELLO_WORLD,
                init_ddk._FILE_MARKER_END,
            ),
        ),
        (
            "BeforeNoMarkers",
            "Existing test\n",
            join(
                "Existing test",
                init_ddk._FILE_MARKER_BEGIN,
                _HELLO_WORLD,
                init_ddk._FILE_MARKER_END,
            ),
        ),
        (
            "AfterMarkers",
            join(
                init_ddk._FILE_MARKER_BEGIN,
                init_ddk._FILE_MARKER_END,
                "Existing test after.",
            ),
            join(
                init_ddk._FILE_MARKER_BEGIN,
                _HELLO_WORLD,
                init_ddk._FILE_MARKER_END,
                "Existing test after.",
            ),
        ),
    ])
    def test_update_file_existing(self, current_content, wanted_content):
        """Tests only text within markers are updated."""
        with tempfile.TemporaryDirectory() as tmp:
            tmp_file = pathlib.Path(tmp) / "some_file"
            with open(tmp_file, "w+", encoding="utf-8") as tf:
                tf.write(current_content)
            init_ddk.KleafProjectSetter._update_file(
                tmp_file, "\n" + _HELLO_WORLD
            )
            with open(tmp_file, "r", encoding="utf-8") as got:
                self.assertEqual(wanted_content, got.read())

    def test_update_file_no_existing(self):
        """Tests files are created when they don't exist."""
        with tempfile.TemporaryDirectory() as tmp:
            tmp_file = pathlib.Path(tmp) / "some_file"
            init_ddk.KleafProjectSetter._update_file(
                tmp_file, "\n" + _HELLO_WORLD
            )
            with open(tmp_file, "r", encoding="utf-8") as got:
                self.assertEqual(
                    join(
                        init_ddk._FILE_MARKER_BEGIN,
                        _HELLO_WORLD,
                        init_ddk._FILE_MARKER_END,
                    ),
                    got.read(),
                )

    def test_relevant_directories_created(self):
        """Tests corresponding directories are created if they don't exist."""
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_dir = pathlib.Path(temp_dir)
            ddk_workspace = temp_dir / "ddk_workspace"
            kleaf_repo = temp_dir / "kleaf_repo"
            prebuilts_dir = temp_dir / "prebuilts_dir"
            try:
                init_ddk.KleafProjectSetter(
                    build_id=None,
                    build_target=None,
                    ddk_workspace=ddk_workspace,
                    kleaf_repo=kleaf_repo,
                    prebuilts_dir=prebuilts_dir,
                    url_fmt=None,
                ).run()
            except:  # pylint: disable=bare-except
                pass
            finally:
                self.assertTrue(ddk_workspace.exists())
                self.assertTrue(kleaf_repo.exists())
                self.assertTrue(prebuilts_dir.exists())

    def test_tools_bazel_symlink(self):
        """Tests a symlink to tools/bazel is correctly created."""
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_dir = pathlib.Path(temp_dir)
            ddk_workspace = temp_dir / "ddk_workspace"
            try:
                init_ddk.KleafProjectSetter(
                    build_id=None,
                    build_target=None,
                    ddk_workspace=ddk_workspace,
                    kleaf_repo=temp_dir / "kleaf_repo",
                    prebuilts_dir=None,
                    url_fmt=None,
                ).run()
            except:  # pylint: disable=bare-except
                pass
            finally:
                tools_bazel_symlink = ddk_workspace / init_ddk._TOOLS_BAZEL
                self.assertTrue(tools_bazel_symlink.is_symlink())

    def _run_test_module_bazel_for_prebuilts(
        self,
        ddk_workspace: pathlib.Path,
        prebuilts_dir: pathlib.Path,
        expected: str,
    ):
        """Helper method for checking path in a prebuilt extension."""
        download_configs = prebuilts_dir / "download_configs.json"
        download_configs.parent.mkdir(parents=True)
        download_configs.write_text("{}")
        try:
            init_ddk.KleafProjectSetter(
                build_id=None,
                build_target=None,
                ddk_workspace=ddk_workspace,
                kleaf_repo=None,
                prebuilts_dir=prebuilts_dir,
                url_fmt=None,
            ).run()
        except:  # pylint: disable=bare-except
            pass
        finally:
            module_bazel = ddk_workspace / init_ddk._MODULE_BAZEL_FILE
            self.assertTrue(module_bazel.exists())
            content = module_bazel.read_text()
            self.assertTrue(f'local_artifact_path = "{expected}",' in content)

    def test_module_bazel_for_prebuilts(self):
        """Tests prebuilts setup is correct for relative and non-relative to workspace dirs."""
        with tempfile.TemporaryDirectory() as tmp:
            ddk_workspace = pathlib.Path(tmp) / "ddk_workspace"

            # Verify the right local_artifact_path is set for prebuilts
            #  in a relative to workspace directory.
            prebuilts_dir_rel = ddk_workspace / "prebuilts_dir"
            self._run_test_module_bazel_for_prebuilts(
                ddk_workspace=ddk_workspace,
                prebuilts_dir=prebuilts_dir_rel,
                expected="prebuilts_dir",
            )

            # Verify the right local_artifact_path is set for prebuilts
            #  in a non-relative to workspace directory.
            prebuilts_dir_abs = pathlib.Path(tmp) / "prebuilts_dir"
            self._run_test_module_bazel_for_prebuilts(
                ddk_workspace=ddk_workspace,
                prebuilts_dir=prebuilts_dir_abs,
                expected=str(prebuilts_dir_abs),
            )


# This could be run as: tools/bazel test //build/kernel:init_ddk_test --test_output=all
if __name__ == "__main__":
    logging.basicConfig(
        level=logging.DEBUG, format="%(levelname)s: %(message)s"
    )
    absltest.main()