Python Forum
script with imports works but pytest gives "ModuleNotFoundError"?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
script with imports works but pytest gives "ModuleNotFoundError"?
#1
I'm trying to setup my first python project with pytest but I'm having trouble executing my tests. The module itself seems to be working as intended and I can't figure it out. I've created a minimal example as follows (using python 3.9):

mkdir /tmp/my_test
cd /tmp/my_test
python -m venv venv
. venv/bin/activate
pip install pytest
Creating the following structure:

my_test
|- venv
|- src
| |- a
| | |- __init__.py
| | |- a.py
| | |- b.py
|- tests
| |- testing_a
| | |- test_a.py
Where src/a/a.py is executable and contains:

#!/usr/bin/env python3

import b

def foo():
  print("A")
  b.bar()

if __name__ == "__main__":
  foo()
And src/a/b.py is a simple module containing:

def bar():
  print("B")
And finally tests/testing_a/test_a.py contains:

from a import a, b


def test_a():
  a.foo()


def test_b():
  b.bar()
Running src/a/a.py produces the expected output:

A
B
But running pytest -v throws ModuleNotFoundError: No module named 'a'. Same if I try to run as python -m pytest -v.

Why is this? How come the imports doesn't work the same way when running the script directly compared to running pytest?

I'm sure I'm missing something about how python imports work and I'm sure it would be obvious with a nudge in the right direction :/
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Best programming practice for imports Curbie 8 1,680 Oct-16-2024, 02:20 AM
Last Post: Curbie
  Sudden Extremely Slow / Failed Python Imports bmccollum 1 1,172 Aug-20-2024, 02:09 PM
Last Post: DeaD_EyE
  ModuleNotFoundError only if script is launched by cron Charles33 8 7,749 Jan-12-2024, 12:55 AM
Last Post: caicaifan
  Pytest Installed, but VS Code Won’t Access Pytest AstralWeeks 9 16,089 Sep-13-2023, 03:00 PM
Last Post: AstralWeeks
  Pytest mocks anthonyrmoss78 0 950 May-30-2023, 08:28 PM
Last Post: anthonyrmoss78
  Imports that work with Python 3.8 fail with 3.9 and 3.10 4slam 1 3,502 Mar-11-2022, 01:50 PM
Last Post: snippsat
  Imports in my first package cuppajoeman 1 2,506 Jun-28-2021, 09:06 AM
Last Post: snippsat
  Help wanted with python imports petros21 3 3,550 Apr-07-2021, 07:16 PM
Last Post: snippsat
Question How to include Modules not found (conditional imports) in my setup.py when I want to cff 0 4,832 Mar-17-2021, 11:57 AM
Last Post: cff
  “NameError” “is not defined” script that I know works on other computers iamwithstupid 0 3,465 Nov-24-2020, 04:23 PM
Last Post: iamwithstupid

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020