56 lines
2.6 KiB
Go
56 lines
2.6 KiB
Go
package documentrefs
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestFreezePreservesUnchangedHTML(t *testing.T) {
|
|
body := `<!DOCTYPE html><!-- sample --><DIV class='A' title="&">日本語<code><img src="asset:image:example"></code><script>const x="asset:image:sample";</script><a HREF='/plain?a=1&b=2'>Link</a></DIV>`
|
|
got, refs, err := Freeze(context.Background(), []byte(body), "text/html; charset=utf-8", func(context.Context, string) (string, error) { t.Fatal("ordinary text resolved"); return "", nil })
|
|
if err != nil || string(got) != body || len(refs) != 0 {
|
|
t.Fatal("unchanged HTML lost bytes", err, string(got))
|
|
}
|
|
for _, mime := range []string{"text/plain", "application/octet-stream", "text/html-not-really"} {
|
|
got, refs, err := Freeze(context.Background(), []byte(`<img src="asset:image:sample">`), mime, nil)
|
|
if err != nil || len(refs) != 0 || string(got) != `<img src="asset:image:sample">` {
|
|
t.Fatal("non-HTML modified", mime, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestFreezeDeduplicatesAndFollowsProvenance(t *testing.T) {
|
|
hash := strings.Repeat("a", 64)
|
|
calls := 0
|
|
resolve := func(context.Context, string) (string, error) { calls++; return hash, nil }
|
|
body := `<img src="asset:image:a"><video poster="asset:image:a"></video><object data="asset:image:b"></object><a href="asset:image:a">a</a><embedded-object immutable-ref="asset:image:a"></embedded-object>`
|
|
got, refs, err := Freeze(context.Background(), []byte(body), "text/html", resolve)
|
|
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 {
|
|
t.Fatal("deduplication", err, refs, calls)
|
|
}
|
|
if !strings.Contains(string(got), `immutable-ref="sha256:`+hash+`"`) || !strings.Contains(string(got), `data-pageswiki-asset-src="asset:image:a"`) {
|
|
t.Fatal("provenance missing")
|
|
}
|
|
hash = strings.Repeat("b", 64)
|
|
calls = 0
|
|
updated, refs, err := Freeze(context.Background(), got, "text/html", resolve)
|
|
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 || strings.Contains(string(updated), strings.Repeat("a", 64)) {
|
|
t.Fatal("resave did not follow HEAD", err)
|
|
}
|
|
}
|
|
|
|
func TestFreezeRejectsMissingInvalidAndCanceled(t *testing.T) {
|
|
for _, hash := range []string{"", strings.Repeat("x", 64)} {
|
|
if _, _, err := Freeze(context.Background(), []byte(`<img src="asset:image:a">`), "text/html", func(context.Context, string) (string, error) { return hash, nil }); !errors.Is(err, ErrUnavailable) {
|
|
t.Fatal("invalid hash accepted", err)
|
|
}
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
if _, _, err := Freeze(ctx, []byte("text"), "text/plain", nil); !errors.Is(err, context.Canceled) {
|
|
t.Fatal("cancellation ignored", err)
|
|
}
|
|
}
|