我正在使用Python编写一个包.我用virtualenv.我在virtualenv的.pth路径中设置了模块根目录的路径,这样我就可以在开发代码的同时导入包的模块并进行测试(问题1:这是一个好方法吗?).这工作正常(这是一个例子,这是我想要的行为):
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rc import ns
>>> exit()
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python tests/test_ns.py
issued command: echo hello
command output: hello
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使用PyTest,我会收到一些导入错误消息:
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ pytest
=========================================== test session starts ============================================
platform linux2 -- Python 2.7.12, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /home/zz/Desktop/GitFolders/rc, inifile:
collected 0 items / 1 errors
================================================== ERRORS ==================================================
________________________________ ERROR collecting tests/test_ns.py ________________________________
ImportError while importing …Run Code Online (Sandbox Code Playgroud) 我无法从pytest函数导入模块。我知道有100万个问题,但是我已经读了一堆,但仍然难以理解。
$ tree
.
??? code
??? eight_puzzle.py
??? missionaries_and_cannibals.py
??? node.py
??? search.py
??? test
??? test_eight_puzzle.py
??? test_search.py
2 directories, 6 files
$
$ grep import code/test/test_search.py
import sys
import pytest
import code.search
$
$ pytest
...
ImportError while importing test module '~/Documents/code/test/test_search.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
code/test/test_search.py:14: in <module>
import code.search
E ModuleNotFoundError: No module named 'code.search'; 'code' is not a package
...
Run Code Online (Sandbox Code Playgroud)
我希望那能奏效。“代码”是一个包,对吗?Python 3中的软件包是其中包含.py文件的任何目录。
我也尝试了相对导入-- from .. import search …
我想使用 pytest 对另一个名为src. 这是我的目录结构:
src
__init__.py
script1.py
script2.py
test
test_fun.py
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试通过命令行在文件夹中运行pytest时test,看到以下错误
from script2 import fun2
E ModuleNotFoundError: No module named 'script2'
在每个脚本中,我有以下内容
脚本2.py:
def fun2():
return('result_from_2')
Run Code Online (Sandbox Code Playgroud)
脚本1.py:
from script2 import fun2
def fun1():
return(fun2()+'_plus_something')
Run Code Online (Sandbox Code Playgroud)
test_fun.py :
import sys
sys.path.append('../')
from src.script1 import fun1
def test_fun1():
output1 = fun1()
# check output
assert output1=='result_from_2_plus_something'
Run Code Online (Sandbox Code Playgroud)
如何使用上面提供的目录运行 pytest?