Files
hunjing/mcp/web-search/internal/providers/tavily_test.go
T
2026-08-21 16:00:13 +08:00

72 lines
1.8 KiB
Go

package providers
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/chenxin/hunjing/mcp/web-search/internal/models"
)
func TestTavilyProvider_Search_Success(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/search" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{
"query": "test",
"results": [
{"title": "Result 1", "url": "https://example.com/1", "content": "Content 1", "score": 0.95}
]
}`))
}))
defer ts.Close()
p := &TavilyProvider{
client: ts.Client(),
apiBase: ts.URL,
maxResults: 10,
}
result, err := p.Search(context.Background(), "test-key", &models.SearchRequest{Query: "test"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.TotalCount != 1 {
t.Fatalf("expected 1 result, got %d", result.TotalCount)
}
if result.Results[0].Title != "Result 1" {
t.Errorf("expected 'Result 1', got '%s'", result.Results[0].Title)
}
}
func TestTavilyProvider_Search_HTTPError(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error": "invalid api key"}`))
}))
defer ts.Close()
p := &TavilyProvider{
client: ts.Client(),
apiBase: ts.URL,
maxResults: 10,
}
_, err := p.Search(context.Background(), "bad-key", &models.SearchRequest{Query: "test"})
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestTavilyProvider_Name(t *testing.T) {
p := NewTavilyProvider(5*time.Second, 10)
if p.Name() != models.ProviderTavily {
t.Errorf("expected tavily, got %s", p.Name())
}
}