Ejemplo n.º 1
0
def _assert_invalid(processor, value, xml_string):
    """Assert the processor rejects the XML and value as invalid."""
    with pytest.raises(_ValidationError):
        xml.parse_from_string(processor, xml_string)

    with pytest.raises(_ValidationError):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 2
0
def test_processor_locations_parsing():
    """Get processor location in hooks callback."""
    expected_locations = [
        xml.ProcessorLocation(element_path='data', array_index=None),
        xml.ProcessorLocation(element_path='value', array_index=None)
    ]

    def trace(state, _):
        assert isinstance(state, xml.ProcessorStateView)
        assert expected_locations == list(state.locations)

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

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

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

    value = {'value': 1}

    xml.parse_from_string(processor, xml_string)
    xml.serialize_to_string(processor, value)
Ejemplo n.º 3
0
def test_dictionary_serialize_root_empty():
    """Serliazes an empty root dictionary"""
    value = {}

    processor = xml.dictionary('root', [xml.string('message')])

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 4
0
def test_primitive_serialize_root():
    """Serialize a primitive value as the root of the document"""
    value = 'Hello'

    processor = xml.string('message')

    with pytest.raises(xml.InvalidRootProcessor):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 5
0
def test_array_serialize_root_not_nested():
    """Serialize an array that is the root"""
    value = [3.14, 13.7, 6.22]

    processor = xml.array(xml.floating_point('constant'))

    with pytest.raises(xml.InvalidRootProcessor):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 6
0
def test_array_serialize_missing_root():
    """Serialize a missing array"""
    value = []

    processor = xml.array(xml.integer('value'), nested='data')

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 7
0
def test_primitive_serialize_missing():
    """Serializes a missing primitive value"""
    value = {'data': 1}

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

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 8
0
def test_array_serialize_missing():
    """Serialize a missing array"""
    value = {'message': 'Hello', 'data': []}

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

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 9
0
def test_attribute_serialize_missing():
    """Serialize a missing attribute value"""
    value = {
        'data': 123,
    }

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

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 10
0
    def _assert_error_message(processor, value, xml_string, expected_location):
        with pytest.raises(_ValidationError) as parse_exception:
            xml.parse_from_string(processor, xml_string)

        actual_parse_message = str(parse_exception.value)
        print(actual_parse_message)
        assert actual_parse_message.endswith(expected_location)

        with pytest.raises(_ValidationError) as serialize_exception:
            xml.serialize_to_string(processor, value)

        actual_serialize_message = str(serialize_exception.value)
        assert actual_serialize_message.endswith(expected_location)
Ejemplo n.º 11
0
def _transform_test_case_run(processor, value, xml_string):
    """Runs the given value transform test case"""
    actual_value = xml.parse_from_string(processor, xml_string)
    assert value == actual_value

    actual_xml_string = xml.serialize_to_string(processor, value)
    assert xml_string == actual_xml_string
