prime8dev

prime8dev
git clone https://git.prime8.dev/prime8dev.git
Log | Files | Refs | README | LICENSE

markdown_images_test.go (1871B)


      1 package tui
      2 
      3 import (
      4 	"bytes"
      5 	"image"
      6 	"image/color"
      7 	"image/png"
      8 	"net/http"
      9 	"net/http/httptest"
     10 	"strings"
     11 	"testing"
     12 
     13 	"github.com/charmbracelet/x/ansi"
     14 )
     15 
     16 func TestReadmeImagesAreCapped(t *testing.T) {
     17 	for _, size := range [][2]int{{2000, 400}, {400, 2000}, {1200, 1200}} {
     18 		img := image.NewRGBA(image.Rect(0, 0, size[0], size[1]))
     19 		for y := 0; y < size[1]; y++ {
     20 			for x := 0; x < size[0]; x++ {
     21 				img.Set(x, y, color.RGBA{200, 100, 50, 255})
     22 			}
     23 		}
     24 		var buf bytes.Buffer
     25 		if err := png.Encode(&buf, img); err != nil {
     26 			t.Fatal(err)
     27 		}
     28 		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
     29 			w.Header().Set("Content-Type", "image/png")
     30 			_, _ = w.Write(buf.Bytes())
     31 		}))
     32 		md := "# demo\n\nsome text\n\n![shot](" + srv.URL + "/a.png)\n\n<p align=\"center\"><img src=\"" + srv.URL + "/b.png\" width=\"900\"></p>\n\nmore text\n"
     33 		out := renderMarkdown(md, 200)
     34 		_, maxRows := imageBox(200)
     35 		srv.Close()
     36 
     37 		rows := 0
     38 		for _, line := range strings.Split(out, "\n") {
     39 			if strings.Contains(line, "▀") || strings.Contains(line, "▄") {
     40 				rows++
     41 				if w := ansi.StringWidth(line); w > imageMaxCols {
     42 					t.Errorf("%v: image row %d cells wide", size, w)
     43 				}
     44 			}
     45 		}
     46 		if rows == 0 {
     47 			t.Fatalf("%v: no image rendered:\n%s", size, out)
     48 		}
     49 		if rows > 2*maxRows {
     50 			t.Errorf("%v: %d image rows for two images, cap is %d each", size, rows, maxRows)
     51 		}
     52 		if !strings.Contains(ansi.Strip(out), "more text") {
     53 			t.Errorf("text after images lost")
     54 		}
     55 	}
     56 }
     57 
     58 func TestImageBoxScalesWithPane(t *testing.T) {
     59 	for _, c := range []struct{ width, cols, rows int }{
     60 		{40, 40, 13}, {60, 60, 20}, {90, 90, 24}, {200, 96, 24}, {10, 10, 4},
     61 	} {
     62 		if cols, rows := imageBox(c.width); cols != c.cols || rows != c.rows {
     63 			t.Errorf("imageBox(%d) = %dx%d, want %dx%d", c.width, cols, rows, c.cols, c.rows)
     64 		}
     65 	}
     66 }