• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2023 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Tests for pw_ide.cpp which require fake envs"""
15
16import os
17from pathlib import Path
18import sys
19import tempfile
20import unittest
21
22import pw_cli.env
23from pw_cli.env import pigweed_environment
24import pw_ide.cpp
25from pw_ide.cpp import find_cipd_installed_exe_path
26
27
28class PwFindCipdInstalledExeTests(unittest.TestCase):
29    """A test case for testing `find_cipd_installed_exe_path`.
30
31    Test case hacks environment value `PW_PIGWEED_CIPD_INSTALL_DIR` and
32    `PW_FAKE_PROJ_CIPD_INSTALL_DIR` to point to temporary directories. It checks
33    that executable file search through these CIPD defined environment variables
34    are working properly.
35    """
36
37    def setUp(self) -> None:
38        self.temp_dir = tempfile.TemporaryDirectory()
39        self.temp_dir_path = Path(self.temp_dir.name)
40
41        self.envs_saves: dict[str, str | None] = {
42            "PW_FAKE_PROJ_CIPD_INSTALL_DIR": None,
43            "PW_PIGWEED_CIPD_INSTALL_DIR": None,
44        }
45
46        for env_name in self.envs_saves:
47            self.envs_saves[env_name] = os.environ.get(env_name, None)
48
49        self.setup_test_files_and_fake_envs()
50
51        # Environment variables are cached in each modules as global variables.
52        # In order to override them, caches need to be reset.
53        # pylint: disable=protected-access
54        pw_cli.env._memoized_environment = None
55        # pylint: enable=protected-access
56        pw_ide.cpp.env = pigweed_environment()
57
58        return super().setUp()
59
60    def tearDown(self) -> None:
61        for env_var_name, env_var in self.envs_saves.items():
62            if env_var is not None:
63                os.environ[env_var_name] = env_var
64            else:
65                os.environ.pop(env_var_name)
66
67        self.temp_dir.cleanup()
68
69        return super().tearDown()
70
71    def setup_test_files_and_fake_envs(self) -> None:
72        """Create necessary temporaries file and sets corresponding envs."""
73        os.environ["PW_FAKE_PROJ_CIPD_INSTALL_DIR"] = str(
74            self.touch_temp_exe_file(
75                Path("proj_install") / "bin" / "exe_in_proj_install"
76            ).parent.parent
77        )
78
79        os.environ["PW_PIGWEED_CIPD_INSTALL_DIR"] = str(
80            self.touch_temp_exe_file(
81                Path("pigweed_install") / "bin" / "exe_in_pigweed_install"
82            ).parent.parent
83        )
84
85    def touch_temp_exe_file(self, exe_path: Path) -> Path:
86        """Create a temporary executable file given a path."""
87        if sys.platform.lower() in ("win32", "cygwin"):
88            exe_path = Path(str(exe_path) + ".exe")
89
90        file_path = self.temp_dir_path / exe_path
91
92        os.makedirs(os.path.dirname(file_path), exist_ok=True)
93        with open(file_path, "w") as f:
94            f.write("aaa")
95
96        return file_path
97
98    def test_find_from_pigweed_cipd_install(self):
99        env_vars = vars(pigweed_environment())
100
101        self.assertTrue(
102            str(
103                find_cipd_installed_exe_path("exe_in_pigweed_install")
104            ).startswith(env_vars.get("PW_PIGWEED_CIPD_INSTALL_DIR"))
105        )
106
107    def test_find_from_project_defined_cipd_install(self):
108        env_vars = vars(pigweed_environment())
109
110        self.assertTrue(
111            str(find_cipd_installed_exe_path("exe_in_proj_install")).startswith(
112                env_vars.get("PW_FAKE_PROJ_CIPD_INSTALL_DIR")
113            )
114        )
115
116
117if __name__ == '__main__':
118    unittest.main()
119