-
Notifications
You must be signed in to change notification settings - Fork 3
/
i18n_test.go
272 lines (232 loc) · 9.24 KB
/
i18n_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package mars
import (
"bytes"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"testing"
"time"
)
const (
testDataPath string = "testdata/i18n"
testConfigName string = "testdata/i18n/config/test_app.conf"
)
func TestI18nLoadMessages(t *testing.T) {
loadMessages(testDataPath)
// Assert that we have the expected number of languages
if len(MessageLanguages()) != 2 {
t.Fatalf("Expected messages to contain no more or less than 2 languages, instead there are %d languages", len(MessageLanguages()))
}
}
func TestI18nMessage(t *testing.T) {
loadMessages(testDataPath)
loadTestI18nConfig(t)
// Assert that we can get a message and we get the expected return value
if message := Message("nl", "greeting"); message != "Hallo" {
t.Errorf("Message 'greeting' for locale 'nl' (%s) does not have the expected value", message)
}
if message := Message("en", "greeting"); message != "Hello" {
t.Errorf("Message 'greeting' for locale 'en' (%s) does not have the expected value", message)
}
if message := Message("en", "folded"); message != "Greeting is 'Hello'" {
t.Error("Unexpected unfolded message: ", message)
}
if message := Message("en", "arguments.string", "Vincent Hanna"); message != "My name is Vincent Hanna" {
t.Errorf("Message 'arguments.string' for locale 'en' (%s) does not have the expected value", message)
}
if message := Message("en", "arguments.hex", 1234567, 1234567); message != "The number 1234567 in hexadecimal notation would be 12d687" {
t.Errorf("Message 'arguments.hex' for locale 'en' (%s) does not have the expected value", message)
}
if message := Message("en", "folded.arguments", 12345); message != "Rob is 12345 years old" {
t.Errorf("Message 'folded.arguments' for locale 'en' (%s) does not have the expected value", message)
}
if message := Message("en-AU", "greeting"); message != "G'day" {
t.Errorf("Message 'greeting' for locale 'en-AU' (%s) does not have the expected value", message)
}
if message := Message("en-AU", "only_exists_in_default"); message != "Default" {
t.Errorf("Message 'only_exists_in_default' for locale 'en-AU' (%s) does not have the expected value", message)
}
// Assert that message merging works
if message := Message("en", "greeting2"); message != "Yo!" {
t.Errorf("Message 'greeting2' for locale 'en' (%s) does not have the expected value", message)
}
// Assert that we get the expected return value for a locale that doesn't exist
if message := Message("unknown locale", "message"); message != "??? message ???" {
t.Error("Locale 'unknown locale' is not supposed to exist")
}
// Assert that we get the expected return value for a message that doesn't exist
if message := Message("nl", "unknown message"); message != "??? unknown message ???" {
t.Error("Message 'unknown message' is not supposed to exist")
}
}
func TestI18nMessageWithDefaultLocale(t *testing.T) {
loadMessages(testDataPath)
loadTestI18nConfig(t)
if message := Message("doesn't exist", "greeting"); message != "Hello" {
t.Errorf("Expected message '%s' for unknown locale to be default '%s' but was '%s'", "greeting", "Hello", message)
}
if message := Message("doesn't exist", "unknown message"); message != "??? unknown message ???" {
t.Error("Message 'unknown message' is not supposed to exist in the default language")
}
}
func TestHasLocaleCookie(t *testing.T) {
loadTestI18nConfig(t)
if found, value := hasLocaleCookie(buildRequestWithCookie("APP_LANG", "en")); !found {
t.Errorf("Expected %s cookie with value '%s' but found nothing or unexpected value '%s'", "APP_LANG", "en", value)
}
if found, value := hasLocaleCookie(buildRequestWithCookie("APP_LANG", "en-US")); !found {
t.Errorf("Expected %s cookie with value '%s' but found nothing or unexpected value '%s'", "APP_LANG", "en-US", value)
}
if found, _ := hasLocaleCookie(buildRequestWithCookie("DOESNT_EXIST", "en-US")); found {
t.Errorf("Expected %s cookie to not exist, but apparently it does", "DOESNT_EXIST")
}
}
func TestHasLocaleCookieWithInvalidConfig(t *testing.T) {
loadTestI18nConfigWithoutLanguageCookieOption(t)
if found, _ := hasLocaleCookie(buildRequestWithCookie("APP_LANG", "en-US")); found {
t.Errorf("Expected %s cookie to not exist because the configured name is missing", "APP_LANG")
}
if found, _ := hasLocaleCookie(buildRequestWithCookie("MARS_LANG", "en-US")); !found {
t.Errorf("Expected %s cookie to exist", "MARS_LANG")
}
}
func TestHasAcceptLanguageHeader(t *testing.T) {
if found, value := hasAcceptLanguageHeader(buildRequestWithAcceptLanguages("en-US")); !found && value != "en-US" {
t.Errorf("Expected to find Accept-Language header with value '%s', found '%s' instead", "en-US", value)
}
if found, value := hasAcceptLanguageHeader(buildRequestWithAcceptLanguages("en-GB", "en-US", "nl")); !found && value != "en-GB" {
t.Errorf("Expected to find Accept-Language header with value '%s', found '%s' instead", "en-GB", value)
}
}
func TestBeforeRequest(t *testing.T) {
loadTestI18nConfig(t)
c := NewController(buildEmptyRequest(), nil)
if I18nFilter(c, NilChain); c.Request.Locale != "" {
t.Errorf("Expected to find current language '%s' in controller, found '%s' instead", "", c.Request.Locale)
}
c = NewController(buildRequestWithCookie("APP_LANG", "en-US"), nil)
if I18nFilter(c, NilChain); c.Request.Locale != "en-US" {
t.Errorf("Expected to find current language '%s' in controller, found '%s' instead", "en-US", c.Request.Locale)
}
c = NewController(buildRequestWithAcceptLanguages("en-GB", "en-US"), nil)
if I18nFilter(c, NilChain); c.Request.Locale != "en-GB" {
t.Errorf("Expected to find current language '%s' in controller, found '%s' instead", "en-GB", c.Request.Locale)
}
}
func BenchmarkI18nLoadMessages(b *testing.B) {
excludeFromTimer(b, func() { TRACE = log.New(ioutil.Discard, "", 0) })
for i := 0; i < b.N; i++ {
loadMessages(testDataPath)
}
}
func BenchmarkI18nMessage(b *testing.B) {
for i := 0; i < b.N; i++ {
Message("nl", "greeting")
}
}
func BenchmarkI18nMessageWithArguments(b *testing.B) {
excludeFromTimer(b, func() { TRACE = log.New(ioutil.Discard, "", 0) })
for i := 0; i < b.N; i++ {
Message("en", "arguments.string", "Vincent Hanna")
}
}
func BenchmarkI18nMessageWithFoldingAndArguments(b *testing.B) {
excludeFromTimer(b, func() { TRACE = log.New(ioutil.Discard, "", 0) })
for i := 0; i < b.N; i++ {
Message("en", "folded.arguments", 12345)
}
}
// Exclude whatever operations the given function performs from the benchmark timer.
func excludeFromTimer(b *testing.B, f func()) {
b.StopTimer()
f()
b.StartTimer()
}
func loadTestI18nConfig(t *testing.T) {
testConfig, error := LoadConfig(testConfigName)
if error != nil {
t.Fatalf("Unable to load test config '%s': %s", testConfigName, error.Error())
}
Config = testConfig
CookiePrefix = Config.StringDefault("cookie.prefix", "MARS")
}
func loadTestI18nConfigWithoutLanguageCookieOption(t *testing.T) {
loadTestI18nConfig(t)
Config.config.RemoveOption("DEFAULT", "i18n.cookie")
}
func buildRequestWithCookie(name, value string) *Request {
httpRequest, _ := http.NewRequest("GET", "/", nil)
request := NewRequest(httpRequest)
request.AddCookie(&http.Cookie{
Name: name,
Value: value,
Path: "",
Domain: "",
Expires: time.Now(),
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
Raw: "",
Unparsed: nil,
})
return request
}
func buildRequestWithAcceptLanguages(acceptLanguages ...string) *Request {
httpRequest, _ := http.NewRequest("GET", "/", nil)
request := NewRequest(httpRequest)
for _, acceptLanguage := range acceptLanguages {
request.AcceptLanguages = append(request.AcceptLanguages, AcceptLanguage{acceptLanguage, 1})
}
return request
}
func buildEmptyRequest() *Request {
httpRequest, _ := http.NewRequest("GET", "/", nil)
request := NewRequest(httpRequest)
return request
}
func runRequest(locale, view string, args Args) string {
w := httptest.NewRecorder()
c := NewController(buildEmptyRequest(), &Response{Out: w})
for k, v := range args {
c.RenderArgs[k] = v
}
c.RenderArgs[CurrentLocaleRenderArg] = locale
c.RenderTemplate(view).Apply(c.Request, c.Response)
buf := &bytes.Buffer{}
buf.ReadFrom(w.Body)
return buf.String()
}
type blurp struct{ s string }
type blarp struct{ s string }
func Blurp(input string) blurp {
return blurp{input}
}
func Blarp(input string) blarp {
return blarp{input}
}
func (b blarp) String() string {
return b.s
}
func TestSafeHTML(t *testing.T) {
loadMessages(testDataPath)
_, filename, _, _ := runtime.Caller(0)
BasePath = filepath.Join(filepath.Dir(filename), "testdata")
SetupViews()
for expected, input := range map[string]interface{}{
"<h1>Hey, there <b>Rob</b>!</h1>": "Rob",
"<h1>Hey, there <b><img src=a onerror=alert(1) /></b>!</h1>": "<img src=a onerror=alert(1) />",
"<h1>Hey, there <b><img src=a onerror=alert(1) /></b>!</h1>": template.HTML("<img src=a onerror=alert(1) />"),
"<h1>Hey, there <b>{<3}</b>!</h1>": Blurp("<3"),
"<h1>Hey, there <b><3</b>!</h1>": Blarp("<3"),
} {
result := runRequest("en", "i18n.html", Args{"input": input})
if result != expected {
t.Errorf("Expected '%s', got '%s' for input '%s'", expected, result, input)
}
}
}