-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_usage.py
More file actions
147 lines (123 loc) · 5.94 KB
/
example_usage.py
File metadata and controls
147 lines (123 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
RedFin API 사용 예제
이 스크립트는 RedFin API의 주요 엔드포인트 사용법을 보여줍니다.
새로운 클린 아키텍처 구조 (v1 API)를 사용합니다.
실행 전 확인사항:
1. 서버가 http://localhost:8000 에서 실행 중이어야 합니다
2. MongoDB가 설정되어 있다면 연결되어 있어야 합니다
3. 필요한 경우 .env 파일을 설정하세요
"""
import asyncio
import httpx
from datetime import datetime
async def test_article_crud():
"""Article CRUD API 테스트"""
base_url = "http://localhost:8000/api/v1/articles"
async with httpx.AsyncClient() as client:
print("=== Article CRUD API 테스트 ===\n")
# 1. 새 기사 생성
print("1. 새 기사 생성")
# 새로운 API 스키마에 맞는 요청 데이터
article_data = {
"Title": "샘플 기사 제목",
"Summary": "이것은 테스트용 기사 요약입니다. MongoDB와 FastAPI를 사용한 CRUD 작업을 테스트합니다.",
"URL": "https://example.com/test-article",
"keywords": "['테스트', 'MongoDB', 'FastAPI', 'CRUD']",
"category": "Research",
"body": "이것은 테스트용 기사 본문입니다. MongoDB와 FastAPI를 사용한 CRUD 작업을 테스트합니다. 실제 데이터베이스에 저장되는 내용입니다.",
"published_at": "2024-01-01 00:00:00",
"tags": ["policy/Technology", "topic/Testing", "geo/KR"]
}
response = await client.post(f"{base_url}/", json=article_data)
if response.status_code == 201:
article = response.json()
article_id = article["id"]
print(f"✅ 기사 생성 성공: ID = {article_id}")
print(f" 제목: {article['title']}")
print(f" 카테고리: {article.get('category', 'N/A')}")
else:
print(f"❌ 기사 생성 실패: {response.status_code} - {response.text}")
return
print()
# 2. 기사 조회
print("2. 기사 조회")
response = await client.get(f"{base_url}/{article_id}")
if response.status_code == 200:
article = response.json()
print(f"✅ 기사 조회 성공")
print(f" 제목: {article['title']}")
print(f" 카테고리: {article.get('category', 'N/A')}")
print(f" 태그: {article.get('tags', [])}")
else:
print(f"❌ 기사 조회 실패: {response.status_code} - {response.text}")
print()
# 3. 기사 목록 조회
print("3. 기사 목록 조회")
response = await client.get(f"{base_url}/?page=1&size=5")
if response.status_code == 200:
result = response.json()
print(f"✅ 기사 목록 조회 성공")
print(f" 전체 개수: {result['total']}")
print(f" 현재 페이지: {result['page']}")
print(f" 페이지 크기: {result['size']}")
print(f" 기사 개수: {len(result['items'])}")
else:
print(f"❌ 기사 목록 조회 실패: {response.status_code} - {response.text}")
print()
# 4. 기사 업데이트
print("4. 기사 업데이트")
update_data = {
"Title": "수정된 기사 제목",
"Summary": "수정된 기사 요약입니다.",
"body": "수정된 기사 본문입니다.",
"tags": ["policy/Technology", "topic/Testing", "geo/KR", "업데이트"]
}
response = await client.put(f"{base_url}/{article_id}", json=update_data)
if response.status_code == 200:
article = response.json()
print(f"✅ 기사 업데이트 성공")
print(f" 수정된 제목: {article['title']}")
print(f" 수정된 요약: {article.get('summary', 'N/A')}")
print(f" 수정된 태그: {article.get('tags', [])}")
else:
print(f"❌ 기사 업데이트 실패: {response.status_code} - {response.text}")
print()
# 5. 기사 개수 조회
print("5. 기사 개수 조회")
response = await client.get(f"{base_url}/stats/count")
if response.status_code == 200:
result = response.json()
print(f"✅ 기사 개수 조회 성공: {result['total_count']}개")
else:
print(f"❌ 기사 개수 조회 실패: {response.status_code} - {response.text}")
print()
# 6. 헬스체크
print("6. 헬스체크")
response = await client.get(f"{base_url}/health/check")
if response.status_code == 200:
result = response.json()
print(f"✅ 헬스체크 성공")
print(f" 상태: {result['status']}")
print(f" 데이터베이스: {result['database']}")
print(f" 전체 기사 수: {result['total_articles']}")
else:
print(f"❌ 헬스체크 실패: {response.status_code} - {response.text}")
print()
# 7. 기사 삭제
print("7. 기사 삭제")
response = await client.delete(f"{base_url}/{article_id}")
if response.status_code == 200:
result = response.json()
print(f"✅ 기사 삭제 성공: {result['message']}")
else:
print(f"❌ 기사 삭제 실패: {response.status_code} - {response.text}")
print("\n=== 테스트 완료 ===")
if __name__ == "__main__":
print("Article CRUD API 테스트를 시작합니다...")
print("서버가 http://localhost:8000 에서 실행 중인지 확인하세요.")
print()
try:
asyncio.run(test_article_crud())
except Exception as e:
print(f"테스트 실행 중 오류 발생: {e}")
print("서버가 실행 중인지 확인하고 다시 시도하세요.")