format_test.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | package htmlformat
import (
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestFormat(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "missing closing tags are inserted",
input: `<li>`,
expected: `<li>
</li>
`,
},
{
name: "html attribute escaping is normalized",
input: `<ol> <li style="&&"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li style="&&">A</li>
<li>B</li>
</ol>
`,
},
{
name: "bare ampersands are escaped",
input: `<ol> <li style="&"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li style="&">A</li>
<li>B</li>
</ol>
`,
},
{
name: "html elements are indented",
input: `<ol> <li class="name"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li class="name">A</li>
<li>B</li>
</ol>
`,
},
{
name: "text fragments are supported",
input: `test 123`,
expected: `test 123` + "\n",
},
{
name: "script tags are only indented",
input: `<script>
var x = 1;
</script>`,
expected: `<script>
var x = 1;
</script>` + "\n",
},
{
name: "phrasing content element children are kept on the same line, including punctuation",
input: `<ul><li><a href="http://example.com">Test</a>.</li></ul>`,
expected: `<ul>
<li>
<a href="http://example.com">Test</a>.
</li>
</ul>
`,
},
{
name: "style content is indented consistently",
input: `<style>
body {
text-color: red;
}
</style>`,
expected: `<style>
body {
text-color: red;
}
</style>
`,
},
{
name: "spaces are not added around elements ending with punctuation",
input: "<div><time>19:00</time>–<time>20:00</time></div>",
expected: `<div>
<time>19:00</time>–<time>20:00</time>
</div>
`,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
r := strings.NewReader(test.input)
w := new(strings.Builder)
if err := Fragment(w, r); err != nil {
t.Fatalf("failed to format: %v", err)
}
if diff := cmp.Diff(test.expected, w.String()); diff != "" {
t.Error(diff)
}
})
}
}
|