简体   繁体   中英

How to test an Azure Function that uses Context?

I'm writing an Azure Function that uses context (for monitoring purposes), this is what my function looks like:

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    logging.info(
        "{}\t{}".format(
            context.invocation_id, context.function_name
        )
    )
    reponse = "foo"    
    return func.HttpResponse(json.dumps(reponse), mimetype="application/json")

And I want to write integration test for this function, like this:

import unittest
import azure.functions as func
from MyFunc import main    

class TestMyFunc(unittest.TestCase):
    def test_myfunc(self):
        req = func.HttpRequest(
            method="GET",
            body=None,
            url="/api/myfunc",
        )
        ctx = ??
        reponse = main(req, ctx) # This part fails because of the context

        self.assertEqual(
            reponse.get_body(),
            b'foo',
        )

How can I create a Context object to pass to my Azure Function?

Looks like Context is an ABC(Abstract Base Class) class , so you cannot directly instantiate. Instead you could subclass the func.Context class and use the instance of that class as ctx

class MockContext(func.Context):
    def __init__(self, ii, fn, fd):
        self._invocation_id = ii
        self._function_name = fn
        self._function_directory = fd

    @property
    def invocation_id(self):
        return self._invocation_id

    @property
    def function_name(self):
        return self._function_name

    @property
    def function_directory(self):
        return self._function_directory

ctx = MockContext("Some dummy values")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM