| 1 |
import subprocess |
| 2 |
import time |
| 3 |
from unittest.mock import MagicMock |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from briefcase.integrations.subprocess import Subprocess |
| 8 |
|
| 9 |
# hardcoded here since subprocess will only include these constants if Python is literally on Windows |
| 10 |
CREATE_NO_WINDOW = 0x8000000 |
| 11 |
CREATE_NEW_PROCESS_GROUP = 0x200 |
| 12 |
|
| 13 |
|
| 14 |
@pytest.fixture |
| 15 |
def streaming_process(): |
| 16 |
"""Mock process returned for Popen context manager in |
| 17 |
Subprocess._run_and_stream_output.""" |
| 18 |
process = MagicMock() |
| 19 |
|
| 20 |
# Mock the readline values of an actual process. The final return value is "", |
| 21 |
# indicating that the process has exited; however, we insert a short sleep |
| 22 |
# to ensure that any other threads will have a chance to run before this |
| 23 |
# thread actually terminates. |
| 24 |
def mock_readline(): |
| 25 |
yield from [ |
| 26 |
"output line 1\n", |
| 27 |
"\n", |
| 28 |
"output line 3\n", |
| 29 |
] |
| 30 |
time.sleep(0.1) |
| 31 |
yield "" |
| 32 |
|
| 33 |
process.stdout.readline.side_effect = mock_readline() |
| 34 |
process.poll.return_value = -3 |
| 35 |
return process |
| 36 |
|
| 37 |
|
| 38 |
@pytest.fixture |
| 39 |
def mock_sub(mock_tools, streaming_process): |
| 40 |
mock_tools.os.environ = { |
| 41 |
"VAR1": "Value 1", |
| 42 |
"PS1": "\nLine 2\n\nLine 4", |
| 43 |
"PWD": "/home/user/", |
| 44 |
} |
| 45 |
|
| 46 |
sub = Subprocess(mock_tools) |
| 47 |
sub._subprocess = MagicMock(spec=subprocess) |
| 48 |
|
| 49 |
run_result = MagicMock(spec=subprocess.CompletedProcess) |
| 50 |
run_result.returncode = 0 |
| 51 |
sub._subprocess.run.return_value = run_result |
| 52 |
|
| 53 |
sub._subprocess.check_output.return_value = "some output line 1\nmore output line 2" |
| 54 |
|
| 55 |
sub._subprocess.CREATE_NO_WINDOW = CREATE_NO_WINDOW |
| 56 |
sub._subprocess.CREATE_NEW_PROCESS_GROUP = CREATE_NEW_PROCESS_GROUP |
| 57 |
|
| 58 |
# Return the streaming process for output streaming |
| 59 |
sub._subprocess.Popen.return_value.__enter__.return_value = streaming_process |
| 60 |
|
| 61 |
return sub |