2013-06-05 145 views
4

我無法導入我的模塊進行測試,以我想要的方式。我跑這一切在virtualenv中的2.7.2模塊導入錯誤在路徑上運行py.test與模塊

我有一個像

/api 
    /api 
     __init__.py 
     my_module.py 
    /tests 
     my_module_test.py 

的目錄結構我有我的PYTHONPATH設置爲/路徑/ API /。我到CD /路徑/ API和運行以下

py.test tests/my_module_test.py 

它不會在以下情況下工作:

  1. 時,我有在my_module_test.py頂部以下from api.my_module import my_function

它在下列情況下工作:

  1. 當我有以下在頂部of my_module_test.py from my_module import my_function

爲什麼我無法像導入情況1那樣導入模塊?

回答

14

我用PYTHONPATH作爲

PYTHONPATH=`pwd` py.test tests/my_module_test.py 
2

從py.text文件,你應該先安裝:

pip install -e . 
2

我創造了這個作爲一個回答你的問題和我自己的困惑。我希望它有幫助。在py.test命令行和tox.ini中都要注意PYTHONPATH

實例項目是here,並且也低於:

mymodule.py

import boto3 

def stuff(): 
    print "Yep!" 

tests/text_syntax_errors.py

import boto3 
import mymodule 


# Define a basic test that actually doesn't do much. 
# I just wanted more than zero tests 
def test_one_equals_one(): 
    assert 1 == 1 

tox.ini

[tox] 
skipsdist = True 
envlist = py27 

[flake8] 
max-line-length = 119 

[testenv] 
deps= -r{toxinidir}/requirements.txt 
commands=py.test 
setenv = 
    PYTHONPATH = {toxinidir} 

requirements.txt

boto3 
pytest 

從我README.md

如何,運行這些例子

我來測試我的代碼最初的動機是,我不得不拼錯在腳本導入模塊我正在寫作工作。

如果您編輯mymodule.py並從「boto3」中刪除b,您將看到下面的命令失敗。這是一件好事。同樣,如果您希望看到實際測試失敗,請簡單編輯tests/test_syntax_errors.py並將1 == 1更改爲1 == 0

py.test

mbp0 pytest_test[master+*] $ PYTHONPATH=. py.test 
========================== test session starts ========================== 
platform darwin -- Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1 
rootdir: /Users/jmacdonald/w/pytest_test, inifile: 
collected 1 items 

tests/test_syntax_errors.py . 

======================= 1 passed in 0.11 seconds ======================== 
mbp0 pytest_test[master+*] $ 

TOX

mbp0 pytest_test[master+*] $ tox 
py27 installed: boto3==1.3.1,botocore==1.4.37,docutils==0.12,futures==3.0.5,jmespath==0.9.0,py==1.4.31,pytest==2.9.2,python-dateutil==2.5.3,six==1.10.0 
py27 runtests: PYTHONHASHSEED='713732044' 
py27 runtests: commands[0] | py.test 
========================== test session starts ========================== 
platform darwin -- Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1 
rootdir: /Users/jmacdonald/w/pytest_test, inifile: 
collected 1 items 

tests/test_syntax_errors.py . 

======================= 1 passed in 0.11 seconds ======================== 
________________________________ summary ________________________________ 
    py27: commands succeeded 
    congratulations :) 
mbp0 pytest_test[master+*] $ 
+0

你不能在這裏發表您的代碼 – Damirchi

+0

這是我在計算器上的第一答案之一。你能詳細說明你的意思嗎?我的代碼是這個問題的具體答案。這只是一個太精心的文章區域張貼。 –

+0

@JeffMacDonald有一個特殊的代碼格式,你可以使用它! :) – gofr1