我在Python包结构中存在一个问题。
以下是我在Mac OSX和Python 3.4中所做的事情:
1. mkdir MyProject
2. cd MyProject
3. virtualenv --python=python3.4 venv
4. . venv/bin/activate
5. pip install pytest pyscaffold
6. putup MyProject
然后,目录结构如下所示:
MyProject/
MyProject/
docs/
myproject/
tests/
requirements.txt
setup.py
.
.
venv/
我在apple.py
和myproject
test_apple.py
添加了tests
。
然后,结构将是这样的:
MyProject/
MyProject/
docs/
myproject/
apple.py
tests/
test_apple.py
requirements.txt
setup.py
.
.
venv/
apple.py
import sys
for path in sys.path:
print(path)
print("start apple")
def get_apple():
print("apple!!")
return 5
当我在apple.py
目录中输入python apple.py
来运行myproject
时,它会打印:
/Users/Chois/Desktop/MyProject/MyProject/myproject
/Users/Chois/Desktop/MyProject/venv/lib/python34.zip
/Users/Chois/Desktop/MyProject/venv/lib/python3.4
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/plat-darwin
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/lib-dynload
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/site-packages
start apple
如上所示,sys.path
包括/Users/Chois/Desktop/MyProject/MyProject/myproject
所以,我这样做test_apple.py
:
test_apple.py
import sys
for path in sys.path:
print(path)
from myproject.apple import get_apple
def test_apple():
assert 5 == get_apple()
当我通过输入py.test -s test_apple.py
来运行此代码时,
(-s
选项用于显示代码中print
语句的结果)
/Users/Chois/Desktop/MyProject/MyProject/tests
/Users/Chois/Desktop/MyProject/venv/lib/python34.zip
/Users/Chois/Desktop/MyProject/venv/lib/python3.4
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/plat-darwin
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/lib-dynload
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin
/Users/Chois/Desktop/MyProject/venv/lib/python3.4/site-packages
Traceback (most recent call last):
File "test_apple.py", line 5, in <module>
from myproject.apple import get_apple
ImportError: No module named 'myproject'
然而,当我通过键入python setup.py test
运行测试时,它运行时没有错误! !!
我想知道的是如何使用py.test -s test_xxxx.py
而不是python setup.py test
的所有测试模块来运行特定的测试模块。
需要你的帮助,谢谢。
答案 0 :(得分:0)
请阅读Good Integration Practices。
确保“mypkg”是可导入的,例如输入一次:
pip install -e . # install package using setup.py in editable mode