From 1a2bd38b359094fc9d0526f1815449bf7739d198 Mon Sep 17 00:00:00 2001 From: "bit4bit@riseup.net" Date: Tue, 27 Oct 2020 03:19:08 +0000 Subject: [PATCH] facho/facho.py: maneja rutas relativas. FossilOrigin-Name: cd97ead663dbbc1e2252f83da6e9cf17f9b3ae32e0ff411427ec62ad3658e89d --- facho/facho.py | 11 ++++++++--- tests/test_facho.py | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/facho/facho.py b/facho/facho.py index 347a679..0f143a9 100644 --- a/facho/facho.py +++ b/facho/facho.py @@ -173,12 +173,17 @@ class FachoXML: xpath = self._path_xpath_for(xpath) node_paths = xpath.split('/') node_paths.pop(0) #remove empty / + root_tag = node_paths.pop(0) - root_node = self.builder.build_from_expression(node_paths[0]) + root_node = self.builder.build_from_expression(root_tag) + if xpath.startswith('.'): + # restaurar ya que no es la raiz y asignar actual como raiz + node_paths.insert(0, root_tag) + root_node = self.root + if not self.builder.same_tag(root_node.tag, self.root.tag): + raise ValueError('xpath %s must be absolute to /%s' % (xpath, self.root.tag)) - else: - node_paths.pop(0) # crea jerarquia segun xpath indicado parent = None diff --git a/tests/test_facho.py b/tests/test_facho.py index 260c737..cfcffa1 100644 --- a/tests/test_facho.py +++ b/tests/test_facho.py @@ -150,3 +150,23 @@ def test_facho_xml_get_element_text_next_child(): line = xml.fragment('/Invoice/Line', append=True) line.set_element('/Line/Quantity', 6) assert line.get_element_text('/Line[2]/Quantity', format_=int) == 6 + + +def test_facho_xml_set_element_relative(): + xml = facho.FachoXML('Invoice') + xml.set_element('./ID', 'ABC123') + + assert xml.get_element_text('/Invoice/ID') == 'ABC123' + +def test_facho_xml_set_element_relative_with_namespace(): + xml = facho.FachoXML('{%s}Invoice' % ('http://www.dian.gov.co/contratos/facturaelectronica/v1'), + nsmap={'fe': 'http://www.dian.gov.co/contratos/facturaelectronica/v1'}) + xml.set_element('./ID', 'ABC123') + + assert xml.get_element_text('/fe:Invoice/ID') == 'ABC123' + +def test_facho_xml_fragment_relative(): + xml = facho.FachoXML('root') + invoice = xml.fragment('./Invoice') + invoice.set_element('./Id', 1) + assert xml.tostring() == '1'