![](/img/trans.png)
[英]How to get pytest to register_assert_rewrites for all modules under tests/ directory?
[英]pytest can't find helper modules located under the tests directory
當使用PyCharm啟動我的測試時,我根本沒有導入問題,但如果我在終端pytest中做了抱怨無法找到的模塊。 准確地說,那些正在tests/tools
。
項目文件夾結構:
src/
app/
tests/
end_to_end/ # End to end/Acceptance tests
tools/ # Helper modules used by some tests
unit # Unit tests
setup.py
setup.py
相關部分:
setup(...
packages=find_packages('src'),
package_dir={'': 'src'},
install_requires=['requests'],
test_suite='tests',
tests_require=[
'flexmock',
'pytest',
'wsgi_intercept'
])
導入執行py.test tests/end_to_end
時失敗的行,無論virtualenv是否處於活動狀態。 從app
包導入的模塊很好:
from tests.tools.foomodule import Foo # Fails
from app.barmodule import Bar # Doesn't fail
我必須使用pip install -e packagename
安裝我的軟件包,以便在從命令行運行測試時可用於pytest。 我想我必須在我的setup.py
添加tools
文件夾作為一個包,但這對我來說很難看,因為這些模塊只是用於幫助測試過程而不是分發。
另一方面,我可以根據pytest網站的集成建議,使用python setup.py test
啟動我的測試。
可能你的tests
和/或tests/tools
目錄中沒有__init__.py
。 如果錯過python確實將它們視為包而無法導入它們。 您可以:
__init__.py
(BAD見這里 conftest.py
中將測試/工具添加到PYTHONPATH並導入文件(從import tests.tools.MODULE
import MODULE
) 為了能夠導入駐留在src
文件夾之外的模塊,我去了PyCharm中的“Project settings”,在“Project structure”中我將tests/end_to_end
和tests/unit
標記為源文件夾 。
我也改變了主意,決定將我的助手模塊放在這些文件夾中。 這樣我就可以直接導入它們,我的測試也可以在終端中正常運行,因為當前的工作目錄總是被添加到PYTHONPATH
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.