【问题标题】:How to properly mock big XML in unit test in Django and Python?如何在 Django 和 Python 的单元测试中正确模拟大 XML?
【发布时间】:2015-09-15 11:41:25
【问题描述】:

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

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

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

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

我正在考虑将其保存到文件中,然后从中加载,但我不知道将文件放在哪里,并且不违反 Django 关于应用程序结构的约定。

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

【问题讨论】:

    标签: python xml django unit-testing


    【解决方案1】:

    我通常会创建一个fixtures 文件夹(你可以在你的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()
    

    【讨论】:

    • 感谢您分享您的方法。我想到了fixtures dir,但我假设Django 每次运行migrate 时都会尝试自动将它们加载到数据库中。但是现在我在文档中看到这种行为自 1.7 以来已被弃用(如果应用程序正在使用迁移则不起作用)docs.djangoproject.com/en/1.8/howto/initial-data/…
    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2022-10-25
    • 2015-12-15
    • 2021-07-04
    • 1970-01-01
    • 2020-06-12
    • 2021-12-23
    相关资源
    最近更新 更多