Lymedo
Lymedo

Reputation: 608

Azure Function ImportError while importing test module / ModuleNotFoundError: No module named

I'm writing some tests for a Python Azure function and I'm getting an import error in the test module.

ImportError while importing test module...

ModuleNotFoundError: No module named...

The error only occurs when the test module is located in the /tests directory. If I drop in to the root directory it runs fine.

Directory Structure:

Project
/.venv
/function/Orchestrator/__init__.py
/function/ActivityA/__init__.py
/function/ActivityB/__init__.py
/function/tests/test_activities.py

test_activities.py

import unittest
from unittest.mock import Mock, patch
import ActivityA

Error:

ImportError while importing test module 'C:\Users\...\function\tests\test_activities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\..\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
function\tests\test_activities.py:4: in <module>
    import A_WorkItemIds
E   ModuleNotFoundError: No module named 'ActivityA'

I've tried using relative paths to import the ActivityA module but get different errors.

Can someone tell me why the test module does not work from the /tests directory?

Is there an approach to get this to work?

I've reviewed similar questions but none of them have given me an answer.

Thanks

Upvotes: 1

Views: 1387

Answers (2)

Lymedo
Lymedo

Reputation: 608

Managed to resolve this with a couple of amendments.

In the tests module (test_activities.py), I changed the ActivityA import to:

from function import ActivityA

When running the test I used:

python -m pytest function/tests

Upvotes: 0

gold_cy
gold_cy

Reputation: 14226

It seems you are missing an __init__.py in your tests folder. I can not reproduce your error using a structure replicating your question. I set up a directory with the following structure:

functions/
├── ActivityA
│   └── __init__.py
└── tests
    ├── __init__.py
    └── test_foo.py

The contents of test_foo.py is the following:

import ActivityA

def test_fizz():
    assert 1 == 1

And when I run the tests I get:

==>pytest tests/
============================= test session starts ==============================
platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: ***/functions
collected 1 item                                                               

tests/test_foo.py .                                                      [100%]

============================== 1 passed in 0.02s ===============================

Upvotes: 3

Related Questions