openai_chatgpt_headers_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package service
  2. import (
  3. "context"
  4. "net/http"
  5. "testing"
  6. "github.com/stretchr/testify/require"
  7. )
  8. // stubChatGPTHeadersRepo 是最小化 AccountRepository stub,仅实现 GetByID,
  9. // 供 TestResolveAndSetOpenAIChatGPTAccountHeaders 使用。
  10. type stubChatGPTHeadersRepo struct {
  11. AccountRepository
  12. byID map[int64]*Account
  13. }
  14. func (r *stubChatGPTHeadersRepo) GetByID(_ context.Context, id int64) (*Account, error) {
  15. return r.byID[id], nil
  16. }
  17. func TestResolveAndSetOpenAIChatGPTAccountHeaders(t *testing.T) {
  18. ctx := context.Background()
  19. pid := int64(100)
  20. parentCreds := map[string]any{"chatgpt_account_id": "org-parent"}
  21. parent := &Account{
  22. ID: 100,
  23. Platform: PlatformOpenAI,
  24. Type: AccountTypeOAuth,
  25. Status: StatusActive,
  26. Credentials: parentCreds,
  27. }
  28. repo := &stubChatGPTHeadersRepo{byID: map[int64]*Account{100: parent}}
  29. t.Run("shadow_resolves_to_parent_org", func(t *testing.T) {
  30. shadow := &Account{
  31. ID: 200,
  32. ParentAccountID: &pid,
  33. Platform: PlatformOpenAI,
  34. Type: AccountTypeOAuth,
  35. }
  36. headers := make(http.Header)
  37. err := resolveAndSetOpenAIChatGPTAccountHeaders(ctx, repo, headers, shadow)
  38. require.NoError(t, err)
  39. require.Equal(t, "org-parent", headers.Get("chatgpt-account-id"),
  40. "影子账号应透传母账号的 chatgpt-account-id")
  41. })
  42. t.Run("normal_account_passthrough", func(t *testing.T) {
  43. ownCreds := map[string]any{"chatgpt_account_id": "org-own"}
  44. normal := &Account{
  45. ID: 300,
  46. Platform: PlatformOpenAI,
  47. Type: AccountTypeOAuth,
  48. Credentials: ownCreds,
  49. }
  50. headers := make(http.Header)
  51. err := resolveAndSetOpenAIChatGPTAccountHeaders(ctx, repo, headers, normal)
  52. require.NoError(t, err)
  53. require.Equal(t, "org-own", headers.Get("chatgpt-account-id"),
  54. "普通账号应透传自身的 chatgpt-account-id")
  55. })
  56. }