def test_xml_to_dict_multiple_records(self): """Test the xml to dict function.""" topics_xml = '''<topics type="array"> <topic> <title>The First Topic</title> <author-name>David</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id nil="true"></parent-id> </topic> <topic> <title>The Second Topic</title> <author-name>Jason</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id></parent-id> </topic> </topics>''' expected_topic_dict = { 'title': 'The First Topic', 'author_name': 'David', 'id': 1, 'approved': False, 'replies_count': 0, 'replies_close_in': 2592000000, 'written_on': datetime.date(2003, 7, 16), 'viewed_at': util.date_parse('2003-07-16T09:28Z'), 'content': 'Have a nice day', 'author_email_address': '*****@*****.**', 'parent_id': None } self.assertEqual(expected_topic_dict, util.xml_to_dict(topics_xml, saveroot=False)[0]) self.assertEqual( expected_topic_dict, util.xml_to_dict(topics_xml, saveroot=True)['topics'][0])
def test_xml_to_dict_multiple_records(self): """Test the xml to dict function.""" topics_xml = '''<topics type="array"> <topic> <title>The First Topic</title> <author-name>David</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id nil="true"></parent-id> </topic> <topic> <title>The Second Topic</title> <author-name>Jason</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id></parent-id> </topic> </topics>''' expected_topic_dict = { 'title': 'The First Topic', 'author_name': 'David', 'id': 1, 'approved': False, 'replies_count': 0, 'replies_close_in': 2592000000, 'written_on': datetime.date(2003, 7, 16), 'viewed_at': util.date_parse('2003-07-16T09:28Z'), 'content': 'Have a nice day', 'author_email_address': '*****@*****.**', 'parent_id': None} self.assertEqual(expected_topic_dict, util.xml_to_dict(topics_xml, saveroot=False)[0]) self.assertEqual( expected_topic_dict, util.xml_to_dict(topics_xml, saveroot=True)['topics'][0])
def test_xml_to_dict_single_record(self): """Test the xml_to_dict function.""" topic_xml = '''<topic> <title>The First Topic</title> <author-name>David</author-name> <id type="integer">1</id> <approved type="boolean"> true </approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content type="yaml">--- \n1: should be an integer\n:message: Have a nice day\narray: \n- should-have-dashes: true\n should_have_underscores: true\n</content> <author-email-address>[email protected]</author-email-address> <parent-id></parent-id> <ad-revenue type="decimal">1.5</ad-revenue> <optimum-viewing-angle type="float">135</optimum-viewing-angle> <resident type="symbol">yes</resident> </topic>''' expected_topic_dict = { 'title': 'The First Topic', 'author_name': 'David', 'id': 1, 'approved': True, 'replies_count': 0, 'replies_close_in': 2592000000, 'written_on': datetime.date(2003, 7, 16), 'viewed_at': util.date_parse('2003-07-16T9:28Z'), 'content': { ':message': 'Have a nice day', 1: 'should be an integer', 'array': [{ 'should-have-dashes': True, 'should_have_underscores': True }] }, 'author_email_address': '*****@*****.**', 'parent_id': None, 'ad_revenue': decimal.Decimal('1.5'), 'optimum_viewing_angle': 135.0, 'resident': 'yes' } self.assertEqual(expected_topic_dict, util.xml_to_dict(topic_xml, saveroot=False)) self.assertEqual(expected_topic_dict, util.xml_to_dict(topic_xml)['topic'])
def test_to_xml_should_handle_attributes_containing_lists_of_strings(self): store = self.store({'name': 'foo', 'id': 1}) store.websites = ['http://example.com', 'http://store.example.com'] xml = store.to_xml() parsed = util.xml_to_dict(xml, saveroot=False) self.assertEqual(['http://example.com', 'http://store.example.com'], parsed['websites'])
def test_xml_to_dict_empty_array(self): blog_xml = '''<blog> <posts type="array"></posts> </blog>''' expected_blog_dict = {'blog': {'posts': []}} self.assertEqual(expected_blog_dict, util.xml_to_dict(blog_xml, saveroot=True))
def test_xml_to_dict_parses_children_which_are_not_of_parent_type(self): product_xml = ''' <products type="array"> <shamwow><made-in>Germany</made-in></shamwow> </products>''' self.assertEqual({'products': [{'made_in': 'Germany'}]}, util.xml_to_dict(product_xml, saveroot=True))
def test_xml_to_dict_parses_datetime_timezones(self): blog_xml = '''<blog> <posted_at type="datetime">2008-09-05T13:34-0700</posted_at> </blog>''' blog_dict = util.xml_to_dict(blog_xml, saveroot=True) self.assertEqual((2008, 9, 5, 20, 34, 0, 4, 249, 0), blog_dict['blog']['posted_at'].utctimetuple())
def test_to_xml_should_handle_attributes_containing_lists_of_dicts(self): children = [{'name': 'child1'}, {'name': 'child2'}] res = activeresource.ActiveResource() res.children = children xml = res.to_xml() parsed = util.xml_to_dict(xml, saveroot=False) self.assertEqual(children, parsed['children'])
def test_xml_to_dict_multiple_records_with_different_types(self): """Test the xml to dict function.""" topics_xml = '''<topics type="array"> <topic> <title>The First Topic</title> <author-name>David</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id nil="true"></parent-id> </topic> <topic type='SubTopic'> <title>The Second Topic</title> <author-name>Jason</author-name> <id type="integer">1</id> <approved type="boolean">false</approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content>Have a nice day</content> <author-email-address>[email protected]</author-email-address> <parent-id></parent-id> </topic> </topics>''' parsed = util.xml_to_dict(topics_xml, saveroot=False) self.assertEqual('topics', parsed.element_type) self.assertEqual('topic', parsed[0].element_type) self.assertEqual('sub_topic', parsed[1].element_type)
def test_xml_to_dict_should_parse_dictionaries_with_unknown_types(self): xml = '''<records type="array"> <record type="MiscData"> <name>misc_data1</name> </record> </records>''' expected = {'records': [{'type': 'MiscData', 'name': 'misc_data1'}]} self.assertEqual(expected, util.xml_to_dict(xml, saveroot=True))
def decode(resource_string): """Convert a resource string to a dictionary.""" log = logging.getLogger('pyactiveresource.format') log.debug('decoding resource: %s', resource_string) try: data = util.xml_to_dict(resource_string, saveroot=False) except util.Error, err: raise Error(err)
def test_xml_to_dict_array_with_one_entry(self): blog_xml = '''<blog> <posts type="array"> <post>a post</post> </posts> </blog>''' expected_blog_dict = {'blog': {'posts': ['a post']}} self.assertEqual(expected_blog_dict, util.xml_to_dict(blog_xml, saveroot=True))
def test_xml_to_dict_unknown_type(self): product_xml = '''<product> <weight type="double">0.5</weight> <image type="ProductImage"><filename>image.gif</filename></image> </product>''' expected_product_dict = { 'weight': 0.5, 'image': {'type': 'ProductImage', 'filename': 'image.gif'}} self.assertEqual( expected_product_dict, util.xml_to_dict(product_xml, saveroot=True)['product'])
def decode(resource_string): """Convert a resource string to a dictionary.""" log = logging.getLogger('pyactiveresource.format') log.debug('decoding resource: %s', resource_string) try: data = util.xml_to_dict(resource_string, saveroot=False) except util.Error as err: raise Error(err) if isinstance(data, dict) and len(data) == 1: data = iter(data.values())[0] return data
def test_xml_to_dict_file_with_defaults(self): blog_xml = '''<blog> <logo type="file"> </logo> </blog>''' blog_dict = util.xml_to_dict(blog_xml, saveroot=True) self.assert_('blog' in blog_dict) self.assert_('logo' in blog_dict['blog']) blog_file = blog_dict['blog']['logo'] self.assertEqual('untitled', blog_file.name) self.assertEqual('application/octet-stream', blog_file.content_type)
def test_xml_to_dict_file(self): blog_xml = '''<blog> <logo type="file" name="logo.png" content_type="image/png"> </logo> </blog>''' blog_dict = util.xml_to_dict(blog_xml, saveroot=True) self.assert_('blog' in blog_dict) self.assert_('logo' in blog_dict['blog']) blog_file = blog_dict['blog']['logo'] self.assertEqual('logo.png', blog_file.name) self.assertEqual('image/png', blog_file.content_type)
def test_xml_to_dict_single_record(self): """Test the xml_to_dict function.""" topic_xml = '''<topic> <title>The First Topic</title> <author-name>David</author-name> <id type="integer">1</id> <approved type="boolean"> true </approved> <replies-count type="integer">0</replies-count> <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> <content type="yaml">--- \n1: should be an integer\n:message: Have a nice day\narray: \n- should-have-dashes: true\n should_have_underscores: true\n</content> <author-email-address>[email protected]</author-email-address> <parent-id></parent-id> <ad-revenue type="decimal">1.5</ad-revenue> <optimum-viewing-angle type="float">135</optimum-viewing-angle> <resident type="symbol">yes</resident> </topic>''' expected_topic_dict = { 'title': 'The First Topic', 'author_name': 'David', 'id': 1, 'approved': True, 'replies_count': 0, 'replies_close_in': 2592000000, 'written_on': datetime.date(2003, 7, 16), 'viewed_at': util.date_parse('2003-07-16T9:28Z'), 'content': {':message': 'Have a nice day', 1: 'should be an integer', 'array': [{'should-have-dashes': True, 'should_have_underscores': True}]}, 'author_email_address': '*****@*****.**', 'parent_id': None, 'ad_revenue': decimal.Decimal('1.5'), 'optimum_viewing_angle': 135.0, 'resident': 'yes'} self.assertEqual(expected_topic_dict, util.xml_to_dict(topic_xml, saveroot=False)) self.assertEqual(expected_topic_dict, util.xml_to_dict(topic_xml)['topic'])
def test_should_be_able_to_add_note_attributes_to_an_order(self): order = shopify.Order() order.note_attributes = [] order.note_attributes.append(shopify.NoteAttribute({'name': "color", 'value': "blue"})) order_xml = xml_to_dict(order.to_xml()) note_attributes = order_xml["order"]["note_attributes"] self.assertTrue(isinstance(note_attributes, list)) attribute = note_attributes[0] self.assertEqual("color", attribute["name"]) self.assertEqual("blue", attribute["value"])
def test_to_xml_should_consider_attributes_on_element_with_children(self): custom_field_xml = ''' <custom_field name="custom1" id="1"> <value>cust1</value> </custom_field>''' expected = { 'custom_field': { 'name': 'custom1', 'id': '1', 'value': 'cust1'} } result = util.xml_to_dict(custom_field_xml, saveroot=True) self.assertEqual(expected, result)
def from_xml(self, xml_string): """Grab errors from an XML response. Args: xml_string: An xml errors object (e.g. '<errors></errors>') Returns: None """ try: messages = util.xml_to_dict(xml_string)["errors"]["error"] if not isinstance(messages, list): messages = [messages] except util.Error: messages = [] self.from_array(messages)
def from_xml(self, xml_string): """Grab errors from an XML response. Args: xml_string: An xml errors object (e.g. '<errors></errors>') Returns: None """ try: messages = util.xml_to_dict(xml_string)['errors']['error'] if not isinstance(messages, list): messages = [messages] except util.Error: messages = [] self.from_array(messages)
def test_should_be_loaded_correctly_from_order_xml(self): order_xml = """<?xml version="1.0" encoding="UTF-8"?> <order> <note-attributes type="array"> <note-attribute> <name>size</name> <value>large</value> </note-attribute> </note-attributes> </order>""" order = shopify.Order(xml_to_dict(order_xml)["order"]) self.assertEqual(1, len(order.note_attributes)) note_attribute = order.note_attributes[0] self.assertEqual("size", note_attribute.name) self.assertEqual("large", note_attribute.value)
def test_xml_to_dict_xsd_like_types(self): bacon_xml = '''<bacon> <weight type="double">0.5</weight> <price type="decimal">12.50</price> <chunky type="boolean"> 1 </chunky> <expires-at type="dateTime">2007-12-25T12:34:56+0000</expires-at> <notes type="string"></notes> <illustration type="base64Binary">YmFiZS5wbmc=</illustration> </bacon>''' expected_bacon_dict = { 'weight': 0.5, 'chunky': True, 'price': decimal.Decimal('12.50'), 'expires_at': util.date_parse('2007-12-25T12:34:56Z'), 'notes': '', 'illustration': b'babe.png'} self.assertEqual(expected_bacon_dict, util.xml_to_dict(bacon_xml, saveroot=True)['bacon'])
def from_xml(self, xml_string): """Grab errors from an XML response. Args: xml_string: An xml errors object (e.g. '<errors></errors>') Returns: None """ attribute_keys = self.base.attributes.keys() try: messages = util.xml_to_dict(xml_string)["errors"]["error"] if not isinstance(messages, list): messages = [messages] except util.Error: messages = [] for message in messages: attr_name = message.split()[0] key = util.underscore(attr_name) if key in attribute_keys: self.add(key, message[len(attr_name) + 1 :]) else: self.add_to_base(message)
def from_xml(self, xml_string): """Grab errors from an XML response. Args: xml_string: An xml errors object (e.g. '<errors></errors>') Returns: None """ attribute_keys = self.base.attributes.keys() try: messages = util.xml_to_dict(xml_string)['errors']['error'] if not isinstance(messages, list): messages = [messages] except util.Error: messages = [] for message in messages: attr_name = message.split()[0] key = util.underscore(attr_name) if key in attribute_keys: self.add(key, message[len(attr_name) + 1:]) else: self.add_to_base(message)
def decode(resource_string): """Convert a resource string to a dictionary.""" try: data = util.xml_to_dict(resource_string, saveroot=True) except util.Error, err: raise Error(err)
def test_xml_to_dict_should_include_xml_attributes_as_dictionary_items( self): xml = '''<record><child name="child_name" id="1234" /></record>''' result = util.xml_to_dict(xml, saveroot=True) self.assertEqual('child_name', result['record']['child']['name']) self.assertEqual('1234', result['record']['child']['id'])
def test_to_xml_should_handle_attributes_containing_lists_of_dicts(self): children = [{"name": "child1"}, {"name": "child2"}] res = activeresource.ActiveResource() res.children = children xml = res.to_xml() self.assertEqual(children, util.xml_to_dict(xml)["children"])
def test_xml_to_dict_should_include_xml_attributes_as_dictionary_items(self): xml = '''<record><child name="child_name" id="1234" /></record>''' result = util.xml_to_dict(xml, saveroot=True) self.assertEqual('child_name', result['record']['child']['name']) self.assertEqual('1234', result['record']['child']['id'])