Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference my Azure function from pytest?

I'm using Python 3.8 with Azure functions. I have the following project layout ...

myproject
    __app__
        __init__.py
        objects
            __init__.py
    tests
        __init__.py
        functions
            __init__.py
            objects
                __init__.py
                test_objects.py

My app/objects/init.py file starts like this ...

import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    """."""
    ...

And then my tests/functions/objects/init.py looks like

import pytest
import azure.functions as func

_import = __import__('__app__/objects')

def test_objects():
    ...
    

However, when I run

pytest tests/functions/test_objects.py 

I get the error

tests/functions/test_objects.py:8: in <module>
    _import = __import__('__app__/objects')
E   ModuleNotFoundError: No module named '__app__/objects'

What's the right way to reference my function? I also tried just "objects", but that results in the same ModuleNotFoundError.

like image 500
Dave Avatar asked Sep 16 '25 15:09

Dave


1 Answers

From the docs I saw that the functions are imported directly, i.e.:

# tests/test_httptrigger.py
import unittest

import azure.functions as func
from __app__.HttpTrigger import my_function

Maybe you could try to reference your tests like this:

# tests/test_objects.py
import unittest

import azure.functions as func
from __app__.objects import main

+++ Update +++

Now I've tried to do it on my own and stumbled upon a similar error. After some googling, I've also found an open issue for this at github.com/Azure/azure-functions-python-worker.

+++ Update 2 +++

I've managed to get it running by adding an empty __init__.py file to the tests folder. Another thing to mention is, that I've adapted to the folder structure in the abovementioned docs and ran the following request in the root folder: pytest .

As a result, the test was executed successfully. Here's an example repository I've created: github.com/DSpirit/azure-functions-python-unit-testing

like image 102
DSpirit Avatar answered Sep 19 '25 07:09

DSpirit