| 1 | package codeview |
| 2 | |
| 3 | import ( |
| 4 | "html" |
| 5 | "regexp" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | var highlightTag = regexp.MustCompile(`</?ds-[tavxs]>`) |
| 11 | |
| 12 | // plain is what a reader sees and copies: the highlighted markup with |
| 13 | // its five elements removed and its entities decoded. |
| 14 | func plain(h string) string { return html.UnescapeString(highlightTag.ReplaceAllString(h, "")) } |
| 15 | |
| 16 | func TestHighlightMarksTheFiveKinds(t *testing.T) { |
| 17 | got := string(Highlight(`{{template "meter" dict "Percent" 140 "Items" .Locales}}`)) |
| 18 | want := `<ds-x>{{</ds-x><ds-x>template</ds-x> <ds-s>"meter"</ds-s> <ds-x>dict</ds-x> <ds-s>"Percent"</ds-s> 140 <ds-s>"Items"</ds-s> <ds-x>.Locales</ds-x><ds-x>}}</ds-x>` |
| 19 | if got != want { |
| 20 | t.Errorf("call:\n got %s\nwant %s", got, want) |
| 21 | } |
| 22 | got = string(Highlight(`<a rst-btn href="/x">Go</a><input disabled>`)) |
| 23 | want = `<ds-t><a</ds-t> <ds-a>rst-btn</ds-a> <ds-a>href</ds-a>=<ds-v>"/x"</ds-v>>Go<ds-t></a</ds-t>><ds-t><input</ds-t> <ds-a>disabled</ds-a>>` |
| 24 | if got != want { |
| 25 | t.Errorf("markup:\n got %s\nwant %s", got, want) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // The text on screen is the source, whatever is in it: entities, a |
| 30 | // '>' inside a quoted value, {{ inside an attribute, upper case. |
| 31 | func TestHighlightRoundTripsAwkwardMarkup(t *testing.T) { |
| 32 | for _, src := range []string{ |
| 33 | `<a href="/x?a=1&b=2" data-tip="a > b">Tom & Jerry € < 3</a>`, |
| 34 | `<DIV Title='it"s'>{{x}}</DIV><!-- a comment <b> -->`, |
| 35 | `<div title="{{.Name}}">a {{ "}}" }} b</div>`, |
| 36 | "{{template \"x\" dict\n \"A\" \"a\\\"b\"\n \"B\" `raw`}}", |
| 37 | `a < b > c & d`, |
| 38 | `<span rst-stat-num>−3%</span>`, |
| 39 | } { |
| 40 | h := string(Highlight(src)) |
| 41 | if got := plain(h); got != src { |
| 42 | t.Errorf("round trip lost bytes:\n src: %s\nplain: %s\n html: %s", src, got, h) |
| 43 | } |
| 44 | if strings.Contains(highlightTag.ReplaceAllString(h, ""), "<") { |
| 45 | t.Errorf("an unescaped '<' reached the page: %s", h) |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |