Skip to content

Commit ba0e2e1

Browse files
author
Steve Canny
committed
api: add Document() factory function
1 parent c254f8e commit ba0e2e1

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

docx/api.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
opc.OpcPackage graph.
1414
"""
1515

16+
from opc import OpcPackage
17+
1618

1719
def Document(docx=None):
1820
"""
@@ -21,3 +23,14 @@ def Document(docx=None):
2123
*docx* is missing or ``None``, the built-in default document "template"
2224
is loaded.
2325
"""
26+
pkg = OpcPackage.open(docx)
27+
document_part = pkg.main_document
28+
return _Document(pkg, document_part)
29+
30+
31+
class _Document(object):
32+
"""
33+
API class representing a Word document.
34+
"""
35+
def __init__(self, pkg, document_part):
36+
super(_Document, self).__init__()

tests/test_api.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# test_api.py
4+
#
5+
# Copyright (C) 2013 Steve Canny scanny@cisco.com
6+
#
7+
# This module is part of python-docx and is released under the MIT License:
8+
# http://www.opensource.org/licenses/mit-license.php
9+
10+
"""Test suite for the docx.api module."""
11+
12+
import pytest
13+
14+
from mock import Mock, PropertyMock
15+
16+
from docx.api import Document, _Document
17+
18+
from .unitutil import class_mock
19+
20+
21+
class DescribeDocument(object):
22+
23+
@pytest.fixture
24+
def _Document_(self, request):
25+
return class_mock('docx.api._Document', request)
26+
27+
@pytest.fixture
28+
def OpcPackage_mockery(self, request):
29+
OpcPackage_ = class_mock('docx.api.OpcPackage', request)
30+
pkg = OpcPackage_.open.return_value
31+
main_document = PropertyMock(name='main_document')
32+
type(pkg).main_document = main_document
33+
document_part = main_document.return_value
34+
return (OpcPackage_, pkg, main_document, document_part)
35+
36+
def it_opens_a_docx_file_on_construction(self, OpcPackage_mockery,
37+
_Document_):
38+
# mockery ----------------------
39+
docx = Mock(name='docx')
40+
OpcPackage_, pkg, main_document, document_part = OpcPackage_mockery
41+
# exercise ---------------------
42+
doc = Document(docx)
43+
# verify -----------------------
44+
OpcPackage_.open.assert_called_once_with(docx)
45+
main_document.assert_called_once_with()
46+
_Document_.assert_called_once_with(pkg, document_part)
47+
assert isinstance(doc, _Document)

0 commit comments

Comments
 (0)