Mark J
Mark J

Reputation: 3

Unit testing Python Firebase Cloud Functions in Flutter and VS Code - can't get the modules to import

I have a Flutter project that has Firebase enabled with cloud_functions. It has created a functions directory in the root of the Flutter project.

Project Structure

my-app/
├─ lib/
├─ ios/
├─ functions/ (This is the cloud functions folder)
│  ├─ cloud_functions/
│  ├─ common/
│  │  ├─ models/
│  │  ├─ services/
│  │  ├─ ... other python files
│  ├─ tests/
│  │  ├─ ... pytest tests
│  ├─ main.py
│  ├─ requirements.txt
├─ ... other flutter folders

The cloud functions work fine in the Firebase Emulator with triggers working from Firestore events as expected. I have written some tests using Pytest which don't work. The issue I have is that can't import the modules.

In the cloud functions in a service for example I import a model with:

from cloud_functions.common.models.app_user import AppUser

This works fine in the emulator as the base directory is functions. However, my python interpreter in vsCode is set to the root directory of the whole project so to get the tests to import modules successfully I need to import as follows:

from functions.cloud_functions.common.models.app_user import AppUser

So basically I can either have the Firebase Emulator working or by changing all of the imports I can get the tests to run and pass.

Is there a way to force vsCode to use the functions directory as the root directory and have all modules defined from there? i.e. cloud_functions.common.models..... rather than functions.cloud_functions.common.models.....?

Upvotes: 0

Views: 34

Answers (1)

htrehrthtr
htrehrthtr

Reputation: 98

Try updating the PythonPath, so that the modules are imported relative to that specific folder.

Add the following to your .env file in your project's root

PYTHONPATH=functions

then you can update your vs code's settings.json as follows:

{
  "python.envFile": "${workspaceFolder}/.env"
}

then you can import as the following with out any issues

from cloud_functions.common.models.app_user import AppUser

Upvotes: 0

Related Questions