Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## [Unreleased] - TBD

### Fixed

- Properly close file descriptors opened by `harfile`.

## [0.3.1] - 2025-08-17

### Added

- `HarFile.flush` method.
Expand Down
12 changes: 11 additions & 1 deletion src/harfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ class HarFile:
_comment: str | None
_is_first_entry: bool = True
_has_preable: bool = False
_is_managed_fd: bool = False
closed: bool = False

def __init__(
Expand Down Expand Up @@ -81,9 +82,13 @@ def open(
fd: IO[str]
if isinstance(name_or_fd, (str, PathLike)):
fd = builtins.open(name_or_fd, "w")
is_managed = True
else:
fd = name_or_fd
return cls(fd=fd, creator=creator, browser=browser, comment=comment)
is_managed = False
instance = cls(fd=fd, creator=creator, browser=browser, comment=comment)
instance._is_managed_fd = is_managed
return instance

def close(self) -> None:
"""Close the HAR file."""
Expand All @@ -94,6 +99,8 @@ def close(self) -> None:
self._write_preamble()
self._has_preable = True
self._write_postscript()
if self._is_managed_fd:
self._fd.close()

def flush(self) -> None:
self._fd.flush()
Expand All @@ -109,6 +116,9 @@ def __exit__(
) -> None:
if type is None:
self.close()
elif self._is_managed_fd:
self._fd.close()
self.closed = True
return None

def add_entry(
Expand Down
5 changes: 3 additions & 2 deletions tests/test_har.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,13 +432,15 @@ def test_close():
buffer = io.StringIO()
with harfile.open(buffer) as har:
har.close()
assert har.closed


def test_exception():
buffer = io.StringIO()
with pytest.raises(ZeroDivisionError):
with harfile.open(buffer):
with harfile.open(buffer) as har:
raise ZeroDivisionError
assert har.closed
assert buffer.getvalue() == ""


Expand All @@ -451,7 +453,6 @@ def test_with_comments():
comment="EXAMPLE-3",
):
pass
print(buffer.getvalue())
assert (
buffer.getvalue()
== """{
Expand Down