如何在 Django 和 Python 的单元测试中正确模拟大 XML? [英] How to properly mock big XML in unit test in Django and Python?

查看:36
本文介绍了如何在 Django 和 Python 的单元测试中正确模拟大 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的 XML 解析器中的方法进行单元测试.该方法接受一个 XML 元素,将其解析为 Django 模型对象并返回该对象.

I want to unit test a method in my XML parser. The method takes an XML element, parses it into Django model object and returns this object.

我已经为解析器编写了单元测试,但它们需要一小部分 XML,我可以将这些部分粘贴到字符串中,例如:

I have already written unit tests for parsers, but they required a small bits of XML and I could just paste these bits in string, like:

xml = ElementTree.fromstring('<xml><item>content</item></xml>')

但现在我必须传递一个 XML 实体,该实体似乎太大而无法将其存储在单元测试文件本身中.

But now I have to pass an XML entity that seems too big for storing it in unit test file itself.

我想将它保存到文件中,然后从中加载,但我无法弄清楚将文件放在哪里并且不违反关于应用程序结构的 Django 约定.

I was thinking to save it to file and then load from it, but I can't fugure out where to put the file and do not break Django conventions about app structure.

是否有Django"或pythonic"方式来模拟这个 XML?

Is there a "Django" or "pythonic" way to mock this XML?

推荐答案

我通常会创建一个 fixtures 文件夹(您可以在 Django 设置文件中对其进行配置).这通常用于 json 固定装置,但也可以在其中添加 XML 文件.您可以通过 unittest 提供的 setUp 方法加载和读取这些 XML 文件 (https://docs.python.org/3/library/unittest.html#module-unittest).然后就像在项目中一样使用它.一个简单的例子:

I usually create a fixtures folder (which you can configure within your Django settings file). This is usually used for json fixtures, but it is perfectly ok to add XML files there as well. You can load and read those XML files through the setUp method that unittest provides (https://docs.python.org/3/library/unittest.html#module-unittest). Then just use it as you would within your project. A quick example:

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()

这篇关于如何在 Django 和 Python 的单元测试中正确模拟大 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