80 lines
2.3 KiB
Go
80 lines
2.3 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"errors"
|
|
"testing"
|
|
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
|
)
|
|
|
|
type fakeImagePublisher struct {
|
|
published []byte
|
|
mime string
|
|
url string
|
|
err error
|
|
calls int
|
|
}
|
|
|
|
func (f *fakeImagePublisher) Publish(_ context.Context, data []byte, contentType string) (string, error) {
|
|
f.calls++
|
|
f.published = data
|
|
f.mime = contentType
|
|
return f.url, f.err
|
|
}
|
|
|
|
func TestDecodeImageDataURI(t *testing.T) {
|
|
raw := []byte("hello-image-bytes")
|
|
uri := "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)
|
|
|
|
decoded, err := decodeImageDataURI(uri)
|
|
if err != nil {
|
|
t.Fatalf("decodeImageDataURI: %v", err)
|
|
}
|
|
if string(decoded) != string(raw) {
|
|
t.Fatalf("decoded=%q, want %q", decoded, raw)
|
|
}
|
|
|
|
if _, err := decodeImageDataURI("data:image/png;base64"); err == nil {
|
|
t.Fatal("expected error for missing base64 payload")
|
|
}
|
|
if _, err := decodeImageDataURI("no comma at all"); err == nil {
|
|
t.Fatal("expected error for non-data URI")
|
|
}
|
|
}
|
|
|
|
func TestPublishQuestionImagePublishesDecodedBytes(t *testing.T) {
|
|
pub := &fakeImagePublisher{url: "https://weknora-api.example/i/001"}
|
|
raw := []byte{0x89, 0x50, 0x4e, 0x47}
|
|
image := core.ImageInput{
|
|
DataURI: "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw),
|
|
MIMEType: "image/png",
|
|
}
|
|
h := &Handler{imagePublisher: pub}
|
|
|
|
got := h.publishQuestionImage(context.Background(), image)
|
|
if got != "https://weknora-api.example/i/001" {
|
|
t.Fatalf("url=%q, want published", got)
|
|
}
|
|
if pub.calls != 1 || pub.mime != "image/png" || string(pub.published) != string(raw) {
|
|
t.Fatalf("publisher calls=%d mime=%q bytes=%q", pub.calls, pub.mime, pub.published)
|
|
}
|
|
}
|
|
|
|
func TestPublishQuestionImageFailsClosedWithoutURL(t *testing.T) {
|
|
h := &Handler{imagePublisher: nil}
|
|
if got := h.publishQuestionImage(context.Background(), core.ImageInput{}); got != "" {
|
|
t.Fatalf("expected empty URL without publisher, got %q", got)
|
|
}
|
|
|
|
pub := &fakeImagePublisher{err: errors.New("oss down")}
|
|
h2 := &Handler{imagePublisher: pub}
|
|
image := core.ImageInput{
|
|
DataURI: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("x")),
|
|
MIMEType: "image/png",
|
|
}
|
|
if got := h2.publishQuestionImage(context.Background(), image); got != "" {
|
|
t.Fatalf("expected empty URL on publish error, got %q", got)
|
|
}
|
|
} |