설치 및 실행

3 minute read

Pythons: Python 2.7, 3.4, 3.5, 3.6, 3.7, Jython, PyPy-2.3 Platforms: Unix/Posix and Windows PyPI 패키지 이름: pytest PDF 다운로드: 최신 버전 다운로드

pytest는 간단하고 확장가능한 테스팅을 지원하는 framework입니다. 테스트는 읽을 수 있는 형태로 표현되어지므로 boilerplate 코드가 필요하지 않습니다. 몇분만에 당신의 프로그램 혹은 라이브러리를 위한 단순하거나 복잡한 테스트를 시작하세요.

1.1 pytest 설치

  1. 당신의 명령창에 다음과 같은 명령을 실행시키세요.
    pip install -U pytest
    
  2. 설치를 확인하고 버전을 확인하세요
    $ pytest --version
    This is pytest version 4.x.y, imported from $PYTHON_PREFIX/lib/python3.6/site-
    ˓→packages/pytest.py
    


1.2 첫 테스트 생성

다음과 같은 간단한 테스트 함수를 생성하세요.

# content of test_sample.py
def func(x):
	return x + 1
def test_answer():
	assert func(3) == 5

이제 당신은 테스트 함수를 실행시킬 수 있습니다.

$ pytest
=========================== test session starts ==========================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_sample.py F 						[100%]
================================= FAILURES ===============================
_______________________________ test_answer ______________________________

	def test_answer():
> 		assert func(3) == 5
E 		assert 4 == 5
E 		+ where 4 = func(3)

test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =======================

func(3)이 5를 반환하지 않기 때문에, 위의 테스트는 실패를 보고합니다.

주의: 테스트에서의 원하는 값을 확인하기 위해 assert구문을 사용할 수 있습니다. pytest의 Advanced assertion introspection은 지능적으로 assert 구문의 중간 내용을 보고합니다. 그래서, 당신은 많은 이름 붙여진 JUnit legacy methods를 피할 수 있습니다.

1.3 여러 테스트 실행

pytest는 현재 directory와 그 내부의 directory 에서 test_*.py 혹은 *_test.py라는 이름을 가진 모든 파일을 실행합니다. 좀 더 일반적으로는, standard test discovery rules에 따라서 실행됩니다.

1.4 특정한 예외를 assert

raise구문을 사용하여 코드에서 일어난 예외사항을 표현하세요.

# content of test_sysexit.py
import pytest
def f():
	raise SystemExit(1)
def test_mytest():
	with pytest.raises(SystemExit):
		f()

위의 테스트 함수를 “quiet” 보고 모드로 실행하면 다음과 같습니다.

$ pytest -q test_sysexit.py
. 																					[100%]
1 passed in 0.12 seconds


1.5 class 내부의 다중 테스트의 그룹화

일단 당신이 여러개의 테스트를 개발하면, 당신은 아마 그것들을 class 내부로 그룹화하길 원할 것입니다. pytest는 한 개 이상의 테스트를 포함하는 class를 생성하는 것을 쉽게 할 수 있게 만듭니다.

# content of test_class.py
class TestClass(object):
	def test_one(self):
		x = "this"
		assert 'h' in x
        
	def test_two(self):
		x = "hello"
		assert hasattr(x, 'check')

pytest는 Conventions for Python test discovery에 따라서 모든 테스트를 찾아냅니다. 그러므로, test_로 시작하는 모든 함수나, Test로 시작하는 class 내부에 있는 test_로 시작하는 함수들을 찾아냅니다. 이 class는 다른 class를 상속받을 필요가 없습니다. 단순히 파일 이름을 입력하고 실행시키면 됩니다.

$ pytest -q test_class.py
.F 								[100%]
================================= FAILURES ===============================
____________________________ TestClass.test_two __________________________
self = <test_class.TestClass object at 0xdeadbeef>

	def test_two(self):
		x = "hello"
> 		assert hasattr(x, 'check')
E 		AssertionError: assert False
E 	    +  where False = hasattr('hello', 'check')

test_class.py:8: AssertionError
1 failed, 1 passed in 0.12 seconds

첫번째 테스트는 통과하고 두번째 테스트는 실패했습니다. 보다 쉽게 실패의 원인을 이해하기 위해, assertion의 중간 내용을 표시합니다.

1.6 함수 테스트를 위한 고유 임시 directory 요청

pytest는 고유한 임시 directory와 같은 임의의 자원을 요청하기 위하여 Builtin fixtures/function argument를 제공합니다.

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
	print(tmpdir)
	assert 0

함수 signature의 안에 tmpdir의 이름을 리스트로 입력하세요. pytest는 확인 후 fixture factory를 불러내어 함수 call이 실행되기 전에 자원을 생성할 것입니다. 테스트가 실행되기 전에, pytest는 테스트 마다 실행되는 고유한 임시 directory를 생성합니다.

$ pytest -q test_tmpdir.py
F 								[100%]
================================= FAILURES ===============================
_____________________________ test_needsfiles ____________________________
tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')

	def test_needsfiles(tmpdir):
		print(tmpdir)
> 		assert 0
E 		assert 0

test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call -------------------------
PYTEST_TMPDIR/test_needsfiles0
1 failed in 0.12 seconds

tmpdir의 사용에 대한 더 많은 정보는 Temporary directories and files에 있습니다. 제공되는 [pytest fixtures]의 종류를 확인하는 명령은 다음과 같습니다.

pytest --fixtures 	# shows builtin and custom fixtures

-v 옵션을 추가하면, 앞에 표시된 _를 제거하고 볼 수 있습니다.

1.7 이후의 내용

pytest의 추가적인 기능과 당신의 고유한 테스트를 제작하는 것에 도움을 받기 위해선 다음과 같은 내용을 참고하십시오.