pytestを使用したPythonテスト。 プラグイン第5章

戻る 次へ







すぐに使える強力なpytestは、プラグインのミックスを追加するとさらに良くなります。 pytestコードベースは設定と拡張機能で構成されており、プラグインを介して変更および改善できるフックがあります。













この本の例は、Python 3.6とpytest 3.2を使用して書かれています。 pytest 3.2は、Python 2.6、2.7、およびPython 3.3+をサポートしています。







Tasksプロジェクトのソースコードと、この本に示されているすべてのテストのソースコードは、 pragprog.comにある本のWebページのリンクから入手できます。 テストコードを理解するためにソースコードをダウンロードする必要はありません。 テストコードは、例では便利な形式で示されています。 ただし、プロジェクトのタスクを実行したり、テストサンプルを調整して自分のプロジェクトをテストしたりするには(手を縛っていない!)、書籍のWebページにアクセスして作品をダウンロードする必要があります。 書籍のWebページには、 正誤表のメッセージへのリンクとディスカッションフォーラムがあります。

ネタバレの下には、このシリーズの記事のリストがあります。









さらに進めましょう!



この本の前の章で作業した場合、すでにいくつかのプラグインを作成していることに驚くかもしれません。 プロジェクトのトップレベルのconftest.py



ファイルにフィクスチャやフック関数を配置するconftest.py



、ローカルのconftest



プラグインを作成します。 これらのconftest.py



ファイルを、プロジェクト間、他の人、または世界と共有できるインストール可能なプラグインに変換するのはほんの少しの追加作業です。







この章は、サードパーティのプラグインを探す場所の質問に答えることから始めます。 かなりの数のプラグインが利用可能であるため、誰かがpytest



行いたい変更をすでに書いている可能性がかなりあります。 私たちはオープンソースのプラグインを検討するので、プラグインがほぼあなたがやりたいことをしているが、そうでない場合は、プラグインを開発するか、参照として使用して独自のプラグインを作成できます。 この章は独自のプラグインの作成に関するものですが、付録3、 Sampler Packプラグイン(163ページ)が含まれており、可能なことの概要を説明しています。







この章では、プラグインの作成方法を学び、テスト、パッケージング、配布の正しい方向を示します。 Pythonのパッケージと配布に関する完全なトピックは広範であり、独自の本であると主張しているため、すべてを網羅するわけではありません。 しかし、あなたはあなたのチームとプラグインを交換することができるのに十分な情報を得ます。 また、PyPIサポートと最小限の作業でプラグインを作成するいくつかの簡単な方法についても説明します。







検索プラグイン



サードパーティのpytestプラグインはいくつかの場所にあります。 付録3、プラグインサンプラパック(163ページ)にリストされているプラ​​グインは、PyPIからダウンロードできます。 ただし、これが素晴らしいpytestプラグインを見つける唯一の場所ではありません。







https://docs.pytest.org/en/latest/plugins.html







メインのpytestドキュメントサイトには、pytestプラグインのインストールと使用について説明し、いくつかの一般的なプラグインをリストしたページがあります。







https://pypi.python.org







Python Package Index(PyPI)は、多くのPythonパッケージを入手するのに最適な場所ですが、pytestプラグインを検索するのにも最適です。 ほとんどのpytestプラグインは「pytest-」で始まるか「-pytest」で終わるため、pytestプラグインを検索するときは、検索フィールドに「pytest」、「pytest-」または「-pytest」と入力します。







https://github.com/pytest-dev







GitHubのpytest-devグループには、pytestのソースコードが保存されています。 さらに、ここでは、pytestカーネルチームが長期的にサポートする必要がある人気のあるpytestプラグインを見つけることができます。







プラグインのインストール



Pytestプラグインは、他のPythonパッケージと同様に、pipとともにインストールされます。 しかし

プラグインをインストールするには、いくつかの方法でpipを使用できます。







