feat: publish outbound answer images to private OSS
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
package outboundimage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeFetcher struct {
|
||||
calls map[string]int
|
||||
fail map[string]bool
|
||||
}
|
||||
|
||||
func (f *fakeFetcher) Fetch(_ context.Context, ref string) ([]byte, string, error) {
|
||||
if f.calls == nil {
|
||||
f.calls = map[string]int{}
|
||||
}
|
||||
f.calls[ref]++
|
||||
if f.fail[ref] {
|
||||
return nil, "", errors.New("fetch failed")
|
||||
}
|
||||
return []byte("image:" + ref), "image/png", nil
|
||||
}
|
||||
|
||||
type fakePublisher struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *fakePublisher) Publish(_ context.Context, data []byte, contentType string) (string, error) {
|
||||
p.calls++
|
||||
if contentType != "image/png" || len(data) == 0 {
|
||||
return "", errors.New("bad image")
|
||||
}
|
||||
return "https://img.example/" + string(rune('0'+p.calls)) + ".png?sig=short", nil
|
||||
}
|
||||
|
||||
func TestRewriteMarkdownResourceImagesDeduplicatesAndPreservesOtherURLs(t *testing.T) {
|
||||
fetcher := &fakeFetcher{}
|
||||
publisher := &fakePublisher{}
|
||||
r := NewRewriter(fetcher, publisher, 5)
|
||||
input := "步骤一\n\n重复\n\n外部\n"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "resource://") {
|
||||
t.Fatalf("resource reference remained: %s", got)
|
||||
}
|
||||
if strings.Count(got, "https://img.example/1.png?sig=short") != 2 {
|
||||
t.Fatalf("deduplicated signed URL count mismatch: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "") {
|
||||
t.Fatalf("ordinary HTTPS image changed: %s", got)
|
||||
}
|
||||
if fetcher.calls["resource://AbCdEfGhIjKlMnOpQrStUv"] != 1 || publisher.calls != 1 {
|
||||
t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteMarkdownResourceImagesDropsFailuresAndImagesBeyondLimit(t *testing.T) {
|
||||
failed := "resource://FailedRefAbCdEfGhIjKlMn"
|
||||
fetcher := &fakeFetcher{fail: map[string]bool{failed: true}}
|
||||
publisher := &fakePublisher{}
|
||||
r := NewRewriter(fetcher, publisher, 3)
|
||||
input := "保留正文\n\n\n\n"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if !strings.Contains(got, "保留正文") {
|
||||
t.Fatalf("text was lost: %s", got)
|
||||
}
|
||||
if strings.Contains(got, "resource://") || strings.Contains(got, "坏图") || strings.Contains(got, "![三]") {
|
||||
t.Fatalf("broken or over-limit image remained: %s", got)
|
||||
}
|
||||
if publisher.calls != 2 {
|
||||
t.Fatalf("publisher calls=%d, want 2", publisher.calls)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user