-1

I have a Python3 project arranged as follows:

C:\automation\framework\constants.py

C:\automation\tests\unit-tests\test_myunittest.py

In my unit test, I'm trying to call methods in framework folder, which has the required init.py file At the start of my unit test, I have the following imports:

import pytest
from framework import constants

When I call pytest, it throws the following error:

ModuleNotFoundError: No module named 'framework'

How do I fix this?

5
  • How exactly are you calling pytest…? Commented Dec 11, 2024 at 14:56
  • I navigate to C:\automation\tests\unit-tests on a windows command prompt and just call pytest Commented Dec 11, 2024 at 15:26
  • So the working directory is tests\unit-tests. How is it to know that two directories up is where the framework is located? Either change the working directory, or set the PYTHONPATH environment variable. Commented Dec 11, 2024 at 15:28
  • The file shout be called __init__.py not init.py Commented Dec 11, 2024 at 16:07
  • @Cincinnatus Just a formatting problem here. Commented Dec 11, 2024 at 16:21

1 Answer 1

1

Most likely your directory (C:\automation\framework) is not on the python sys.path, so python cannot find the package framework.

You could test this by checking the python path:

from sys import path
for p in path:
    print(p)

To fix this you can add the path to framework manually by inserting it

sys.path.append("C:\automation\framework")

But this will only update sys.path for the current python session! So if you want to add framework permanently you could e.g. use a .pth-file in your python installation site-packages folder. Just create a new file like C:\PATH_TO_PYTHON\lib\site-packages\framework.pth with content:

C:\automation\framework

See more information on the python module search path here

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

2 Comments

Creating the .pth file and adding it to site-packages worked. I assume this would have to be done BEFORE python is fired up, via a .bat file or something?
Normally that's something you only do once at the beginning of your project. Maybe also consider using a virtual python environment (venv) for THAT project. Thats good practice to not get into requirement issues. Then you need to set the pth file inside your venv. You could also install framework as "editable" with pip. There are a lot of options to add a project (package) to the python sys.path ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.