PyPIからインストールする



PyPIはpipのデフォルトの場所であるため、PyPIからプラグインをインストールするのが最も簡単な方法です。 pytest-cov



プラグインをインストールしましょう。







 $ pip install pytest-cov
      
      





PyPIの最新の安定バージョンがインストールされます。







PyPIから特定のバージョンをインストールする



プラグインの特定のバージョンが必要な場合は、 ==



後にバージョンを指定できます。







 $ pip install pytest-cov==2.4.0
      
      





.tar.gzまたは.whlファイルからインストールする



PyPIパッケージは、拡張子が.tar.gz



または.whl



zipファイルとして配布されます。 彼らはしばしば「タールボール」と「ホイール」と呼ばれます。 PyPIを直接操作しようとすると問題が発生する場合(ファイアウォールやその他のネットワークの複雑な.whl



で発生する可能性があります) .whl



または.whl



をダウンロードして、 .whl



からインストールできます。







タンバリンで開梱したりダンスしたりする必要はありません。 ピップを向けるだけです:







 $ pip install pytest-cov-2.4.0.tar.gz # or $ pip install pytest_cov-2.4.0-py2.py3-none-any.whl
      
      





ローカルディレクトリからのインストール



.tar.gz



または.whl



ローカルまたは共有ディレクトリにプラグイン(および他のPythonパッケージ)用のプラグインを用意し、PyPIの代わりにこれを使用してプラグインをインストールできます。







 $ mkdir some_plugins $ cp pytest_cov-2.4.0-py2.py3-none-any.whl some_plugins/ $ pip install --no-index --find-links=./some_plugins/ pytest-cov
      
      





--no-index



は、PipにPyPIに接続しないように指示します。 --find-links=./some_plugins/



は、pipにsome_plugins



ディレクトリを調べるように指示します。 この方法は、サードパーティとネイティブの両方のプラグインがローカルに保存されている場合、および継続的統合またはtoxを使用して新しい仮想環境を作成している場合に特に便利です。 (Toxと継続的インテグレーションの両方については、第7章でpytestを他のツールと使用して、125ページで説明します。)







ローカルディレクトリのインストール方法を使用すると、==とバージョン番号を追加して、複数のバージョンをインストールし、必要なバージョンを指定できることに注意してください。







 $ pip install --no-index --find-links=./some_plugins/ pytest-cov==2.4.0
      
      





Gitリポジトリからインストールする



この場合はGitHubのGitリポジトリからプラグインを直接インストールできます。







 $ pip install git+https://github.com/pytest-dev/pytest-cov
      
      





バージョンタグを指定することもできます。







 $ pip install git+https://github.com/pytest-dev/pytest-cov@v2.4.0
      
      





または、ブランチを指定できます:







 $ pip install git+https://github.com/pytest-dev/pytest-cov@master
      
      





Gitリポジトリからのインストールは、Gitに独自の作業を保存している場合、またはプラグインまたはプラグインの必要なバージョンがPyPIにない場合に特に便利です。







翻訳者注:



pipはGit、Mercurial、Subversion、およびBazaarからのインストールをサポートし、URLプレフィックスを使用してVCSタイプを定義します:「git +」、「hg +」、「svn +」、「bzr +」。

詳細については、 PyPIのドキュメントを参照してください。


独自のプラグインを書く



多くのサードパーティプラグインには、非常に多くのコードが含まれています。 これは、これらすべてを自分で開発する時間を節約するために使用する理由の1つです。 ただし、特定のコードについては、テストに役立つ特別なフィクスチャと修正を間違いなく思い付きます。 プラグインを作成することにより、複数のプロジェクト間で共有したい複数のフィクスチャを簡単に共有できます。 独自のプラグインを開発および配布することにより、これらの変更をいくつかのプロジェクト(場合によっては他の地域)と共有できます。 これは非常に簡単です。 このセクションでは、pytestの動作の小さな変更を開発し、プラグインとしてパックし、テストして、配布方法を検討します。







