feat: initialize Eino examples and ADK applications
Include chat, weather, image, travel, streaming ASR and text examples, shared model initialization, documentation, and existing tests. Co-authored-by: TRAE CLI <traecli@bytedance.com>
This commit is contained in:
commit
81deca8c8e
75 files changed
+7048
No files matched your search
@@ -0,0 +1,47 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
"example.com/ueino/pkg/provider"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// Image 根据完整提示词调用图片接口并保存结果。
|
||||
type Image struct {
|
||||
client *provider.Image
|
||||
}
|
||||
|
||||
func NewImage(client *provider.Image) *Image { return &Image{client: client} }
|
||||
|
||||
func (i *Image) Info(context.Context) (*schema.ToolInfo, error) {
|
||||
return &schema.ToolInfo{
|
||||
Name: "generate_image",
|
||||
Desc: "根据完整的创作提示词生成一张图片,保存到本地并返回实际路径。",
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"prompt": {Type: schema.String, Required: true, Desc: "包含主体、构图、风格及用户约束的完整创作提示词"},
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Image) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
var args model.ImageArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
return "", fmt.Errorf("生图参数无效: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(args.Prompt) == "" {
|
||||
return "", fmt.Errorf("生图提示词不能为空")
|
||||
}
|
||||
result, err := i.client.Generate(ctx, args.Prompt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
return string(data), err
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImageArguments(t *testing.T) {
|
||||
image := NewImage(nil)
|
||||
for _, arguments := range []string{`{`, `{}`, `{"prompt":" "}`} {
|
||||
if _, err := image.InvokableRun(context.Background(), arguments); err == nil {
|
||||
t.Fatalf("应拒绝无效参数: %s", arguments)
|
||||
}
|
||||
}
|
||||
info, err := image.Info(context.Background())
|
||||
if err != nil || info.Name != "generate_image" {
|
||||
t.Fatalf("工具定义 = %+v,错误 = %v", info, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Tool 提供模型可见的定义和实际执行方法。
|
||||
type Tool interface {
|
||||
Definition() model.ToolDefinition
|
||||
Execute(ctx context.Context, arguments string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Weather 通过 Open-Meteo 查询指定地点的逐日天气预报。
|
||||
type Weather struct {
|
||||
client *http.Client
|
||||
geocodingURL string
|
||||
forecastURL string
|
||||
}
|
||||
|
||||
func NewWeather() *Weather {
|
||||
return &Weather{
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
geocodingURL: "https://geocoding-api.open-meteo.com/v1/search",
|
||||
forecastURL: "https://api.open-meteo.com/v1/forecast",
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Weather) Definition() model.ToolDefinition {
|
||||
return model.ToolDefinition{
|
||||
Type: "function",
|
||||
Function: model.ToolFunctionDefinition{
|
||||
Name: "get_weather",
|
||||
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": "需要查询的城市或地点,例如北京、上海"},
|
||||
"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"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Weather) Execute(ctx context.Context, arguments string) (string, error) {
|
||||
var args model.WeatherArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
log.Printf("[D] unmarshal weather arguments failed, err = %v, raw = %s", err, arguments)
|
||||
return "", fmt.Errorf("天气参数无效: %w", err)
|
||||
}
|
||||
location := strings.TrimSpace(args.Location)
|
||||
if location == "" {
|
||||
return "", fmt.Errorf("请提供要查询的地点")
|
||||
}
|
||||
args.Location = location
|
||||
args.StartDate = strings.TrimSpace(args.StartDate)
|
||||
args.EndDate = strings.TrimSpace(args.EndDate)
|
||||
return w.forecast(ctx, args)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// Info 提供 Eino 所需的天气工具定义。
|
||||
func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
|
||||
definition := w.Definition().Function
|
||||
return &schema.ToolInfo{
|
||||
Name: definition.Name,
|
||||
Desc: definition.Description,
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"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
|
||||
}
|
||||
|
||||
// InvokableRun 直接复用天气查询,执行失败时把错误交回模型。
|
||||
func (w *Weather) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
result, err := w.Execute(ctx, arguments)
|
||||
if err != nil {
|
||||
return "工具执行失败: " + err.Error(), nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
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)
|
||||
now = now.In(zone)
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone)
|
||||
start := today
|
||||
var err error
|
||||
if args.StartDate != "" {
|
||||
start, err = time.ParseInLocation(time.DateOnly, args.StartDate, zone)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
}
|
||||
} else if args.EndDate != "" {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("end_date 不能单独提供,请同时提供 start_date")
|
||||
}
|
||||
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 格式的有效日期")
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
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: "默认今天", wantEnd: "2027-01-01"},
|
||||
{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
|
||||
}
|
||||
wantStart := tt.start
|
||||
if wantStart == "" {
|
||||
wantStart = "2027-01-01"
|
||||
}
|
||||
if err != nil || start.Format(time.DateOnly) != wantStart || 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.geocodingURL = server.URL
|
||||
for _, args := range []string{
|
||||
`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`,
|
||||
`{"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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
func TestWeatherDefaultsToToday(t *testing.T) {
|
||||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.URL.Path == "/search" {
|
||||
if r.URL.Query().Get("name") != "北京" {
|
||||
t.Errorf("地点参数错误: %s", r.URL)
|
||||
}
|
||||
fmt.Fprint(w, `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/forecast" || r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today {
|
||||
t.Errorf("未指定日期时应查询北京时间今天: %s", r.URL)
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
|
||||
"time": []string{today}, "weather_code": []int{0},
|
||||
"temperature_2m_min": []int{10}, "temperature_2m_max": []int{20},
|
||||
"precipitation_probability_max": []int{0},
|
||||
}})
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
|
||||
result, err := weather.Execute(context.Background(), `{"location":" 北京 "}`)
|
||||
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 || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" {
|
||||
t.Fatalf("默认查询结果不正确: %+v,请求次数=%d", forecast, calls)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user