github.com/golazy/golazy@v0.0.7-0.20221012133820-968fe65a0b65/lazyview/nodes/element_test.go (about) 1 package nodes 2 3 import ( 4 "bytes" 5 "os" 6 "strings" 7 "testing" 8 ) 9 10 func TestElementWriteTo(t *testing.T) { 11 Beautify = true 12 13 test := func(e Element, expectation string) { 14 t.Helper() 15 lines := strings.Split(expectation, "\n") 16 if len(lines) > 1 { 17 lines = lines[1:] 18 19 l := strings.TrimLeft(lines[0], " \t") 20 pad := lines[0][0 : len(lines[0])-len(l)] 21 22 for i, l := range lines { 23 lines[i] = strings.TrimPrefix(l, pad) 24 } 25 } 26 expectation = strings.Join(lines, "\n") 27 28 if expectation != e.String() { 29 t.Errorf("\nExpecting -----\n%s\nGot --------\n%s\n------\n%q\n%q", expectation, e.String(), expectation, e.String()) 30 } 31 } 32 33 test(NewElement("html", NewAttr("lang", "en"), 34 NewElement("head", 35 NewElement("title", "Mi pagina")), 36 NewElement("body", 37 NewElement("h1", "This is my page"), 38 NewElement("br")), 39 ), ` 40 <!DOCTYPE html> 41 <html lang=en> 42 <head> 43 <title>Mi pagina</title> 44 45 <body> 46 <h1>This is my page</h1> 47 <br> 48 49 `) 50 51 } 52 53 func ExampleBeautify() { 54 Beautify = true 55 defer (func() { 56 Beautify = false 57 })() 58 59 NewElement("html", NewAttr("lang", "en"), 60 NewElement("head", 61 NewElement("title", "Mi pagina")), 62 NewElement("body", 63 NewElement("h1", "This is my page"), 64 NewElement("br")), 65 ).WriteTo(os.Stdout) 66 67 // Output: 68 // <!DOCTYPE html> 69 // <html lang=en> 70 // <head> 71 // <title>Mi pagina</title> 72 // 73 // <body> 74 // <h1>This is my page</h1> 75 // <br> 76 // 77 // 78 79 } 80 81 func testElement(t *testing.T, title, expectation string, e Element) { 82 t.Helper() 83 t.Run(title, func(t *testing.T) { 84 t.Helper() 85 b := &bytes.Buffer{} 86 e.WriteTo(b) 87 if b.String() != expectation { 88 t.Errorf("Expected %q Got %q", expectation, b.String()) 89 } 90 }) 91 } 92 93 func TestAdd(t *testing.T) { 94 Beautify = false 95 testElement(t, "have attributes", `<div id=hola></div>`, NewElement("div", NewAttr("id", "hola"))) 96 testElement(t, "have attributes and content", `<div id=hola>hey</div>`, NewElement("div", NewAttr("id", "hola"), "hey")) 97 testElement(t, "escapes string", `<div><b>hola</b></div>`, NewElement("div", "<b>hola</b>")) 98 testElement(t, "have raw content", `<div><b>hola</b></div>`, NewElement("div", Raw(`<b>hola</b>`))) 99 }