package imgbundler
import (
"bytes"
_ "embed"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"oss.terrastruct.com/cmdlog"
"oss.terrastruct.com/xos"
"oss.terrastruct.com/d2/lib/xmain"
)
//go:embed test_png.png
var testPNGFile []byte
type RoundTripFunc func(req *http.Request) *http.Response
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
func TestRegex(t *testing.T) {
urls := []string{
"https://icons.terrastruct.com/essentials/004-picture.svg",
"http://icons.terrastruct.com/essentials/004-picture.svg",
}
notURLs := []string{
"hi.png",
"./cat.png",
"/cat.png",
}
for _, href := range append(urls, notURLs...) {
str := fmt.Sprintf(``, href)
matches := imageRe.FindAllStringSubmatch(str, -1)
if len(matches) != 1 {
t.Fatalf("uri regex didn't match %s", str)
}
}
}
func TestInlineRemote(t *testing.T) {
svgURL := "https://icons.terrastruct.com/essentials/004-picture.svg"
pngURL := "https://cdn4.iconfinder.com/data/icons/smart-phones-technologies/512/android-phone.png"
sampleSVG := fmt.Sprintf(`
`, svgURL, pngURL)
transport = RoundTripFunc(func(req *http.Request) *http.Response {
if req.URL.String() != svgURL && req.URL.String() != pngURL {
t.Fatal(req.URL.String())
}
var body string
switch req.URL.String() {
case svgURL:
body = `\r\n\r\n`
case pngURL:
body = string(testPNGFile)
default:
t.Fatal(req.URL)
}
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(body)),
ContentLength: int64(len(body)),
Header: make(http.Header),
}
})
ms := &xmain.State{
Name: "test",
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Env: xos.NewEnv(os.Environ()),
}
ms.Log = cmdlog.Log(ms.Env, os.Stderr)
out, err := InlineRemote(ms, []byte(sampleSVG))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), "https://") {
t.Fatal("links still exist")
}
if !strings.Contains(string(out), "image/svg+xml") {
t.Fatal("no svg image inserted")
}
if !strings.Contains(string(out), "image/png") {
t.Fatal("no png image inserted")
}
}
func TestInlineLocal(t *testing.T) {
svgURL, err := filepath.Abs("./test_svg.svg")
if err != nil {
t.Fatal(err)
}
pngURL, err := filepath.Abs("./test_png.png")
if err != nil {
t.Fatal(err)
}
sampleSVG := fmt.Sprintf(`
`, svgURL, pngURL)
ms := &xmain.State{
Name: "test",
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Env: xos.NewEnv(os.Environ()),
}
ms.Log = cmdlog.Log(ms.Env, os.Stderr)
out, err := InlineLocal(ms, []byte(sampleSVG))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), svgURL) {
t.Fatal("links still exist")
}
if !strings.Contains(string(out), "image/svg+xml") {
t.Fatal("no svg image inserted")
}
if !strings.Contains(string(out), "image/png") {
t.Fatal("no png image inserted")
}
}