プラグインには、pytestの動作を変更するフック関数を含めることができます。 pytestはプラグインがpytestの動作をわずかに変更できるように設計されているため、多くのフック関数が利用可能です。 pytestのフックは、pytestドキュメントサイトにリストされています 。 この例では、テストステータスの外観を変更するプラグインを作成します。 コマンドラインパラメーターを追加して、この新しい動作を有効にします。 出力ヘッダーにテキストを追加します。 特に、すべてのFAILEDステータスインジケータ(失敗)を「改善のためにOPPORTUNITY(見込み)」に変更し、FをOに変更し、「テストを実行していただきありがとうございます」をヘッダーに追加します。 これを行うには、 --nice



オプションを使用します。







動作の変更をプラグインのメカニズムの説明とは別にするために、conftest.pyを再配布可能なプラグインに変える前に変更を加えます。 この方法でプラグインを実行する必要はありません。 しかし、多くの場合、1つのプロジェクトでのみ使用することを意図した変更は、共有してプラグインに変換するのに十分に役立ちます。 したがって、conftest.pyファイルに機能を追加することから始め、conftest.pyですべてが機能した後、コードをパッケージに移動します。







タスクプロジェクトに戻ります。 30ページの「例外の待機」セクションでは、誰かがAPI関数を誤って呼び出した場合に例外がスローされるかどうかを確認するいくつかのテストを作成しました。 少なくともいくつかの考えられるエラー状態を見逃したようです。







さらにいくつかのテストを示します。







ch5 / a / tasks_proj / tests / func / test_api_exceptions.py


 """     API wrong.""" import pytest import tasks from tasks import Task @pytest.mark.usefixtures('tasks_db') class TestAdd(): """,   tasks.add().""" def test_missing_summary(self): """  ,  summary missing.""" with pytest.raises(ValueError): tasks.add(Task(owner='bob')) def test_done_not_bool(self): """  ,  done   bool.""" with pytest.raises(ValueError): tasks.add(Task(summary='summary', done='True'))
      
      





それらを実行して、合格するかどうかを確認しましょう。







 $ cd /path/to/code/ch5/a/tasks_proj $ pytest ===================== test session starts ====================== collected 57 items tests/func/test_add.py ... tests/func/test_add_variety.py ............................ tests/func/test_add_variety2.py ............ tests/func/test_api_exceptions.py .F....... tests/func/test_unique_id.py . tests/unit/test_task.py .... =========================== FAILURES =========================== __________________ TestAdd.test_done_not_bool __________________ self = <func.test_api_exceptions.TestAdd object at 0x103a71a20> def test_done_not_bool(self): """Should raise an exception if done is not a bool.""" with pytest.raises(ValueError): > tasks.add(Task(summary='summary', done='True')) E Failed: DID NOT RAISE <class 'ValueError'> tests/func/test_api_exceptions.py:20: Failed ============= 1 failed, 56 passed in 0.28 seconds ==============
      
      





詳細については、 -v



で再度実行してみましょう。 トレースはすでに表示されているので、-- --tb=no



押して--tb=no



オフにできます。







-k TestAdd



を使用した新しいテストに焦点を当てましょう。これは、「TestAdd」を含む名前のテストが他にないため機能します。







「すべてを落として」このテストの修正を試みることもできます(そして、後でテストを行います)が、今度は開発者にとって失敗をより快適にすることに焦点を当てます。







まず、ヘッダーに「ありがとう」というメッセージを追加します。これは、 pytest_report_header()



というpytest_report_header()



フックを使用して実行できます。







ch5 / b / tasks_proj / tests / conftest.py


 def pytest_report_header(): """    .""" return "Thanks for running the tests."
      
      





