Files
YMhut-box-C-/server/unified-management/internal/sources/sources_test.go
T
2026-06-26 20:17:48 +08:00

83 lines
2.3 KiB
Go

package sources
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"ymhut-box/server/unified-management/internal/config"
"ymhut-box/server/unified-management/internal/db"
)
func TestCheckOneTreatsRedirectToOKAsRedirected(t *testing.T) {
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer target.Close()
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusFound)
}))
defer redirector.Close()
cfg, store := testStore(t)
service := NewService(cfg, store)
item, err := store.UpsertSource(db.Source{
CategoryID: "test",
CategoryName: "Test",
SourceID: "redirect",
Name: "Redirect",
Method: "GET",
APIURL: redirector.URL,
TimeoutMS: 3000,
CheckIntervalSec: 300,
Enabled: true,
ClientVisible: true,
})
if err != nil {
t.Fatal(err)
}
if err := service.CheckOne(context.Background(), item); err != nil {
t.Fatal(err)
}
checked, err := store.GetSourceBySourceID("redirect")
if err != nil {
t.Fatal(err)
}
if checked.LastStatus != "redirected" {
t.Fatalf("LastStatus = %q, want redirected", checked.LastStatus)
}
if !strings.Contains(checked.LastError, `"redirected":true`) {
t.Fatalf("LastError does not contain redirect metadata: %s", checked.LastError)
}
if checked.ConsecutiveFailure != 0 {
t.Fatalf("ConsecutiveFailure = %d, want 0", checked.ConsecutiveFailure)
}
}
func testStore(t *testing.T) (*config.Config, *db.Store) {
t.Helper()
dir := t.TempDir()
cfg := &config.Config{
BaseDir: dir,
StorageDir: filepath.Join(dir, "storage"),
DataDir: filepath.Join(dir, "data"),
UpdatePublicDir: filepath.Join(dir, "data", "update", "public"),
DownloadsDir: filepath.Join(dir, "data", "update", "public", "downloads"),
BaseURL: "https://update.ymhut.cn",
Database: config.DatabaseConfig{
Provider: "sqlite",
SQLitePath: filepath.Join(dir, "storage", "unified.sqlite"),
HealthIntervalSec: 30,
},
}
store, err := db.Open(cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
return cfg, store
}