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
  ModuleNotFoundError only if script is launched by cron Charles33 8 5,078 Jan-12-2024, 12:55 AM
Last Post: caicaifan
  Pytest Installed, but VS Code Won’t Access Pytest AstralWeeks 9 2,873 Sep-13-2023, 03:00 PM
Last Post: AstralWeeks
  Pytest mocks anthonyrmoss78 0 426 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 2,543 Mar-11-2022, 01:50 PM
Last Post: snippsat
  Imports in my first package cuppajoeman 1 1,912 Jun-28-2021, 09:06 AM
Last Post: snippsat
  Help wanted with python imports petros21 3 2,478 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 3,764 Mar-17-2021, 11:57 AM
Last Post: cff
  “NameError” “is not defined” script that I know works on other computers iamwithstupid 0 2,472 Nov-24-2020, 04:23 PM
Last Post: iamwithstupid
  threading across imports Nickd12 2 2,101 Nov-09-2020, 01:59 AM
Last Post: Nickd12
  refreshing imports seandepagnier 4 2,672 Sep-20-2020, 11:51 PM
Last Post: seandepagnier

Forum Jump:

User Panel Messages

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