Sebastian.M
Sebastian.M

Reputation: 676

How to mock an object used in an Azure Function written in Python

I found resources on how to add custom bindings to Azure Functions written in C# and how to mock them, however, I haven't been able to find a solution in Python.

To describe my usecase:

I have an http-triggered function that creates a connection to a SQL database, retrieves some values and returns them, ie. a simple GET. The database connection is wrapped in an object that provides a method to execute the SELECT query.

Now, the database is a serverless Azure SQL Database. I want to avoid actually querying it in manual tests or unittests. How can I do that? Is there any way to inject a mock into the body of the Azure function?

The only thing I could come up with so far is something like this:

def main(req: func.HttpRequest) -> func.HttpResponse:
    if req.headers.get("is-test", False):
        database = Database()
    else:
        database = MockDatabase()

    ...

Which is something I would really like to avoid.

Upvotes: 2

Views: 827

Answers (1)

Sebastian.M
Sebastian.M

Reputation: 676

I think I have a solution that's quite usable for unittests, but doesn't do anything for a local deployment.

__init__py:

def main(req: func.HttpRequest) -> func.HttpResponse:
    wrapper = MyFunctionWrap(Database())
    return wrapper.exec(req)

myfunctionwrap.py:

class MyFunctionWrap:

    def __init__(self, dependency: Dependency):
        self._dependency = dependency

    def exec(self, req: func.HttpRequest) -> func.HttpResponse:
        ...

test_myfunction.py:

class TestFunction(unittest.TestCase):

    def test_my_function(self):
        req = func.HttpRequest(...)

        database = MockDatabase()
        wrapper = MyFunctionWrap(database)
        resp = wrapper.exec(req)

        ...

Upvotes: 1

Related Questions