2015-09-15 84 views
0

我想單元測試我的XML解析器中的一個方法。該方法接受一個XML元素,將其解析爲Django模型對象並返回該對象。如何在Django和Python的單元測試中正確地模擬大XML?

我已經寫了解析器單元測試,但他們需要的XML的一個小位,我可以只粘貼字符串這些位,如:

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

但現在我必須要通過一個XML實體似乎太大,不適合將其存儲在單元測試文件本身中。

我正在考慮將它保存到文件中,然後從中加載,但我無法找到將文件放在哪裏,也不會破壞有關應用程序結構的Django約定。

是否有「Django」或「pythonic」方式來模擬此XML?

回答

1

我通常會創建一個fixtures文件夾(您可以在您的Django設置文件中進行配置)。 這通常用於json fixtures,但在這裏添加XML文件也是完全可以的。 您可以通過unittest提供的setUp方法加載並讀取這些XML文件(https://docs.python.org/3/library/unittest.html#module-unittest)。 然後就像你在你的項目中那樣使用它。 一個簡單的例子:

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

感謝您分享您的方法。我想過fixtures dir,但我認爲Django每次運行'migrate'時都會嘗試自動將它們加載到數據庫中。但是現在我在文檔中看到,此行爲從1.7開始不推薦使用(並且在應用程序使用遷移時不起作用)https://docs.djangoproject.com/en/1.8/howto/initial-data/#automatically-loading-初始數據夾具 –