测试时,' python setup.py test'是在Python包中测试的唯一方法吗?

时间:2016-02-09 12:07:24

标签: python python-3.x tdd scaffolding

我在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.pymyproject 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所有测试模块来运行特定的测试模块。

需要你的帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

请阅读Good Integration Practices

  

确保“mypkg”是可导入的,例如输入一次:

     

pip install -e . # install package using setup.py in editable mode