|
1 |
| -import os |
2 |
| -import tempfile |
3 |
| -from io import TextIOWrapper |
| 1 | +"""Tests for IO redirection in shell executor with mocked file operations.""" |
| 2 | + |
| 3 | +from unittest.mock import MagicMock, patch |
4 | 4 |
|
5 | 5 | import pytest
|
6 | 6 |
|
7 |
| -from mcp_shell_server.shell_executor import ShellExecutor |
| 7 | +from mcp_shell_server.io_redirection_handler import IORedirectionHandler |
8 | 8 |
|
9 | 9 |
|
10 | 10 | @pytest.fixture
|
11 |
| -def temp_test_dir(): |
12 |
| - """Create a temporary directory for testing""" |
13 |
| - with tempfile.TemporaryDirectory() as tmpdirname: |
14 |
| - yield os.path.realpath(tmpdirname) |
| 11 | +def mock_file(): |
| 12 | + """Create a mock file object.""" |
| 13 | + file_mock = MagicMock() |
| 14 | + file_mock.closed = False |
| 15 | + file_mock.close = MagicMock() |
| 16 | + file_mock.write = MagicMock() |
| 17 | + file_mock.read = MagicMock(return_value="test content") |
| 18 | + return file_mock |
15 | 19 |
|
16 | 20 |
|
17 |
| -@pytest.mark.asyncio |
18 |
| -async def test_redirection_setup(temp_test_dir): |
19 |
| - """Test setup of redirections with files""" |
20 |
| - executor = ShellExecutor() |
21 |
| - |
22 |
| - # Create a test input file |
23 |
| - with open(os.path.join(temp_test_dir, "input.txt"), "w") as f: |
24 |
| - f.write("test content") |
25 |
| - |
26 |
| - # Test input redirection setup |
27 |
| - redirects = { |
28 |
| - "stdin": "input.txt", |
29 |
| - "stdout": None, |
30 |
| - "stdout_append": False, |
31 |
| - } |
32 |
| - handles = await executor._setup_redirects(redirects, temp_test_dir) |
33 |
| - assert "stdin" in handles |
34 |
| - assert "stdin_data" in handles |
35 |
| - assert handles["stdin_data"] == "test content" |
36 |
| - assert isinstance(handles["stdout"], int) |
37 |
| - assert isinstance(handles["stderr"], int) |
38 |
| - |
39 |
| - # Test output redirection setup |
40 |
| - output_file = os.path.join(temp_test_dir, "output.txt") |
41 |
| - redirects = { |
42 |
| - "stdin": None, |
43 |
| - "stdout": output_file, |
44 |
| - "stdout_append": False, |
45 |
| - } |
46 |
| - handles = await executor._setup_redirects(redirects, temp_test_dir) |
47 |
| - assert isinstance(handles["stdout"], TextIOWrapper) |
48 |
| - assert not handles["stdout"].closed |
49 |
| - await executor._cleanup_handles(handles) |
50 |
| - try: |
51 |
| - assert handles["stdout"].closed |
52 |
| - except ValueError: |
53 |
| - # Ignore errors from already closed file |
54 |
| - pass |
| 21 | +@pytest.fixture |
| 22 | +def handler(): |
| 23 | + """Create a new IORedirectionHandler instance for each test.""" |
| 24 | + return IORedirectionHandler() |
55 | 25 |
|
56 | 26 |
|
57 | 27 | @pytest.mark.asyncio
|
58 |
| -async def test_redirection_append_mode(temp_test_dir): |
59 |
| - """Test output redirection in append mode""" |
60 |
| - executor = ShellExecutor() |
61 |
| - |
62 |
| - output_file = os.path.join(temp_test_dir, "output.txt") |
| 28 | +async def test_file_input_redirection(handler, mock_file): |
| 29 | + """Test input redirection from a file using mocks.""" |
| 30 | + with ( |
| 31 | + patch("builtins.open", return_value=mock_file), |
| 32 | + patch("os.path.exists", return_value=True), |
| 33 | + ): |
63 | 34 |
|
64 |
| - # Test append mode |
65 |
| - redirects = { |
66 |
| - "stdin": None, |
67 |
| - "stdout": output_file, |
68 |
| - "stdout_append": True, |
69 |
| - } |
70 |
| - handles = await executor._setup_redirects(redirects, temp_test_dir) |
71 |
| - assert handles["stdout"].mode == "a" |
72 |
| - await executor._cleanup_handles(handles) |
| 35 | + redirects = { |
| 36 | + "stdin": "input.txt", |
| 37 | + "stdout": None, |
| 38 | + "stdout_append": False, |
| 39 | + } |
| 40 | + handles = await handler.setup_redirects(redirects, "/mock/dir") |
73 | 41 |
|
74 |
| - # Test write mode |
75 |
| - redirects["stdout_append"] = False |
76 |
| - handles = await executor._setup_redirects(redirects, temp_test_dir) |
77 |
| - assert handles["stdout"].mode == "w" |
78 |
| - await executor._cleanup_handles(handles) |
| 42 | + assert "stdin" in handles |
| 43 | + assert "stdin_data" in handles |
| 44 | + assert handles["stdin_data"] == "test content" |
| 45 | + assert isinstance(handles["stdout"], int) |
| 46 | + assert isinstance(handles["stderr"], int) |
79 | 47 |
|
80 | 48 |
|
81 | 49 | @pytest.mark.asyncio
|
82 |
| -async def test_redirection_setup_errors(temp_test_dir): |
83 |
| - """Test error cases in redirection setup""" |
84 |
| - executor = ShellExecutor() |
85 |
| - |
86 |
| - # Test non-existent input file |
87 |
| - redirects = { |
88 |
| - "stdin": "nonexistent.txt", |
89 |
| - "stdout": None, |
90 |
| - "stdout_append": False, |
91 |
| - } |
92 |
| - with pytest.raises(ValueError, match="Failed to open input file"): |
93 |
| - await executor._setup_redirects(redirects, temp_test_dir) |
94 |
| - |
95 |
| - # Test error in output file creation |
96 |
| - os.chmod(temp_test_dir, 0o444) # Make directory read-only |
97 |
| - try: |
| 50 | +async def test_file_output_redirection(handler, mock_file): |
| 51 | + """Test output redirection to a file using mocks.""" |
| 52 | + with patch("builtins.open", return_value=mock_file): |
98 | 53 | redirects = {
|
99 | 54 | "stdin": None,
|
100 | 55 | "stdout": "output.txt",
|
101 | 56 | "stdout_append": False,
|
102 | 57 | }
|
103 |
| - with pytest.raises(ValueError, match="Failed to open output file"): |
104 |
| - await executor._setup_redirects(redirects, temp_test_dir) |
105 |
| - finally: |
106 |
| - os.chmod(temp_test_dir, 0o755) # Reset permissions |
| 58 | + handles = await handler.setup_redirects(redirects, "/mock/dir") |
107 | 59 |
|
| 60 | + assert "stdout" in handles |
| 61 | + assert not handles["stdout"].closed |
| 62 | + await handler.cleanup_handles(handles) |
| 63 | + mock_file.close.assert_called_once() |
108 | 64 |
|
109 |
| -@pytest.mark.asyncio |
110 |
| -async def test_invalid_redirection_paths(): |
111 |
| - """Test invalid redirection path scenarios""" |
112 |
| - executor = ShellExecutor() |
113 | 65 |
|
114 |
| - # Test missing path for output redirection |
115 |
| - with pytest.raises(ValueError, match="Missing path for output redirection"): |
116 |
| - executor._parse_command(["echo", "test", ">"]) |
| 66 | +@pytest.mark.asyncio |
| 67 | +async def test_append_mode(handler, mock_file): |
| 68 | + """Test output redirection in append mode using mocks.""" |
| 69 | + with patch("builtins.open", return_value=mock_file): |
| 70 | + # Test append mode |
| 71 | + redirects = { |
| 72 | + "stdin": None, |
| 73 | + "stdout": "output.txt", |
| 74 | + "stdout_append": True, |
| 75 | + } |
| 76 | + mock_file.mode = "a" # Set the expected mode |
| 77 | + handles = await handler.setup_redirects(redirects, "/mock/dir") |
| 78 | + assert handles["stdout"].mode == "a" |
| 79 | + await handler.cleanup_handles(handles) |
| 80 | + mock_file.close.assert_called_once() |
| 81 | + |
| 82 | + # Reset mock and test write mode |
| 83 | + mock_file.reset_mock() |
| 84 | + mock_file.mode = "w" # Set the expected mode for write mode |
| 85 | + redirects["stdout_append"] = False |
| 86 | + handles = await handler.setup_redirects(redirects, "/mock/dir") |
| 87 | + assert handles["stdout"].mode == "w" |
| 88 | + await handler.cleanup_handles(handles) |
| 89 | + mock_file.close.assert_called_once() |
| 90 | + |
| 91 | + |
| 92 | +def test_validate_redirection_syntax(handler): |
| 93 | + """Test validation of redirection syntax.""" |
| 94 | + # Valid cases |
| 95 | + handler.validate_redirection_syntax(["echo", "hello", ">", "output.txt"]) |
| 96 | + handler.validate_redirection_syntax(["cat", "<", "input.txt", ">", "output.txt"]) |
| 97 | + handler.validate_redirection_syntax(["echo", "hello", ">>", "output.txt"]) |
| 98 | + |
| 99 | + # Invalid cases |
| 100 | + with pytest.raises(ValueError, match="consecutive operators"): |
| 101 | + handler.validate_redirection_syntax(["echo", ">", ">", "output.txt"]) |
| 102 | + |
| 103 | + with pytest.raises(ValueError, match="consecutive operators"): |
| 104 | + handler.validate_redirection_syntax(["cat", "<", ">", "output.txt"]) |
| 105 | + |
| 106 | + |
| 107 | +def test_process_redirections(handler): |
| 108 | + """Test processing of redirection operators.""" |
| 109 | + # Input redirection |
| 110 | + cmd, redirects = handler.process_redirections(["cat", "<", "input.txt"]) |
| 111 | + assert cmd == ["cat"] |
| 112 | + assert redirects["stdin"] == "input.txt" |
| 113 | + assert redirects["stdout"] is None |
| 114 | + |
| 115 | + # Output redirection |
| 116 | + cmd, redirects = handler.process_redirections(["echo", "test", ">", "output.txt"]) |
| 117 | + assert cmd == ["echo", "test"] |
| 118 | + assert redirects["stdout"] == "output.txt" |
| 119 | + assert not redirects["stdout_append"] |
| 120 | + |
| 121 | + # Combined redirections |
| 122 | + cmd, redirects = handler.process_redirections( |
| 123 | + ["cat", "<", "in.txt", ">", "out.txt"] |
| 124 | + ) |
| 125 | + assert cmd == ["cat"] |
| 126 | + assert redirects["stdin"] == "in.txt" |
| 127 | + assert redirects["stdout"] == "out.txt" |
117 | 128 |
|
118 |
| - # Test invalid redirection target (operator found) |
119 |
| - with pytest.raises(ValueError, match="Invalid redirection target: operator found"): |
120 |
| - executor._parse_command(["echo", "test", ">", ">"]) |
121 | 129 |
|
122 |
| - # Test missing path for input redirection |
123 |
| - with pytest.raises(ValueError, match="Missing path for input redirection"): |
124 |
| - executor._parse_command(["cat", "<"]) |
| 130 | +@pytest.mark.asyncio |
| 131 | +async def test_setup_errors(handler, mock_file): |
| 132 | + """Test error cases in redirection setup using mocks.""" |
| 133 | + # Test non-existent input file |
| 134 | + with patch("os.path.exists", return_value=False): |
| 135 | + redirects = { |
| 136 | + "stdin": "nonexistent.txt", |
| 137 | + "stdout": None, |
| 138 | + "stdout_append": False, |
| 139 | + } |
| 140 | + with pytest.raises(ValueError, match="Failed to open input file"): |
| 141 | + await handler.setup_redirects(redirects, "/mock/dir") |
125 | 142 |
|
126 |
| - # Test missing path for output redirection |
127 |
| - with pytest.raises(ValueError, match="Missing path for output redirection"): |
128 |
| - executor._parse_command(["echo", "test", ">"]) |
| 143 | + # Test error in output file creation |
| 144 | + # Mock builtins.open to raise PermissionError |
| 145 | + mock_open = MagicMock(side_effect=PermissionError("Permission denied")) |
| 146 | + with patch("builtins.open", mock_open): |
| 147 | + redirects = { |
| 148 | + "stdin": None, |
| 149 | + "stdout": "output.txt", |
| 150 | + "stdout_append": False, |
| 151 | + } |
| 152 | + with pytest.raises(ValueError, match="Failed to open output file"): |
| 153 | + await handler.setup_redirects(redirects, "/mock/dir") |
129 | 154 |
|
130 |
| - # Test invalid redirection target: operator found for output |
131 |
| - with pytest.raises(ValueError, match="Invalid redirection target: operator found"): |
132 |
| - executor._parse_command(["echo", "test", ">", ">"]) |
| 155 | + mock_file.close.assert_not_called() |
0 commit comments