| … | … | @@ -0,0 +1,492 @@ |
| 1 | """ |
| 2 | Tests for the system tools module. |
| 3 | """ |
| 4 | import pytest |
| 5 | import sys |
| 6 | import os |
| 7 | import re |
| 8 | import tempfile |
| 9 | import shutil |
| 10 | from unittest.mock import patch, MagicMock |
| 11 | import subprocess |
| 12 | |
| 13 | # Add the parent directory to the path so we can import the package |
| 14 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) |
| 15 | |
| 16 | from ollamatools.tools.system_tools import ( |
| 17 | execute_command, |
| 18 | read_file, |
| 19 | write_file, |
| 20 | find_files, |
| 21 | _sanitize_command, |
| 22 | _sanitize_argument |
| 23 | ) |
| 24 | from ollamatools.security import PermissionManager |
| 25 | |
| 26 | |
| 27 | # Setup and teardown for temporary test directory |
| 28 | @pytest.fixture |
| 29 | def temp_dir(): |
| 30 | """Create a temporary directory for file operations tests.""" |
| 31 | tmp_dir = tempfile.mkdtemp() |
| 32 | try: |
| 33 | yield tmp_dir |
| 34 | finally: |
| 35 | shutil.rmtree(tmp_dir) |
| 36 | |
| 37 | |
| 38 | def test_sanitize_command(): |
| 39 | """Test the command sanitization function.""" |
| 40 | # Valid commands |
| 41 | assert _sanitize_command("ls") == "ls" |
| 42 | assert _sanitize_command("ls -la") == "ls -la" |
| 43 | assert _sanitize_command("echo 'Hello World'") == "echo 'Hello World'" |
| 44 | assert _sanitize_command(" find /tmp -name '*.txt' ") == "find /tmp -name '*.txt'" |
| 45 | |
| 46 | # Invalid commands |
| 47 | with pytest.raises(ValueError) as excinfo: |
| 48 | _sanitize_command("") |
| 49 | assert "Empty command" in str(excinfo.value) |
| 50 | |
| 51 | with pytest.raises(ValueError) as excinfo: |
| 52 | _sanitize_command("ls | grep txt") |
| 53 | assert "dangerous pattern" in str(excinfo.value) |
| 54 | |
| 55 | with pytest.raises(ValueError) as excinfo: |
| 56 | _sanitize_command("echo 'hello' > file.txt") |
| 57 | assert "dangerous pattern" in str(excinfo.value) |
| 58 | |
| 59 | with pytest.raises(ValueError) as excinfo: |
| 60 | _sanitize_command("cat < file.txt") |
| 61 | assert "dangerous pattern" in str(excinfo.value) |
| 62 | |
| 63 | with pytest.raises(ValueError) as excinfo: |
| 64 | _sanitize_command("echo $(whoami)") |
| 65 | assert "dangerous pattern" in str(excinfo.value) |
| 66 | |
| 67 | with pytest.raises(ValueError) as excinfo: |
| 68 | _sanitize_command("echo `whoami`") |
| 69 | assert "dangerous pattern" in str(excinfo.value) |
| 70 | |
| 71 | |
| 72 | def test_sanitize_argument(): |
| 73 | """Test the argument sanitization function.""" |
| 74 | # Valid arguments |
| 75 | assert _sanitize_argument("file.txt") == "file.txt" |
| 76 | assert _sanitize_argument("-la") == "-la" |
| 77 | assert _sanitize_argument("--help") == "--help" |
| 78 | assert _sanitize_argument("/tmp/file with spaces.txt") == "/tmp/file with spaces.txt" |
| 79 | |
| 80 | # Test non-string arguments |
| 81 | assert _sanitize_argument(123) == "123" |
| 82 | |
| 83 | # Invalid arguments |
| 84 | with pytest.raises(ValueError) as excinfo: |
| 85 | _sanitize_argument("file.txt | grep txt") |
| 86 | assert "dangerous pattern" in str(excinfo.value) |
| 87 | |
| 88 | with pytest.raises(ValueError) as excinfo: |
| 89 | _sanitize_argument("$(whoami)") |
| 90 | assert "dangerous pattern" in str(excinfo.value) |
| 91 | |
| 92 | |
| 93 | def test_execute_command_simple(): |
| 94 | """Test executing a simple command.""" |
| 95 | # Test a simple echo command |
| 96 | result = execute_command("echo", ["Hello", "World"]) |
| 97 | |
| 98 | assert result["stdout"].strip() == "Hello World" |
| 99 | assert result["stderr"] == "" |
| 100 | assert result["exit_code"] == 0 |
| 101 | assert result["command"] == "echo Hello World" |
| 102 | |
| 103 | |
| 104 | def test_execute_command_error(): |
| 105 | """Test executing a command that returns an error.""" |
| 106 | # Test a command that should fail (non-existent command) |
| 107 | result = execute_command("ls", ["--invalid-option"]) |
| 108 | |
| 109 | assert result["stderr"] != "" # Should have error output |
| 110 | assert result["exit_code"] != 0 # Non-zero exit code |
| 111 | |
| 112 | # Test a command that doesn't exist |
| 113 | with pytest.raises(subprocess.SubprocessError): |
| 114 | execute_command("command_that_does_not_exist") |
| 115 | |
| 116 | |
| 117 | def test_execute_command_timeout(): |
| 118 | """Test command timeout handling.""" |
| 119 | # Patch subprocess.run to simulate a timeout |
| 120 | with patch('subprocess.run') as mock_run: |
| 121 | mock_run.side_effect = subprocess.TimeoutExpired(cmd="sleep 10", timeout=1) |
| 122 | |
| 123 | with pytest.raises(TimeoutError) as excinfo: |
| 124 | execute_command("sleep", ["10"], timeout=1) |
| 125 | |
| 126 | assert "timed out" in str(excinfo.value) |
| 127 | |
| 128 | |
| 129 | def test_execute_command_with_permission_manager(): |
| 130 | """Test executing a command with the permission manager.""" |
| 131 | # Create a mock permission manager |
| 132 | mock_pm = MagicMock(spec=PermissionManager) |
| 133 | |
| 134 | # Test with permission granted |
| 135 | mock_pm.request_permission.return_value = True |
| 136 | result = execute_command("echo", ["Hello"], permission_manager=mock_pm) |
| 137 | assert result["stdout"].strip() == "Hello" |
| 138 | assert mock_pm.request_permission.called |
| 139 | |
| 140 | # Test with permission denied |
| 141 | mock_pm.request_permission.return_value = False |
| 142 | with pytest.raises(PermissionError) as excinfo: |
| 143 | execute_command("echo", ["Hello"], permission_manager=mock_pm) |
| 144 | assert "Permission denied" in str(excinfo.value) |
| 145 | assert mock_pm.request_permission.called |
| 146 | |
| 147 | |
| 148 | def test_execute_command_sudo(): |
| 149 | """Test sudo command detection and handling.""" |
| 150 | # Create a mock permission manager |
| 151 | mock_pm = MagicMock(spec=PermissionManager) |
| 152 | mock_pm.request_permission.return_value = True |
| 153 | |
| 154 | # We can't actually execute sudo commands in tests, so we'll just check |
| 155 | # that the sudo flag is correctly passed to the permission manager |
| 156 | with patch('subprocess.run') as mock_run: |
| 157 | mock_run.return_value = subprocess.CompletedProcess( |
| 158 | args=["sudo", "ls"], returncode=0, stdout="", stderr="" |
| 159 | ) |
| 160 | |
| 161 | execute_command("sudo", ["ls"], permission_manager=mock_pm) |
| 162 | |
| 163 | # Check that the is_sudo flag was set to True |
| 164 | mock_pm.request_permission.assert_called_with( |
| 165 | "execute_command", |
| 166 | {"command": "sudo ls"}, |
| 167 | is_sudo=True |
| 168 | ) |
| 169 | |
| 170 | |
| 171 | def test_read_file(temp_dir): |
| 172 | """Test reading file contents.""" |
| 173 | # Create a test file |
| 174 | test_file_path = os.path.join(temp_dir, "test_file.txt") |
| 175 | test_content = "Hello, world!\nThis is a test file." |
| 176 | |
| 177 | with open(test_file_path, 'w') as f: |
| 178 | f.write(test_content) |
| 179 | |
| 180 | # Test reading the file |
| 181 | content = read_file(test_file_path) |
| 182 | assert content == test_content |
| 183 | |
| 184 | # Test with non-existent file |
| 185 | with pytest.raises(FileNotFoundError): |
| 186 | read_file(os.path.join(temp_dir, "nonexistent.txt")) |
| 187 | |
| 188 | |
| 189 | def test_read_file_with_max_size(temp_dir): |
| 190 | """Test reading file with max size limit.""" |
| 191 | # Create a test file |
| 192 | test_file_path = os.path.join(temp_dir, "large_file.txt") |
| 193 | test_content = "X" * 1000 # 1000 bytes |
| 194 | |
| 195 | with open(test_file_path, 'w') as f: |
| 196 | f.write(test_content) |
| 197 | |
| 198 | # Test reading with sufficient max_size |
| 199 | content = read_file(test_file_path, max_size=2000) |
| 200 | assert content == test_content |
| 201 | |
| 202 | # Test reading with insufficient max_size |
| 203 | with pytest.raises(ValueError) as excinfo: |
| 204 | read_file(test_file_path, max_size=500) |
| 205 | assert "exceeds maximum allowed size" in str(excinfo.value) |
| 206 | |
| 207 | |
| 208 | def test_read_file_with_permission_manager(temp_dir): |
| 209 | """Test reading file with permission manager.""" |
| 210 | # Create a test file |
| 211 | test_file_path = os.path.join(temp_dir, "test_file.txt") |
| 212 | test_content = "Hello, world!" |
| 213 | |
| 214 | with open(test_file_path, 'w') as f: |
| 215 | f.write(test_content) |
| 216 | |
| 217 | # Create a mock permission manager |
| 218 | mock_pm = MagicMock(spec=PermissionManager) |
| 219 | |
| 220 | # Test with permission granted |
| 221 | mock_pm.request_permission.return_value = True |
| 222 | content = read_file(test_file_path, permission_manager=mock_pm) |
| 223 | assert content == test_content |
| 224 | assert mock_pm.request_permission.called |
| 225 | |
| 226 | # Test with permission denied |
| 227 | mock_pm.request_permission.return_value = False |
| 228 | with pytest.raises(PermissionError) as excinfo: |
| 229 | read_file(test_file_path, permission_manager=mock_pm) |
| 230 | assert "Permission denied" in str(excinfo.value) |
| 231 | assert mock_pm.request_permission.called |
| 232 | |
| 233 | |
| 234 | def test_write_file(temp_dir): |
| 235 | """Test writing content to a file.""" |
| 236 | # Define test file path and content |
| 237 | test_file_path = os.path.join(temp_dir, "write_test.txt") |
| 238 | test_content = "This is test content to write to a file." |
| 239 | |
| 240 | # Test writing to file |
| 241 | result = write_file(test_file_path, test_content) |
| 242 | assert result is True |
| 243 | |
| 244 | # Verify file content |
| 245 | with open(test_file_path, 'r') as f: |
| 246 | assert f.read() == test_content |
| 247 | |
| 248 | # Test append mode |
| 249 | additional_content = "\nThis is additional content." |
| 250 | result = write_file(test_file_path, additional_content, mode='a') |
| 251 | assert result is True |
| 252 | |
| 253 | # Verify appended content |
| 254 | with open(test_file_path, 'r') as f: |
| 255 | assert f.read() == test_content + additional_content |
| 256 | |
| 257 | # Test invalid mode |
| 258 | with pytest.raises(ValueError) as excinfo: |
| 259 | write_file(test_file_path, test_content, mode='x') |
| 260 | assert "Invalid mode" in str(excinfo.value) |
| 261 | |
| 262 | |
| 263 | def test_write_file_with_new_directory(temp_dir): |
| 264 | """Test writing to a file in a non-existent directory.""" |
| 265 | # Define test file path in a new directory |
| 266 | new_dir = os.path.join(temp_dir, "new_directory") |
| 267 | test_file_path = os.path.join(new_dir, "test_file.txt") |
| 268 | test_content = "This is a test file in a new directory." |
| 269 | |
| 270 | # Write to file (should create directory) |
| 271 | result = write_file(test_file_path, test_content) |
| 272 | assert result is True |
| 273 | |
| 274 | # Verify directory and file were created |
| 275 | assert os.path.exists(new_dir) |
| 276 | assert os.path.isfile(test_file_path) |
| 277 | |
| 278 | # Verify file content |
| 279 | with open(test_file_path, 'r') as f: |
| 280 | assert f.read() == test_content |
| 281 | |
| 282 | |
| 283 | def test_write_file_with_permission_manager(temp_dir): |
| 284 | """Test writing file with permission manager.""" |
| 285 | # Define test file path and content |
| 286 | test_file_path = os.path.join(temp_dir, "permission_test.txt") |
| 287 | test_content = "Test content for permission test." |
| 288 | |
| 289 | # Create a mock permission manager |
| 290 | mock_pm = MagicMock(spec=PermissionManager) |
| 291 | |
| 292 | # Test with permission granted |
| 293 | mock_pm.request_permission.return_value = True |
| 294 | result = write_file(test_file_path, test_content, permission_manager=mock_pm) |
| 295 | assert result is True |
| 296 | assert os.path.exists(test_file_path) |
| 297 | assert mock_pm.request_permission.called |
| 298 | |
| 299 | # Test with permission denied |
| 300 | mock_pm.request_permission.return_value = False |
| 301 | with pytest.raises(PermissionError) as excinfo: |
| 302 | write_file(test_file_path, test_content, permission_manager=mock_pm) |
| 303 | assert "Permission denied" in str(excinfo.value) |
| 304 | assert mock_pm.request_permission.called |
| 305 | |
| 306 | |
| 307 | def test_find_files(temp_dir): |
| 308 | """Test finding files matching a pattern.""" |
| 309 | # Create test files |
| 310 | test_files = [ |
| 311 | "file1.txt", |
| 312 | "file2.txt", |
| 313 | "image1.jpg", |
| 314 | "image2.jpg", |
| 315 | "nested/file3.txt", |
| 316 | "nested/file4.txt", |
| 317 | "nested/deep/file5.txt" |
| 318 | ] |
| 319 | |
| 320 | # Create directories and files |
| 321 | for file_path in test_files: |
| 322 | full_path = os.path.join(temp_dir, file_path) |
| 323 | os.makedirs(os.path.dirname(full_path), exist_ok=True) |
| 324 | with open(full_path, 'w') as f: |
| 325 | f.write(f"Content of {file_path}") |
| 326 | |
| 327 | # Test non-recursive search for txt files |
| 328 | txt_files = find_files("*.txt", directory=temp_dir, recursive=False) |
| 329 | assert len(txt_files) == 2 # Only top-level txt files |
| 330 | assert all(os.path.basename(f) in ["file1.txt", "file2.txt"] for f in txt_files) |
| 331 | |
| 332 | # Test recursive search for txt files |
| 333 | all_txt_files = find_files("*.txt", directory=temp_dir, recursive=True) |
| 334 | assert len(all_txt_files) == 5 # All txt files |
| 335 | |
| 336 | # Test search for jpg files |
| 337 | jpg_files = find_files("*.jpg", directory=temp_dir, recursive=True) |
| 338 | assert len(jpg_files) == 2 |
| 339 | assert all(os.path.basename(f) in ["image1.jpg", "image2.jpg"] for f in jpg_files) |
| 340 | |
| 341 | # Test search""" |
| 342 | Tests for the system tools module. |
| 343 | """ |
| 344 | import pytest |
| 345 | import sys |
| 346 | import os |
| 347 | import re |
| 348 | from unittest.mock import patch, MagicMock |
| 349 | import subprocess |
| 350 | |
| 351 | # Add the parent directory to the path so we can import the package |
| 352 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) |
| 353 | |
| 354 | from ollamatools.tools.system_tools import ( |
| 355 | execute_command, |
| 356 | _sanitize_command, |
| 357 | _sanitize_argument |
| 358 | ) |
| 359 | from ollamatools.security import PermissionManager |
| 360 | |
| 361 | |
| 362 | def test_sanitize_command(): |
| 363 | """Test the command sanitization function.""" |
| 364 | # Valid commands |
| 365 | assert _sanitize_command("ls") == "ls" |
| 366 | assert _sanitize_command("ls -la") == "ls -la" |
| 367 | assert _sanitize_command("echo 'Hello World'") == "echo 'Hello World'" |
| 368 | assert _sanitize_command(" find /tmp -name '*.txt' ") == "find /tmp -name '*.txt'" |
| 369 | |
| 370 | # Invalid commands |
| 371 | with pytest.raises(ValueError) as excinfo: |
| 372 | _sanitize_command("") |
| 373 | assert "Empty command" in str(excinfo.value) |
| 374 | |
| 375 | with pytest.raises(ValueError) as excinfo: |
| 376 | _sanitize_command("ls | grep txt") |
| 377 | assert "dangerous pattern" in str(excinfo.value) |
| 378 | |
| 379 | with pytest.raises(ValueError) as excinfo: |
| 380 | _sanitize_command("echo 'hello' > file.txt") |
| 381 | assert "dangerous pattern" in str(excinfo.value) |
| 382 | |
| 383 | with pytest.raises(ValueError) as excinfo: |
| 384 | _sanitize_command("cat < file.txt") |
| 385 | assert "dangerous pattern" in str(excinfo.value) |
| 386 | |
| 387 | with pytest.raises(ValueError) as excinfo: |
| 388 | _sanitize_command("echo $(whoami)") |
| 389 | assert "dangerous pattern" in str(excinfo.value) |
| 390 | |
| 391 | with pytest.raises(ValueError) as excinfo: |
| 392 | _sanitize_command("echo `whoami`") |
| 393 | assert "dangerous pattern" in str(excinfo.value) |
| 394 | |
| 395 | |
| 396 | def test_sanitize_argument(): |
| 397 | """Test the argument sanitization function.""" |
| 398 | # Valid arguments |
| 399 | assert _sanitize_argument("file.txt") == "file.txt" |
| 400 | assert _sanitize_argument("-la") == "-la" |
| 401 | assert _sanitize_argument("--help") == "--help" |
| 402 | assert _sanitize_argument("/tmp/file with spaces.txt") == "/tmp/file with spaces.txt" |
| 403 | |
| 404 | # Test non-string arguments |
| 405 | assert _sanitize_argument(123) == "123" |
| 406 | |
| 407 | # Invalid arguments |
| 408 | with pytest.raises(ValueError) as excinfo: |
| 409 | _sanitize_argument("file.txt | grep txt") |
| 410 | assert "dangerous pattern" in str(excinfo.value) |
| 411 | |
| 412 | with pytest.raises(ValueError) as excinfo: |
| 413 | _sanitize_argument("$(whoami)") |
| 414 | assert "dangerous pattern" in str(excinfo.value) |
| 415 | |
| 416 | |
| 417 | def test_execute_command_simple(): |
| 418 | """Test executing a simple command.""" |
| 419 | # Test a simple echo command |
| 420 | result = execute_command("echo", ["Hello", "World"]) |
| 421 | |
| 422 | assert result["stdout"].strip() == "Hello World" |
| 423 | assert result["stderr"] == "" |
| 424 | assert result["exit_code"] == 0 |
| 425 | assert result["command"] == "echo Hello World" |
| 426 | |
| 427 | |
| 428 | def test_execute_command_error(): |
| 429 | """Test executing a command that returns an error.""" |
| 430 | # Test a command that should fail (non-existent command) |
| 431 | result = execute_command("ls", ["--invalid-option"]) |
| 432 | |
| 433 | assert result["stderr"] != "" # Should have error output |
| 434 | assert result["exit_code"] != 0 # Non-zero exit code |
| 435 | |
| 436 | # Test a command that doesn't exist |
| 437 | with pytest.raises(subprocess.SubprocessError): |
| 438 | execute_command("command_that_does_not_exist") |
| 439 | |
| 440 | |
| 441 | def test_execute_command_timeout(): |
| 442 | """Test command timeout handling.""" |
| 443 | # Patch subprocess.run to simulate a timeout |
| 444 | with patch('subprocess.run') as mock_run: |
| 445 | mock_run.side_effect = subprocess.TimeoutExpired(cmd="sleep 10", timeout=1) |
| 446 | |
| 447 | with pytest.raises(TimeoutError) as excinfo: |
| 448 | execute_command("sleep", ["10"], timeout=1) |
| 449 | |
| 450 | assert "timed out" in str(excinfo.value) |
| 451 | |
| 452 | |
| 453 | def test_execute_command_with_permission_manager(): |
| 454 | """Test executing a command with the permission manager.""" |
| 455 | # Create a mock permission manager |
| 456 | mock_pm = MagicMock(spec=PermissionManager) |
| 457 | |
| 458 | # Test with permission granted |
| 459 | mock_pm.request_permission.return_value = True |
| 460 | result = execute_command("echo", ["Hello"], permission_manager=mock_pm) |
| 461 | assert result["stdout"].strip() == "Hello" |
| 462 | assert mock_pm.request_permission.called |
| 463 | |
| 464 | # Test with permission denied |
| 465 | mock_pm.request_permission.return_value = False |
| 466 | with pytest.raises(PermissionError) as excinfo: |
| 467 | execute_command("echo", ["Hello"], permission_manager=mock_pm) |
| 468 | assert "Permission denied" in str(excinfo.value) |
| 469 | assert mock_pm.request_permission.called |
| 470 | |
| 471 | |
| 472 | def test_execute_command_sudo(): |
| 473 | """Test sudo command detection and handling.""" |
| 474 | # Create a mock permission manager |
| 475 | mock_pm = MagicMock(spec=PermissionManager) |
| 476 | mock_pm.request_permission.return_value = True |
| 477 | |
| 478 | # We can't actually execute sudo commands in tests, so we'll just check |
| 479 | # that the sudo flag is correctly passed to the permission manager |
| 480 | with patch('subprocess.run') as mock_run: |
| 481 | mock_run.return_value = subprocess.CompletedProcess( |
| 482 | args=["sudo", "ls"], returncode=0, stdout="", stderr="" |
| 483 | ) |
| 484 | |
| 485 | execute_command("sudo", ["ls"], permission_manager=mock_pm) |
| 486 | |
| 487 | # Check that the is_sudo flag was set to True |
| 488 | mock_pm.request_permission.assert_called_with( |
| 489 | "execute_command", |
| 490 | {"command": "sudo ls"}, |
| 491 | is_sudo=True |
| 492 | ) |