Python 在运行测试时导入 src 模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4761041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:23:22  来源:igfitidea点击:

Python import src modules when running tests

pythonunit-testingimport

提问by Karan

My source files are located under src and my test files are located under tests. When I want to run a test file, say python myTest.py, I get an import error: "No module named ASourceModule.py".

我的源文件位于 src 下,我的测试文件位于测试下。当我想运行一个测试文件时,比如 python myTest.py,我收到一个导入错误:“没有名为 ASourceModule.py 的模块”。

How do I import all the modules from source needed to run my tests?

如何从源代码中导入运行测试所需的所有模块?

采纳答案by Thomas

You need to add that directory to the path:

您需要将该目录添加到路径中:

import sys
sys.path.append('../src')

Maybe put this into a module if you are using it a lot.

如果你经常使用它,也许可以把它放到一个模块中。

回答by Barry Wark

The best (most manageable) solution appears to be using a virtualenv and setuptools/distribute to install andebelopment copy of your (src) package. That way your tests execute against a fully "installed" system.

最好的(最易于管理的)解决方案似乎是使用 virtualenv 和 setuptools/distribute 来安装您的 (src) 包的和ebelopment 副本。这样,您的测试将针对完全“安装”的系统执行。

回答by Anderson Vieira

If you don't want to add the source path to each test file or change your PYTHONPATH, you can use noseto run the tests.

如果你不希望到源路径添加到每个测试文件或者改变你的PYTHONPATH,你可以用鼻子来运行测试。

Suppose your directory structure is like this:

假设你的目录结构是这样的:

project
    package
        __init__.py
        module.py
    tests
        __init__.py
        test_module.py

You should import the module normally in the test_module.py(e.g. from package import module). Then run the tests by running nosetestsin the project folder. You can also run specific tests by doing nosetests tests/test_module.py.

您应该在test_module.py(例如from package import module)中正常导入模块。然后通过nosetests在项目文件夹中运行来运行测试。您还可以通过执行nosetests tests/test_module.py.

The __init__.pyin the testsdirectory is necessary if you want to run the tests from inside it.

__init__.pytests,如果你想运行从它里面的测试目录是必要的。

You can install nose easily with easy_installor pip:

您可以使用easy_install或轻松安装鼻子pip

easy_install nose

or

或者

pip install nose

nose extends unittest in a lot more ways, to learn more about it you can check their website: https://nose.readthedocs.org/en/latest/

鼻子以更多方式扩展单元测试,要了解更多信息,您可以查看他们的网站:https: //nose.readthedocs.org/en/latest/

回答by Frank Bryce

On my system (Windows 10), I was required to do something like this:

在我的系统(Windows 10)上,我需要做这样的事情:

import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../src")

Appending the relative directory directly to sys.pathdid not work

直接追加相对目录sys.path不起作用