Programming/Unittest

API Test

c29130811 2024. 10. 12. 12:24
project_root/
│
├── tests/                      # 모든 테스트 관련 코드가 들어가는 폴더
│   ├── __init__.py             # 패키지 초기화 파일
│   ├── test_setup.py           # 공통 API 설정 및 유틸리티 함수
│   ├── test_get.py       		# GET 요청 관련 테스트
│   └── ...
│
├── reports/                    # HTML 테스트 리포트가 저장되는 폴더
│   └── test_report.html
│
└── requirements.txt            # 필요한 라이브러리 목록

 

기본 폴더 구조

 

test_setup.py

class APITestSetup:

	def __init__(self):
        self.base_url = "https://your-api-url.com"
        self.headers = {
            'Content-Type': 'application/json'
        }
        
        ...

 

기본적으로 요청할 설정값 url, header 등 관련을 설정

import unittest
import requests
from test_setup import APITestSetup

class GetBook(unittest.TestCase):

    def setUp(self):
        # APITestSetup을 인스턴스로 생성하여 사용
        self.api_setup = APITestSetup()

    def test_book_item(self):
        response = requests.get(f"{self.api_setup.base_url}/book/118840967", headers=self.api_setup.headers)
        self.assertEqual(response.status_code, 200)
        data = response.json()
        print(data, 'data')
        self.assertIsInstance(data, dict)

if __name__ == '__main__':
    unittest.main()

 

이런 josn인데 위에 형태로 요청해서 

python -m unittest discover -s tests

 

로 실행한다.

 

(testing) june@juneui-MacBookPro unittest % python -m unittest discover -s tests

{'id': 118840967, 'title': '풀스택 테스트 10가지 테스트 기술의 기본 원칙과 전략', 'original_title': 'Full Stack Testing', 'price': '30,600원', 'author': 'Gayathri Mohan', 'publishers': '한빛미디어', 'category': 'IT/Mobile', 'published_date': '2023-05-26', 'isbn10': 1169211097, 'isbn13': 9791169211093, 'rating': 9.7, 'best_seller': True, 'review_count': 10} data
.
----------------------------------------------------------------------
Ran 1 test in 0.979s

OK

 

위에 print(data, 'data') 때문에 response 가 출력되기는 하는데 위처럼 출력된다.

728x90

'Programming > Unittest' 카테고리의 다른 글

Assertion  (1) 2024.09.13
Unittest  (3) 2024.09.08