Py.test cannot import my module

I am trying to get the right to import python. I want to reach a module with several source files and a test folder with unit tests.

No matter what I do, I cannot get py.test-3 to execute my tests. My directory looks like this:

. ├── module │  ├── __init__.py │  └── testclass.py └── tests └── test_testclass.py 

The __init__.py file looks like this:

 __all__ = ['testclass'] 

The testclass.py file looks like this:

 class TestClass(object): def __init__(self): self.id = 1 

And my unit test is like this:

 import pytest from module import TestClass def test_test_class(): tc = TestClass() assert(tc.id==1) 

No matter what I call py.test-3, I get:

 E ImportError: No module named 'module' 
+5
source share
2 answers

First, if you do not change tests/test_testclass.py , you need to change module/__init__.py as follows:

 from .testclass import TestClass __all__ = ['TestClass'] 

And when you run py.test, set the environment variable PYTHONPATH so that the interpreter knows when to find the modules:

 PYTHONPATH=. py.test 
+7
source

I would put the header of the test file to execute the path for pytest:

Example:

 import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) 

With this, I could know the path of any subfolder in my (test) project

+1
source

Source: https://habr.com/ru/post/1237381/


All Articles