package oss import ( "bytes" "encoding/json" "io" "net/http" "os" "testing" "time" aliyunoss "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/tinode/chat/server/media" ) func TestLiveAliyunOSSUploadPublic(t *testing.T) { endpoint := os.Getenv("LIVE_OSS_ENDPOINT") bucket := os.Getenv("LIVE_OSS_BUCKET") accessKeyID := os.Getenv("LIVE_OSS_ACCESS_KEY_ID") accessKeySecret := os.Getenv("LIVE_OSS_ACCESS_KEY_SECRET") if endpoint == "" || bucket == "" || accessKeyID == "" || accessKeySecret == "" { t.Skip("LIVE_OSS_* env is not configured") } conf, err := json.Marshal(ossConfig{ Endpoint: endpoint, BucketName: bucket, AccessKeyID: accessKeyID, AccessKeySecret: accessKeySecret, PresignTTL: 60, CacheControl: "no-cache", CorsOrigins: []string{"*"}, }) if err != nil { t.Fatal(err) } handler := &ossHandler{} if err = handler.Init(string(conf)); err != nil { t.Fatalf("oss init failed: %v", err) } body := []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'} file := &media.PublicFileDef{ ID: "codex-live-" + time.Now().UTC().Format("20060102150405"), Purpose: "codex_live", MimeType: "image/png", CreatedAt: time.Now().UTC(), } location, size, err := handler.UploadPublic(file, bytes.NewReader(body)) if err != nil { t.Fatalf("oss upload failed: %v", err) } defer func() { if err := handler.Delete([]string{file.Location}); err != nil { t.Logf("oss cleanup failed: %v", err) } }() if size != int64(len(body)) || location == "" || file.Location == "" || file.ETag == "" { t.Fatalf("unexpected upload result: location=%q file=%+v size=%d", location, file, size) } got, err := handler.bucket.GetObject(file.Location) if err != nil { t.Fatalf("oss get object failed: %v", err) } defer got.Close() downloaded, err := io.ReadAll(got) if err != nil { t.Fatalf("oss read object failed: %v", err) } if !bytes.Equal(downloaded, body) { t.Fatalf("oss downloaded bytes mismatch: got %x want %x", downloaded, body) } signedURL, err := handler.bucket.SignURL(file.Location, aliyunoss.HTTPGet, 60) if err != nil { t.Fatalf("oss sign url failed: %v", err) } resp, err := http.Get(signedURL) if err != nil { t.Fatalf("oss signed url get failed: %v", err) } resp.Body.Close() if resp.StatusCode >= http.StatusBadRequest { t.Fatalf("oss signed url get status=%d", resp.StatusCode) } }