def __init__(self): self.processor = xml.user_object( "annotation", Annotation, [ xml.user_object("size", Size, [ xml.integer("width"), xml.integer("height"), ]), xml.array( xml.user_object( "object", Object, [ xml.string("name"), xml.user_object( "bndbox", Box, [ xml.floating_point("xmin"), xml.floating_point("ymin"), xml.floating_point("xmax"), xml.floating_point("ymax"), ], alias="box" ) ] ), alias="objects" ), xml.string("filename") ] )
def update(self): logging.debug('AnnotationEntryBuilder') annotation_proc = xml.user_object('PASSPORT', Annotation, [ xml.string('ANNOTATION', alias='text') ]) annotation = xml.parse_from_file(annotation_proc, self.xml_data) super(AnnotationEntryBuilder, self).replace_bookmark(self.doc, 'ANNOTATION', annotation.text)
def test_user_object_parse_nested(): """Parse a user object as a nested element in the document""" xml_string = """ <root> <position>quarterback</position> <person> <name>Bob</name> <pet>Fluffy</pet> <pet>Spots</pet> </person> </root> """ processor = xml.dictionary('root', [ xml.string('position'), xml.user_object('person', Person, [ xml.string('name'), xml.array(xml.string('pet'), alias='pets'), ]) ]) expected = { 'position': 'quarterback', 'person': Person().set_values(name='Bob', pets=['Fluffy', 'Spots']) } actual = xml.parse_from_string(processor, xml_string) assert expected == actual
def test_serialize_none_object_issue_7(): """Attempts to serialize an object value that is None""" class Athlete(object): def __init__(self): self.name = '' self.age = 0 processor = xml.dictionary('race-result', [ xml.floating_point('time'), xml.user_object('athlete', Athlete, [ xml.string('name'), xml.integer('age'), ], required=False) ]) value = { 'time': 87.5, 'athlete': None, } expected_xml = strip_xml(""" <race-result> <time>87.5</time> </race-result> """) actual_xml = xml.serialize_to_string(processor, value) assert expected_xml == actual_xml
def test_user_object_serialize_array(): """Serializes an array of user objects""" value = [ Person().set_values(name='Bob', age=33), Person().set_values(name='Jan', age=24), Person().set_values(name='Tom', age=29) ] processor = xml.array(xml.user_object( 'person', Person, [xml.string('name'), xml.integer('age')]), nested='people') expected = strip_xml(""" <people> <person> <name>Bob</name> <age>33</age> </person> <person> <name>Jan</name> <age>24</age> </person> <person> <name>Tom</name> <age>29</age> </person> </people> """) actual = xml.serialize_to_string(processor, value) assert expected == actual
def test_user_object_non_root(self): """Custom error message for user object values.""" processor = xml.dictionary('data', [ xml.user_object('user', _UserClass, [ xml.string('name'), xml.integer('age'), ], hooks=self._hooks) ]) xml_string = strip_xml(""" <data> <user> <name>Bob</name> <age>24</age> </user> </data> """) value = {'user': _UserClass(name='Bob', age=24)} location = 'data/user' self._assert_error_message(processor, value, xml_string, location)
def test_user_object_serialize_nested(): """Serializes a nested user object""" value = { 'position': 'quarterback', 'person': Person().set_values(name='Bob', pets=['Fluffy', 'Spots']) } processor = xml.dictionary('root', [ xml.string('position'), xml.user_object('person', Person, [ xml.string('name'), xml.array(xml.string('pet'), alias='pets'), ]) ]) expected = strip_xml(""" <root> <position>quarterback</position> <person> <name>Bob</name> <pet>Fluffy</pet> <pet>Spots</pet> </person> </root> """) actual = xml.serialize_to_string(processor, value) assert expected == actual
def test_user_object_parse_aliased(): """Parse an aliased user object""" xml_string = """ <root> <book>Harry Potter</book> <person> <name>Ron</name> <age>18</age> </person> </root> """ processor = xml.dictionary('root', [ xml.string('book'), xml.user_object('person', Person, [xml.string('name'), xml.integer('age')], alias='character') ]) expected = { 'book': 'Harry Potter', 'character': Person().set_values(name='Ron', age=18) } actual = xml.parse_from_string(processor, xml_string) assert expected == actual
def test_user_object_serialize_aliased(): """Serializes an aliased user object""" value = { 'book': 'Harry Potter', 'character': Person().set_values(name='Malfoy', age=17) } processor = xml.dictionary('root', [ xml.string('book'), xml.user_object('person', Person, [xml.string('name'), xml.integer('age')], alias='character') ]) expected = strip_xml(""" <root> <book>Harry Potter</book> <person> <name>Malfoy</name> <age>17</age> </person> </root> """) actual = xml.serialize_to_string(processor, value) assert expected == actual
def update(self): logging.debug('ExecutorEntryBuilder') executor_proc = xml.user_object('PASSPORT/EXECUTOR', Executor, [ xml.string('EXECUTORNAME', alias='name'), xml.string('EXECUTORPHONE', alias='phone') ]) executor = xml.parse_from_file(executor_proc, self.xml_data) super(ExecutorEntryBuilder, self).replace_bookmark(self.doc, 'EXECUTORNAME', executor.name) super(ExecutorEntryBuilder, self).replace_bookmark(self.doc, 'EXECUTORPHONE', executor.phone)
def _user_object_processor(self): hooks = xml.Hooks( after_parse=self._after_parse, before_serialize=self._before_serialize, ) return xml.user_object('person', self._Person, [ xml.string('name'), xml.integer('age'), ], hooks=hooks)
def test_can_parse_and_serialize_frozen_attrs_class(): """Parse and serialize a frozen attrs class.""" processor = xml.user_object('book', _FrozenBook, [ xml.string('title'), xml.string('author'), ]) value = _FrozenBook( title='The Three Body Problem', author='Liu Cixin' ) assert_can_roundtrip_xml_value(processor, value)
def test_can_parse_and_serialize_attrs_class_with_no_defaults(): """Parse and serialize an attrs class.""" processor = xml.user_object('book', _BookWithNoDefaults, [ xml.string('title'), xml.string('author'), ]) value = _BookWithNoDefaults( title='The Three Body Problem', author='Liu Cixin' ) assert_can_roundtrip_xml_value(processor, value)
def _processor(self): def validate(state, value): if value.name == 'Bob' and value.age == 24: state.raise_error(_ValidationError) return value hooks = xml.Hooks( after_parse=validate, before_serialize=validate, ) processor = xml.user_object( 'user', _UserClass, [xml.string('name'), xml.integer('age')], hooks=hooks) return processor
def __get_data_items(self): ''' Построить список элементов данных, для вставки в указанные позиции (закладки). Параметры: нет Возвращает: max_index - кол-во элементов данных exist - список элементов данных ''' signers_proc = xml.dictionary('PASSPORT/SIGNERLIST', [ xml.array(xml.user_object('SignerInfo', Signer, [ xml.string('SIGNERDUE', alias='due'), xml.string('SIGNERPOST', alias='post'), xml.string('SIGNERNAME', alias='name') ], alias='slist')) ]) s = xml.parse_from_file(signers_proc, self.xml_data) return s['slist']
def test_user_object_serialize_root(): """Serializes a user object as the root of the document""" value = Person().set_values(name='Bob', age=27, gender='male') processor = xml.user_object( 'person', Person, [xml.string('name'), xml.integer('age'), xml.string('gender')]) expected = strip_xml(""" <person> <name>Bob</name> <age>27</age> <gender>male</gender> </person> """) actual = xml.serialize_to_string(processor, value) assert expected == actual
def test_user_object_parse_root(): """Parse a user object as the root of the document""" xml_string = """ <person> <name>Bob</name> <age>23</age> <gender>male</gender> </person> """ processor = xml.user_object( 'person', Person, [xml.string('name'), xml.integer('age'), xml.string('gender')]) expected = Person().set_values(name='Bob', age=23, gender='male') actual = xml.parse_from_string(processor, xml_string) assert expected == actual
def __get_data_items(self): ''' Построить список элементов данных, для вставки в указанные позиции (закладки). Параметры: нет Возвращает: max_index - кол-во элементов данных exist - список элементов данных ''' addr_proc = xml.dictionary('PASSPORT/ADDRLIST', [ xml.array(xml.user_object('AddrInfo', Signer, [ xml.string('ADDRORG', alias='addrorg'), xml.string('ADDRSPOST', alias='addrspost'), xml.string('ADDRLPOST', alias='addrlpost'), xml.string('ADDRNAME', alias='addrname'), xml.string('ADDRADRESS', alias='addraddress'), xml.string('ADDRKIND', alias='addrkind') ], alias='slist')) ]) s = xml.parse_from_file(addr_proc, self.xml_data) return s['slist']
def test_user_object_parse_array(): """Parse a user object in an array""" xml_string = """ <root> <team>A Team</team> <person> <name>Bob</name> <age>23</age> </person> <person> <name>Jane</name> <age>26</age> </person> </root> """ processor = xml.dictionary('root', [ xml.string('team'), xml.array(xml.user_object( 'person', Person, [xml.string('name'), xml.integer('age')]), alias='members') ]) expected = { 'team': 'A Team', 'members': [ Person().set_values(name='Bob', age=23), Person().set_values(name='Jane', age=26), ] } actual = xml.parse_from_string(processor, xml_string) assert expected == actual
def __init__(self, group_name="Imported", group_desc=""): self.group_name = group_name self.group_desc = group_desc self.scenario_group = None def dict_to_scenario(state, value): session = Session() value['id'] = Scenario.scenario_hash(value['acq_time'], value['scen_materials'], value['scen_bckg_materials'], value['influences']) q = session.query(Scenario).filter_by(id=value['id']).first() if q: if self.scenario_group: self.scenario_group.scenarios.append(q) return q else: scenario = Scenario(value['acq_time'], value['replication'], value['scen_materials'], value['scen_bckg_materials'], value['influences'], [self.scenario_group]) return scenario def scenario_to_dict(state, value): return value.__dict__ def material_validate(state, value): session = Session() q = session.query(Material).filter_by(name=value.name).first() if q: return q else: session.add(value) return value def trace(state, value): print('Got {} at {}'.format(value, state)) print(value.__dict__) return value def influence_validate(state, value): session = Session() q = session.query(Influence).filter_by(name=value.name).first() if q: return q else: session.add(value) return value self.scenario_hooks = xml.Hooks( after_parse=dict_to_scenario, before_serialize=scenario_to_dict, ) self.material_hooks = xml.Hooks( after_parse=material_validate, before_serialize=lambda _, x: x, ) self.influence_hooks = xml.Hooks( after_parse=influence_validate, before_serialize=lambda _, x: x, ) self.material_processor = xml.user_object( 'Material', Material, [xml.string('BaseMaterialName', alias='name')], alias='material', hooks=self.material_hooks) self.sourcematerials_processor = xml.user_object( 'ScenarioMaterial', ScenarioMaterial, [ self.material_processor, xml.string('fd_mode'), xml.floating_point('dose'), ], alias='scen_materials') self.bkgmaterial_processor = xml.user_object( 'ScenarioBackgroundMaterial', ScenarioBackgroundMaterial, [ self.material_processor, xml.string('fd_mode'), xml.floating_point('dose'), ], alias='scen_bckg_materials', required=False) self.influence_processor = xml.user_object( 'Influence', Influence, [xml.string('InfluenceName', alias='name')], alias='influences', hooks=self.influence_hooks, required=False) self.scenario_processor = xml.dictionary('Scenario', [ xml.string("id", required=False), xml.floating_point("acq_time"), xml.integer("replication"), xml.array(self.sourcematerials_processor), xml.array(self.bkgmaterial_processor), xml.array(self.influence_processor) ], hooks=self.scenario_hooks) self.scenarios_processor = xml.dictionary( 'Scenarios', [xml.array(self.scenario_processor)])