お礼のメモを入力するのは明らかに愚かです。 ただし、ヘッダーに情報を追加する機能は拡張できます。 ユーザー名を追加し、使用する機器とテストするバージョンを指定できます。 一般に、文字列に変換できるものはすべてテストのタイトルに挿入できます。







次に、テストステータスレポートを変更して、 F



O



FAILED



OPPORTUNITY for improvement



ます。 このことを可能にするフックがあります: pytest_report_teststatus()









ch5 / b / tasks_proj / tests / conftest.py


 def pytest_report_teststatus(report): """   .""" if report.when == 'call' and report.failed: return (report.outcome, 'O', 'OPPORTUNITY for improvement')
      
      





そして今、私たちは探していたソリューションを手に入れました。 --verbose



フラグを使用しないテストセッションでは、失敗に対してO



が表示されます。つまり、改善が可能です。







 $ cd /path/to/code/ch5/b/tasks_proj/tests/func $ pytest --tb=no test_api_exceptions.py -k TestAdd ===================== test session starts ====================== Thanks for running the tests. collected 9 items test_api_exceptions.py .O ====================== 7 tests deselected ====================== ======= 1 failed, 1 passed, 7 deselected in 0.06 seconds =======
      
      





-v



または--verbose



フラグを使用した方が良いでしょう:







 $ pytest -v --tb=no test_api_exceptions.py -k TestAdd ===================== test session starts ====================== Thanks for running the tests. collected 9 items test_api_exceptions.py::TestAdd::test_missing_summary PASSED test_api_exceptions.py::TestAdd::test_done_not_bool OPPORTUNITY for improvement ====================== 7 tests deselected ====================== ======= 1 failed, 1 passed, 7 deselected in 0.07 seconds =======
      
      





最後に行う変更は、コマンドラインパラメーター--nice,



を追加することです--nice,



これにより、ステータスの変更は、-- --nice



を置き換えた場合にのみ発生します。







 def pytest_addoption(parser): """ nice    --nice.""" group = parser.getgroup('nice') group.addoption("--nice", action="store_true", help="nice: turn failures into opportunities") def pytest_report_header(): """    .""" if pytest.config.getoption('nice'): return "Thanks for running the tests." def pytest_report_teststatus(report): """   .""" if report.when == 'call': if report.failed and pytest.config.getoption('nice'): return (report.outcome, 'O', 'OPPORTUNITY for improvement')
      
      





このプラグインでは、いくつかのフックしか使用しないことに注意してください。 メインのPytestドキュメントサイトには、他にも多数のサイトがあります。







これで、例でプラグインを実行するだけで、プラグインを手動でテストできます。 最初に、 --nice



オプションを使用せずに、ユーザー名のみが表示されるようにします。







 $ cd /path/to/code/ch5/c/tasks_proj/tests/func $ pytest --tb=no test_api_exceptions.py -k TestAdd ===================== test session starts ====================== collected 9 items test_api_exceptions.py .F ====================== 7 tests deselected ====================== ======= 1 failed, 1 passed, 7 deselected in 0.07 seconds =======
      
      





--nice









 $ pytest --nice --tb=no test_api_exceptions.py -k TestAdd ===================== test session starts ====================== Thanks for running the tests. collected 9 items test_api_exceptions.py .O ====================== 7 tests deselected ====================== ======= 1 failed, 1 passed, 7 deselected in 0.07 seconds =======
      
      





--nice



--verbose









 $ pytest -v --nice --tb=no test_api_exceptions.py -k TestAdd ===================== test session starts ====================== Thanks for running the tests. collected 9 items test_api_exceptions.py::TestAdd::test_missing_summary PASSED test_api_exceptions.py::TestAdd::test_done_not_bool OPPORTUNITY for improvement ====================== 7 tests deselected ====================== ======= 1 failed, 1 passed, 7 deselected in 0.06 seconds =======
      
      





いいね! conftest.py



ファイルの約10行のコードで、 conftest.py



