@@ -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,42 @@ 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 {}, [1 ]int {0 },
88
+ []int (nil ), []int {}, []int {0 },
89
+ map [any ]any (nil ), map [any ]any {}, map [any ]any {"k" : "v" },
90
+ complex (0 , 0 ), complex (1 , 0 ),
91
+ (chan int )(nil ), make (chan int ),
92
+ (func ())(nil ), func () {},
93
+ util .ToPointer (0 ), util .ToPointer (util .ToPointer (0 )),
94
+ util .ToPointer (1 ), util .ToPointer (util .ToPointer (1 )),
95
+ (* struct {})(nil ),
96
+ struct {}{},
97
+ util .ToPointer (struct {}{}),
98
+ }
99
+ w := & strings.Builder {}
100
+ truthyCount := 0
101
+ for i , v := range cases {
102
+ w .Reset ()
103
+ assert .NoError (t , tmpl .Execute (w , struct { Value any }{v }), "case %d (%T) %#v fails" , i , v , v )
104
+ out := w .String ()
105
+ truthyCount += util .Iif (out == "true:true" , 1 , 0 )
106
+ truthyMatches := out == "true:true" || out == "false:false"
107
+ assert .True (t , truthyMatches , "case %d (%T) %#v fail: %s" , i , v , v , out )
108
+ }
109
+ assert .True (t , truthyCount != 0 && truthyCount != len (cases ))
82
110
}
0 commit comments