|
4 | 4 | package i18n
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "html/template" |
7 | 8 | "strings"
|
8 | 9 | "testing"
|
9 | 10 |
|
|
82 | 83 | assert.Equal(t, "22", lang1.TrString("c"))
|
83 | 84 | }
|
84 | 85 |
|
| 86 | +type stringerPointerReceiver struct { |
| 87 | + s string |
| 88 | +} |
| 89 | + |
| 90 | +func (s *stringerPointerReceiver) String() string { |
| 91 | + return s.s |
| 92 | +} |
| 93 | + |
| 94 | +type stringerStructReceiver struct { |
| 95 | + s string |
| 96 | +} |
| 97 | + |
| 98 | +func (s stringerStructReceiver) String() string { |
| 99 | + return s.s |
| 100 | +} |
| 101 | + |
| 102 | +type errorStructReceiver struct { |
| 103 | + s string |
| 104 | +} |
| 105 | + |
| 106 | +func (e errorStructReceiver) Error() string { |
| 107 | + return e.s |
| 108 | +} |
| 109 | + |
| 110 | +type errorPointerReceiver struct { |
| 111 | + s string |
| 112 | +} |
| 113 | + |
| 114 | +func (e *errorPointerReceiver) Error() string { |
| 115 | + return e.s |
| 116 | +} |
| 117 | + |
| 118 | +func TestLocaleWithTemplate(t *testing.T) { |
| 119 | + ls := NewLocaleStore() |
| 120 | + assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", []byte(`key=<a>%s</a>`), nil)) |
| 121 | + lang1, _ := ls.Locale("lang1") |
| 122 | + |
| 123 | + tmpl := template.New("test").Funcs(template.FuncMap{"tr": lang1.TrHTML}) |
| 124 | + tmpl = template.Must(tmpl.Parse(`{{tr "key" .var}}`)) |
| 125 | + |
| 126 | + cases := []struct { |
| 127 | + in any |
| 128 | + want string |
| 129 | + }{ |
| 130 | + {"<str>", "<a><str></a>"}, |
| 131 | + {[]byte("<bytes>"), "<a>[60 98 121 116 101 115 62]</a>"}, |
| 132 | + {template.HTML("<html>"), "<a><html></a>"}, |
| 133 | + {stringerPointerReceiver{"<stringerPointerReceiver>"}, "<a>{<stringerPointerReceiver>}</a>"}, |
| 134 | + {&stringerPointerReceiver{"<stringerPointerReceiver ptr>"}, "<a><stringerPointerReceiver ptr></a>"}, |
| 135 | + {stringerStructReceiver{"<stringerStructReceiver>"}, "<a><stringerStructReceiver></a>"}, |
| 136 | + {&stringerStructReceiver{"<stringerStructReceiver ptr>"}, "<a><stringerStructReceiver ptr></a>"}, |
| 137 | + {errorStructReceiver{"<errorStructReceiver>"}, "<a><errorStructReceiver></a>"}, |
| 138 | + {&errorStructReceiver{"<errorStructReceiver ptr>"}, "<a><errorStructReceiver ptr></a>"}, |
| 139 | + {errorPointerReceiver{"<errorPointerReceiver>"}, "<a>{<errorPointerReceiver>}</a>"}, |
| 140 | + {&errorPointerReceiver{"<errorPointerReceiver ptr>"}, "<a><errorPointerReceiver ptr></a>"}, |
| 141 | + } |
| 142 | + |
| 143 | + buf := &strings.Builder{} |
| 144 | + for _, c := range cases { |
| 145 | + buf.Reset() |
| 146 | + assert.NoError(t, tmpl.Execute(buf, map[string]any{"var": c.in})) |
| 147 | + assert.Equal(t, c.want, buf.String()) |
| 148 | + } |
| 149 | +} |
| 150 | + |
85 | 151 | func TestLocaleStoreQuirks(t *testing.T) {
|
86 | 152 | const nl = "\n"
|
87 | 153 | q := func(q1, s string, q2 ...string) string {
|
|
0 commit comments