Skip to content
This repository was archived by the owner on Jan 12, 2018. It is now read-only.

Commit 6ba94ff

Browse files
author
Steve Canny
committed
fix: issue #60, some reformatting
1 parent 37a3709 commit 6ba94ff

File tree

3 files changed

+127
-56
lines changed

3 files changed

+127
-56
lines changed

docx.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
#!/usr/bin/env python2.6
2-
# -*- coding: utf-8 -*-
1+
# encoding: utf-8
2+
33
"""
44
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
55
'Office OpenXML' by Microsoft)
@@ -104,7 +104,7 @@ def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
104104
# FIXME: rest of code below expects a single prefix
105105
nsprefix = nsprefix[0]
106106
if nsprefix:
107-
namespace = '{'+nsprefixes[nsprefix]+'}'
107+
namespace = '{%s}' % nsprefixes[nsprefix]
108108
else:
109109
# For when namespace = None
110110
namespace = ''
@@ -485,12 +485,13 @@ def picture(
485485
image = Image.open(picpath)
486486

487487
# Extract EXIF data, if available
488-
imageExif = {}
489488
try:
490489
exif = image._getexif()
490+
exif = {} if exif is None else exif
491491
except:
492492
exif = {}
493493

494+
imageExif = {}
494495
for tag, value in exif.items():
495496
imageExif[TAGS.get(tag, tag)] = value
496497

@@ -1069,12 +1070,14 @@ def savedocx(
10691070
os.chdir(template_dir)
10701071

10711072
# Serialize our trees into out zip file
1072-
treesandfiles = {document: 'word/document.xml',
1073-
coreprops: 'docProps/core.xml',
1074-
appprops: 'docProps/app.xml',
1075-
contenttypes: '[Content_Types].xml',
1076-
websettings: 'word/webSettings.xml',
1077-
wordrelationships: 'word/_rels/document.xml.rels'}
1073+
treesandfiles = {
1074+
document: 'word/document.xml',
1075+
coreprops: 'docProps/core.xml',
1076+
appprops: 'docProps/app.xml',
1077+
contenttypes: '[Content_Types].xml',
1078+
websettings: 'word/webSettings.xml',
1079+
wordrelationships: 'word/_rels/document.xml.rels'
1080+
}
10781081
for tree in treesandfiles:
10791082
log.info('Saving: %s' % treesandfiles[tree])
10801083
treestring = etree.tostring(tree, pretty_print=True)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
setup(
2020
name='docx',
21-
version='0.2.3',
21+
version='0.2.4',
2222
install_requires=['lxml', 'Pillow>=2.0'],
2323
description=DESCRIPTION,
2424
author='Mike MacCana',

tests/test_docx.py

Lines changed: 113 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,69 @@
1-
#!/usr/bin/env python2.6
2-
'''
1+
#!/usr/bin/env python
2+
3+
"""
34
Test docx module
4-
'''
5+
"""
6+
57
import os
68
import lxml
7-
from docx import *
9+
from docx import (
10+
appproperties, contenttypes, coreproperties, getdocumenttext, heading,
11+
makeelement, newdocument, nsprefixes, opendocx, pagebreak, paragraph,
12+
picture, relationshiplist, replace, savedocx, search, table, websettings,
13+
wordrelationships
14+
)
815

916
TEST_FILE = 'ShortTest.docx'
1017
IMAGE1_FILE = 'image1.png'
1118

19+
1220
# --- Setup & Support Functions ---
1321
def setup_module():
14-
'''Set up test fixtures'''
22+
"""Set up test fixtures"""
1523
import shutil
1624
if IMAGE1_FILE not in os.listdir('.'):
17-
shutil.copyfile(os.path.join(os.path.pardir,IMAGE1_FILE), IMAGE1_FILE)
25+
shutil.copyfile(os.path.join(os.path.pardir, IMAGE1_FILE), IMAGE1_FILE)
1826
testnewdocument()
1927

28+
2029
def teardown_module():
21-
'''Tear down test fixtures'''
30+
"""Tear down test fixtures"""
2231
if TEST_FILE in os.listdir('.'):
2332
os.remove(TEST_FILE)
2433

34+
2535
def simpledoc(noimagecopy=False):
26-
'''Make a docx (document, relationships) for use in other docx tests'''
36+
"""Make a docx (document, relationships) for use in other docx tests"""
2737
relationships = relationshiplist()
2838
imagefiledict = {}
2939
document = newdocument()
3040
docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
31-
docbody.append(heading('Heading 1',1) )
32-
docbody.append(heading('Heading 2',2))
41+
docbody.append(heading('Heading 1', 1))
42+
docbody.append(heading('Heading 2', 2))
3343
docbody.append(paragraph('Paragraph 1'))
34-
for point in ['List Item 1','List Item 2','List Item 3']:
35-
docbody.append(paragraph(point,style='ListNumber'))
44+
for point in ['List Item 1', 'List Item 2', 'List Item 3']:
45+
docbody.append(paragraph(point, style='ListNumber'))
3646
docbody.append(pagebreak(type='page'))
37-
docbody.append(paragraph('Paragraph 2'))
38-
docbody.append(table([['A1','A2','A3'],['B1','B2','B3'],['C1','C2','C3']]))
47+
docbody.append(paragraph('Paragraph 2'))
48+
docbody.append(
49+
table(
50+
[
51+
['A1', 'A2', 'A3'],
52+
['B1', 'B2', 'B3'],
53+
['C1', 'C2', 'C3']
54+
]
55+
)
56+
)
3957
docbody.append(pagebreak(type='section', orient='portrait'))
4058
if noimagecopy:
41-
relationships,picpara,imagefiledict = picture(relationships,IMAGE1_FILE,'This is a test description', imagefiledict=imagefiledict)
59+
relationships, picpara, imagefiledict = picture(
60+
relationships, IMAGE1_FILE, 'This is a test description',
61+
imagefiledict=imagefiledict
62+
)
4263
else:
43-
relationships,picpara = picture(relationships,IMAGE1_FILE,'This is a test description')
64+
relationships, picpara = picture(
65+
relationships, IMAGE1_FILE, 'This is a test description'
66+
)
4467
docbody.append(picpara)
4568
docbody.append(pagebreak(type='section', orient='landscape'))
4669
docbody.append(paragraph('Paragraph 3'))
@@ -52,72 +75,117 @@ def simpledoc(noimagecopy=False):
5275

5376
# --- Test Functions ---
5477
def testsearchandreplace():
55-
'''Ensure search and replace functions work'''
78+
"""Ensure search and replace functions work"""
5679
document, docbody, relationships = simpledoc()
5780
docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
5881
assert search(docbody, 'ing 1')
5982
assert search(docbody, 'ing 2')
6083
assert search(docbody, 'graph 3')
6184
assert search(docbody, 'ist Item')
6285
assert search(docbody, 'A1')
63-
if search(docbody, 'Paragraph 2'):
64-
docbody = replace(docbody,'Paragraph 2','Whacko 55')
86+
if search(docbody, 'Paragraph 2'):
87+
docbody = replace(docbody, 'Paragraph 2', 'Whacko 55')
6588
assert search(docbody, 'Whacko 55')
6689

90+
6791
def testtextextraction():
68-
'''Ensure text can be pulled out of a document'''
92+
"""Ensure text can be pulled out of a document"""
6993
document = opendocx(TEST_FILE)
7094
paratextlist = getdocumenttext(document)
7195
assert len(paratextlist) > 0
7296

97+
7398
def testunsupportedpagebreak():
74-
'''Ensure unsupported page break types are trapped'''
99+
"""Ensure unsupported page break types are trapped"""
75100
document = newdocument()
76101
docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
77102
try:
78103
docbody.append(pagebreak(type='unsup'))
79104
except ValueError:
80-
return # passed
81-
assert False # failed
105+
return # passed
106+
assert False # failed
107+
82108

83109
def testnewdocument():
84-
'''Test that a new document can be created'''
110+
"""Test that a new document can be created"""
85111
document, docbody, relationships = simpledoc()
86-
coreprops = coreproperties('Python docx testnewdocument','A short example of making docx from Python','Alan Brooks',['python','Office Open XML','Word'])
87-
savedocx(document, coreprops, appproperties(), contenttypes(), websettings(), wordrelationships(relationships), TEST_FILE)
112+
coreprops = coreproperties(
113+
'Python docx testnewdocument',
114+
'A short example of making docx from Python', 'Alan Brooks',
115+
['python', 'Office Open XML', 'Word']
116+
)
117+
savedocx(
118+
document, coreprops, appproperties(), contenttypes(), websettings(),
119+
wordrelationships(relationships), TEST_FILE
120+
)
121+
88122

89123
def testnewdocument_noimagecopy():
90-
'''Test that a new document can be created'''
91-
document, docbody, relationships, imagefiledict = simpledoc(noimagecopy=True)
92-
coreprops = coreproperties('Python docx testnewdocument','A short example of making docx from Python','Alan Brooks',['python','Office Open XML','Word'])
93-
savedocx(document, coreprops, appproperties(), contenttypes(), websettings(), wordrelationships(relationships), TEST_FILE, imagefiledict=imagefiledict)
124+
"""
125+
Test that a new document can be created
126+
"""
127+
document, docbody, relationships, imagefiledict = simpledoc(
128+
noimagecopy=True
129+
)
130+
coreprops = coreproperties(
131+
'Python docx testnewdocument',
132+
'A short example of making docx from Python', 'Alan Brooks',
133+
['python', 'Office Open XML', 'Word']
134+
)
135+
savedocx(
136+
document, coreprops, appproperties(), contenttypes(), websettings(),
137+
wordrelationships(relationships), TEST_FILE,
138+
imagefiledict=imagefiledict
139+
)
140+
94141

95142
def testopendocx():
96-
'''Ensure an etree element is returned'''
97-
if isinstance(opendocx(TEST_FILE),lxml.etree._Element):
143+
"""Ensure an etree element is returned"""
144+
if isinstance(opendocx(TEST_FILE), lxml.etree._Element):
98145
pass
99146
else:
100147
assert False
101148

149+
102150
def testmakeelement():
103-
'''Ensure custom elements get created'''
104-
testelement = makeelement('testname',attributes={'testattribute':'testvalue'},tagtext='testtagtext')
105-
assert testelement.tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}testname'
106-
assert testelement.attrib == {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}testattribute': 'testvalue'}
151+
"""Ensure custom elements get created"""
152+
testelement = makeelement(
153+
'testname',
154+
attributes={'testattribute': 'testvalue'},
155+
tagtext='testtagtext'
156+
)
157+
assert testelement.tag == (
158+
'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}testn'
159+
'ame'
160+
)
161+
assert testelement.attrib == {
162+
'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}testa'
163+
'ttribute': 'testvalue'
164+
}
107165
assert testelement.text == 'testtagtext'
108166

167+
109168
def testparagraph():
110-
'''Ensure paragraph creates p elements'''
111-
testpara = paragraph('paratext',style='BodyText')
112-
assert testpara.tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p'
169+
"""Ensure paragraph creates p elements"""
170+
testpara = paragraph('paratext', style='BodyText')
171+
assert testpara.tag == (
172+
'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p'
173+
)
113174
pass
114-
175+
176+
115177
def testtable():
116-
'''Ensure tables make sense'''
117-
testtable = table([['A1','A2'],['B1','B2'],['C1','C2']])
118-
ns = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
119-
assert testtable.xpath('/ns0:tbl/ns0:tr[2]/ns0:tc[2]/ns0:p/ns0:r/ns0:t',namespaces={'ns0':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})[0].text == 'B2'
178+
"""Ensure tables make sense"""
179+
testtable = table([['A1', 'A2'], ['B1', 'B2'], ['C1', 'C2']])
180+
assert (
181+
testtable.xpath(
182+
'/ns0:tbl/ns0:tr[2]/ns0:tc[2]/ns0:p/ns0:r/ns0:t',
183+
namespaces={'ns0': ('http://schemas.openxmlformats.org/wordproce'
184+
'ssingml/2006/main')}
185+
)[0].text == 'B2'
186+
)
187+
120188

121-
if __name__=='__main__':
189+
if __name__ == '__main__':
122190
import nose
123191
nose.main()

0 commit comments

Comments
 (0)