Skip to content

Commit 0252990

Browse files
author
Steve Canny
committed
api: Document raises on not .docx
docx.api.Document should raise on construction if supplied file is not a Word .docx file.
1 parent e75d056 commit 0252990

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

docx/api.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import os
1717

1818
from opc import OpcPackage
19+
from opc.constants import CONTENT_TYPE as CT
1920

2021

2122
thisdir = os.path.split(__file__)[0]
@@ -33,6 +34,9 @@ def Document(docx=None):
3334
docx = _default_docx_path
3435
pkg = OpcPackage.open(docx)
3536
document_part = pkg.main_document
37+
if document_part.content_type != CT.WML_DOCUMENT_MAIN:
38+
tmpl = "file '%s' is not a Word file, content type is '%s'"
39+
raise ValueError(tmpl % (docx, document_part.content_type))
3640
return _Document(pkg, document_part)
3741

3842

tests/test_api.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from mock import Mock, PropertyMock
1515

1616
from docx.api import Document, _Document
17+
from opc.constants import CONTENT_TYPE as CT
1718

1819
from .unitutil import class_mock, var_mock
1920

@@ -37,6 +38,7 @@ def OpcPackage_mockery(self, request):
3738
OpcPackage_ = class_mock('docx.api.OpcPackage', request)
3839
pkg = OpcPackage_.open.return_value
3940
main_document = PropertyMock(name='main_document')
41+
main_document.return_value.content_type = CT.WML_DOCUMENT_MAIN
4042
type(pkg).main_document = main_document
4143
document_part = main_document.return_value
4244
return (OpcPackage_, pkg, main_document, document_part)
@@ -58,3 +60,12 @@ def it_uses_default_if_no_file_provided(self, OpcPackage_, _Document_,
5860
default_docx):
5961
Document()
6062
OpcPackage_.open.assert_called_once_with(default_docx)
63+
64+
def it_should_raise_if_not_a_docx_file(self, OpcPackage_mockery):
65+
# mockery ----------------------
66+
docx = Mock(name='docx')
67+
OpcPackage_, pkg, main_document, document_part = OpcPackage_mockery
68+
main_document.return_value.content_type = 'foobar'
69+
# verify -----------------------
70+
with pytest.raises(ValueError):
71+
Document(docx)

0 commit comments

Comments
 (0)