0

I have a project named unit_testing with 2 subfolders named src/ and tests/. In src there is a file called my_functions.py and in tests I have a file called test_my_functions.py.

This is the code in my_functions.py

def adding_pos(a, b, c):
if a < 0 or b < 0 or c < 0:
    output = f'function needs positive numbers'
else:
    output = a + b + c
return output

This is the code in test_my_functions.py

# import libs

import pytest
from src.my_functions import adding_pos


# %% test

class TestAddingPos(object):
    def test_adding(self):
        assert adding_pos(2, 5, 6) == 13

    def test_adding_neg(self):
        assert adding_pos(-1, 2, 3) == 'function needs positive numbers'

In the CLI, if I go to the test folder and then run pytest, I keep getting a ModuleNotfoundError saying the src module can not be found. I don' understand why because in test_my_functions.py I import functions from src.my_functions and this works.

Why does this not work?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
HH_macro
  • 23
  • 4
  • What happens if you run `pytest` from the outermost folder, not from the tests folder? Instead of going inside tests and doing `pytest test_my_functions.py` (which I assume you are doing), how about doing `pytest tests`? – Gino Mempin Jul 16 '23 at 11:11
  • Does this answer your question? [PATH issue with pytest 'ImportError: No module named ...'](https://stackoverflow.com/q/10253826/2745495) – Gino Mempin Jul 16 '23 at 11:15
  • If I go to the root director unit_testing and run from the CLI $pytest tests I still get the error: – HH_macro Jul 16 '23 at 11:16
  • ___________________________________________________________________ ImportError while importing test module 'C:\Users\Hans\Documents\Python\education\unit_testing\tests\test_my_functions.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ..\..\..\..\anaconda3\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests\test_my_functions.py:4: in from src.my_functions import adding_pos E ModuleNotFoundError: No module named 'src' – HH_macro Jul 16 '23 at 11:17
  • Does this answer your question? [No module name error for a module which I created](https://stackoverflow.com/questions/76661222/no-module-name-error-for-a-module-which-i-created). Check [my answer](https://stackoverflow.com/a/76677272/20307768) – Constantin Hong Jul 16 '23 at 11:24
  • Hi, If I add an empty init file to both src and tests and run $pytest in tests it works! however, this makes it a package. I do not want that. So is there any way around this without the init files? – HH_macro Jul 16 '23 at 11:34
  • I don't think so. You didn't make any package unless you did `$python -m build`or `$python setup.py sdist bdist_wheel` and so on. `So is there any way around this without the init files?` is another question that you need to write. – Constantin Hong Jul 16 '23 at 11:38

0 Answers0