tachitomonn’s blog

IT技術関連の学習メモがメインでたまに趣味のこととか

Python でテスト pytest

nose に引き続き、やはりテストを容易に行う為のフレームワークである pytest の基本を押さえます。
公式ドキュメント
pytest: helps you write better programs — pytest documentation
を参考に基本だけやってみました。

テスト対象の自動探索ができることは nose と同様ですが pytest では検証はシンプルにassert文を使います。
インストールは pip で行います。

pip install pytest

今回はバージョン 5.3.4 が入りました。
インストールが完了すると pytest コマンドが使えるようになります。
前回の nose の勉強で使用したテストスクリプトを pytest 向けに書き直してテストを実行してみます。

test_sample2.py

#! /usr/bin/env python

u"""pytestの勉強用サンプル
"""

from pytest import raises

from study_doctest import heisei2seireki

def test_heisei2seireki():
    assert [heisei2seireki(n) for n in range(1, 32)] == [1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]

def test_heisei2seireki_exception1():
    with raises(ValueError):
        heisei2seireki(-1)
    
def test_heisei2seireki_exception2():
    with raises(ValueError):
        heisei2seireki(0)

def test_heisei2seireki_exception3():
    with raises(ValueError):
        heisei2seireki(1.5)

def test_heisei2seireki_exception4():
    with raises(ValueError):
        heisei2seireki(32)

テストしてみます。

>pytest -v c:\selfstudy\test_sample2.py
============================= test session starts =============================
platform win32 -- Python 3.7.2, pytest-5.3.4, py-1.8.1, pluggy-0.13.1 -- c:\venv\selfstudy\scripts\python.exe
cachedir: .pytest_cache
rootdir: c:\
collected 5 items

..\..\selfstudy\test_sample2.py::test_heisei2seireki PASSED              [ 20%]
..\..\selfstudy\test_sample2.py::test_heisei2seireki_exception1 PASSED   [ 40%]
..\..\selfstudy\test_sample2.py::test_heisei2seireki_exception2 PASSED   [ 60%]
..\..\selfstudy\test_sample2.py::test_heisei2seireki_exception3 PASSED   [ 80%]
..\..\selfstudy\test_sample2.py::test_heisei2seireki_exception4 PASSED   [100%]

============================== 5 passed in 0.05s ==============================

シンプルで使いやすいかも。
もう少しきちんと勉強する時は
pytest ヘビー🐍ユーザーへの第一歩 - エムスリーテックブログ
がわかりやすく書いてくださっているので参考にさせていただきます。