try:
if not (os.path.is.dir('directory')):
os.makedirs(os.path.join('directory'))
except OSError as error:
if error.errno != errno.EEXIST:
print('Directory has already created')
raise
파일 쓰기
#동일한 이름의 파일이 있을 경우 덮어쓰기
open('directory' + '파일명.txt', 'w') as file:
file.write('파일 내용')
#동일한 이름의 파일이 있을 경우 이어쓰기
open('directory' + '파일명.txt', 'a') as file:
file.write('파일 내용')
※ Pytest를 지원하는 Python 버전은Python 3.6, 3.7, 3.8, 3.9, PyPy3 이다.
1. Windows 명령 프롬프트 혹은 MacOS 터미널에 다음 명령어를 입력한다.
$ pip install -U pytest
2. 설치 과정이 끝나면, 다음 명령어를 입력하여 Pytest의 버전이 뜨는지(= 제대로 설치 되었는지) 확인한다.
$ pytest --version
pytest 6.1.2 // 제대로 설치 된 경우 출력
Pytest 사용 방법
일반 라이브러리를 사용하듯이 Python 스크립트에 pytest 모듈을 import하여 사용한다.
단, Python 스크립트 파일명과 테스트 결과를 확인할 함수명은test_로 시작 혹은 _test로 끝나야 한다.
※ 파일명/함수명을 지키지 않으면, pytest에서 test 대상으로 인지하지 못해 다음과 같이 Collected 0 item 으로 나타난다.
$ pytest test.py
================================== test session starts =======================================
platform win32 -- Python 3.8.3, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: C:\Users\User
collected 0 items
================================= no tests ran in 0.02s ======================================
예시)
동일한 Python 스크립트를 일반 Python으로 실행 VS Pytest로 실행
# 파일명 : test.py
import pytest
def test_success():
test = 'Test Success !!'
print(test)
assert 'Success' in test // Test 결과 판별 기준
def test_fail():
test = 'Test Failed !!'
print(test)
assert 'Success' in test // Test 결과 판별 기준
test_success() 와 test_fail() 이라는 함수 두개만 선언되어 있고, main 에서 함수를 호출하지 않기 때문에
일반 Python으로 실행시켰을 때는 아무런 동작도 표시되지 않는다.
$ python test.py
test.py를 pytest로 실행하면, 다음과 같은 테스트 결과가 나타난다.
$ pytest test.py
===================================== test session starts =================================================
platform win32 -- Python 3.8.3, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: C:\Users\User
collected 2 items
PycharmProjects\test\test.py .F [100%]
========================================== FAILURES =======================================================
__________________________________________ test_fail ______________________________________________________
def test_fail():
test = 'Test Failed !!'
print(test)
> assert 'Success' in test
E AssertionError: assert 'Success' in 'Test Failed !!'
PycharmProjects\test\test.py:11: AssertionError
------------------------------------ Captured stdout call -------------------------------------------------
Test Failed !!
=================================== short test summary info ===============================================
FAILED PycharmProjects/test/test.py::test_fail - AssertionError: assert 'Success' in 'Test Failed !!'
================================= 1 failed, 1 passed in 0.13s =============================================
test_success() 함수의 결과는 Pass로 따로 출력되지 않았고,
test_fail() 함수의 결과만 어느 부분에서 테스트가 실패했는지 친절하게 테스트 결과가 표시 된다.
+)
테스트 결과뿐만 아니라, 콘솔에 내용을 출력하고 싶다면 -s 옵션을 사용한다.
$ pytest test.py -s
====================================== test session starts =================================================
platform win32 -- Python 3.8.3, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: C:\Users\HyeJungSeo
collected 2 items
PycharmProjects\test\test.py Test Success !! // test_success() 출력결과 확인
.Test Failed !! // test_fail() 출력결과 확인
F
========================================== FAILURES =======================================================
___________________________________________ test_fail ______________________________________________________
def test_fail():
test = 'Test Failed !!'
print(test)
> assert 'Success' in test
E AssertionError: assert 'Success' in 'Test Failed !!'
PycharmProjects\test\test.py:11: AssertionError
==================================== short test summary info ===============================================
FAILED PycharmProjects/test/test.py::test_fail - AssertionError: assert 'Success' in 'Test Failed !!'
================================== 1 failed, 1 passed in 0.08s =============================================