Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Python Azure Function: How do I construct a mock test request message with a JSON payload?

I want to unit test my Python Azure function. I'm following the Microsoft documentation.

The documentation mocks the call to the function as follows

req = func.HttpRequest(
            method='GET',
            body=None,
            url='/api/HttpTrigger',
            params={'name': 'Test'})

I would like to do this but with the parameters passed as a JSON object so that I can follow the req_body = req.get_json() branch of the function code. I guessed I would be able to do this with a function call like

req = func.HttpRequest(
            method='GET',
            body=json.dumps({'name': 'Test'}),
            url='/api/HttpTrigger',
            params=None)

If I construct the call like this, req.get_json() fails with the error message AttributeError: 'str' object has no attribute 'decode'.

How do I construct the request with JSON input parameters? It should be trivial but I'm clearly missing something obvious.

like image 804
Steven Avatar asked Sep 20 '25 00:09

Steven


1 Answers

If I construct my mock call as follows:

import json


req = func.HttpRequest(
            method='POST',
            body=json.dumps({'name': 'Test'}).encode('utf8'),
            url='/api/HttpTrigger',
            params=None)

Then I am able to make a successful call to req.get_json(). Thanks to @MrBeanBremen and @JoeyCai for pointing me in the correct direction i.e. don't call GET and make the message a byte string.

like image 179
Steven Avatar answered Sep 21 '25 13:09

Steven