[Fixed]-How to properly mock big XML in unit test in Django and Python?

1๐Ÿ‘

โœ…

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()
๐Ÿ‘คpetkostas

Leave a comment