| 360 | return tests |
| 361 | |
| 362 | class TestRunner: |
| 363 | def __init__(self): |
| 364 | self.env = os.environ.copy() |
| 365 | self.cwd = os.getcwd() |
| 366 | self.oldpwd = self.cwd # Track OLDPWD for 'cd -' support |
| 367 | self.dirstack = [] # Track directory stack for pushd/popd |
| 368 | self.last_exit_code = 0 |
| 369 | |
| 370 | def run(self, tests, file_path): |
| 371 | passed = 0 |
| 372 | failed = 0 |
| 373 | |
| 374 | print(f"Running {len(tests)} code snippets...\n") |
| 375 | |
| 376 | for test in tests: |
| 377 | print(f"▶️ {file_path}:{test.line_number}: {test.command} ... ", end='', flush=True) |
| 378 | |
| 379 | with tempfile.NamedTemporaryFile(mode='w+', delete=False) as env_dump: |
| 380 | env_dump_path = env_dump.name |
| 381 | |
| 382 | state_dumper = ( |
| 383 | f"{sys.executable} -c " |
| 384 | f"'import os, json; " |
| 385 | f"d=dict(os.environ); " |
| 386 | f"d[\"__CWD__\"]=os.getcwd(); " |
| 387 | f"d[\"__EXIT__\"]=os.getenv(\"__RET\", \"0\"); " |
| 388 | f"print(json.dumps(d))' > {env_dump_path}" |
| 389 | ) |
| 390 | |
| 391 | # Set OLDPWD for 'cd -' support |
| 392 | self.env["OLDPWD"] = self.oldpwd |
| 393 | |
| 394 | # Handle pushd/popd specially since each command runs in a fresh shell |
| 395 | command = test.command |
| 396 | command_stripped = command.strip() |
| 397 | |
| 398 | if command_stripped.startswith("pushd "): |
| 399 | # pushd: save current dir to stack, then cd |
| 400 | target_dir = command_stripped[6:].strip() |
| 401 | self.dirstack.append(self.cwd) |
| 402 | # Let the shell do the pushd, but we track the stack ourselves |
| 403 | elif command_stripped == "popd": |
| 404 | if self.dirstack: |
| 405 | # Replace popd with cd to the popped directory |
| 406 | popped = self.dirstack.pop() |
| 407 | command = f"cd {popped}" |
| 408 | |
| 409 | # Export OLDPWD for 'cd -' support (must be shell variable, not just env) |
| 410 | full_command = ( |
| 411 | f"export OLDPWD='{self.oldpwd}'\n" |
| 412 | f"(exit {self.last_exit_code})\n" |
| 413 | f"{command}\n" |
| 414 | f"export __RET=$?\n" |
| 415 | f"{state_dumper}" |
| 416 | ) |
| 417 | |
| 418 | stream_output = test.options.get("print_command_output", False) |
| 419 | if stream_output: |