I'm writing tests for an Azure Function. The function reads multipart/form-data from the frontend, which it accesses using data = dict(req.form)
where req
is the func.HttpRequest. This works fine, and I can access the form data passed from the frontend. My problem is I can't seem to mock up the req.form
object for my unit tests. I've written:
req = func.HttpRequest(
method="POST",
headers={
"x-ms-client-principal": my-test-user-object,
"Content-Type": "multipart/form-data"
},
body=SOMETHING-GOES-HERE,
url="/api/users"
)
I've tried setting the body to a bytes object; this allows me to access the bytes object using req.get_body()
. When I dump a JSON object I can get it with req.get_json()
. But I can't figure out what to pass in so that I can access it using req.form
. Does anyone know how to do this?
CodePudding user response:
We can use the function in a below way to get the whole form in return response
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
return func.HttpResponse(
json.dumps({
'method': req.method,
'url': req.url,
'headers': dict(req.headers),
'params': dict(req.params),
'get_body': req.get_body().decode()
})
)
CodePudding user response:
I ended up finding the solution on this blog post. The encode_multipart_formdata()
function described in the blog post allows for the creation of a mock form which can then be passed into the body of the HttpResponse object as follows:
body, content_type = encode_multipart_formdata({
"username": os.environ["TEST_USERNAME1"],
"email": os.environ["TEST_USER_EMAIL2"]
})
req = func.HttpRequest(
method="POST",
headers={
"x-ms-client-principal": my-test-user-obj,
"Content-Type": content_type
},
body=bytes(body, "utf-8"),
url="/api/users"
)