| 6 | |
| 7 | |
| 8 | class ProgramMock: |
| 9 | def __init__(self, directory: str): |
| 10 | self.directory = Path(os.path.abspath(directory)) |
| 11 | os.makedirs(self.directory, exist_ok=True) |
| 12 | |
| 13 | def update_env(self, env: Dict[str, str]): |
| 14 | path = str(self.directory) |
| 15 | if "PATH" in env: |
| 16 | path += f":{env['PATH']}" |
| 17 | env["PATH"] = path |
| 18 | |
| 19 | def redirect_program_to_binary(self, mocked_program: str, target_binary: Path): |
| 20 | """ |
| 21 | Mocks `mocked_program` so that when you try to execute it, `target_binary` will be executed |
| 22 | instead. |
| 23 | """ |
| 24 | link_path = self.directory / mocked_program |
| 25 | link_path.unlink(missing_ok=True) |
| 26 | os.symlink(dst=link_path, src=target_binary) |
| 27 | # Make the link executable |
| 28 | os.chmod(link_path, 0o700) |
| 29 | |
| 30 | @contextlib.contextmanager |
| 31 | def mock_program_with_code(self, name: str, code: str): |
| 32 | import textwrap |
| 33 | |
| 34 | content = f"#!{sys.executable}\n{textwrap.dedent(code)}" |
| 35 | program_path = self.directory / name |
| 36 | assert not program_path.is_file() |
| 37 | |
| 38 | with open(program_path, "w") as f: |
| 39 | f.write(content) |
| 40 | os.chmod(program_path, 0o700) |
| 41 | |
| 42 | yield program_path |
| 43 | |
| 44 | os.unlink(program_path) |
no outgoing calls