I'm trying to write some unit tests with certain methods that parse different elements of my XML. But I'm having a few issues parsing a "test" xml file in my unit test.
My question isn't so much about anything to do with the XML/XSD files, but it's just around how to parse them correctly in my unit test.
This is my code so far:
import unittest
from lxml import etree
from Directory.method_in_class import ClassName #changed the names for security
class TestXmlData(unittest.TestCase):
def setUp(self):
self.method_in_class = ClassName()
XSDDoc = etree.parse("dir/testxsd.xsd")
rootXSD = XSDDoc.getroot()
def test_whatever(self):
# Test whatever
if __name__ == '__main__':
unittest.main()
Even though I'm parsing the same way in the implementation method, I'm getting the below error:
OSError: Error reading file 'dir/testxsd.xsd': failed to load external entity "dir/testxsd.xsd"
I've tried a couple of other alternatives, such as loading the file from this answer , but doing this gives me an error:
import unittest
from lxml import etree
import os
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class TestSpecData(unittest.TestCase):
def setUp(self):
my_data_path = os.path.join(THIS_DIR, os.pardir, 'dir/testxsd.xsd')
rootXSD = my_data_path.getroot()
def test_whatever(self):
data = sum(1, 2)
self.assertEqual(data, 3)
if __name__ == '__main__':
unittest.main()
AttributeError: 'str' object has no attribute 'getroot'
I've also tried this answer , but I'm not familiar with Django so was getting a bunch of errors.
In the second version after your edit, you are calling getroot
on a string instead of a parsed XML tree. Still, if you properly parse the file with an absolute path, this could solve your problem.
Schema example ( test.xsd)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xs:element name="config" type="xs:string" />
</xs:schema>
Python code ( test.py
)
import unittest
from lxml import etree
import os
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class TestSpecData(unittest.TestCase):
def setUp(self):
my_data_path = os.path.join(THIS_DIR, 'data/test.xsd')
tree = etree.parse(my_data_path)
root = tree.getroot()
def test_whatever(self):
data = sum([1, 2])
self.assertEqual(data, 3)
if __name__ == '__main__':
unittest.main()
Output
Assuming a folder test
that contains test.py
, and that test.xsd
is in a subfolder called data
, and after fixing an error in your test (adding list brackets) the output is
$ python test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.