Ejemplo n.º 12
0
def test_array_serialize_aggregate():
    """Serialize an array of aggregate values"""
    value = {
        'people': [{
            'name': 'Bob',
            'age': 27
        }, {
            'name': 'Jane',
            'age': 25
        }]
    }

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

    expected = strip_xml("""
    <root>
        <person>
            <name>Bob</name>
            <age>27</age>
        </person>
        <person>
            <name>Jane</name>
            <age>25</age>
        </person>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 13
0
def test_primitive_values_serialize():
    """Serializes primitive values"""
    value = {
        'boolean': True,
        'float': 3.14,
        'int': 1,
        'string': 'Hello, World'
    }

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

    expected = strip_xml("""
    <root>
        <boolean>True</boolean>
        <float>3.14</float>
        <int>1</int>
        <string>Hello, World</string>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
def test_dictionary_serialize_nested_missing_optional():
    """Serializes nested dictionaries"""
    value = {
        'name': 'John Doe',
        'demographics': {
            'age': 27,
            'gender': 'male',
        },
    }

    processor = xml.dictionary('root', [
        xml.string('name'),
        xml.dictionary(
            'demographics',
            [xml.integer('age'), xml.string('gender')]),
        xml.dictionary('favorites', [xml.string('food'),
                                     xml.string('color')],
                       required=False)
    ])

    expected = strip_xml("""
    <root>
        <name>John Doe</name>
        <demographics>
            <age>27</age>
            <gender>male</gender>
        </demographics>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 16
0
def test_named_tuple_serialize():
    """Serialize a namedtuple value"""
    value = Author(name='Robert A. Heinlein',
                   books=[
                       Book(title='Starship Troopers', year_published=1959),
                       Book(title='Stranger in a Strange Land',
                            year_published=1961)
                   ])

    processor = xml.named_tuple('author', Author, [
        xml.string('name'),
        xml.array(xml.named_tuple('book', Book, [
            xml.string('title'),
            xml.integer('year-published', alias='year_published')
        ]),
                  alias='books')
    ])

    expected = strip_xml("""
    <author>
        <name>Robert A. Heinlein</name>
        <book>
            <title>Starship Troopers</title>
            <year-published>1959</year-published>
        </book>
        <book>
            <title>Stranger in a Strange Land</title>
            <year-published>1961</year-published>
        </book>
    </author>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
def test_attribute_serialize_multiple():
    """Serializing multiple attributes to the same element"""
    value = {
        'attribute_a': 'Hello, World',
        'attribute_b': True,
        'data': 1,
        'message': 'Hello, World'
    }

    processor = xml.dictionary('root', [
        xml.integer('data'),
        xml.string('data', attribute='attribute_a'),
        xml.boolean('data', attribute='attribute_b'),
        xml.string('message')
    ])

    expected = strip_xml("""
    <root>
        <data attribute_a="Hello, World" attribute_b="True">1</data>
        <message>Hello, World</message>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 19
0
def test_array_serialize_nested():
    """Tests serializing nested arrays"""
    value = {
        'date': '3-21',
        'data-points': [
            21.1,
            1897.17,
            13.1,
        ]
    }

    processor = xml.dictionary('root', [
        xml.string('date'),
        xml.array(xml.floating_point('value'), nested='data-points')
    ])

    expected = strip_xml("""
    <root>
        <date>3-21</date>
        <data-points>
            <value>21.1</value>
            <value>1897.17</value>
            <value>13.1</value>
        </data-points>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
def test_array_serialize_omit_empty_present():
    """Seralizes a non-empty array with the omit_empty option"""
    value = {
        'message': 'Hello',
        'data': [3, 17],
    }

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

    expected = strip_xml("""
    <root>
        <message>Hello</message>
        <data>
            <value>3</value>
            <value>17</value>
        </data>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
def test_dictionary_serialize_nested_aliased():
    """Serializes nested aliased dictionaries"""
    value = {
        'name': 'John Doe',
        'stats': {
            'age': 27,
            'gender': 'male',
        }
    }

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

    expected = strip_xml("""
    <root>
        <name>John Doe</name>
        <demographics>
            <age>27</age>
            <gender>male</gender>
        </demographics>
    </root>
    """)

    actual = xml.serialize_to_string(processor, value)

    assert expected == actual
Ejemplo n.º 24
0
def _assert_valid(processor, value, xml_string):
    """Assert the processor accepts the XML and value as valid."""
    actual_value = xml.parse_from_string(processor, xml_string)
    assert value == actual_value

    actual_xml_string = xml.serialize_to_string(processor, value)
    assert xml_string == actual_xml_string
Ejemplo n.º 25
0
def test_serialize_none_namedtuple_issue_7():
    """Tests attempting to serialize a named tuple value that is None"""
    Athlete = namedtuple('Athlete', [
        'name',
        'age',
    ])

    processor = xml.dictionary('race-result', [
        xml.floating_point('time'),
        xml.named_tuple('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
Ejemplo n.º 26
0
    def serialize(self, annotation, xml_file):
        if os.path.exists(xml_file):
            os.remove(xml_file)

        with open(xml_file, "a+") as f:
            f.write(
                xml.serialize_to_string(self.processor,
                                        annotation,
                                        indent='    '))
Ejemplo n.º 27
0
def test_dictionary_serialize_nested_missing():
    """Serializes nested dictionaries"""
    value = {
        'name': 'John Doe',
        'demographics': {
            'age': 27,
            'gender': 'male',
        },
    }

    processor = xml.dictionary('root', [
        xml.string('name'),
        xml.dictionary(
            'demographics',
            [xml.integer('age'), xml.string('gender')]),
        xml.dictionary('favorites', [xml.string('food'),
                                     xml.string('color')])
    ])

    with pytest.raises(xml.MissingValue):
        xml.serialize_to_string(processor, value)
Ejemplo n.º 28
0
def insert_xml():
    print('Inserting XML data')

    transaction_processor = xml.dictionary('transaction', [
        xml.string('.', attribute='date'),
        xml.integer('.', attribute='reseller-id'),
        xml.integer('transactionId'),
        xml.string('productName'),
        xml.integer('qty'),
        xml.floating_point('totalAmount'),
        xml.string('salesChannel'),
        xml.dictionary('customer',[xml.string('firstname'), xml.string('lastname'), xml.string('email')]),
        xml.string('dateCreated'),
        xml.string('seriesCity')
    ])


    for resellerid in XML_RESELLERS:

        tran_id = 0

        export = generate_xml(resellerid)

        for day in ALL_DAYS:

            data = [tran for tran in export if tran['Created Date']== day]

            for entry in data:
                entry['transactionId'] = tran_id
                tran_id += 1
            
            result = []

            xml_header = None


            result.append('<?xml version="1.0" encoding="utf-8"?>')
            result.append('<transactions>')
            for tran in data:

                xml_str = xml.serialize_to_string(transaction_processor, tran, indent='    ')
                
                splitted =xml_str.split('\n')
                    
                result += splitted[1:]

            result.append('</transactions>')

            date_nameformat = day.split('-')
            new_format = date_nameformat[0] + date_nameformat[2] + date_nameformat[1]

            with open(f"/home/generator/xml/rawDailySales_{new_format}_{resellerid}.xml", 'w')  as output_file:
                output_file.write('\n'.join(result))
Ejemplo n.º 29
0
 def json2cdata(input):
     author_processor = xml.dictionary('rows', [
         xml.array(xml.dictionary('row', [
             xml.string('qid'),
             xml.integer('code'),
             xml.string('answer'),
             xml.integer('sortorder'),
             xml.integer('assessment_value'),
             xml.integer('language'),
             xml.integer('scale_id'),
         ]),
                   alias='rows')
     ])
     xmlstr = xml.serialize_to_string(author_processor, input, indent='   ')
     return xmlstr
Ejemplo n.º 30
0
def export_to_string() -> str:
    return xml.serialize_to_string(
        configuration_processor,
        {
            'Settings':
            gina_config.settings.settings,
            'BehaviorGroups': [
                *gina_config.overlays.text_overlays,
                *gina_config.overlays.timer_overlays
            ],
            'Categories':
            gina_config.categories.categories,
            # 'TriggerGroups': config_data.trigger_groups,
            # 'Characters': characters
        },
        indent='  ')