Skip to content

Raise PackageNotFoundError for a non-zip stream, not BadZipFile - #1596

Open
eeshsaxena wants to merge 1 commit into
python-openxml:masterfrom
eeshsaxena:fix/non-zip-stream-packagenotfound
Open

Raise PackageNotFoundError for a non-zip stream, not BadZipFile#1596
eeshsaxena wants to merge 1 commit into
python-openxml:masterfrom
eeshsaxena:fix/non-zip-stream-packagenotfound

Conversation

@eeshsaxena

Copy link
Copy Markdown

Opening a document from a path that isn't a package raises PackageNotFoundError, but opening one from a stream that isn't a zip leaks a bare zipfile.BadZipFile:

import io, docx
docx.Document(io.BytesIO(b"not a docx"))
# zipfile.BadZipFile: File is not a zip file

PhysPkgReader.__new__ checks is_zipfile() for a path and raises PackageNotFoundError when it isn't a package, but for a stream it hands the file straight to the zip reader ("assume it's a stream and pass it to Zip reader to sort out"). The zip reader never sorted out the not-a-zip case, so callers catching PackageNotFoundError (the documented error for a bad package) miss the stream case.

This catches BadZipFile in _ZipPkgReader and re-raises PackageNotFoundError, so a bad stream and a bad path fail the same way. Valid packages are unaffected (verified a normal open/save/read round-trip still works). Added a test mirroring the existing not-a-package-path test.

Opening a document from a path that is not a package raises PackageNotFoundError,
but opening one from a *stream* that is not a zip fell through to ZipFile and
raised a bare zipfile.BadZipFile instead. PhysPkgReader.__new__ passes streams
straight to the zip reader ("pass it to Zip reader to sort out"), but the reader
never sorted out the not-a-zip case.

Catch BadZipFile in _ZipPkgReader and raise PackageNotFoundError, so a bad stream
and a bad path fail the same way. Added a test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant