[英]How to properly mock big XML in unit test in Django and Python?
我想对XML解析器中的方法进行单元测试。 该方法采用XML元素,将其解析为Django模型对象,然后返回此对象。
我已经为解析器编写了单元测试,但是它们需要少量的XML,我可以将这些位粘贴到字符串中,例如:
xml = ElementTree.fromstring('<xml><item>content</item></xml>')
但是现在我必须传递一个看起来太大的XML实体,无法将其存储在单元测试文件本身中。
我当时想将其保存到文件中,然后再从中加载,但是我无法弄清楚将文件放置在哪里,也不会违反有关应用程序结构的Django约定。
是否有模拟这种XML的“ Django”或“ pythonic”方式?
我通常会创建一个夹具文件夹(您可以在Django设置文件中进行配置)。 这通常用于json固定装置,但是也可以在其中添加XML文件。 您可以通过unittest提供的setUp
方法( https://docs.python.org/3/library/unittest.html#module-unittest )加载和读取这些XML文件。 然后,就像在项目中一样使用它即可。 一个简单的例子:
import os
from django.test import TestCase
from django.conf import settings
import xml.etree.ElementTree as ET
# Configure your XML_FILE_DIR inside your settings, this can be the
# same dir as the FIXTURE_DIR that Django uses for testing.
XML_FILE_DIR = getattr(settings, 'XML_FILE_DIR')
class MyExampleTestCase(TestCase):
def setUp(self):
"""
Load the xml files and pass them to the parser.
"""
test_file = os.path.join(XML_FILE_DIR, 'my-test.xml')
if os.path.isfile(test_file):
# Through this now you can reffer to the parser through
# self.parser.
self.parser = ET.parse(test_file)
# And of course assign the root as well.
self.root = self.parser.getroot()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.