• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#
2# Copyright (C) 2023 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16"""Unit tests for fileutils."""
17
18import contextlib
19import unittest
20from pathlib import Path
21from tempfile import TemporaryDirectory
22
23import fileutils
24
25UNFORMATTED_BP_FILE = """\
26cc_library_shared {
27    name: "test",
28    srcs: [
29        "source2.c",
30        "source1.c",
31    ],
32    cflags: ["-Wno-error=ignored-attributes", "-Wall", "-Werror"],
33}
34"""
35
36FORMATTED_BP_FILE = """\
37cc_library_shared {
38    name: "test",
39    srcs: [
40        "source2.c",
41        "source1.c",
42    ],
43    cflags: [
44        "-Wno-error=ignored-attributes",
45        "-Wall",
46        "-Werror",
47    ],
48}
49"""
50
51
52class ResolveCommandLinePathsTest(unittest.TestCase):
53    """Unit tests for resolve_command_line_paths."""
54
55    def test_empty_paths(self) -> None:
56        """Tests that an empty argument returns an empty list."""
57        self.assertListEqual([], fileutils.resolve_command_line_paths([]))
58
59    def test_absolute_paths(self) -> None:
60        """Tests that absolute paths are resolved correctly."""
61        with TemporaryDirectory() as temp_dir_str:
62            temp_dir = Path(temp_dir_str)
63            a = temp_dir / "a"
64            b = temp_dir / "external" / "b"
65            a.mkdir()
66            b.mkdir(parents=True)
67            self.assertListEqual(
68                [a, b],
69                fileutils.resolve_command_line_paths(
70                    [str(a), str(b), "/does/not/exist"]
71                ),
72            )
73
74    def test_relative_paths(self) -> None:
75        """Tests that relative paths are resolved correctly."""
76        with TemporaryDirectory() as temp_dir_str:
77            # Make this absolute so the CWD change later doesn't break it.
78            temp_dir = Path(temp_dir_str).resolve()
79            external = temp_dir / "external"
80            external.mkdir()
81            a = external / "a"
82            a.mkdir()
83
84            working_dir = temp_dir / "cwd"
85            working_dir.mkdir()
86            b = working_dir / "b"
87            b.mkdir()
88            with contextlib.chdir(working_dir):
89                self.assertListEqual(
90                    [a, working_dir, b],
91                    fileutils.resolve_command_line_paths(
92                        [
93                            # These will all be resolved as absolute paths and returned.
94                            "../external/a",
95                            ".",
96                            "b",
97                            # This one doesn't exist. It will be pruned from the result.
98                            "c",
99                        ]
100                    ),
101                )
102
103
104class FindTreeContainingTest(unittest.TestCase):
105    """Unit tests for find_tree_containing."""
106
107    def setUp(self) -> None:
108        self._temp_dir = TemporaryDirectory()
109        self.temp_dir = Path(self._temp_dir.name)
110        self.repo_tree = self.temp_dir / "tree"
111        (self.repo_tree / ".repo").mkdir(parents=True)
112
113    def tearDown(self) -> None:
114        self._temp_dir.cleanup()
115
116    def test_cwd_is_in_tree(self) -> None:
117        """Tests that the root is found when the CWD is in the same tree."""
118        (self.repo_tree / "external/a").mkdir(parents=True)
119        (self.repo_tree / "external/b").mkdir(parents=True)
120
121        with contextlib.chdir(self.repo_tree / "external/a"):
122            self.assertEqual(
123                fileutils.find_tree_containing(self.repo_tree / "external/b"),
124                self.repo_tree,
125            )
126
127    def test_cwd_is_in_other_tree(self) -> None:
128        """Tests that the root is found when the CWD is in another tree."""
129        tree_a = self.temp_dir / "a"
130        (tree_a / ".repo").mkdir(parents=True)
131        (tree_a / "external/a").mkdir(parents=True)
132
133        tree_b = self.temp_dir / "b"
134        (tree_b / ".repo").mkdir(parents=True)
135        (tree_b / "external/b").mkdir(parents=True)
136
137        with contextlib.chdir(tree_a / "external/a"):
138            self.assertEqual(
139                fileutils.find_tree_containing(tree_b / "external/b"), tree_b
140            )
141
142    def test_no_root(self) -> None:
143        """Tests that an error is raised when no tree is found."""
144        with self.assertRaises(FileNotFoundError):
145            fileutils.find_tree_containing(self.temp_dir)
146
147
148class BpfmtTest(unittest.TestCase):
149    """Unit tests for bpfmt."""
150
151    def setUp(self) -> None:
152        self._temp_dir = TemporaryDirectory()
153        self.temp_dir = Path(self._temp_dir.name)
154        (self.temp_dir / "Android.bp").write_text(UNFORMATTED_BP_FILE)
155
156    def tearDown(self) -> None:
157        self._temp_dir.cleanup()
158
159    def test_unformatted_bpfmt(self) -> None:
160        """Tests that bpfmt formats the bp file."""
161        results = fileutils.bpfmt(self.temp_dir, ['Android.bp'])
162        content = (self.temp_dir / "Android.bp").read_text()
163        if results:
164            self.assertEqual(content, FORMATTED_BP_FILE)
165
166
167if __name__ == "__main__":
168    unittest.main(verbosity=2)
169