Skip to content

Commit 1534871

Browse files
2bndy5shenxianpeng
authored andcommitted
fix: capture output and patch test's mocks
1 parent fa6bdbb commit 1534871

File tree

2 files changed

+19
-15
lines changed

2 files changed

+19
-15
lines changed

cpp_linter_hooks/util.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,16 @@ def parse_version(v: str):
6161

6262
def _install_tool(tool: str, version: str) -> Optional[Path]:
6363
"""Install a tool using pip, suppressing output."""
64-
try:
65-
subprocess.run(
66-
[sys.executable, "-m", "pip", "install", f"{tool}=={version}"],
67-
capture_output=True,
68-
check=True,
69-
)
64+
result = subprocess.run(
65+
[sys.executable, "-m", "pip", "install", f"{tool}=={version}"],
66+
capture_output=True,
67+
)
68+
if result.returncode == 0:
7069
return shutil.which(tool)
71-
except subprocess.CalledProcessError as e:
70+
else:
7271
LOG.error("pip failed to install %s %s", tool, version)
73-
LOG.error(e.stdout.decode(encoding="utf-8"))
74-
LOG.error(e.stderr.decode(encoding="utf-8"))
72+
LOG.error(result.stdout.decode(encoding="utf-8"))
73+
LOG.error(result.stderr.decode(encoding="utf-8"))
7574
return None
7675

7776

tests/test_util.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,11 @@ def test_install_tool_success():
123123
"""Test _install_tool successful installation."""
124124
mock_path = "/usr/bin/clang-format"
125125

126+
def patched_run(*args, **kwargs):
127+
return subprocess.CompletedProcess(args, returncode=0)
128+
126129
with (
127-
patch("subprocess.run") as mock_run,
130+
patch("subprocess.run", side_effect=patched_run) as mock_run,
128131
patch("shutil.which", return_value=mock_path),
129132
):
130133
result = _install_tool("clang-format", "20.1.7")
@@ -133,18 +136,20 @@ def test_install_tool_success():
133136
mock_run.assert_called_once_with(
134137
[sys.executable, "-m", "pip", "install", "clang-format==20.1.7"],
135138
capture_output=True,
136-
check=True,
137139
)
138140

139141

140142
@pytest.mark.benchmark
141143
def test_install_tool_failure():
142144
"""Test _install_tool when pip install fails."""
145+
146+
def patched_run(*args, **kwargs):
147+
return subprocess.CompletedProcess(
148+
args, returncode=1, stderr=b"Error", stdout=b"Installation failed"
149+
)
150+
143151
with (
144-
patch(
145-
"subprocess.run",
146-
side_effect=subprocess.CalledProcessError(1, ["pip"]),
147-
),
152+
patch("subprocess.run", side_effect=patched_run),
148153
patch("cpp_linter_hooks.util.LOG"),
149154
):
150155
result = _install_tool("clang-format", "20.1.7")

0 commit comments

Comments
 (0)