10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pytestまとめ

Last updated at Posted at 2015-04-28

1.install

pip install pytest pytest-pep8 pytest-cov

2.write test code

test_hoge.py
import pytest

def TestClass:
	def pytest_funcarg__hoge(request):
		return Hoge(1)
		
	def test_type(self, hoge):
		assert isinstance(hoge, Hoge)

pytest_funcarg__hogeは、setupみたいなもので、各テスト実行時に実行されテストの引数として渡してくれる。self.hogeとか不要なので便利。ただ、こちらはオールドスタイルで、デコレータを使うのが新しいやり方。

test_hoge.py
import pytest

def TestClass:
	@pytest.fixture()
	def hoge(request):
		return Hoge(1)
		
	def test_type(self, hoge):
		assert isinstance(hoge, Hoge)

3.run tests

  • 詳細表示
  • カバレッジ取得
  • カバレッジレポート出力(HTML形式)
  • ソースコードチェック(PEP8)
py.test --verbose --cov . --cov-report=html --pep8

4.write production code

hoge.py
class Hoge:
	def __init__(self, v):
		self.val = v

5.write test code

test_hoge.py
class MockClass:
	def method1(self, p1, p2):
		pass
		
class TestClass:
	@pytest.fixture()
	def mockclass(request):
		return MockClass()
	
	def test_method1(self, mockclass, monkeypatch):
		monkeypatch.setattr(module1, 'method1', mockclass.method1)
		val = module1.method1(p1, p2)
		assert val == "..."
10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?