feat: add date-based weather forecasts and dynamic time context

This commit is contained in:
loveuer committed 2026-11-18 11:30:38 +08:00
1 parent a394f22d77
commit 975352c7d6
12 files changed
+607 -15

No files matched your search

+16
View File
@@ -50,6 +50,22 @@ go run ./adk \
图片服务需支持 OpenAI 兼容的 `POST /images/generations`。客户端发送模型、提示词和 `n=1`,支持返回 base64 或图片 URL,将 PNG、JPEG、WebP 保存为不重复的文件名。当前只支持生成单张新图,不包含改图和预览。
## 当前天气与日期预报
可以直接输入“帮我查查明天北京的天气”或“查询成都本周末两天的天气”。ADK 主助手每轮都会收到当前日期、星期和 `Asia/Shanghai` 时区,由模型将相对日期转换成工具参数,不单独创建提槽 Agent。
`get_weather` 接收 `location` 和可选的 `start_date`、`end_date`:
```json
{"location":"北京","start_date":"2026-11-19"}
```
这里的日期仅作参数格式示例,实际查询应使用当前日期起 16 天内的日期。`start_date`、`end_date` 均为 `YYYY-MM-DD`,范围包含两端;只传开始日期就查当天,结束日期不能单独提供。缺少地点且历史中没有地点时,助手先询问用户。
不传日期仍使用 wttr.in 查询当前天气。指定日期时使用 Open-Meteo:先搜索城市坐标,再查询逐日天气、最低/最高温度和最大降雨概率,不需要额外 API key。城市搜索使用首个匹配结果,工具返回实际地点、行政区和国家供核对;区县或重名地点建议明确城市名称。
预报统一按 `Asia/Shanghai` 查询,支持今天至未来第 15 天,不支持历史天气。日期无效、超出范围或接口缺少目标日期数据时,明确返回错误,不以当前天气代替预报。这里只增加天气查询能力,尚未加入旅行规划 Chain。
## 文字与语音子命令
命令行使用 Cobra,参数使用双横线。默认文字聊天,`voice` 子命令启动语音交互:
+2 -1
View File
@@ -47,7 +47,8 @@ func New(ctx context.Context, cfg config.Config) (*Agent, error) {
mainAgent, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
Name: mainAgentName, Instruction: instruction, Model: chat, MaxIterations: opt.MAX_TOOL_ROUND,
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}, EmitInternalEvents: true},
GenModelInput: genModelInput,
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}, EmitInternalEvents: true},
})
if err != nil {
+33
View File
@@ -0,0 +1,33 @@
package agent
import (
"context"
"fmt"
"time"
"github.com/cloudwego/eino/adk"
"github.com/cloudwego/eino/schema"
)
func genModelInput(_ context.Context, instruction string, input *adk.AgentInput) ([]adk.Message, error) {
messages := []adk.Message{schema.SystemMessage(timedInstruction(instruction, time.Now()))}
return append(messages, input.Messages...), nil
}
// timedInstruction 每轮生成时间信息,避免使用进程启动时的旧日期。
func timedInstruction(instruction string, now time.Time) string {
now = now.In(time.FixedZone("Asia/Shanghai", 8*60*60))
weekdays := [...]string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
// 按周一至周日确定当前周,给模型明确的日期参照。
weekday := (int(now.Weekday()) + 6) % 7
saturday := now.AddDate(0, 0, 5-weekday)
return instruction + fmt.Sprintf(`
当前日期:%s,%s,时区:Asia/Shanghai(UTC+08:00)。
明天:%s;本周六:%s;本周日:%s。
查询天气时将相对时间换算为 YYYY-MM-DD,日期参数只能是一个完整日期,不要把多个日期拼进同一个字段。
查询本周末两天时,日期参数示例:{"start_date":"%s","end_date":"%s"},location 使用用户指定的地点。日期存在歧义时先询问。
未提供查询地点且历史中也没有时,先询问,不要猜测。收到预报后直接根据结果回答,不重复查询相同日期;无法获取时如实说明,不用当前天气代替目标日期预报。`,
now.Format(time.DateOnly), weekdays[now.Weekday()], now.AddDate(0, 0, 1).Format(time.DateOnly),
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly),
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly))
}
+45
View File
@@ -0,0 +1,45 @@
package agent
import (
"context"
"strings"
"testing"
"time"
"github.com/cloudwego/eino/adk"
"github.com/cloudwego/eino/schema"
)
func TestTimedInstruction(t *testing.T) {
// 同一进程跨越北京时间午夜后,日期与星期都必须更新。
before := time.Date(2026, 11, 18, 15, 59, 0, 0, time.UTC)
after := before.Add(time.Minute)
for _, tt := range []struct {
now time.Time
date string
day string
}{
{before, "2026-11-18", "星期三"},
{after, "2026-11-19", "星期四"},
} {
prompt := timedInstruction("原有指令", tt.now)
for _, expected := range []string{"原有指令", tt.date, tt.day, "Asia/Shanghai", "YYYY-MM-DD", "先询问", `"start_date":"2026-11-21","end_date":"2026-11-22"`} {
if !strings.Contains(prompt, expected) {
t.Errorf("系统消息缺少 %q", expected)
}
}
}
}
func TestGenModelInput(t *testing.T) {
user := schema.UserMessage("明天北京的天气")
input := &adk.AgentInput{Messages: []adk.Message{user}}
messages, err := genModelInput(context.Background(), "原有指令", input)
if err != nil || len(messages) != 2 || messages[0].Role != schema.System || messages[1] != user || len(input.Messages) != 1 {
t.Fatalf("模型输入 = %+v,错误 = %v", messages, err)
}
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
if !strings.Contains(messages[0].Content, date) {
t.Fatal("系统消息缺少当前日期")
}
}
+96
View File
@@ -0,0 +1,96 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"example.com/ueino/adk/internal/config"
"example.com/ueino/pkg/model"
)
func TestChatForecast(t *testing.T) {
for _, days := range []int{1, 2} {
t.Run(fmt.Sprintf("预报%d天", days), func(t *testing.T) {
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
start, end := today.AddDate(0, 0, 1).Format(time.DateOnly), today.AddDate(0, 0, days).Format(time.DateOnly)
previous := http.DefaultTransport
var weatherCalls atomic.Int32
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
var response any
switch r.URL.Host {
case "geocoding-api.open-meteo.com":
if r.URL.Query().Get("name") != "北京" {
t.Errorf("城市提取错误: %s", r.URL)
}
response = map[string]any{"results": []map[string]any{{"name": "北京", "country": "中国", "latitude": 39.9, "longitude": 116.4}}}
case "api.open-meteo.com":
if r.URL.Query().Get("start_date") != start || r.URL.Query().Get("end_date") != end {
t.Errorf("日期传递错误: %s", r.URL)
}
dates, codes := []string{}, []int{}
maxTemps, minTemps, rain := []int{}, []int{}, []int{}
for i := 1; i <= days; i++ {
dates = append(dates, today.AddDate(0, 0, i).Format(time.DateOnly))
codes, maxTemps, minTemps, rain = append(codes, 61), append(maxTemps, 18), append(minTemps, 8), append(rain, 70)
}
response = map[string]any{"daily": map[string]any{"time": dates, "weather_code": codes, "temperature_2m_max": maxTemps, "temperature_2m_min": minTemps, "precipitation_probability_max": rain}}
default:
return previous.RoundTrip(r)
}
weatherCalls.Add(1)
data, _ := json.Marshal(response)
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header), Request: r}, nil
})
t.Cleanup(func() { http.DefaultTransport = previous })
var modelCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request model.ChatCompletionRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Error(err)
}
if !strings.Contains(request.Messages[0].Content.(string), today.Format(time.DateOnly)) || !strings.Contains(request.Messages[0].Content.(string), "Asia/Shanghai") {
t.Error("系统消息缺少当前日期或时区")
}
properties := request.Tools[0].Function.Parameters["properties"].(map[string]any)
if properties["start_date"] == nil || properties["end_date"] == nil {
t.Error("Eino 工具定义缺少日期参数")
}
if modelCalls.Add(1) == 1 {
arguments, _ := json.Marshal(model.WeatherArguments{Location: "北京", StartDate: start, EndDate: end})
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "forecast-1", Type: "function", Function: model.ToolFunction{Name: "get_weather", Arguments: string(arguments)}}})
return
}
last := request.Messages[len(request.Messages)-1]
var forecast model.WeatherForecast
if last.Role != "tool" || last.ToolCallID != "forecast-1" {
t.Errorf("工具消息不正确: %+v", last)
} else if err := json.Unmarshal([]byte(last.Content.(string)), &forecast); err != nil || len(forecast.Days) != days || forecast.Days[0].Date != start || forecast.Days[0].Condition != "小雨" {
t.Errorf("预报没有正确回传: %+v,%v", forecast, err)
}
writeCompletion(w, request.Stream, start+" 北京小雨,记得带伞。", nil)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
chat, err := New(ctx, config.Config{Chat: config.ModelConfig{BaseURL: server.URL, Model: "test-model"}, MaxToken: 4096})
if err != nil {
t.Fatal(err)
}
var output strings.Builder
if err := chat.Chat(ctx, "查询北京的预报", func(s string) { output.WriteString(s) }, nil, nil); err != nil {
t.Fatal(err)
}
if modelCalls.Load() != 2 || weatherCalls.Load() != 2 || !strings.Contains(output.String(), start) || !strings.Contains(output.String(), "小雨") {
t.Fatalf("模型调用=%d,天气请求=%d,输出=%q", modelCalls.Load(), weatherCalls.Load(), output.String())
}
})
}
}
+2 -2
View File
@@ -52,7 +52,7 @@ description: 面向传统开发者,结合终端聊天、天气、生图、人
用户给出目标;具体调用哪些能力、如何整理任务,由模型参与决定。
<!--
讲者备注:这是期望的执行路径,不是对模型每次行为的保证。天气工具查询当前天气,不提供未来多日预报。若主模型只回答文字而未委托,应检查模型能力、工具描述和提示词。
讲者备注:这是期望的执行路径,不是对模型每次行为的保证。天气工具支持当前天气和指定日期预报;日期预报使用 Open-Meteo,支持北京时间今天起 16 天,超出范围需如实说明。若主模型只回答文字而未委托,应检查模型能力、工具描述和提示词。
-->
---
@@ -577,7 +577,7 @@ go run adk/main.go
观察:加载历史 → 补齐地点 → 调用天气工具 → 根据结果回答。
<!--
讲者备注:需要模型服务和 wttr.in 可用。模型可能确认地点或不调用工具,这时用“查询成都当前天气”作为明确输入。不要把历史能力全部归功于 ADK:项目每轮先从自己的 memory 加载消息,再交给 Runner。legacy 基础聊天入口是 go run ./legacy,可选展示一次工具循环,不必现场逐行对照。
讲者备注:需要模型服务和 wttr.in 可用。模型可能确认地点或不调用工具,这时用“查询成都当前天气”作为明确输入。不要把历史能力全部归功于 ADK:项目每轮先从自己的 memory 加载消息,再交给 Runner;系统消息动态提供当前日期、星期和时区。可补充演示“明天北京的天气”,观察日期提取与预报查询。legacy 基础聊天入口是 go run ./legacy,可选展示一次工具循环,不必现场逐行对照。
-->
---
-5
View File
@@ -12,8 +12,3 @@ type ToolFunctionDefinition struct {
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
// WeatherArguments 指定要查询当前天气的地点。
type WeatherArguments struct {
Location string `json:"location"`
}
+45
View File
@@ -0,0 +1,45 @@
package model
// WeatherArguments 指定地点,以及可选的预报日期范围。
type WeatherArguments struct {
Location string `json:"location"`
StartDate string `json:"start_date,omitempty"`
EndDate string `json:"end_date,omitempty"`
}
// WeatherLocations 是 Open-Meteo 的城市搜索结果,使用首个匹配项。
type WeatherLocations struct {
Results []struct {
Name string `json:"name"`
Admin1 string `json:"admin1"`
Country string `json:"country"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
} `json:"results"`
}
// WeatherDailyResponse 只保留本示例使用的逐日预报字段。
type WeatherDailyResponse struct {
Daily struct {
Dates []string `json:"time"`
Codes []*int `json:"weather_code"`
MaxTemps []*float64 `json:"temperature_2m_max"`
MinTemps []*float64 `json:"temperature_2m_min"`
RainChances []*float64 `json:"precipitation_probability_max"`
} `json:"daily"`
}
// WeatherForecast 向模型返回实际匹配地点和指定日期的预报。
type WeatherForecast struct {
Location string `json:"location"`
Timezone string `json:"timezone"`
Days []WeatherDay `json:"days"`
}
type WeatherDay struct {
Date string `json:"date"`
Condition string `json:"condition"`
MinTemperatureC float64 `json:"min_temperature_c"`
MaxTemperatureC float64 `json:"max_temperature_c"`
PrecipitationChancePct float64 `json:"precipitation_probability_max_pct"`
}
+20 -6
View File
@@ -13,14 +13,20 @@ import (
"example.com/ueino/pkg/model"
)
// Weather 通过 wttr.in 查询当前天气。
// Weather 查询 wttr.in 当前天气或 Open-Meteo 日期预报。
type Weather struct {
client *http.Client
baseURL string
client *http.Client
baseURL string
geocodingURL string
forecastURL string
}
func NewWeather() *Weather {
return &Weather{client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in"}
return &Weather{
client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in",
geocodingURL: "https://geocoding-api.open-meteo.com/v1/search",
forecastURL: "https://api.open-meteo.com/v1/forecast",
}
}
func (w *Weather) Definition() model.ToolDefinition {
@@ -28,11 +34,13 @@ func (w *Weather) Definition() model.ToolDefinition {
Type: "function",
Function: model.ToolFunctionDefinition{
Name: "get_weather",
Description: "查询指定地点的当前天气,不提供未来预报。地点可从当前对话中获取;如果未提供地点,先询问用户,不要猜测。",
Description: "查询指定地点天气。不传日期查询当前天气;传 start_date 查询该日,end_date 可指定结束日期(含)。预报支持北京时间今天起共16天,不支持历史天气。日期必须是 YYYY-MM-DD,明天、本周末等需根据系统当前日期换算。地点可从对话获取,缺少地点时先询问,不要猜测。",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
"start_date": map[string]string{"type": "string", "description": "预报开始日期,YYYY-MM-DD;不传则查当前天气"},
"end_date": map[string]string{"type": "string", "description": "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
},
"required": []string{"location"},
},
@@ -49,6 +57,12 @@ func (w *Weather) Execute(ctx context.Context, arguments string) (string, error)
if location == "" {
return "", fmt.Errorf("请提供要查询的地点")
}
args.Location = location
args.StartDate = strings.TrimSpace(args.StartDate)
args.EndDate = strings.TrimSpace(args.EndDate)
if args.StartDate != "" || args.EndDate != "" {
return w.forecast(ctx, args)
}
query := url.Values{"format": {"3"}, "lang": {"zh"}, "m": {""}}
endpoint := w.baseURL + "/" + url.PathEscape(location) + "?" + query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+3 -1
View File
@@ -14,7 +14,9 @@ func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
Name: definition.Name,
Desc: definition.Description,
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
"start_date": {Type: schema.String, Desc: "预报开始日期,YYYY-MM-DD;不传则查当前天气"},
"end_date": {Type: schema.String, Desc: "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
}),
}, nil
}
+144
View File
@@ -0,0 +1,144 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"
"example.com/ueino/pkg/model"
)
func forecastDates(args model.WeatherArguments, now time.Time) (time.Time, time.Time, error) {
zone := time.FixedZone("Asia/Shanghai", 8*60*60)
start, err := time.ParseInLocation(time.DateOnly, args.StartDate, zone)
if err != nil {
return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期")
}
end := start
if args.EndDate != "" {
end, err = time.ParseInLocation(time.DateOnly, args.EndDate, zone)
if err != nil {
return time.Time{}, time.Time{}, fmt.Errorf("end_date 必须是 YYYY-MM-DD 格式的有效日期")
}
}
today, _ := time.ParseInLocation(time.DateOnly, now.In(zone).Format(time.DateOnly), zone)
last := today.AddDate(0, 0, 15)
if end.Before(start) {
return time.Time{}, time.Time{}, fmt.Errorf("结束日期不能早于开始日期")
}
if start.Before(today) || end.After(last) {
return time.Time{}, time.Time{}, fmt.Errorf("预报仅支持 %s 至 %s,不支持历史或更远日期", today.Format(time.DateOnly), last.Format(time.DateOnly))
}
return start, end, nil
}
func (w *Weather) forecast(ctx context.Context, args model.WeatherArguments) (string, error) {
start, end, err := forecastDates(args, time.Now())
if err != nil {
return "", err
}
search := url.Values{"name": {args.Location}, "count": {"1"}, "language": {"zh"}, "format": {"json"}}
var locations model.WeatherLocations
if err := w.getWeatherJSON(ctx, w.geocodingURL+"?"+search.Encode(), &locations); err != nil {
return "", err
}
if len(locations.Results) == 0 {
return "", fmt.Errorf("未找到地点 %q,请提供明确的城市名称", args.Location)
}
location := locations.Results[0]
query := url.Values{
"latitude": {strconv.FormatFloat(location.Latitude, 'f', -1, 64)},
"longitude": {strconv.FormatFloat(location.Longitude, 'f', -1, 64)},
"start_date": {start.Format(time.DateOnly)}, "end_date": {end.Format(time.DateOnly)},
"timezone": {"Asia/Shanghai"},
"daily": {"weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"},
}
var response model.WeatherDailyResponse
if err := w.getWeatherJSON(ctx, w.forecastURL+"?"+query.Encode(), &response); err != nil {
return "", err
}
result := model.WeatherForecast{
Location: strings.TrimSpace(location.Name + " " + location.Admin1 + " " + location.Country),
Timezone: "Asia/Shanghai",
}
daily := response.Daily
for date := start; !date.After(end); date = date.AddDate(0, 0, 1) {
day := date.Format(time.DateOnly)
index := slices.Index(daily.Dates, day)
if index < 0 || index >= len(daily.Codes) || index >= len(daily.MaxTemps) || index >= len(daily.MinTemps) || index >= len(daily.RainChances) {
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
}
if daily.Codes[index] == nil || daily.MaxTemps[index] == nil || daily.MinTemps[index] == nil || daily.RainChances[index] == nil {
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
}
result.Days = append(result.Days, model.WeatherDay{
Date: day, Condition: weatherCondition(*daily.Codes[index]),
MinTemperatureC: *daily.MinTemps[index], MaxTemperatureC: *daily.MaxTemps[index],
PrecipitationChancePct: *daily.RainChances[index],
})
}
data, err := json.Marshal(result)
return string(data), err
}
func (w *Weather) getWeatherJSON(ctx context.Context, endpoint string, result any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
resp, err := w.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("天气接口返回 %s", resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return fmt.Errorf("解析天气接口响应失败: %w", err)
}
return nil
}
func weatherCondition(code int) string {
switch code {
case 0:
return "晴"
case 1:
return "大部晴朗"
case 2:
return "多云"
case 3:
return "阴"
case 45, 48:
return "雾"
case 51, 53, 55:
return "毛毛雨"
case 56, 57, 66, 67:
return "冻雨"
case 61:
return "小雨"
case 63:
return "中雨"
case 65:
return "大雨"
case 71, 73, 75, 77:
return "雪"
case 80, 81, 82:
return "阵雨"
case 85, 86:
return "阵雪"
case 95:
return "雷暴"
case 96, 99:
return "雷暴伴冰雹"
default:
return fmt.Sprintf("未知天气(WMO %d)", code)
}
}
+201
View File
@@ -0,0 +1,201 @@
package tool
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"example.com/ueino/pkg/model"
)
func TestForecastDates(t *testing.T) {
// UTC 尚未跨年,北京时间已是下一年的第一天。
now := time.Date(2026, 12, 31, 16, 30, 0, 0, time.UTC)
for _, tt := range []struct {
name, start, end, wantEnd string
invalid bool
}{
{name: "单日", start: "2027-01-02", wantEnd: "2027-01-02"},
{name: "整个窗口", start: "2027-01-01", end: "2027-01-16", wantEnd: "2027-01-16"},
{name: "缺少开始日期", end: "2027-01-02", invalid: true},
{name: "相对日期", start: "明天", invalid: true},
{name: "无效日期", start: "2027-02-30", invalid: true},
{name: "无效结束", start: "2027-01-02", end: "周末", invalid: true},
{name: "过去日期", start: "2026-12-31", invalid: true},
{name: "超出窗口", start: "2027-01-16", end: "2027-01-17", invalid: true},
{name: "反向范围", start: "2027-01-02", end: "2027-01-01", invalid: true},
} {
t.Run(tt.name, func(t *testing.T) {
start, end, err := forecastDates(model.WeatherArguments{StartDate: tt.start, EndDate: tt.end}, now)
if tt.invalid {
if err == nil {
t.Fatal("预期参数错误")
}
return
}
if err != nil || start.Format(time.DateOnly) != tt.start || end.Format(time.DateOnly) != tt.wantEnd {
t.Fatalf("日期范围 = %s 至 %s,错误 = %v", start, end, err)
}
})
}
}
func TestWeatherForecast(t *testing.T) {
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
for _, days := range []int{1, 2} {
t.Run(fmt.Sprintf("%d天", days), func(t *testing.T) {
start := today.AddDate(0, 0, 1).Format(time.DateOnly)
end := today.AddDate(0, 0, days).Format(time.DateOnly)
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != http.MethodGet {
t.Error("应使用 GET")
}
query := r.URL.Query()
if r.URL.Path == "/search" {
if query.Get("name") != "北京 海淀/?&" || query.Get("count") != "1" || query.Get("language") != "zh" {
t.Errorf("地点查询编码错误: %v", query)
}
fmt.Fprint(w, `{"results":[{"name":"北京","admin1":"北京市","country":"中国","latitude":39.9,"longitude":116.4}]}`)
return
}
if r.URL.Path != "/forecast" || query.Get("latitude") != "39.9" || query.Get("longitude") != "116.4" || query.Get("start_date") != start || query.Get("end_date") != end || query.Get("timezone") != "Asia/Shanghai" || query.Get("daily") != "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max" {
t.Errorf("预报请求错误: %s", r.URL)
}
// 返回乱序日期及额外日期,必须按请求范围提取排序。
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
"time": []string{today.AddDate(0, 0, 2).Format(time.DateOnly), start, today.Format(time.DateOnly)},
"weather_code": []int{61, 0, 3}, "temperature_2m_max": []float64{12, 18, 15},
"temperature_2m_min": []float64{3, 8, 6}, "precipitation_probability_max": []float64{80, 0, 30},
}})
}))
defer server.Close()
weather := NewWeather()
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
args := model.WeatherArguments{Location: " 北京 海淀/?& ", StartDate: start}
if days == 2 {
args.EndDate = end
}
arguments, _ := json.Marshal(args)
result, err := weather.Execute(context.Background(), string(arguments))
if err != nil {
t.Fatal(err)
}
var forecast model.WeatherForecast
if err := json.Unmarshal([]byte(result), &forecast); err != nil {
t.Fatal(err)
}
if calls != 2 || forecast.Location != "北京 北京市 中国" || forecast.Timezone != "Asia/Shanghai" || len(forecast.Days) != days {
t.Fatalf("预报结果 = %+v,调用次数 = %d", forecast, calls)
}
first := forecast.Days[0]
if first.Date != start || first.Condition != "晴" || first.MinTemperatureC != 8 || first.MaxTemperatureC != 18 || first.PrecipitationChancePct != 0 {
t.Fatalf("单日数据错误: %+v", first)
}
if days == 2 && (forecast.Days[1].Date != end || forecast.Days[1].Condition != "小雨") {
t.Fatalf("日期顺序错误: %+v", forecast.Days)
}
})
}
}
func TestForecastInvalidArguments(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ }))
defer server.Close()
weather := NewWeather()
weather.baseURL, weather.geocodingURL = server.URL, server.URL
for _, args := range []string{
`{"location":"北京","end_date":"2026-11-20"}`,
`{"location":"北京","start_date":"明天"}`,
`{"location":"北京","start_date":"2000-01-01"}`,
`{"location":"北京","start_date":"2999-01-01"}`,
`{"start_date":"2026-11-19"}`,
`{"location":"北京","start_date":123}`,
} {
if _, err := weather.Execute(context.Background(), args); err == nil {
t.Errorf("参数 %s 应返回错误", args)
}
}
if calls != 0 {
t.Fatalf("无效参数请求了接口 %d 次", calls)
}
}
func TestForecastResponseErrors(t *testing.T) {
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
for _, mode := range []string{"查无城市", "搜索失败", "预报失败", "错误JSON", "缺少日期", "缺少字段", "字段为空"} {
t.Run(mode, func(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.URL.Path == "/search" {
switch mode {
case "查无城市":
fmt.Fprint(w, `{}`)
case "搜索失败":
w.WriteHeader(http.StatusServiceUnavailable)
case "错误JSON":
fmt.Fprint(w, "{")
default:
fmt.Fprint(w, `{"results":[{"name":"北京","latitude":39.9,"longitude":116.4}]}`)
}
return
}
if mode == "预报失败" {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
daily := map[string]any{
"time": []string{date}, "weather_code": []int{0},
"temperature_2m_max": []float64{18}, "temperature_2m_min": []float64{8},
"precipitation_probability_max": []float64{0},
}
switch mode {
case "缺少日期":
daily["time"] = []string{}
case "缺少字段":
delete(daily, "temperature_2m_min")
case "字段为空":
daily["weather_code"] = []any{nil}
}
json.NewEncoder(w).Encode(map[string]any{"daily": daily})
}))
defer server.Close()
weather := NewWeather()
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
args := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
if _, err := weather.Execute(context.Background(), args); err == nil {
t.Fatal("接口异常应返回错误")
}
if (mode == "查无城市" || mode == "搜索失败" || mode == "错误JSON") && calls != 1 {
t.Fatal("城市查询失败后不应请求预报")
}
})
}
}
func TestForecastCancellationAndTimeout(t *testing.T) {
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
arguments := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
defer server.Close()
weather := NewWeather()
weather.geocodingURL = server.URL
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := weather.Execute(ctx, arguments); !errors.Is(err, context.Canceled) {
t.Fatalf("取消错误 = %v", err)
}
weather.client.Timeout = 20 * time.Millisecond
if _, err := weather.Execute(context.Background(), arguments); err == nil || !strings.Contains(err.Error(), "Client.Timeout") {
t.Fatalf("超时错误 = %v", err)
}
}