@@ -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
@@ -66,17 +69,47 @@ 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
}
68
71
69
- func TestIsTruthy (t * testing.T ) {
70
- var test any
71
- assert .Equal (t , false , IsTruthy (test ))
72
- assert .Equal (t , false , IsTruthy (nil ))
73
- assert .Equal (t , false , IsTruthy ("" ))
74
- assert .Equal (t , true , IsTruthy ("non-empty" ))
75
- assert .Equal (t , true , IsTruthy (- 1 ))
76
- assert .Equal (t , false , IsTruthy (0 ))
77
- assert .Equal (t , true , IsTruthy (42 ))
78
- assert .Equal (t , false , IsTruthy (0.0 ))
79
- assert .Equal (t , true , IsTruthy (3.14 ))
80
- assert .Equal (t , false , IsTruthy ([]int {}))
81
- assert .Equal (t , true , IsTruthy ([]int {1 }))
72
+ func TestTemplateTruthy (t * testing.T ) {
73
+ tmpl := template .New ("test" )
74
+ tmpl .Funcs (template.FuncMap {"Iif" : Iif })
75
+ template .Must (tmpl .Parse (`
76
+ {{- if .Value}}true{{else}}false{{end -}}
77
+ :{{- Iif .Value "true" "false" -}}
78
+ ` ))
79
+
80
+ cases := []any {
81
+ nil , false , true ,
82
+ "" , "string" ,
83
+ 0 , 1 ,
84
+ byte (0 ), byte (1 ),
85
+ int64 (0 ), int64 (1 ),
86
+ float64 (0 ), float64 (1 ),
87
+ [0 ]int {},
88
+ [1 ]int {0 },
89
+ []int (nil ),
90
+ []int {},
91
+ []int {0 },
92
+ map [any ]any (nil ),
93
+ map [any ]any {},
94
+ map [any ]any {"k" : "v" },
95
+ complex (0 , 0 ), complex (1 , 0 ),
96
+ (chan int )(nil ), make (chan int ),
97
+ (func ())(nil ), func () {},
98
+ util .ToPointer (0 ), util .ToPointer (util .ToPointer (0 )),
99
+ util .ToPointer (1 ), util .ToPointer (util .ToPointer (1 )),
100
+ (* struct {})(nil ),
101
+ struct {}{},
102
+ util .ToPointer (struct {}{}),
103
+ }
104
+ w := & strings.Builder {}
105
+ truthyCount := 0
106
+ for i , v := range cases {
107
+ w .Reset ()
108
+ assert .NoError (t , tmpl .Execute (w , struct { Value any }{v }), "case %d (%T) %#v fails" , i , v , v )
109
+ out := w .String ()
110
+ truthyCount += util .Iif (out == "true:true" , 1 , 0 )
111
+ truthyMatches := out == "true:true" || out == "false:false"
112
+ assert .True (t , truthyMatches , "case %d (%T) %#v fail: %s" , i , v , v , out )
113
+ }
114
+ assert .True (t , truthyCount != 0 && truthyCount != len (cases ))
82
115
}
0 commit comments