@@ -5,8 +5,11 @@ package templates
5
5
6
6
import (
7
7
"html/template"
8
+ "strings"
8
9
"testing"
9
10
11
+ "code.gitea.io/gitea/modules/util"
12
+
10
13
"github.com/stretchr/testify/assert"
11
14
)
12
15
@@ -65,3 +68,41 @@ func TestHTMLFormat(t *testing.T) {
65
68
func TestSanitizeHTML (t * testing.T ) {
66
69
assert .Equal (t , template .HTML (`<a href="/" rel="nofollow">link</a> xss <div>inline</div>` ), SanitizeHTML (`<a href="/">link</a> <a href="javascript:">xss</a> <div style="dangerous">inline</div>` ))
67
70
}
71
+
72
+ func TestTemplateTruthy (t * testing.T ) {
73
+ tmpl := template .New ("test" )
74
+ tmpl .Funcs (template.FuncMap {"Iif" : Iif })
75
+ template .Must (tmpl .Parse (`{{if .Value}}true{{else}}false{{end}}:{{Iif .Value "true" "false"}}` ))
76
+
77
+ cases := []any {
78
+ nil , false , true , "" , "string" , 0 , 1 ,
79
+ byte (0 ), byte (1 ), int64 (0 ), int64 (1 ), float64 (0 ), float64 (1 ),
80
+ complex (0 , 0 ), complex (1 , 0 ),
81
+ (chan int )(nil ), make (chan int ),
82
+ (func ())(nil ), func () {},
83
+ util .ToPointer (0 ), util .ToPointer (util .ToPointer (0 )),
84
+ util .ToPointer (1 ), util .ToPointer (util .ToPointer (1 )),
85
+ [0 ]int {},
86
+ [1 ]int {0 },
87
+ []int (nil ),
88
+ []int {},
89
+ []int {0 },
90
+ map [any ]any (nil ),
91
+ map [any ]any {},
92
+ map [any ]any {"k" : "v" },
93
+ (* struct {})(nil ),
94
+ struct {}{},
95
+ util .ToPointer (struct {}{}),
96
+ }
97
+ w := & strings.Builder {}
98
+ truthyCount := 0
99
+ for i , v := range cases {
100
+ w .Reset ()
101
+ assert .NoError (t , tmpl .Execute (w , struct { Value any }{v }), "case %d (%T) %#v fails" , i , v , v )
102
+ out := w .String ()
103
+ truthyCount += util .Iif (out == "true:true" , 1 , 0 )
104
+ truthyMatches := out == "true:true" || out == "false:false"
105
+ assert .True (t , truthyMatches , "case %d (%T) %#v fail: %s" , i , v , v , out )
106
+ }
107
+ assert .True (t , truthyCount != 0 && truthyCount != len (cases ))
108
+ }
0 commit comments