Skip to content
Open
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
7 changes: 6 additions & 1 deletion python/extract_har.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ def extract_har(harzip, mimetypes, output, paths, pretty_json):
output_dir = Path(output)
output_dir.mkdir(parents=True, exist_ok=True)

with zipfile.ZipFile(harzip) as zf:
try:
archive = zipfile.ZipFile(harzip)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Catch BadZipFile raised while reading har.har

When a ZIP's central directory is valid but its har.har bytes fail CRC validation, ZipFile(harzip) succeeds and this new try ends, then zf.read("har.har") raises zipfile.BadZipFile outside the handler. Running the CLI on such a damaged HAR still produces an uncaught traceback and no Invalid ZIP archive message, so the clean-error handling needs to cover the initial member read as well.

Useful? React with 👍 / 👎.

except zipfile.BadZipFile as exc:
raise click.ClickException(f"Invalid ZIP archive: {harzip}") from exc

with archive as zf:
# Read the HAR JSON file
try:
har_content = json.loads(zf.read("har.har"))
Expand Down
33 changes: 33 additions & 0 deletions python/test_extract_har.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import importlib.util
import tempfile
import unittest
from pathlib import Path

from click.testing import CliRunner


SCRIPT = Path(__file__).with_name("extract_har.py")
SPEC = importlib.util.spec_from_file_location("extract_har", SCRIPT)
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)


class ExtractHarBadZipTests(unittest.TestCase):
def test_non_zip_input_returns_a_click_error_without_traceback(self):
runner = CliRunner()
with tempfile.TemporaryDirectory() as directory:
input_path = Path(directory) / "invalid.txt"
input_path.write_text("not a zip file", encoding="utf-8")

result = runner.invoke(
MODULE.extract_har,
[str(input_path), "text/plain", "--output", str(Path(directory) / "out")],
)

self.assertEqual(result.exit_code, 1)
self.assertIn("Invalid ZIP archive", result.output)
self.assertNotIn("Traceback", result.output)


if __name__ == "__main__":
unittest.main()