Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_identifies_complex_fields_correctly(self):
document = Document(docx_path('three_props_in_same_paragraph.docx'))
properties = CustomProperties(document).find_docprops_in_document()
assert 1 == len(document.paragraphs), 'input file should contains one paragraph'
assert 3 == len(properties), \
'input should contain three complex field docproperties'
# check that all fields were identified as complex fields
for prop in properties:
assert isinstance(prop, ComplexField)
# check that all field names were parsed correctly
expected_names = ('Text Property', 'Number Property', 'Text Property')
for name, prop in zip(expected_names, properties):
assert name == prop.name
# check that begin, separate and end were identified correctly
attrib_key = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}fldCharType'
expected_indexes = ((1, 3, 11), (13, 15, 17), (25, 27, 32))
for prop, indexes in zip(properties, expected_indexes):
assert prop.begin_run.getchildren()[1].attrib[attrib_key] == "begin"
assert prop.get_separate_run().getchildren()[1].attrib[attrib_key] == "separate"
assert prop.end_run.getchildren()[1].attrib[attrib_key] == "end"
assert prop.w_p.index(prop.begin_run) == indexes[0]
assert prop.w_p.index(prop.get_separate_run()) == indexes[1]
assert prop.w_p.index(prop.end_run) == indexes[2]
def _find_docprops_in(self, element, name=None):
# First we search for the simple fields:
sfield_nodes = xpath(
element,
u'.//w:fldSimple[contains(@w:instr, \'DOCPROPERTY \')]')
docprops = [SimpleField(sfield_node) for sfield_node in sfield_nodes]
# Now for the complex fields
cfield_nodes = xpath(
element,
u'.//w:instrText[contains(.,\'DOCPROPERTY \')]')
docprops.extend([ComplexField(cfield_node) for cfield_node in cfield_nodes])
if name is not None:
docprops = filter(lambda prop: prop.name == name, docprops)
return docprops
def __init__(self, field_node):
super(ComplexField, self).__init__(field_node)
# run and paragraph containing the field
self.w_r = self.node.getparent()
self.w_p = self.w_r.getparent()