変更をすべて行いました。 次に、このコードをプラグイン構造に移動します。







インストール可能なプラグインを作成する



プラグインを他のユーザーと共有するプロセスは明確に定義されています。 独自のプラグインをPyPIに含めない場合でも、このプロセスを実行すると、オープンソースプラグインからコードを読みやすくなり、それらが役立つかどうかを評価する機会が増えます。







このトピックは他の場所で十分に文書化されているため、この本でPythonパッケージのパッケージ化と配布を完全にカバーすることは不要です。 こここことロシア語。 ただし、前のセクションで作成したローカル構成プラグインから、pipを使用してインストールされたものに移行することは大したことではありません。 、







最初に、プラグインコードをホストする新しいディレクトリを作成する必要があります。 呼び方は関係ありませんが、ナイスフラグ用のプラグインを作成しているので、pytest-niceと呼びましょう。 この新しいディレクトリには、pytest_nice.pyとsetup.pyの2つのファイルがあります。 (テストカタログについては、105ページの「テストプラグイン」セクションで説明します。)







 │ LICENSE │ pytest_nice.py │ setup.py │ └───tests │ conftest.py │ test_nice.py
      
      





pytest_nice.py



、この関数に関連付けられたconftest.pyの正確なコンテンツを配置します(そしてtasks_proj/tests/conftest.py



から抽出しtasks_proj/tests/conftest.py



):







ch5 / pytest-nice / pytest_nice.py







 """  pytest-nice .""" import pytest def pytest_addoption(parser): """ nice    --nice.""" group = parser.getgroup('nice') group.addoption("--nice", action="store_true", help="nice: turn FAILED into OPPORTUNITY for improvement") def pytest_report_header(): """    .""" if pytest.config.getoption('nice'): return "Thanks for running the tests." def pytest_report_teststatus(report): """   .""" if report.when == 'call': if report.failed and pytest.config.getoption('nice'): return (report.outcome, 'O', 'OPPORTUNITY for improvement')
      
      





setup.py



最小限のsetup()



呼び出しが必要です。







ch5 / pytest-nice / setup.py


 """Setup  pytest-nice plugin.""" from setuptools import setup setup( name='pytest-nice', version='0.1.0', description=' Pytest,   FAILURE into OPPORTUNITY', url='https:////////', author=' ', author_email='your_email@somewhere.com', license='proprietary', py_modules=['pytest_nice'], install_requires=['pytest'], entry_points={'pytest11': ['nice = pytest_nice', ], }, )
      
      





幅広いオーディエンスまたはインターネットに配信する場合は、設定でさらに情報が必要になります。 ただし、小さなチームの場合や自分自身の場合はこれで十分です。







setup()



他のパラメーターを含めることができます。 ここには必須フィールドのみがあります。 バージョンフィールドは、このプラグインのバージョンです。 そして、あなたがバージョンを立ち上げるとき、それは完全にあなた次第です。 URLフィールドは必須です。 空白のままにできますが、警告が表示されます。 author_email



author_email



は、 maintainer



maintainer_email



置き換えることができますが、これらのペアのいずれかが存在するはずです。 license



フィールドは短いテキストフィールドです。 それは、多くのオープンソースライセンスの1つ、あなたの名前や会社、またはあなたに適したものです。 py_modules



は、このプラグインの唯一のモジュールとしてpy_modules



リストされています。 これはリストであり、複数のモジュールを含めることができますが、複数ある場合は、パッケージを使用してすべてのモジュールを1つのディレクトリに配置します。







これまでのところ、すべてのsetup()



オプションは標準であり、すべてのPythonインストーラーによって使用されます。 Pytestプラグインで異なる部分は、 entry_points



パラメーターです。 entry_points={'pytest11': ['nice = pytest_nice', ], },.



をリストしentry_points={'pytest11': ['nice = pytest_nice', ], },.



entry_points



関数はsetuptools



