简体   繁体   中英

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 = self.client.post('/json-endpoint/', {'a': 1}, format='json')

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

response = self.client.post('/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? All tips are welcome!

In unit tests I use this:

result = self.client.post(
    path='/xml-endpoint/', 
    data='<?xml version="1.0" encoding="UTF-8" ?><myDataStructure></myDataStructure>', 
    content_type='text/xml',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM