お世話になります。
Pythonのテストツールであるpytestを実行時のディレクトリ構成に関する質問です。よろしくお願いします。
環境
Python 3.6.7
Ubuntu 16.04
内容
pytestを用いる際のtypicalなディレクトリ構成を説明において、ほぼ間違いなく__init__.py
が入っています。
同ファイルがあると、パッケージとして認識されるから云々は、文言上は存じております。
(ただ、普段Pythonは本業の解析ツールとして使っているため、実際には気にしたことがありません)
https://docs.pytest.org/en/latest/goodpractices.html#choosing-a-test-layout-import-rules
自分で実際に以下の構成で、python -m pytest
を実行すると
__init__.py
が無くても、問題なくテスト可能です。
具体的な質問は以下になります。
- pytestと
__init__.py
は関係あるのでしょうか? - 説明サイトによって、
__init__.py
がmypkgの下だけにある場合、testsの下だけにある場合、両方にある場合があります。どれが正しいのでしょうか。 - 下記の例では
test_pkg.py
でfrom mypkg.pkg import Hoge
としていますが、これより適切なインポートの仕方はありますか?ベストプラクティスを知りたいです。(また、__init__.py
はimportの書き方で必要不要が変わってくるのかな?と思ったりもしましたが、分かりませんでした)
よろしくお願い致します。
sh
1. 2├── mypkg 3│ └── pkg.py 4└── tests 5 └── test_pkg.py
python
1# pkg.py 2class Hoge: 3 def say(self): 4 return 'hello'
python
1# test_pkg.py 2from mypkg.pkg import Hoge 3 4def test_hoge(): 5 h = Hoge() 6 assert h.say() == 'hello'
sh
1python -m pytest 2============================= test session starts ============================== 3platform linux -- Python 3.6.7, pytest-4.4.1, py-1.8.0, pluggy-0.9.0 4rootdir: /home/***secret***/test_sample 5collected 1 item 6 7tests/test_pkg.py . [100%] 8 9=========================== 1 passed in 0.02 seconds ===========================

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。