-
Notifications
You must be signed in to change notification settings - Fork 107
Unit Testing Guide
Hanzhang Zeng (Roger) edited this page Mar 19, 2020
·
13 revisions
- Create a virtual python environment under azure-functions-python-worker project directory (supports Python 3.6/3.7/3.8)
- Run
python -m pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple -U -e .[dev]
to install the dependencies - Run
python setup.py webhost
to download the WEBHOST defined in setup.py - Test a case with
pytest ./tests/unittests/test_code_quality.py::TestCodeQuality::test_mypy
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',
)