簡體   English   中英

如何在Django和Python的單元測試中正確模擬大型XML?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM