package api import ( "context" "encoding/json" "os" "strconv" "testing" "time" accountdomain "git.ipao.vip/rogee/creator-hub/internal/account" "git.ipao.vip/rogee/creator-hub/internal/creator" hub "git.ipao.vip/rogee/creator-hub/internal/environment" ) func TestPersistDouyinMessageHistory(t *testing.T) { databaseURL := os.Getenv("CREATORHUB_POSTGRES_TEST_URL") if databaseURL == "" { t.Skip("set CREATORHUB_POSTGRES_TEST_URL to run history coverage") } ctx := context.Background() databaseURL = isolatedControlPlaneDatabaseURL(t, databaseURL) phaseAStore, err := accountdomain.Open(ctx, databaseURL) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = phaseAStore.Close() }) hubStore, err := hub.Open(ctx, databaseURL) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = hubStore.Close() }) store, err := creator.Open(ctx, databaseURL) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = store.Close() }) credentials := &testCredentialBridge{values: make(map[string]string)} if err := phaseAStore.CreateAccount(ctx, accountdomain.Account{ ID: "history-account", Name: "History Account", Platform: creator.PlatformDouyin, PlatformAccountKey: "history-platform", Tags: []string{}, Cookies: "", CredentialReference: accountdomain.CredentialReference{ID: "history-credential", Provider: "os_keyring"}, CredentialKey: "creatorhub/history-account/cookies", }, credentials); err != nil { t.Fatal(err) } if err := store.EnsureAccountProfile(ctx, "history-account"); err != nil { t.Fatal(err) } conversation := creator.Conversation{Platform: creator.PlatformDouyin, AccountID: "history-account", PeerUID: "peer", PeerName: "Peer"} stamp := time.Now().UTC().UnixMilli() messages := []douyinHistoryMessage{ {ServerID: "history-inbound", SenderUID: "peer", Content: json.RawMessage(`{"text":"inbound"}`), CreatedAt: strconv.FormatInt(stamp, 10)}, {ServerID: "history-outbound", SenderUID: "history-account", Content: json.RawMessage(`{"text":"outbound"}`), CreatedAt: strconv.FormatInt(stamp+1, 10)}, } inserted, err := persistDouyinMessageHistory(ctx, store, conversation, "history-account", messages) if err != nil || inserted != 2 { t.Fatalf("persist history: inserted=%d err=%v", inserted, err) } inserted, err = persistDouyinMessageHistory(ctx, store, conversation, "history-account", messages) if err != nil || inserted != 0 { t.Fatalf("deduplicate history: inserted=%d err=%v", inserted, err) } badContent := []douyinHistoryMessage{{ServerID: "bad", SenderUID: "peer", Content: json.RawMessage(`{"text":`), CreatedAt: strconv.FormatInt(stamp, 10)}} if _, err := persistDouyinMessageHistory(ctx, store, conversation, "history-account", badContent); err != creator.ErrInvalid { t.Fatalf("bad history content: %v", err) } }