def test_path_property(self): root = ElementTree.XML( '<A><B1><C1/></B1><B2/><B3><C1/><C2 max="10"/></B3></A>') context = XPathContext(root) self.assertEqual(context.root.path, '/A') self.assertEqual(context.root[0].path, '/A/B1') self.assertEqual(context.root[0][0].path, '/A/B1/C1') self.assertEqual(context.root[1].path, '/A/B2') self.assertEqual(context.root[2].path, '/A/B3') self.assertEqual(context.root[2][0].path, '/A/B3/C1') self.assertEqual(context.root[2][1].path, '/A/B3/C2') attr = context.root[2][1].attributes[0] self.assertEqual(attr.path, '/A/B3/C2/@max') document = ElementTree.ElementTree(root) context = XPathContext(root=document) self.assertEqual(context.root[0][2][0].path, '/A/B3/C1') root = ElementTree.XML('<A><B1>10</B1><B2 min="1"/><B3/></A>') context = XPathContext(root) with patch.object(DummyXsdType(), 'is_simple', return_value=True) as xsd_type: elem = context.root[0] elem.xsd_type = xsd_type self.assertEqual(elem.path, '/A/B1') with patch.object(DummyXsdType(), 'is_simple', return_value=True) as xsd_type: context = XPathContext(root) attr = context.root[1].attributes[0] attr.xsd_type = xsd_type self.assertEqual(attr.path, '/A/B2/@min')
def test_string_value_function(self): token = self.parser.parse('true()') document = ElementTree.parse( io.StringIO(u'<A>123<B1>456</B1><B2>789</B2></A>')) element = ElementTree.Element('schema') comment = ElementTree.Comment('nothing important') pi = ElementTree.ProcessingInstruction('action', 'nothing to do') document_node = XPathContext(document).root context = XPathContext(element) element_node = context.root attribute_node = AttributeNode('id', '0212349350') namespace_node = NamespaceNode('xs', 'http://www.w3.org/2001/XMLSchema') comment_node = CommentNode(comment) pi_node = ProcessingInstructionNode(pi) text_node = TextNode('betelgeuse') self.assertEqual(token.string_value(document_node), '123456789') self.assertEqual(token.string_value(element_node), '') self.assertEqual(token.string_value(attribute_node), '0212349350') self.assertEqual(token.string_value(namespace_node), 'http://www.w3.org/2001/XMLSchema') self.assertEqual(token.string_value(comment_node), 'nothing important') self.assertEqual(token.string_value(pi_node), 'action nothing to do') self.assertEqual(token.string_value(text_node), 'betelgeuse') self.assertEqual(token.string_value(None), '') self.assertEqual(token.string_value(Decimal(+1999)), '1999') self.assertEqual(token.string_value(Decimal('+1999')), '1999') self.assertEqual(token.string_value(Decimal('+19.0010')), '19.001') self.assertEqual(token.string_value(10), '10') self.assertEqual(token.string_value(1e99), '1E99') self.assertEqual(token.string_value(1e-05), '1E-05') self.assertEqual(token.string_value(1.00), '1') self.assertEqual(token.string_value(+19.0010), '19.001') self.assertEqual(token.string_value(float('nan')), 'NaN') self.assertEqual(token.string_value(float('inf')), 'INF') self.assertEqual(token.string_value(float('-inf')), '-INF') self.assertEqual(token.string_value(()), '()') tagged_object = Tagged() self.assertEqual(token.string_value(tagged_object), "Tagged(tag='root')") with patch.multiple(DummyXsdType, is_simple=lambda x: True): xsd_type = DummyXsdType() element.text = '10' typed_elem = ElementNode(elem=element, xsd_type=xsd_type) self.assertEqual(token.string_value(typed_elem), '10') self.assertEqual(token.data_value(typed_elem), 10)
def get_counter_example(error): assertion = error.validator if not isinstance(assertion, xmlschema.validators.assertions.XsdAssert): return {} elem = error.obj context = XPathContext(elem, variables={'value': None}) context.counter_example = {} result = assertion.token.evaluate(context) if result == False: return context.counter_example else: return {}
def oselect_with_context(document_root, context_item, path, namespaces=None, parser=None, **kwargs): """ XPath selector function that apply a *path* expression on *root* Element. :param root: An Element or ElementTree instance. :param path: The XPath expression. :param namespaces: A dictionary with mapping from namespace prefixes into URIs. :param parser: The parser class to use, that is :class:`XPath2Parser` for default. :param kwargs: Other optional parameters for the XPath parser instance. :return: A list with XPath nodes or a basic type for expressions based \ on a function or literal. """ parser = (parser or XPath2Parser)(namespaces, **kwargs) root_token = parser.parse(path) context = XPathContext(document_root, item=context_item) eval_result = root_token.evaluate(context) print("[XX] EVALUATE WOULD RESULT IN: %s (%s)" % (str(eval_result), str(type(eval_result)))) results = root_token.get_results(context) print("[XX] RESULTS ARE: %s (%s)" % (str(results), str(type(results)))) return results
def test_document_node_iter(self): root = ElementTree.XML('<A><B1><C1/></B1><B2/><B3><C1/><C2/></B3></A>') doc = ElementTree.ElementTree(root) context = XPathContext(doc) self.assertListEqual( list(e.elem for e in context.root.iter() if isinstance(e, ElementNode)), list(doc.iter()))
def test_data_value_function(self): token = self.parser.parse('true()') if self.parser.version != '1.0': xsd_type = DummyXsdType() context = XPathContext(ElementTree.XML('<age>19</age>')) context.root.xsd_type = xsd_type self.assertEqual(token.data_value(context.root), 19) context = XPathContext(ElementTree.XML('<dummy/>')) obj = AttributeNode('age', '19') self.assertEqual(token.data_value(obj), UntypedAtomic('19')) obj = NamespaceNode('tns', 'http://xpath.test/ns') self.assertEqual(token.data_value(obj), 'http://xpath.test/ns') obj = TextNode('19') self.assertEqual(token.data_value(obj), UntypedAtomic('19')) obj = ElementTree.XML('<root>a<e1>b</e1>c<e2>d</e2>e</root>') element_node = ElementNode(obj) self.assertEqual(token.data_value(element_node), UntypedAtomic('abcde')) obj = ElementTree.parse( io.StringIO('<root>a<e1>b</e1>c<e2>d</e2>e</root>')) document_node = DocumentNode(obj) self.assertEqual(token.data_value(document_node), UntypedAtomic('abcde')) obj = ElementTree.Comment("foo bar") comment_node = CommentNode(obj) self.assertEqual(token.data_value(comment_node), 'foo bar') obj = ElementTree.ProcessingInstruction('action', 'nothing to do') pi_node = ProcessingInstructionNode(obj) self.assertEqual(token.data_value(pi_node), 'action nothing to do') self.assertIsNone(token.data_value(None)) self.assertEqual(token.data_value(19), 19) self.assertEqual(token.data_value('19'), '19') self.assertFalse(token.data_value(False)) # Does not check type of non nodes, simply returns the object. tagged_object = Tagged() self.assertIs(token.data_value(tagged_object), tagged_object)
def test_select_results(self): token = self.parser.parse('.') elem = ElementTree.Element('A', attrib={'max': '30'}) elem.text = '10' context = XPathContext(elem) self.assertListEqual(list(token.select_results(context)), [elem]) context = XPathContext(elem, item=TypedElement(elem, 10)) self.assertListEqual(list(token.select_results(context)), [elem]) context = XPathContext(elem, item=AttributeNode('max', '30')) self.assertListEqual(list(token.select_results(context)), ['30']) context = XPathContext(elem, item=TypedAttribute(AttributeNode('max', '30'), 30)) self.assertListEqual(list(token.select_results(context)), [30]) attribute = namedtuple('XsdAttribute', 'name type')('max', 'xs:string') context = XPathContext(elem, item=TypedAttribute( AttributeNode('max', attribute), 30)) self.assertListEqual(list(token.select_results(context)), [attribute]) context = XPathContext(elem, item=10) self.assertListEqual(list(token.select_results(context)), [10]) context = XPathContext(elem, item='10') self.assertListEqual(list(token.select_results(context)), ['10'])
def test_atomization_function(self): root = ElementTree.Element('root') token = self.parser.parse('/unknown/.') context = XPathContext(root) self.assertListEqual(list(token.atomization(context)), []) if self.parser.version > '1.0': token = self.parser.parse('((), 1, 3, "a")') self.assertListEqual(list(token.atomization()), [1, 3, 'a'])
def test_typed_element_nodes(self): element = ElementTree.Element('schema') with patch.multiple(DummyXsdType, is_simple=lambda x: True): xsd_type = DummyXsdType() context = XPathContext(element) context.root.xsd_type = xsd_type self.assertTrue( repr(context.root).startswith( "ElementNode(elem=<Element 'schema' at 0x"))
def test_element_node_iter(self): root = ElementTree.XML( '<A>text1\n<B1 a="10">text2</B1><B2/><B3><C1>text3</C1></B3></A>') context = XPathContext(root) expected = [ context.root, context.root.namespace_nodes[0], context.root[0], context.root[1], context.root[1].namespace_nodes[0], context.root[1].attributes[0], context.root[1][0], context.root[2], context.root[2].namespace_nodes[0], context.root[3], context.root[3].namespace_nodes[0], context.root[3][0], context.root[3][0].namespace_nodes[0], context.root[3][0][0] ] result = list(context.root.iter()) self.assertListEqual(result, expected) root = ElementTree.XML('<A><B1><C1/></B1><B2/><B3><C1/><C2/></B3></A>') context = XPathContext(root) # iter includes also xml namespace nodes self.assertListEqual( list(e.elem for e in context.root.iter() if isinstance(e, ElementNode)), list(root.iter()))
def test_boolean_value_function(self): token = self.parser.parse('true()') elem = ElementTree.Element('A') context = XPathContext(elem) self.assertTrue(token.boolean_value(context.root)) self.assertFalse(token.boolean_value([])) self.assertTrue(token.boolean_value([context.root])) self.assertFalse(token.boolean_value([0])) self.assertTrue(token.boolean_value([1])) with self.assertRaises(TypeError): token.boolean_value([1, 1]) self.assertFalse(token.boolean_value(0)) self.assertTrue(token.boolean_value(1)) self.assertTrue(token.boolean_value(1.0)) self.assertFalse(token.boolean_value(None))
def test_string_value_function(self): super(XPath2TokenTest, self).test_string_value_function() if xmlschema is not None: schema = xmlschema.XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:int"/> </xs:schema>""") token = self.parser.parse('.') self.parser.schema = xmlschema.xpath.XMLSchemaProxy(schema) context = XPathContext(schema) try: value = token.string_value(context.root[0]) # 'root' element self.assertIsInstance(value, str) self.assertEqual(value, '1') finally: self.parser.schema = None
def setUp(self): root = ElementTree.Element('root') self.context = XPathContext(root) # Dummy context for creating nodes
def test_get_typed_node(self): schema = xmlschema.XMLSchema(""" <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="root" type="xs:int"/> <xs:attribute name="a" type="xs:int"/> </xs:schema>""") self.parser.schema = xmlschema.xpath.XMLSchemaProxy(schema) try: root_token = self.parser.parse('root') elem = ElementTree.Element('root') elem.text = '49' context = XPathContext(elem) node = root_token.get_typed_node(context.root) self.assertIsInstance(node, ElementNode) self.assertIsInstance(node.xsd_type, xmlschema.XsdType) self.assertEqual(node.typed_value, 49) self.assertIs(root_token.get_typed_node(node), node) # elem.text = 'beta' # with self.assertRaises(TypeError) as err: # root_token.get_typed_node(elem) # self.assertIn('XPDY0050', str(err.exception)) # self.assertIn('does not match sequence type', str(err.exception)) root_token.xsd_types['root'] = schema.meta_schema.types[ 'anySimpleType'] elem.text = '36' context = XPathContext(elem) node = root_token.get_typed_node(context.root) self.assertIsInstance(node, ElementNode) self.assertIsInstance(node.xsd_type, xmlschema.XsdType) self.assertIsInstance(node.typed_value, UntypedAtomic) self.assertEqual(node.typed_value, 36) # Convert untyped to int root_token.xsd_types['root'] = schema.meta_schema.types['anyType'] context = XPathContext(elem) node = root_token.get_typed_node(context.root) self.assertIs(node.elem, elem) root_token = self.parser.parse('@a') self.assertEqual(root_token[0].xsd_types, {'a': schema.meta_schema.types['int']}) elem = ElementTree.Element('root', a='10') context = XPathContext(elem) attribute = context.root.attributes[0] node = root_token[0].get_typed_node(attribute) self.assertIsInstance(node, AttributeNode) self.assertIsInstance(node.xsd_type, xmlschema.XsdType) self.assertEqual(node.value, '10') root_token[0].xsd_types['a'] = schema.meta_schema.types['anyType'] node = root_token[0].get_typed_node(attribute) self.assertIsInstance(node, AttributeNode) self.assertIsInstance(node.xsd_type, xmlschema.XsdType) self.assertIsInstance(node.typed_value, int) self.assertEqual(node.value, '10') self.assertEqual(node.typed_value, 10) finally: self.parser.schema = None
def test_select_results(self): token = self.parser.parse('.') elem = ElementTree.Element('A', attrib={'max': '30'}) elem.text = '10' xsd_type = DummyXsdType() context = XPathContext(elem) self.assertListEqual(list(token.select_results(context)), [elem]) context = XPathContext(elem, item=elem) context.root.xsd_type = xsd_type self.assertListEqual(list(token.select_results(context)), [elem]) context = XPathContext(elem) context.item = context.root.attributes[0] self.assertListEqual(list(token.select_results(context)), ['30']) context = XPathContext(elem) context.item = context.root.attributes[0] context.item.xsd_type = xsd_type self.assertListEqual(list(token.select_results(context)), ['30']) context = XPathContext(elem, item=10) self.assertListEqual(list(token.select_results(context)), [10]) context = XPathContext(elem, item='10') self.assertListEqual(list(token.select_results(context)), ['10'])