Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

py.test can't import my module

I am struggeling getting a python import right. What I want to achieve is to have a module with several source files and a test folder with unit tests.

No matter what I do, I can't get py.test-3 to execute my tests. My directory layout 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 like this:

import pytest
from module import TestClass

def test_test_class():
    tc = TestClass()
    assert(tc.id==1)

No matter how I call py.test-3 I will end up with a:

E   ImportError: No module named 'module'
like image 781
Fabian Avatar asked Dec 04 '15 07:12

Fabian


People also ask

Why can I not import a module in Python?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

What is the __ init __ py module?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

Can you manually import a module in Python?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


1 Answers

First, unless you change the tests/test_testclass.py, you need to change module/__init__.py as follow:

from .testclass import TestClass

__all__ = ['TestClass']

And, when you run py.test set PYTHONPATH environment variable to let the interpreter know when to find modules:

PYTHONPATH=. py.test
like image 177
falsetru Avatar answered Oct 19 '22 03:10

falsetru