Flask의 엔드포인트는 함수로 구현되어 있어 unit test를 직접 할 수 있는 장점이 있다.
1. test_endpoint.py 파일 생성
2. test용 DB 만들기
3. test 코드 작성
import pytest
import config
from app import create_app # test할 플라스크 앱 호출 (미니터 API가 있는 코드파일)
@pytest.fixture # fixture 데코레이터가 적용된 함수와 같은 인자가 test 함수에 있으면 pytest 알아서 실행
def api() : # fixture의 함수명
app = create_app(config.test_config)
app.config['TEST'] = True
api = app.test_client()
return api
def test_ping(api) : # fixture 데코레이터의 함수가 인자로 들어감, test_client가 자동으로 적용됨
resp = api.get('/ping') # 가상의 GET 요청을 연결된 엔드포인트에 보냄
assert b'pong' in resp.data
- create_app(config.test_config) : 테스트 할 미니터 API 애플리케이션 생성. config 파일에 있는 test_config에 설정해놓은 DB 테스트 설정 적용.
- app.config['TEST'] = True : 플라스크가 에러날 경우 http 요청 오류에서 불필요한 오류메시지 출력 안되게 함
- test_client() : 테스트용 클라이언트 생성. URI 기반으로 원하는 엔드포인트 호출 가능
- return api : 호출한 test_clinet 리턴
- test_ping() : test 함수로 인식. ping 엔드포인트 테스트 함수.
- assert b'pong' in resp.data : 리턴받은 응답의 body에서 'pong' 텍스트가 포함되있는지 확인.
resp.data는 byte라서 'pong'앞에 b를 붙여줌
4. unit test 실행
'Python > Flask' 카테고리의 다른 글
[미니터] unit-test 시 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 오류 (0) | 2022.08.01 |
---|---|
[미니터] Test - 테스트 자동화 (0) | 2022.07.19 |
[미니터] 인증 구현시 ValueError : Invalid salt과 AttributeError: 'str' object has no attribute 'decode'에러 (0) | 2022.07.18 |
[미니터] 인증 - tweet, follow, unfollow에 decorator 추가 (0) | 2022.07.15 |
[미니터] 인증 - 인증 decorator 함수 (0) | 2022.07.15 |