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
9 changes: 7 additions & 2 deletions src/docx/opc/phys_pkg.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Provides a general interface to a `physical` OPC package, such as a zip file."""

import os
from zipfile import ZIP_DEFLATED, ZipFile, is_zipfile
from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile

from docx.opc.exceptions import PackageNotFoundError
from docx.opc.packuri import CONTENT_TYPES_URI
Expand Down Expand Up @@ -73,7 +73,12 @@ class _ZipPkgReader(PhysPkgReader):

def __init__(self, pkg_file):
super(_ZipPkgReader, self).__init__()
self._zipf = ZipFile(pkg_file, "r")
try:
self._zipf = ZipFile(pkg_file, "r")
except BadZipFile:
raise PackageNotFoundError(
"Package not found or not a valid OPC package file"
)

def blob_for(self, pack_uri):
"""Return blob corresponding to `pack_uri`.
Expand Down
4 changes: 4 additions & 0 deletions tests/opc/test_phys_pkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ def it_raises_when_pkg_path_is_not_a_package(self):
with pytest.raises(PackageNotFoundError):
PhysPkgReader("foobar")

def it_raises_when_pkg_stream_is_not_a_zip(self):
with pytest.raises(PackageNotFoundError):
PhysPkgReader(io.BytesIO(b"not a zip"))


class DescribeZipPkgReader:
def it_is_used_by_PhysPkgReader_when_pkg_is_a_zip(self):
Expand Down