github.com/evanw/esbuild@v0.21.4/internal/helpers/dataurl_test.go (about) 1 package helpers_test 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/evanw/esbuild/internal/helpers" 8 ) 9 10 func TestEncodeDataURL(t *testing.T) { 11 check := func(raw string, expected string) { 12 url, ok := helpers.EncodeStringAsPercentEscapedDataURL("text/plain", raw) 13 if !ok { 14 t.Fatalf("Failed to encode %q", raw) 15 } else if url != expected { 16 t.Fatalf("Got %q but expected %q", url, expected) 17 } 18 } 19 20 for i := 0; i <= 0xFF; i++ { 21 alwaysEscape := i == '\t' || i == '\r' || i == '\n' || i == '#' 22 trailingEscape := i <= 0x20 || i == '#' 23 24 if trailingEscape { 25 check(string(rune(i)), fmt.Sprintf("data:text/plain,%%%02X", i)) 26 check("foo"+string(rune(i)), fmt.Sprintf("data:text/plain,foo%%%02X", i)) 27 } else { 28 check(string(rune(i)), fmt.Sprintf("data:text/plain,%c", i)) 29 check("foo"+string(rune(i)), fmt.Sprintf("data:text/plain,foo%c", i)) 30 } 31 32 if alwaysEscape { 33 check(string(rune(i))+"foo", fmt.Sprintf("data:text/plain,%%%02Xfoo", i)) 34 } else { 35 check(string(rune(i))+"foo", fmt.Sprintf("data:text/plain,%cfoo", i)) 36 } 37 } 38 39 // Test leading vs. trailing 40 check(" \t ", "data:text/plain, %09%20") 41 check(" \n ", "data:text/plain, %0A%20") 42 check(" \r ", "data:text/plain, %0D%20") 43 check(" # ", "data:text/plain, %23%20") 44 check("\x08#\x08", "data:text/plain,\x08%23%08") 45 46 // Only "%" symbols that could form an escape need to be escaped 47 check("%, %3, %33, %333", "data:text/plain,%, %3, %2533, %25333") 48 }