AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | from agent_guard.parser import parse_argv, parse_command |
| 5 | |
| 6 | |
| 7 | def test_parse_simple() -> None: |
| 8 | p = parse_command("git status") |
| 9 | assert p.program == "git" |
| 10 | assert p.subcommand == "status" |
| 11 | assert p.parse_error is None |
| 12 | |
| 13 | |
| 14 | def test_parse_flags_and_args() -> None: |
| 15 | p = parse_command("git push --force origin main") |
| 16 | assert p.program == "git" |
| 17 | assert p.subcommand == "push" |
| 18 | assert "--force" in p.flags |
| 19 | assert "origin" in p.positional |
| 20 | assert "main" in p.positional |
| 21 | |
| 22 | |
| 23 | def test_parse_quoted_strings() -> None: |
| 24 | p = parse_command('echo "hello world"') |
| 25 | assert p.program == "echo" |
| 26 | assert p.arguments == ("hello world",) |
| 27 | |
| 28 | |
| 29 | def test_parse_windows_path() -> None: |
| 30 | p = parse_command(r"type C:\Users\demo\.env") |
| 31 | assert p.program == "type" |
| 32 | assert any(".env" in a or "Users" in a for a in p.arguments) |
| 33 | |
| 34 | |
| 35 | def test_parse_shell_operators() -> None: |
| 36 | p = parse_command("rm -rf ./src && npm install") |
| 37 | assert p.has_shell_operators |
| 38 | assert "&&" in p.shell_operators |
| 39 | assert len(p.segments) >= 2 |
| 40 | |
| 41 | |
| 42 | def test_parse_empty() -> None: |
| 43 | p = parse_command(" ") |
| 44 | assert p.parse_error == "empty command" |
| 45 | |
| 46 | |
| 47 | def test_parse_null_bytes() -> None: |
| 48 | p = parse_command("echo\x00hi") |
| 49 | assert p.parse_error is not None or p.program == "echohi" or "null" in (p.parse_error or "") |
| 50 | |
| 51 | |
| 52 | def test_parse_malformed_quotes() -> None: |
| 53 | p = parse_command('echo "unterminated') |
| 54 | # Must not raise; may set parse_error |
| 55 | assert isinstance(p.program, str) |
| 56 | |
| 57 | |
| 58 | def test_parse_huge_string() -> None: |
| 59 | p = parse_command("a" * 100_001) |
| 60 | assert p.parse_error == "command too large" |
| 61 | |
| 62 | |
| 63 | def test_parse_docker_compose() -> None: |
| 64 | p = parse_command("docker compose down -v") |
| 65 | assert p.program == "docker" |
| 66 | assert p.subcommand is not None |
| 67 | assert "compose" in p.subcommand |
| 68 | |
| 69 | |
| 70 | def test_parse_argv() -> None: |
| 71 | p = parse_argv(["git", "reset", "--hard", "HEAD"]) |
| 72 | assert p.program == "git" |
| 73 | assert p.subcommand == "reset" |
| 74 | assert "--hard" in p.flags |
| 75 | |
| 76 | |
| 77 | def test_parse_unicode() -> None: |
| 78 | p = parse_command("echo café") |
| 79 | assert p.program == "echo" |