You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

189 regels
5.7 KiB

  1. package router
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "os"
  6. "strings"
  7. "sync/atomic"
  8. "testing"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/constant"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/service"
  13. "github.com/QuantumNous/new-api/setting/ratio_setting"
  14. "github.com/gin-gonic/gin"
  15. "github.com/stretchr/testify/require"
  16. "gorm.io/gorm"
  17. "gorm.io/gorm/logger"
  18. )
  19. func setupTianyiYunSeedanceE2EDB(t *testing.T) *gorm.DB {
  20. t.Helper()
  21. oldDB := model.DB
  22. oldLOGDB := model.LOG_DB
  23. oldSQLitePath := common.SQLitePath
  24. oldMemoryCacheEnabled := common.MemoryCacheEnabled
  25. oldRedisEnabled := common.RedisEnabled
  26. oldIsMasterNode := common.IsMasterNode
  27. oldUsingSQLite := common.UsingSQLite
  28. oldUsingMySQL := common.UsingMySQL
  29. oldUsingPostgreSQL := common.UsingPostgreSQL
  30. oldSQLDSN, hadSQLDSN := os.LookupEnv("SQL_DSN")
  31. oldModelRatio := ratio_setting.ModelRatio2JSONString()
  32. oldGroupRatio := ratio_setting.GroupRatio2JSONString()
  33. common.SQLitePath = "file:" + strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()) + "?mode=memory&cache=shared"
  34. common.MemoryCacheEnabled = false
  35. common.RedisEnabled = false
  36. common.IsMasterNode = false
  37. common.UsingSQLite = false
  38. common.UsingMySQL = false
  39. common.UsingPostgreSQL = false
  40. require.NoError(t, os.Setenv("SQL_DSN", "local"))
  41. require.NoError(t, model.InitDB())
  42. require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(`{"cdance2.0-0611":0}`))
  43. require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1}`))
  44. service.InitHttpClient()
  45. model.DB = model.DB.Session(&gorm.Session{Logger: logger.Default.LogMode(logger.Silent)})
  46. model.LOG_DB = model.DB
  47. db := model.DB
  48. sqlDB, err := db.DB()
  49. require.NoError(t, err)
  50. sqlDB.SetMaxOpenConns(1)
  51. require.NoError(t, db.AutoMigrate(
  52. &model.User{},
  53. &model.Token{},
  54. &model.Channel{},
  55. &model.Ability{},
  56. &model.UserAssetChannel{},
  57. &model.Task{},
  58. &model.Log{},
  59. &model.SubscriptionPlan{},
  60. &model.SubscriptionOrder{},
  61. &model.UserSubscription{},
  62. &model.SubscriptionPreConsumeRecord{},
  63. ))
  64. t.Cleanup(func() {
  65. _ = sqlDB.Close()
  66. model.DB = oldDB
  67. model.LOG_DB = oldLOGDB
  68. common.SQLitePath = oldSQLitePath
  69. common.MemoryCacheEnabled = oldMemoryCacheEnabled
  70. common.RedisEnabled = oldRedisEnabled
  71. common.IsMasterNode = oldIsMasterNode
  72. common.UsingSQLite = oldUsingSQLite
  73. common.UsingMySQL = oldUsingMySQL
  74. common.UsingPostgreSQL = oldUsingPostgreSQL
  75. _ = ratio_setting.UpdateModelRatioByJSONString(oldModelRatio)
  76. _ = ratio_setting.UpdateGroupRatioByJSONString(oldGroupRatio)
  77. if hadSQLDSN {
  78. _ = os.Setenv("SQL_DSN", oldSQLDSN)
  79. } else {
  80. _ = os.Unsetenv("SQL_DSN")
  81. }
  82. })
  83. return db
  84. }
  85. func TestTianyiYunSeedanceSubmitE2EUsesBoundUserChannel(t *testing.T) {
  86. gin.SetMode(gin.TestMode)
  87. db := setupTianyiYunSeedanceE2EDB(t)
  88. var upstreamCalls int32
  89. var gotPath string
  90. var gotAuth string
  91. upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. atomic.AddInt32(&upstreamCalls, 1)
  93. gotPath = r.URL.Path
  94. gotAuth = r.Header.Get("Authorization")
  95. w.Header().Set("Content-Type", "application/json")
  96. _, _ = w.Write([]byte(`{"id":"task-upstream","status":"queued","model":"cdance2.0-0611"}`))
  97. }))
  98. t.Cleanup(upstream.Close)
  99. require.NoError(t, db.Create(&model.User{
  100. Id: 10,
  101. Username: "e2e-user",
  102. Status: common.UserStatusEnabled,
  103. Group: "default",
  104. Quota: 1000000,
  105. }).Error)
  106. require.NoError(t, db.Create(&model.Token{
  107. Id: 20,
  108. UserId: 10,
  109. Key: "e2etokenkey",
  110. Status: common.TokenStatusEnabled,
  111. Name: "e2e-token",
  112. ExpiredTime: -1,
  113. UnlimitedQuota: true,
  114. Group: "default",
  115. }).Error)
  116. priority := int64(1)
  117. weight := uint(10)
  118. autoBan := 1
  119. baseURL := upstream.URL
  120. require.NoError(t, db.Create(&model.Channel{
  121. Id: 30,
  122. Type: constant.ChannelTypeDoubaoVideoCompatibleTianyiYun,
  123. Key: "upstream-secret",
  124. Status: common.ChannelStatusEnabled,
  125. Name: "tianyiyun-e2e",
  126. Group: "default",
  127. Models: "cdance2.0-0611",
  128. BaseURL: &baseURL,
  129. Priority: &priority,
  130. Weight: &weight,
  131. AutoBan: &autoBan,
  132. CreatedTime: 30,
  133. }).Error)
  134. require.NoError(t, db.Create(&model.Ability{
  135. Group: "default",
  136. Model: "cdance2.0-0611",
  137. ChannelId: 30,
  138. Enabled: true,
  139. Priority: &priority,
  140. Weight: 10,
  141. }).Error)
  142. require.NoError(t, model.BindUserAssetChannel(10, constant.ChannelTypeDoubaoVideoCompatibleTianyiYun, "default", 30))
  143. r := gin.New()
  144. SetVideoRouter(r)
  145. body := `{
  146. "model":"cdance2.0-0611",
  147. "content":[{"type":"text","text":"e2e prompt"}],
  148. "ratio":"16:9",
  149. "duration":5,
  150. "watermark":false
  151. }`
  152. req := httptest.NewRequest(http.MethodPost, "/api/v3/contents/generations/tasks", strings.NewReader(body))
  153. req.Header.Set("Content-Type", "application/json")
  154. req.Header.Set("Authorization", "Bearer sk-e2etokenkey")
  155. w := httptest.NewRecorder()
  156. r.ServeHTTP(w, req)
  157. require.Equal(t, http.StatusOK, w.Code, w.Body.String())
  158. require.Equal(t, int32(1), atomic.LoadInt32(&upstreamCalls))
  159. require.Equal(t, "/v1/contents/generations/tasks", gotPath)
  160. require.Equal(t, "Bearer upstream-secret", gotAuth)
  161. require.Contains(t, w.Body.String(), `"id":"task_`)
  162. binding, err := model.GetUserAssetChannel(10, constant.ChannelTypeDoubaoVideoCompatibleTianyiYun, "default")
  163. require.NoError(t, err)
  164. require.NotNil(t, binding)
  165. require.Equal(t, 30, binding.ChannelId)
  166. var task model.Task
  167. require.NoError(t, db.Where("user_id = ? AND channel_id = ?", 10, 30).First(&task).Error)
  168. require.Equal(t, constant.TaskPlatform("60"), task.Platform)
  169. require.Equal(t, "task-upstream", task.PrivateData.UpstreamTaskID)
  170. require.Equal(t, "cdance2.0-0611", task.Properties.OriginModelName)
  171. }