Search code examples
pythondjangounit-testingdjango-rest-framework

django REST Framework - How to properly unittest a custom parser


I have been googling around for some time now and I still couldn't come up with a single match! I wrote a quite elaborate custom parser to convert the incoming data to match my serializer structure.

I want to unittest this properly to be sure that it remains functional when changing or refactoring my code.

But I don't know how! There are literally no example in the internet and just using it naive like this:

def test_me(self):
    parser_class = MyFancyParser()
    parser_class.parse(stream={'id': 27, 'other_data': 117})

... is not working because it requires a stream and not a data dictionary.

Any ideas on the topic?


Solution

  • Ok, what I went with is encapsulating the logic in a custom service/class and just call the class in the parser.

    class MyParser(parsers.JSONParser):
        def parse(self, stream, *args, **kwargs):
            raw_data = super().parse(stream, *args, **kwargs)
            pk = args[1]['kwargs']['pk']
            service = MyService()
            return service.parse_incoming_data(raw_data, pk)
    

    The benefit is obvious: I can test and structure my code as I please without any regard to DRF specifics.

    The "general" test if the parser stil works (for example after updating DRF) is handled implicitly by testing the viewset with the API client.