標準ですが、pytest11はpytestが探している特別な識別子です。 この行では、 nice



はプラグインの名前であり、 pytest_nice



プラグインが存在するモジュールpytest_nice



名前であることをpytestに伝えます。 パッケージを使用した場合、ここでのエントリは次のようになります。







README.rst



ファイルについてはREADME.rst



話してREADME.rst



。 何らかの形式のREADMEがsetuptoolsの要件です。 スキップすると、これが得られます:







 ... warning: sdist: standard file not found: should have one of README, README.rst, README.txt ...
      
      





とにかく、プロジェクト情報を含めるための標準的な方法としてREADMEを保持することは良い考えです。 pytest-niceのファイルに入れたものは次のとおりです。







ch5 / pytest-nice / README.rst


 pytest-nice : A pytest plugin =============================   pytest     .  -------- -   ,     pytest. -  ``--nice`` , : -  ``F``  ``O`` -  ``-v``,  ``FAILURE``  ``OPPORTUNITY for improvement``  ------------ ,    Pytest    .tar.gz    PATH,  : :: $ pip install PATH/pytest-nice-0.1.0.tar.gz $ pip install --no-index --find-links PATH pytest-nice  ----- :: $ pytest --nice
      
      





READMEファイルの内容について多くの意見があります。 これは大幅にトリミングされたバージョンですが、動作します。







プラグインのテスト



プラグインは、他のコードと同様にテストする必要があるコードです。 ただし、テストツールへの変更のテストはもう少し複雑です。 98ページの「独自のプラグインの作成」セクションでプラグインコードを開発したとき、サンプルテストファイルを使用して手動でチェックし、pytestを実行して、出力が正しいことを確認しました。 pytester



に付属しているがデフォルトでは無効になっているpytesterというプラグインを使用して、自動モードでも同じことができます。







pytest-niceのテストディレクトリには、conftest.pyとtest_nice.pyの2つのファイルがあります。 pytester



を使用するには、 pytester



に1行だけ追加する必要がありconftest.py









ch5 / pytest-nice / tests / conftest.py


 """pytester is needed for testing plugins.""" pytest_plugins = 'pytester'
      
      





この行には、 pytester



プラグインが含まれてpytester



ます。 testdir



というフィクスチャを使用します。 pytester



pytester



オンになったときに使用可能になります。

多くの場合、プラグインのテストは、手動で説明した形式を取ります。







  1. サンプルのテストファイルを作成します。
  2. サンプルファイルを含むディレクトリでいくつかのパラメーターを使用して、または使用せずにpytestを実行します。
  3. 出力を確認してください。
  4. 可能な場合、結果コードをチェックするには、すべてのパスで0、一部の失敗で1になります。


1つの例を見てみましょう。







ch5 / pytest-nice / tests / test_nice.py


 def test_pass_fail(testdir): #     Pytest testdir.makepyfile(""" def test_pass(): assert 1 == 1 def test_fail(): assert 1 == 2 """) #  pytest result = testdir.runpytest() # fnmatch_lines    result.stdout.fnmatch_lines([ '*.F', # .  Pass, F  Fail ]) # ,      '1'  testsuite assert result.ret == 1
      
      





Fixture testdir



は、テストファイルをホストするための一時ディレクトリを自動的に作成します。 makepyfile()



, . : , , .







pytest testdir.runpytest()



. , . RunResult .







stdout



ret



. , , , fnmatch_lines



, , , , ret



0 1 . , fnmatch_lines



, . . , , :







ch5/pytest-nice/tests/test_nice.py


 @pytest.fixture() def sample_test(testdir): testdir.makepyfile(""" def test_pass(): assert 1 == 1 def test_fail(): assert 1 == 2 """) return testdir
      
      





, , sample_test



, . :







