简体   繁体   中英

Not able to import Python module

I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py

This is my testing code

"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200

But when i run it it shows:

Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'

What am I doing wrong here.

Python checks for the module only in the current path of the script, which in your case is /tests . You would need to add /project to your path as well. The following code snippet should work:

import sys
sys.path.append("../")

import server

First you have to set the add your project directory to the PYTHONPATH or put your project inside a directory that is already added. This lets python to use your package.

You can add the directory using set command on cmd . For example if you want to add C:\\Python use command set PYTHONPATH = C:\\Python

Now to import server.py you have to type import project.server or from project import server .

If you type import project.server , to use a function in server you will have to type in project.server.<fuction>() and if you used from project import server you will have to use server.<function>() .

The best solution would be to make your package installable, rather then fiddle with the PYTHONPATH. See guidelines to python packaging here: https://packaging.python.org/tutorials/packaging-projects/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM