示例#1
0
def test_primitive_serialize_default_present():
    """Serializes a missing primitive value with a defualt specified"""
    value = {'message': 'Hola, Mars'}

    processor = xml.dictionary('root', [
        xml.string('message', required=False, default='Hello, World'),
    ])

    expected = strip_xml("""
    <root>
        <message>Hola, Mars</message>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#2
0
def test_serialize_pretty():
    """Serialize a pretty-formatted XML string"""
    value = {'name': 'Bob', 'age': 27}

    processor = xml.dictionary(
        'root', [xml.string('name'), xml.integer('age')])

    expected = """<?xml version="1.0" encoding="utf-8"?>
<root>
    <name>Bob</name>
    <age>27</age>
</root>
"""

    actual = xml.serialize_to_string(processor, value, indent='    ')

    assert expected == actual
    def test_non_root_user_object(self):
        """Apply a transform to a root user object"""
        xml_string = strip_xml("""
        <data>
            <person>
                <name>John</name>
                <age>24</age>
            </person>
        </data>
        """)

        value = {'person': ('John', 24)}

        processor = xml.dictionary('data', [
            self._user_object_processor,
        ])

        _transform_test_case_run(processor, value, xml_string)
示例#4
0
def test_parse_string_leave_whitespace():
    """Parses a string value without stripping whitespace"""
    xml_string = """
    <root>
        <value>    Hello, World! </value>
    </root>
    """

    processor = xml.dictionary('root',
                               [xml.string('value', strip_whitespace=False)])

    expected = {
        'value': '    Hello, World! ',
    }

    actual = xml.parse_from_string(processor, xml_string)

    assert expected == actual
示例#5
0
def test_attribute_serialize_default_present():
    """Serializes an attribute value with a default specified"""
    value = {'data': 123, 'units': 'miles'}

    processor = xml.dictionary('root', [
        xml.integer('data'),
        xml.string('data', attribute='units', required=False, default='feet')
    ])

    expected = strip_xml("""
    <root>
        <data units="miles">123</data>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#6
0
def test_primitive_values_serialize_falsey_omitted():
    """Serialize false primitive values"""
    value = {'boolean': False, 'float': 0.0, 'int': 0, 'string': ''}

    processor = xml.dictionary('root', [
        xml.boolean('boolean', required=False, omit_empty=True),
        xml.floating_point('float', required=False, omit_empty=True),
        xml.integer('int', required=False, omit_empty=True),
        xml.string('string', required=False, omit_empty=True),
    ])

    expected = strip_xml("""
    <root />
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#7
0
def test_primitive_serialize_missing_omitted():
    """Serializes a missing primitive value"""
    value = {'data': 1}

    processor = xml.dictionary('root', [
        xml.string('message', required=False, omit_empty=True),
        xml.integer('data')
    ])

    expected = strip_xml("""
    <root>
        <data>1</data>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#8
0
    def _processor(self):
        def validate(state, value):
            if value['a'] == 5 and value['b'] == 6:
                state.raise_error(_ValidationError)
            return value

        hooks = xml.Hooks(
            after_parse=validate,
            before_serialize=validate,
        )

        processor = xml.dictionary('data', [
            xml.integer('a'),
            xml.integer('b'),
        ],
                                   hooks=hooks)

        return processor
    def test_array_of_arrays(self):
        """Transform array values for a nested array"""
        xml_string = strip_xml("""
            <data>
                <name>Dataset 1</name>
                <values>
                    <value key="a">17</value>
                    <value key="b">42</value>
                    <value key="c">37</value>
                </values>
                <values>
                    <value key="x">34</value>
                    <value key="y">4</value>
                    <value key="z">58</value>
                </values>
            </data>
        """)

        value = {
            'name':
            'Dataset 1',
            'values': [
                OrderedDict([
                    ('a', 17),
                    ('b', 42),
                    ('c', 37),
                ]),
                OrderedDict([
                    ('x', 34),
                    ('y', 4),
                    ('z', 58),
                ])
            ],
        }

        processor = xml.dictionary('data', [
            xml.string('name'),
            xml.array(
                xml.array(self._item_processor,
                          nested='values',
                          hooks=self._hooks), )
        ])

        _transform_test_case_run(processor, value, xml_string)
示例#10
0
 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']
示例#11
0
def test_parse_attribute_only():
    """Parses an attribute value that is the only value in an element"""
    xml_string = """
        <root>
            <element value="hello" />
        </root>
    """

    processor = xml.dictionary('root', [
        xml.string('element', attribute='value'),
    ])

    expected = {
        'value': 'hello',
    }

    actual = xml.parse_from_string(processor, xml_string)

    assert expected == actual
示例#12
0
def test_primitive_serialize_aliased():
    """Serializes an aliased primitive value"""
    value = {
        'data': 456,
    }

    processor = xml.dictionary('root', [
        xml.integer('element', alias='data'),
    ])

    expected = strip_xml("""
    <root>
        <element>456</element>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#13
0
def test_parse_attribute_aliased():
    """Parses an attribute value with an alias"""
    xml_string = """
        <root>
            <element value="hello">27</element>
        </root>
    """

    processor = xml.dictionary('root', [
        xml.string('element', attribute='value', alias='value_alias'),
    ])

    expected = {
        'value_alias': 'hello',
    }

    actual = xml.parse_from_string(processor, xml_string)

    assert expected == actual
示例#14
0
def test_attribute_serialize_aliased():
    """Serialize an aliased attribute"""
    value = {
        'pi': 3.14,
    }

    processor = xml.dictionary('root', [
        xml.floating_point('constant', attribute='value', alias='pi'),
    ])

    expected = strip_xml("""
    <root>
        <constant value="3.14" />
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#15
0
def test_array_serialize_primitive():
    """Serialize an array of primitive values"""
    value = {'values': [14, 3, 17, 5]}

    processor = xml.dictionary(
        'root', [xml.array(xml.integer('value'), alias='values')])

    expected = strip_xml("""
    <root>
        <value>14</value>
        <value>3</value>
        <value>17</value>
        <value>5</value>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#16
0
def test_array_serialize_missing_optional():
    """Serialize a missing array"""
    value = {
        'message': 'Hello',
    }

    processor = xml.dictionary('root', [
        xml.string('message'),
        xml.array(xml.integer('value', required=False), alias='data')
    ])

    expected = strip_xml("""
    <root>
        <message>Hello</message>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#17
0
def test_array_serialize_optinal_present():
    """Serializes an optional array that is present"""
    value = {'message': 'Hello', 'value': [1, 14]}

    processor = xml.dictionary('root', [
        xml.string('message'),
        xml.array(xml.integer('value', required=False))
    ])

    expected = strip_xml("""
    <root>
        <message>Hello</message>
        <value>1</value>
        <value>14</value>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#18
0
def test_aggregate_missing_hooks():
    """Process with missing aggregate hooks."""
    hooks = xml.Hooks(after_parse=None, before_serialize=None)

    processor = xml.dictionary(
        'data', [xml.integer('a'), xml.integer('b')], hooks=hooks)

    xml_string = strip_xml("""
    <data>
        <a>1</a>
        <b>2</b>
    </data>
    """)

    value = {
        'a': 1,
        'b': 2,
    }

    _assert_valid(processor, value, xml_string)
示例#19
0
def test_parse_attribute_default_present():
    """Parses an attribute with a default value specified"""
    xml_string = """
    <root>
        <element value="Hello">27</element>
    </root>
    """

    processor = xml.dictionary('root', [
        xml.string(
            'element', attribute='value', required=False, default='Goodbye'),
    ])

    expected = {
        'value': 'Hello',
    }

    actual = xml.parse_from_string(processor, xml_string)

    assert expected == actual
示例#20
0
def test_array_serialize_shared_element():
    """Serialize an array on an element shared with an attribute"""
    value = {'units': 'grams', 'results': [32.4, 3.11]}

    processor = xml.dictionary('root', [
        xml.string('results', attribute='units'),
        xml.array(xml.floating_point('value'), nested='results')
    ])

    expected = strip_xml("""
    <root>
        <results units="grams">
            <value>32.4</value>
            <value>3.11</value>
        </results>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#21
0
    def test_array_non_root(self):
        """Custom error message for array values."""
        processor = xml.dictionary('data', [
            xml.array(xml.integer('value'), nested='values', hooks=self._hooks)
        ])

        xml_string = strip_xml("""
        <data>
            <values>
                <value>1</value>
            </values>
        </data>
        """)

        value = {
            'values': [1],
        }

        location = 'data/values'

        self._assert_error_message(processor, value, xml_string, location)
示例#22
0
def test_attribute_serialize_missing_empty():
    """Tests serializing a Falsey attribute value"""
    value = {
        'data': 123,
    }

    processor = xml.dictionary('root', [
        xml.integer('data'),
        xml.string(
            'data', attribute='message', required=False, omit_empty=True)
    ])

    expected = strip_xml("""
    <root>
        <data>123</data>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#23
0
def test_parse_array_nested_missing_optional():
    """Parse a nested missing array"""
    xml_string = """
    <root>
        <message>Hello</message>
    </root>
    """

    processor = xml.dictionary('root', [
        xml.string('message'),
        xml.array(xml.integer('number', required=False), nested='numbers')
    ])

    expected = {
        'message': 'Hello',
        'numbers': [],
    }

    actual = xml.parse_from_string(processor, xml_string)

    assert expected == actual
示例#24
0
 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_string_transform():
    """Transform string values"""
    xml_string = strip_xml("""
        <data>
            <value>hello</value>
        </data>
    """)

    value = {'value': 'HELLO'}

    def _after_parse(_, x):
        return x.upper()

    def _before_serialize(_, x):
        return x.lower()

    hooks = xml.Hooks(after_parse=_after_parse,
                      before_serialize=_before_serialize)

    processor = xml.dictionary('data', [xml.string('value', hooks=hooks)])

    _transform_test_case_run(processor, value, xml_string)
def test_integer_transform():
    """Transform integer values"""
    xml_string = strip_xml("""
        <data>
            <value>3</value>
        </data>
    """)

    value = {'value': 6}

    def _after_parse(_, x):
        return int(x * 2)

    def _before_serialize(_, x):
        return int(x / 2)

    hooks = xml.Hooks(after_parse=_after_parse,
                      before_serialize=_before_serialize)

    processor = xml.dictionary('data', [xml.integer('value', hooks=hooks)])

    _transform_test_case_run(processor, value, xml_string)
示例#27
0
def test_parse_from_file(tmpdir):
    """Tests parsing an XML file"""
    xml_contents = """
    <root>
        <value>27</value>
    </root>
    """

    xml_file = tmpdir.join('data.xml')
    xml_file.write(xml_contents)

    processor = xml.dictionary('root', [
        xml.integer('value'),
    ])

    expected = {
        'value': 27,
    }

    actual = xml.parse_from_file(processor, xml_file.strpath)

    assert expected == actual
示例#28
0
def test_array_serialize_array_of_arrays_omit_empty():
    """Tests serializing arrays of arrays with omit empty option specified"""
    value = {
        'results': [
            [3, 2, 4],
            [],
            [12, 32, 87, 9],
        ]
    }

    processor = xml.dictionary('root', [
        xml.array(xml.array(xml.integer('value', required=False),
                            nested='test-run',
                            omit_empty=True),
                  alias='results')
    ])

    # Empty arrays contained within arrays should never be omitted because we would
    # lose information when serialzing to XML
    expected = strip_xml("""
    <root>
        <test-run>
            <value>3</value>
            <value>2</value>
            <value>4</value>
        </test-run>
        <test-run />
        <test-run>
            <value>12</value>
            <value>32</value>
            <value>87</value>
            <value>9</value>
        </test-run>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#29
0
def test_array_serialize_array_of_arrays():
    """Tests serializing arrays of arrays"""
    value = {
        'results': [
            [3, 2, 4],
            [4, 3],
            [12, 32, 87, 9],
        ]
    }

    processor = xml.dictionary('root', [
        xml.array(xml.array(xml.integer('value'), nested='test-run'),
                  alias='results')
    ])

    expected = strip_xml("""
    <root>
        <test-run>
            <value>3</value>
            <value>2</value>
            <value>4</value>
        </test-run>
        <test-run>
            <value>4</value>
            <value>3</value>
        </test-run>
        <test-run>
            <value>12</value>
            <value>32</value>
            <value>87</value>
            <value>9</value>
        </test-run>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
示例#30
0
    def test_dictionary_root(self):
        """Custom error message for dictionary values."""
        processor = xml.dictionary('data', [
            xml.string('name'),
            xml.integer('age'),
        ],
                                   hooks=self._hooks)

        xml_string = strip_xml("""
        <data>
            <name>Bob</name>
            <age>24</age>
        </data>
        """)

        value = {
            'name': 'Bob',
            'age': 24,
        }

        location = 'data'

        self._assert_error_message(processor, value, xml_string, location)