test_travel_service.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. from __future__ import annotations
  2. """测试TravelSearchService的航班/酒店搜索与规范化功能。"""
  3. import asyncio
  4. from collections import Counter
  5. from datetime import date
  6. from rich.console import Console
  7. from rich.table import Table
  8. from app.clients.serpapi_client import (
  9. SerpApiClient,
  10. SerpApiError,
  11. )
  12. from app.config import get_settings
  13. from app.schemas.flight import FlightSearchQuery
  14. from app.schemas.hotel import HotelSearchQuery
  15. from app.services.travel_search_service import (
  16. TravelSearchService,
  17. )
  18. console = Console()
  19. def format_duration(minutes: int | None) -> str:
  20. if minutes is None:
  21. return "未知"
  22. hours, remaining_minutes = divmod(minutes, 60)
  23. return f"{hours}小时{remaining_minutes}分"
  24. def format_flight_numbers(flight) -> str:
  25. flight_numbers = [
  26. segment.flight_number
  27. for segment in flight.segments
  28. if segment.flight_number
  29. ]
  30. return " / ".join(flight_numbers) or "未知"
  31. async def test_flight_service(
  32. service: TravelSearchService,
  33. ) -> None:
  34. console.rule("[bold]TravelSearchService 航班测试")
  35. query = FlightSearchQuery(
  36. departure_airports=["SHA", "PVG"],
  37. arrival_airports=["CTU", "TFU"],
  38. outbound_date=date(2026, 8, 10),
  39. flight_type="one_way",
  40. adults=2,
  41. # 当前不限制时间、机场、中转次数和价格。
  42. show_hidden=False,
  43. deep_search=False,
  44. )
  45. result = await service.search_flights(query)
  46. airport_counts = Counter(
  47. flight.final_arrival_airport_code
  48. for flight in result.flights
  49. )
  50. console.print(
  51. {
  52. "标准化航班总数": result.total_count,
  53. "抵达机场分布": dict(airport_counts),
  54. "数据源": result.source.provider,
  55. "查询ID": result.source.search_id,
  56. }
  57. )
  58. table = Table(
  59. title=(
  60. f"航班结果预览:展示10条,"
  61. f"实际保留{result.total_count}条"
  62. )
  63. )
  64. table.add_column("来源")
  65. table.add_column("航司/航班号")
  66. table.add_column("出发")
  67. table.add_column("到达")
  68. table.add_column("耗时")
  69. table.add_column("中转")
  70. table.add_column("单张票价")
  71. # 这里只限制终端预览,不修改 result.flights。
  72. for flight in result.flights[:10]:
  73. first_segment = flight.segments[0]
  74. last_segment = flight.segments[-1]
  75. airline_text = (
  76. "/".join(flight.airlines)
  77. if flight.airlines
  78. else "未知"
  79. )
  80. table.add_row(
  81. flight.source_group,
  82. (
  83. f"{airline_text}\n"
  84. f"{format_flight_numbers(flight)}"
  85. ),
  86. (
  87. f"{first_segment.departure_airport_code}\n"
  88. f"{flight.departure_time:%m-%d %H:%M}"
  89. ),
  90. (
  91. f"{last_segment.arrival_airport_code}\n"
  92. f"{flight.arrival_time:%m-%d %H:%M}"
  93. ),
  94. format_duration(
  95. flight.total_duration_minutes
  96. ),
  97. (
  98. "直飞"
  99. if flight.stop_count == 0
  100. else f"{flight.stop_count}次"
  101. ),
  102. (
  103. f"¥{flight.price}"
  104. if flight.price is not None
  105. else "未知"
  106. ),
  107. )
  108. console.print(table)
  109. for warning in result.warnings:
  110. console.print(f"[yellow]提示:{warning}[/yellow]")
  111. async def test_hotel_service(
  112. service: TravelSearchService,
  113. ) -> None:
  114. console.rule("[bold]TravelSearchService 酒店测试")
  115. query = HotelSearchQuery(
  116. query="成都酒店",
  117. check_in_date=date(2026, 8, 10),
  118. check_out_date=date(2026, 8, 13),
  119. adults=2,
  120. )
  121. result = await service.search_hotels(query)
  122. console.print(
  123. {
  124. "标准化酒店总数": result.total_count,
  125. "数据源": result.source.provider,
  126. "查询ID": result.source.search_id,
  127. }
  128. )
  129. table = Table(
  130. title=(
  131. f"酒店结果预览:展示10家,"
  132. f"实际保留{result.total_count}家"
  133. )
  134. )
  135. table.add_column("酒店")
  136. table.add_column("星级")
  137. table.add_column("评分")
  138. table.add_column("每晚")
  139. table.add_column("整个入住期")
  140. table.add_column("客观信息")
  141. # 这里是客观信息摘要,不是个性化推荐理由。
  142. for hotel in result.hotels[:10]:
  143. highlights: list[str] = []
  144. if hotel.review_count is not None:
  145. highlights.append(
  146. f"{hotel.review_count}条评价"
  147. )
  148. if hotel.location_rating is not None:
  149. highlights.append(
  150. f"位置评分{hotel.location_rating}"
  151. )
  152. highlights.extend(hotel.amenities[:2])
  153. if hotel.deal_description:
  154. highlights.append(
  155. hotel.deal_description
  156. )
  157. table.add_row(
  158. hotel.name,
  159. (
  160. f"{hotel.hotel_class}星"
  161. if hotel.hotel_class
  162. else "未知"
  163. ),
  164. (
  165. str(hotel.overall_rating)
  166. if hotel.overall_rating is not None
  167. else "未知"
  168. ),
  169. (
  170. f"¥{hotel.price_per_night:.0f}"
  171. if hotel.price_per_night is not None
  172. else "未知"
  173. ),
  174. (
  175. f"¥{hotel.total_price:.0f}"
  176. if hotel.total_price is not None
  177. else "未知"
  178. ),
  179. ";".join(highlights) or "暂无",
  180. )
  181. console.print(table)
  182. async def main() -> None:
  183. settings = get_settings()
  184. async with SerpApiClient(
  185. api_key=settings.require(
  186. "serpapi_api_key"
  187. ),
  188. timeout_seconds=(
  189. settings.request_timeout_seconds
  190. ),
  191. ) as client:
  192. service = TravelSearchService(client)
  193. await test_flight_service(service)
  194. await test_hotel_service(service)
  195. if __name__ == "__main__":
  196. try:
  197. asyncio.run(main())
  198. except SerpApiError as exc:
  199. console.print(
  200. f"[red]真实接口测试失败:{exc}[/red]"
  201. )
  202. raise SystemExit(1) from exc