Skip to content

Commit d5bcfee

Browse files
Guard file checks against invalid truthy return values
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 55b9ecc commit d5bcfee

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

hyperbrowser/client/file_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def ensure_existing_file_path(
3737
):
3838
raise HyperbrowserError("file_path must not contain control characters")
3939
try:
40-
path_exists = os.path.exists(normalized_path)
40+
path_exists = bool(os.path.exists(normalized_path))
4141
except HyperbrowserError:
4242
raise
4343
except (OSError, ValueError, TypeError) as exc:
@@ -47,7 +47,7 @@ def ensure_existing_file_path(
4747
if not path_exists:
4848
raise HyperbrowserError(missing_file_message)
4949
try:
50-
is_file = os.path.isfile(normalized_path)
50+
is_file = bool(os.path.isfile(normalized_path))
5151
except HyperbrowserError:
5252
raise
5353
except (OSError, ValueError, TypeError) as exc:

tests/test_file_utils.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,53 @@ def raising_isfile(path: str) -> bool:
175175
assert exc_info.value.original_error is not None
176176

177177

178+
def test_ensure_existing_file_path_wraps_non_boolean_exists_results(monkeypatch):
179+
class _BrokenTruthValue:
180+
def __bool__(self) -> bool:
181+
raise RuntimeError("cannot coerce exists result")
182+
183+
def invalid_exists(path: str):
184+
_ = path
185+
return _BrokenTruthValue()
186+
187+
monkeypatch.setattr(file_utils.os.path, "exists", invalid_exists)
188+
189+
with pytest.raises(HyperbrowserError, match="file_path is invalid") as exc_info:
190+
ensure_existing_file_path(
191+
"/tmp/maybe-invalid",
192+
missing_file_message="missing",
193+
not_file_message="not-file",
194+
)
195+
196+
assert exc_info.value.original_error is not None
197+
198+
199+
def test_ensure_existing_file_path_wraps_non_boolean_isfile_results(
200+
monkeypatch, tmp_path: Path
201+
):
202+
class _BrokenTruthValue:
203+
def __bool__(self) -> bool:
204+
raise RuntimeError("cannot coerce isfile result")
205+
206+
file_path = tmp_path / "target.txt"
207+
file_path.write_text("content")
208+
209+
def invalid_isfile(path: str):
210+
_ = path
211+
return _BrokenTruthValue()
212+
213+
monkeypatch.setattr(file_utils.os.path, "isfile", invalid_isfile)
214+
215+
with pytest.raises(HyperbrowserError, match="file_path is invalid") as exc_info:
216+
ensure_existing_file_path(
217+
str(file_path),
218+
missing_file_message="missing",
219+
not_file_message="not-file",
220+
)
221+
222+
assert exc_info.value.original_error is not None
223+
224+
178225
def test_ensure_existing_file_path_wraps_fspath_runtime_errors():
179226
class _BrokenPathLike:
180227
def __fspath__(self) -> str:

0 commit comments

Comments
 (0)