|
1 | | -from pathlib import Path |
2 | | - |
3 | | -from py_app_dev.core.subprocess import SubprocessExecutor, which |
4 | | - |
5 | | - |
6 | | -def test_get_app_path(): |
7 | | - assert which("python") |
8 | | - |
9 | | - |
10 | | -def test_subprocess_executor(tmp_path: Path) -> None: |
11 | | - SubprocessExecutor(["python", "-V"], cwd=tmp_path, capture_output=True).execute() |
12 | | - |
13 | | - |
14 | | -def test_subprocess_executor_no_error_handling() -> None: |
15 | | - process = SubprocessExecutor(["python", "-V"], capture_output=True).execute(handle_errors=False) |
16 | | - assert process and process.returncode == 0 |
17 | | - assert process.stdout == "" |
18 | | - process = SubprocessExecutor(["python", "-V"], capture_output=True, print_output=False).execute(handle_errors=False) |
19 | | - assert process and process.returncode == 0 |
20 | | - assert "Python" in process.stdout |
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from pathlib import Path |
| 4 | +from unittest.mock import Mock, patch |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +from py_app_dev.core.subprocess import SubprocessExecutor, which |
| 9 | + |
| 10 | + |
| 11 | +def test_get_app_path(): |
| 12 | + """Test the which function for finding executables in PATH.""" |
| 13 | + assert which("python") |
| 14 | + |
| 15 | + |
| 16 | +class TestSubprocessExecutor: |
| 17 | + """Test class for SubprocessExecutor functionality.""" |
| 18 | + |
| 19 | + @patch("loguru._logger.Logger.info") |
| 20 | + def test_no_error_handling_scenarios(self, mock_info: Mock) -> None: |
| 21 | + """Test various scenarios when error handling is disabled.""" |
| 22 | + # Test 1: Default behavior (print_output=True) - should log both command and output |
| 23 | + mock_info.reset_mock() |
| 24 | + process = SubprocessExecutor(["python", "-V"]).execute(handle_errors=False) |
| 25 | + assert process and process.returncode == 0 |
| 26 | + assert "Python" in process.stdout |
| 27 | + |
| 28 | + # Verify logger was called - should have at least 2 calls: command + python version output |
| 29 | + assert mock_info.call_count >= 2 |
| 30 | + # Check that the command execution was logged |
| 31 | + command_logged = any("Running command: python -V" in str(call) for call in mock_info.call_args_list) |
| 32 | + assert command_logged, "Command execution should be logged" |
| 33 | + # Check that Python version output was logged |
| 34 | + python_output_logged = any("Python" in str(call) and "Running command" not in str(call) for call in mock_info.call_args_list) |
| 35 | + assert python_output_logged, "Python version output should be logged when print_output=True" |
| 36 | + |
| 37 | + # Test 2: print_output=False - should only log command, not output |
| 38 | + mock_info.reset_mock() |
| 39 | + process = SubprocessExecutor(["python", "-V"], capture_output=True, print_output=False).execute(handle_errors=False) |
| 40 | + assert process and process.returncode == 0 |
| 41 | + assert "Python" in process.stdout |
| 42 | + |
| 43 | + # Should only log the command execution, not the output |
| 44 | + assert mock_info.call_count == 1 |
| 45 | + assert "Running command: python -V" in str(mock_info.call_args_list[0]) |
| 46 | + |
| 47 | + # Test 3: capture_output=False - should only log command, no stdout captured |
| 48 | + mock_info.reset_mock() |
| 49 | + process = SubprocessExecutor(["python", "-V"], capture_output=False, print_output=False).execute(handle_errors=False) |
| 50 | + assert process and process.returncode == 0 |
| 51 | + assert process.stdout == "" |
| 52 | + |
| 53 | + # Should only log the command execution |
| 54 | + assert mock_info.call_count == 1 |
| 55 | + assert "Running command: python -V" in str(mock_info.call_args_list[0]) |
| 56 | + |
| 57 | + @pytest.mark.parametrize( |
| 58 | + "capture_output,print_output,expected_stdout_empty", |
| 59 | + [ |
| 60 | + (True, True, False), # Capture and print - should have stdout |
| 61 | + (True, False, False), # Capture but don't print - should have stdout |
| 62 | + (False, True, True), # Don't capture but print - should have empty stdout |
| 63 | + (False, False, True), # Don't capture or print - should have empty stdout |
| 64 | + ], |
| 65 | + ) |
| 66 | + def test_output_capture_combinations(self, capture_output: bool, print_output: bool, expected_stdout_empty: bool) -> None: |
| 67 | + """Test different combinations of capture_output and print_output parameters.""" |
| 68 | + process = SubprocessExecutor(["python", "-V"], capture_output=capture_output, print_output=print_output).execute(handle_errors=False) |
| 69 | + |
| 70 | + assert process and process.returncode == 0 |
| 71 | + |
| 72 | + if expected_stdout_empty: |
| 73 | + assert process.stdout == "" |
| 74 | + else: |
| 75 | + assert "Python" in process.stdout |
| 76 | + |
| 77 | + @pytest.mark.parametrize( |
| 78 | + "command, exp_stdout, exp_returncode", |
| 79 | + [ |
| 80 | + (["python", "-c", "print('Hello World!')"], "Hello World!\n", 0), |
| 81 | + # SubprocessExecutor redirects stderr to stdout when capture_output=True |
| 82 | + ( |
| 83 | + [ |
| 84 | + "python", |
| 85 | + "-c", |
| 86 | + "import sys; print('Hello World!', file=sys.stderr)", |
| 87 | + ], |
| 88 | + "Hello World!\n", |
| 89 | + 0, |
| 90 | + ), |
| 91 | + (["python", "-c", "exit(0)"], "", 0), |
| 92 | + (["python", "-c", "exit(1)"], "", 1), |
| 93 | + (["python", "-c", "exit(42)"], "", 42), |
| 94 | + ], |
| 95 | + ) |
| 96 | + def test_command_execution_scenarios(self, command, exp_stdout, exp_returncode): |
| 97 | + """Test various command execution scenarios adapted from CommandLineExecutor tests.""" |
| 98 | + # Arrange |
| 99 | + executor = SubprocessExecutor(command, capture_output=True, print_output=False) |
| 100 | + |
| 101 | + # Act |
| 102 | + result = executor.execute(handle_errors=False) |
| 103 | + |
| 104 | + # Assert |
| 105 | + assert result is not None |
| 106 | + assert result.stdout == exp_stdout |
| 107 | + # Note: SubprocessExecutor redirects stderr to stdout, so stderr is always None |
| 108 | + # This is different from CommandLineExecutor which returned empty string for stderr |
| 109 | + assert result.stderr is None |
| 110 | + assert result.returncode == exp_returncode |
| 111 | + |
| 112 | + def test_junction_creation(self, tmp_path: Path) -> None: |
| 113 | + """Test creating a junction link (Windows-specific test adapted from CommandLineExecutor).""" |
| 114 | + import platform |
| 115 | + |
| 116 | + if platform.system() != "Windows": |
| 117 | + pytest.skip("Junction creation test is Windows-specific") |
| 118 | + |
| 119 | + # Arrange |
| 120 | + test_path = tmp_path.joinpath("test") |
| 121 | + test_path.mkdir() |
| 122 | + link_path = test_path.joinpath("link") |
| 123 | + command = ["cmd", "/c", "mklink", "/J", str(link_path), str(test_path)] |
| 124 | + executor = SubprocessExecutor(command, capture_output=True, print_output=False) |
| 125 | + |
| 126 | + # Act |
| 127 | + result = executor.execute(handle_errors=False) |
| 128 | + |
| 129 | + # Assert |
| 130 | + assert result is not None |
| 131 | + assert result.returncode == 0 |
| 132 | + |
| 133 | + @pytest.mark.parametrize( |
| 134 | + "stream_type, test_data, expected_text_parts", |
| 135 | + [ |
| 136 | + ("stdout", b"Hello\x85World\n", ["Hello", "World"]), |
| 137 | + ("stderr", b"Error\x85Message\n", ["Error", "Message"]), |
| 138 | + ], |
| 139 | + ) |
| 140 | + def test_undecodable_bytes_handling(self, stream_type: str, test_data: bytes, expected_text_parts: list[str]) -> None: |
| 141 | + """Test that undecodable bytes in stdout/stderr are handled gracefully.""" |
| 142 | + # Arrange |
| 143 | + with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp: |
| 144 | + # Write bytes that are invalid in UTF-8 (e.g., 0x85) |
| 145 | + tmp.write(test_data) |
| 146 | + tmp_path = tmp.name |
| 147 | + |
| 148 | + try: |
| 149 | + if stream_type == "stdout": |
| 150 | + py_cmd = ["python", "-c", f"import sys; sys.stdout.buffer.write(open(r'{tmp_path}', 'rb').read())"] |
| 151 | + else: # stderr |
| 152 | + py_cmd = ["python", "-c", f"import sys; sys.stderr.buffer.write(open(r'{tmp_path}', 'rb').read())"] |
| 153 | + |
| 154 | + executor = SubprocessExecutor(py_cmd, capture_output=True, print_output=False) |
| 155 | + |
| 156 | + # Act |
| 157 | + result = executor.execute(handle_errors=False) |
| 158 | + |
| 159 | + # Assert |
| 160 | + assert result is not None |
| 161 | + for expected_part in expected_text_parts: |
| 162 | + assert expected_part in result.stdout |
| 163 | + # Should not raise UnicodeDecodeError due to errors="replace" in subprocess.py |
| 164 | + assert result.returncode == 0 |
| 165 | + finally: |
| 166 | + os.remove(tmp_path) |
0 commit comments