Mock environment that simulates container file system and command execution.
| 13 | |
| 14 | |
| 15 | class MockEnvironment: |
| 16 | """Mock environment that simulates container file system and command execution.""" |
| 17 | |
| 18 | def __init__(self, files: dict[str, str] | None = None, command_outputs: dict[str, dict] | None = None): |
| 19 | """ |
| 20 | Args: |
| 21 | files: Dict mapping file paths to their contents |
| 22 | command_outputs: Dict mapping command prefixes to their outputs |
| 23 | Format: {"ls": {"output": "file1.py\nfile2.py", "returncode": 0}} |
| 24 | """ |
| 25 | self.files = files or {} |
| 26 | self.command_outputs = command_outputs or {} |
| 27 | self.config = MagicMock() |
| 28 | self.config.cwd = "/workspace" |
| 29 | self._executed_commands: list[str] = [] |
| 30 | |
| 31 | def execute(self, cmd: str, cwd: str | None = None, timeout: int | None = None) -> dict[str, Any]: |
| 32 | """Simulate command execution based on configured outputs.""" |
| 33 | self._executed_commands.append(cmd) |
| 34 | |
| 35 | # Check for exact matches first |
| 36 | if cmd in self.command_outputs: |
| 37 | return self.command_outputs[cmd] |
| 38 | |
| 39 | # Check for prefix matches |
| 40 | for prefix, output in self.command_outputs.items(): |
| 41 | if cmd.startswith(prefix): |
| 42 | return output |
| 43 | |
| 44 | # Default behavior for common commands |
| 45 | if cmd.startswith("ls"): |
| 46 | # Extract path from command |
| 47 | parts = cmd.split() |
| 48 | path = parts[1] if len(parts) > 1 else "." |
| 49 | matching_files = [Path(f).name for f in self.files.keys() if f.startswith(path) or path == "."] |
| 50 | return {"output": "\n".join(matching_files), "returncode": 0} |
| 51 | |
| 52 | if cmd.startswith("cat "): |
| 53 | file_path = cmd.split("cat ", 1)[1].strip() |
| 54 | if file_path in self.files: |
| 55 | return {"output": self.files[file_path], "returncode": 0} |
| 56 | return {"output": f"cat: {file_path}: No such file or directory", "returncode": 1} |
| 57 | |
| 58 | if cmd.startswith("test -f ") and "echo" in cmd: |
| 59 | file_path = cmd.split("test -f ")[1].split(" &&")[0].strip() |
| 60 | exists = file_path in self.files |
| 61 | return {"output": "exists" if exists else "", "returncode": 0 if exists else 1} |
| 62 | |
| 63 | if cmd.startswith("test -d ") and "echo" in cmd: |
| 64 | dir_path = cmd.split("test -d ")[1].split(" &&")[0].strip() |
| 65 | # Check if any file path starts with this directory |
| 66 | exists = any(f.startswith(dir_path + "/") or f == dir_path for f in self.files.keys()) |
| 67 | return {"output": "exists" if exists else "", "returncode": 0 if exists else 1} |
| 68 | |
| 69 | # Default: command succeeded with no output |
| 70 | return {"output": "", "returncode": 0} |
| 71 | |
| 72 |
no outgoing calls