ch5/pytest-nice/tests/test_nice.py


 def test_with_nice(sample_test): result = sample_test.runpytest('--nice') result.stdout.fnmatch_lines(['*.O', ]) # . for Pass, O for Fail assert result.ret == 1 def test_with_nice_verbose(sample_test): result = sample_test.runpytest('-v', '--nice') result.stdout.fnmatch_lines([ '*::test_fail OPPORTUNITY for improvement', ]) assert result.ret == 1 def test_not_nice_verbose(sample_test): result = sample_test.runpytest('-v') result.stdout.fnmatch_lines(['*::test_fail FAILED']) assert result.ret == 1
      
      





. , :







ch5/pytest-nice/tests/test_nice.py


 def test_header(sample_test): result = sample_test.runpytest('--nice') result.stdout.fnmatch_lines(['Thanks for running the tests.']) def test_header_not_nice(sample_test): result = sample_test.runpytest() thanks_message = 'Thanks for running the tests.' assert thanks_message not in result.stdout.str()
      
      





, , .







:







ch5/pytest-nice/tests/test_nice.py


 def test_help_message(testdir): result = testdir.runpytest('--help') # fnmatch_lines    result.stdout.fnmatch_lines([ 'nice:', '*--nice*nice: turn FAILED into OPPORTUNITY for improvement', ])
      
      





, , , .







pytest-nice



, . .zip.gz



, :







 $ cd /path/to/code/ch5/pytest-nice/ $ pip install . Processing /path/to/code/ch5/pytest-nice Requirement already satisfied: pytest in /path/to/venv/lib/python3.6/site-packages (from pytest-nice==0.1.0) Requirement already satisfied: py>=1.4.33 in /path/to/venv/lib/python3.6/site-packages (from pytest->pytest-nice==0.1.0) Requirement already satisfied: setuptools in /path/to/venv/lib/python3.6/site-packages (from pytest->pytest-nice==0.1.0) Building wheels for collected packages: pytest-nice Running setup.py bdist_wheel for pytest-nice ... done ... Successfully built pytest-nice Installing collected packages: pytest-nice Successfully installed pytest-nice-0.1.0
      
      





, , :







 $ pytest -v ===================== test session starts ====================== plugins: nice-0.1.0 collected 7 items tests/test_nice.py::test_pass_fail PASSED tests/test_nice.py::test_with_nice PASSED tests/test_nice.py::test_with_nice_verbose PASSED tests/test_nice.py::test_not_nice_verbose PASSED tests/test_nice.py::test_header PASSED tests/test_nice.py::test_header_not_nice PASSED tests/test_nice.py::test_help_message PASSED =================== 7 passed in 0.34 seconds ===================
      
      





