Anton Belonovich
Anton Belonovich

Reputation: 1551

How to properly mock big XML in unit test in Django and Python?

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.

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

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

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.

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

Upvotes: 0

Views: 2478

Answers (1)

petkostas
petkostas

Reputation: 7450

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

Upvotes: 1

Related Questions