How to unittest Django Rest Framework endpoint with XML?


I’ve got an endpoint which I built with Django Rest Framework. It works great when I test it with something like Postman, but my unit tests fail.

When I test my JSON endpoints I always post Python dicts instead of JSON strings, like this:

response ='/json-endpoint/', {'a': 1}, format='json')

When I test the XML endpoint I tried to post a raw xml string like this:

response ='/xml-endpoint/', '<?xml version="1.0" encoding="UTF-8" ?><myDataStructure></myDataStructure>', format='xml')

But this doesn’t work. In my Viewset I override the create() method, and in there, my XML somehow seems to be "packaged" into another XML. If I print out request.body in the create() method I see this:

b'<?xml version="1.0" encoding="utf-8"?>\n<root>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;\n&lt;myDataStructure&gt;\n etc..

As you can see my XML is somehow encoded and then packed into another <?xml version="1.0" encoding="utf-8"?>\n<root>.

Does anybody know how I can properly provide the xml when I write unit tests for the XML endpoint?


In unit tests I use this:

result =
    data='<?xml version="1.0" encoding="UTF-8" ?><myDataStructure></myDataStructure>', 

Answered By – MikeS

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published