Files
dobotai-platform/internal/outboundimage/publisher_test.go

91 lines
2.6 KiB
Go

package outboundimage
import (
"context"
"strings"
"testing"
)
type fakeObjectStore struct {
key string
data []byte
contentType string
}
func (s *fakeObjectStore) Put(_ context.Context, key string, data []byte, contentType string) error {
s.key = key
s.data = append([]byte(nil), data...)
s.contentType = contentType
return nil
}
func TestStableHashPublisherUsesDeterministicUUIDURLWithoutPresigning(t *testing.T) {
store := &fakeObjectStore{}
publisher, err := NewStableHashPublisher(
store,
"dobotai/im-images",
"https://weknora-api-test.dobot.cn/dingtalk/i",
)
if err != nil {
t.Fatal(err)
}
first, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg")
if err != nil {
t.Fatal(err)
}
firstKey := store.key
second, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg")
if err != nil {
t.Fatal(err)
}
if first != second || firstKey != store.key {
t.Fatalf("publish is not deterministic: url1=%q url2=%q key1=%q key2=%q", first, second, firstKey, store.key)
}
wantURLPrefix := "https://weknora-api-test.dobot.cn/dingtalk/i/"
if !strings.HasPrefix(first, wantURLPrefix) {
t.Fatalf("url=%q", first)
}
id := strings.TrimPrefix(first, wantURLPrefix)
if !stableImageIDRE.MatchString(id) {
t.Fatalf("stable image id=%q", id)
}
if store.key != "dobotai/im-images/"+id {
t.Fatalf("key=%q id=%q", store.key, id)
}
}
func TestStableHashPublisherRejectsUnsafeConfigurationAndNonImages(t *testing.T) {
store := &fakeObjectStore{}
for _, test := range []struct {
name string
store ObjectWriter
prefix string
baseURL string
}{
{name: "nil store", prefix: "dobotai/im-images", baseURL: "https://img.example/i"},
{name: "empty prefix", store: store, baseURL: "https://img.example/i"},
{name: "http base", store: store, prefix: "dobotai/im-images", baseURL: "http://img.example/i"},
{name: "query base", store: store, prefix: "dobotai/im-images", baseURL: "https://img.example/i?token=secret"},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := NewStableHashPublisher(test.store, test.prefix, test.baseURL); err == nil {
t.Fatal("expected configuration error")
}
})
}
publisher, err := NewStableHashPublisher(store, "dobotai/im-images", "https://img.example/i")
if err != nil {
t.Fatal(err)
}
if _, err := publisher.Publish(context.Background(), nil, "image/png"); err == nil {
t.Fatal("expected empty image error")
}
if _, err := publisher.Publish(context.Background(), []byte("text"), "text/plain"); err == nil {
t.Fatal("expected non-image error")
}
}