path error when running Pytest tests from cmd

Question:

I have this issue with Pytest where unit tests run fine from PyCharm but doesn’t when I run through pipeline "python -m pytest".

Below is my project structure:

Common
   |_____configuration.py
   |
Services
   |
   |-----ServiceA
   |        |
   |        |___src
   |        |    |___utils
   |        |           |__ __init__.py
   |        |           |__   helper1.py
            |           |__   helper2.py  
   |        |___Test
   |              |___utils
   |                     |__  __init.py
   |                     |__    test1.py
   |                     
   |-----ServiceB
   |
   |

In helper1 I have code as

 from Common import configuration

Tests runs absolutely fine when I run through Pycharm because it resolves all path but when I run it through pipeline, I get below error when running through cmd,

ModuleNotFoundError: No module named 'Common'

Can anyone help how to resolve this issue. TIA

Asked By: Pijush

||

Answers:

Added path to the common in test init.py and resolved the issue

sys.path.append(‘….Common’)

Answered By: Pijush

In pytest >= 7.0.0 you can register extra path using Pytest’s pythonpath config option. The path value should be relative to the rootdir. So it might be Common or ../Common or even prefixed with more parent levels.

If you use pyproject.toml:

[tool.pytest.ini_options]
pythonpath = ["Common"]

If you use pytest.ini instead:

[pytest]
pythonpath = Common
Answered By: tmt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.