pytest/mock
code: python
'''
pip install pytest pytest-mock
'''
import subprocess
import os
def ssh(path):
try:
cmd = 'ssh', path
res = subprocess.run(cmd, text=True)
return res.stdout.strip()
except Exception as e:
print(f"Error executing command: {e}")
return None
def open_file(path):
contents = []
try:
with open(path, 'r') as file:
contents.append(file.read())
except Exception as e:
print(f"Error opening file: {e}")
return None
try:
with open(os.path.join(path, "foo"), 'r') as file:
contents.append(file.read())
except Exception as e:
print(f"Error opening file: {e}")
return None
return contents
def test_ssh(mocker):
mock_run = mocker.patch("subprocess.run")
mock_result = mocker.MagicMock()
mock_result.stdout = "success"
mock_run.return_value = mock_result
result = ssh("./path")
assert result == "success"
mock_run.assert_called_once_with('ssh', './path', text=True)
def test_ssh_failure(mocker):
mock_run = mocker.patch("subprocess.run")
mock_run.side_effect = Exception("Connection failed")
result = ssh("./path")
assert result is None
mock_run.assert_called_once_with('ssh', './path', text=True)
def test_open_file(mocker):
mock_open = mocker.patch("builtins.open")
mock_open.side_effect = [
mocker.mock_open(read_data="content1")(),
mocker.mock_open(read_data="content2")()
]
result = open_file("./path")
assert result == "content1", "content2"
assert mock_open.call_count == 2
mock_open.assert_has_calls([
mocker.call('./path', 'r'),
mocker.call(os.path.join('./path', 'foo'), 'r')
])
def test_open_file_second_failure(mocker):
mock_open = mocker.patch("builtins.open")
mock_open.side_effect = [
mocker.mock_open(read_data="content1")(),
FileNotFoundError("File not found")
]
result = open_file("./path")
assert result is None
assert mock_open.call_count == 2
mock_open.assert_has_calls([
mocker.call('./path', 'r'),
mocker.call(os.path.join('./path', 'foo'), 'r')
])