2

I'm messing around with Azure Functions with Python and running into issues with getting a proper project directory structure. My goal is to have a library directory that I can put all the business logic in and then reference that from the functions entry point and also have a test directory that can test the functions and the library code directly. I have the following structure currently:

__app__
 | - MyFirstFunction
 | | - __init__.py
 | | - function.json
 | - library
 | | - __init__.py
 | | - services
 | | | - __init__.py
 | | | - sample_service.py
 | - host.json
 | - requirements.txt
 | - __init__.py
 | - tests
 | | - __init__.py
 | | - test_first_function.py

I ended up with this structure and am able to reference sample_service from the azure function using from __app__.library.services import sample_service and things seem to work, but I am unable to get the unit test to be able to properly reference the azure function. I have tried from ..HttpTrigger import main and from __app__.HttpTrigger import main in the test, but visual studio code is unable to discover the test when either of those imports statements are in place. I get the following errors respectively when I execute the test_first_function.py file directly: ImportError: attempted relative import with no known parent package and ModuleNotFoundError: No module named '__app__'

I'm far from an expert when it comes to Python modules and packages so any insight in how to fix these issues would be helpful. It would be good to get other ideas on how anyone else structures their Python azure functions projects

2
  • 1
    If your functions are in the same project folder, you could reference it directly with from functionname import modulename. i.sstatic.net/Y2BSB.png Commented Dec 12, 2019 at 8:41
  • AFAIK this now applies only to what is called the "v1" programming model. In the v2 programming model you would stuff several functions into one file and use decorators. learn.microsoft.com/en-us/azure/azure-functions/… Commented Jan 5, 2024 at 23:34

1 Answer 1

2

If you move your tests directory one level up, outside the __app__ directory, you should be able to, then, run the tests and import using from __app__.MyFirstFunction import myfunction

There is a discussion going on for improving the testing experience and the proper guidance (discussion) (work-item).

Meanwhile, the above suggestion should work fine. You could use this project (azure-functions branch) as a reference (linked by Brett Canon in the discussion tagged above).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.