-
Notifications
You must be signed in to change notification settings - Fork 107
Unit Testing Guide
Elvis Pranskevichus edited this page Jan 30, 2019
·
13 revisions
Python functions for Azure can be tested like regular Python code using standard testing frameworks. For most bindings it is possible to create a mock input object by creating an instance of an appropriate class from the azure.functions
package.
For example, below is a mock test of an HttpTrigger function:
myapp/__init__.py
:
import azure.functions as func
def my_function(req: func.HttpRequest) -> func.HttpResponse:
name = req.params.get('name')
if not name:
name = 'Incognito'
return func.HttpResponse(f"Hello {name}!")
myapp/test_func.py
:
import unittest
import azure.functions as func
from . import my_function
class TestFunction(unittest.TestCase):
def test_my_function(self):
# Construct a mock HTTP request.
req = func.HttpRequest(
method='GET',
body=None,
url='/my_function',
params={'name': 'Test'})
# Call the function.
resp = my_function(req)
# Check the output.
self.assertEqual(
resp.get_body(),
'Hello, Test!',
)
Another example, with a queue trigger function:
queueapp/__init__.py
:
import azure.functions as func
def my_function(msg: func.QueueMessage) -> str:
return f'msg body: {msg.get_body().decode()}'
queueapp/test_func.py
:
import unittest
import azure.functions as func
from . import my_function
class TestFunction(unittest.TestCase):
def test_my_function(self):
# Construct a mock Queue message.
req = func.QueueMessage(
body=b'test')
# Call the function.
resp = my_function(req)
# Check the output.
self.assertEqual(
resp,
'msg body: test',
)