ご注意 : , . .

 platform win32 -- Python 3.6.5, pytest-3.9.3, py-1.7.0, pluggy-0.8.0 -- c:\venv36\scripts\python.exe collected 7 items tests/test_nice.py::test_pass_fail FAILED [ 14%] tests/test_nice.py::test_with_nice OPPORTUNITY for improvement [ 28%] tests/test_nice.py::test_with_nice_verbose OPPORTUNITY for improvement [ 42%] tests/test_nice.py::test_not_nice_verbose FAILED [ 57%] tests/test_nice.py::test_header PASSED [ 71%] tests/test_nice.py::test_header_not_nice PASSED [ 85%] tests/test_nice.py::test_help_message PASSED [100%] ================================== FAILURES =================================== _______________________________ test_pass_fail ________________________________
      
      









  result.stdout.fnmatch_lines([ '*.F', # . for Pass, F for Fail ])
      
      









  result.stdout.fnmatch_lines([ '*.F*', # . for Pass, F for Fail ])
      
      







*



F







test_with_nice



, test_with_nice_verbose



, test_not_nice_verbose







pytest.

c

'test_with_nice.py .O [100%]'





.





,



RemovedInPytest4Warning: usage of Session.Class is deprecated, please use pytest.Class instead



!

 (venv36) c:\_BOOKS_\pytest_si\bopytest-code\code\ch5\pytest-nice>pytest -v ============================= test session starts ============================= platform win32 -- Python 3.6.5, pytest-3.9.3, py-1.7.0, pluggy-0.8.0 -- c:\venv36\scripts\python.exe cachedir: .pytest_cache rootdir: c:\_BOOKS_\pytest_si\bopytest-code\code\ch5\pytest-nice, inifile: plugins: nice-0.1.0 collected 7 items tests/test_nice.py::test_pass_fail PASSED [ 14%] tests/test_nice.py::test_with_nice PASSED [ 28%] tests/test_nice.py::test_with_nice_verbose PASSED [ 42%] tests/test_nice.py::test_not_nice_verbose PASSED [ 57%] tests/test_nice.py::test_header PASSED [ 71%] tests/test_nice.py::test_header_not_nice PASSED [ 85%] tests/test_nice.py::test_help_message PASSED [100%] ============================== warnings summary =============================== tests/test_nice.py::test_pass_fail c:\venv36\lib\site-packages\_pytest\compat.py:332: RemovedInPytest4Warning: usage of Session.Class is deprecated, please use pytest.Class instead return getattr(object, name, default)
      
      





やった! . (pytest-nice), Python

pytest-:







 $ pip uninstall pytest-nice Uninstalling pytest-nice-0.1.0: Would remove: \path\to\venv\lib\site-packages\pytest_nice-0.1.0.dist-info\* ... Proceed (y/n)? y Successfully uninstalled pytest-nice-0.1.0
      
      





— , pytest, PyPI.









, . , setup.py :







 $ cd /path/to/code/ch5/pytest-nice $ python setup.py sdist running sdist running egg_info creating pytest_nice.egg-info ... running check creating pytest-nice-0.1.0 ... creating dist Creating tar archive ... $ ls dist pytest-nice-0.1.0.tar.gz
      
      





( , sdist source distribution — “ .”)







pytest-nice dist pytest-nice-0.1.0.tar.gz



.







, , :







 $ pip install dist/pytest-nice-0.1.0.tar.gz Processing ./dist/pytest-nice-0.1.0.tar.gz ... Installing collected packages: pytest-nice Successfully installed pytest-nice-0.1.0
      
      





.tar.gz



, .









pip



, , , , , , .tar.gz



. , pytest-nice-0.1.0.tar.gz



myplugins



.







pytest-nice



myplugins



:







 $ pip install --no-index --find-links myplugins pytest-nice
      
      





--no-index



pip



PyPI, , .

The --find-links myplugins tells PyPI to look in myplugins for packages to install. And of course, pytest-nice is what we want to install.

--find-links myplugins



PyPI myplugins



. , pytest-nice



— , .







myplugins



, , --upgrade



:







 $ pip install --upgrade --no-index --find-links myplugins pytest-nice
      
      





pip



, --no-index --find-links myplugins



.







PyPI



, , . , . , , , Python Packaging .







pytest, — cookiecutter-pytest-plugin



:







 $ pip install cookiecutter $ cookiecutter https://github.com/pytest-dev/cookiecutter-pytest-plugin
      
      





. , . ; , , . pytest, , .









ch4/cache/test_slower.py



autouse fixture, check_duration()



. 4. .







  1. pytest-slower, , , « » . 102.
  2. , pytest-slower , .
  3. プラグインのテストコードを作成します。
  4. 見てみましょうPythonのパッケージインデックスをと«pytest-»を探します。おもしろそうなpytestプラグインを見つけてください。
  5. 選択したプラグインをインストールし、タスクテストで試してください。


次は何ですか



conftest.py



この本ではこれまで何度も使用しましたたとえば、pytestの実行に影響する設定ファイルもありますpytest.ini



次の章では、さまざまな構成ファイルに精通し、テスト時に生活を楽にするためにできることを見つけます。







戻る 次へ








All Articles