forked from gin-contrib/i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embed_test.go
122 lines (108 loc) · 2.36 KB
/
embed_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
//go:build go1.16
// +build go1.16
package i18n
import (
"context"
"embed"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
type server struct {
*gin.Engine
}
func newEmbedServer(middleware ...gin.HandlerFunc) *server {
server := &server{gin.New()}
server.Use(middleware...)
server.GET("/", func(context *gin.Context) {
context.String(http.StatusOK, MustGetMessage(context, "welcome"))
})
server.GET("/:name", func(context *gin.Context) {
context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
MessageID: "welcomeWithName",
TemplateData: map[string]string{
"name": context.Param("name"),
},
}))
})
return server
}
func (s *server) request(lng language.Tag, name string) string {
path := "/" + name
ctx := context.Background()
req, _ := http.NewRequestWithContext(ctx, "GET", path, nil)
req.Header.Add("Accept-Language", lng.String())
w := httptest.NewRecorder()
s.ServeHTTP(w, req)
return w.Body.String()
}
var (
//go:embed testdata/localizeJSON/*
fs embed.FS
s = newEmbedServer(Localize(WithBundle(&BundleCfg{
DefaultLanguage: language.English,
FormatBundleFile: "json",
AcceptLanguage: []language.Tag{language.English, language.German, language.Chinese},
RootPath: "./testdata/localizeJSON/",
UnmarshalFunc: json.Unmarshal,
// After commenting this line, use defaultLoader
// it will be loaded from the file
Loader: &EmbedLoader{fs},
})))
)
func TestEmbedLoader(t *testing.T) {
type args struct {
lng language.Tag
name string
}
tests := []struct {
name string
args args
want string
}{
{
name: "hello world",
args: args{
name: "",
lng: language.English,
},
want: "hello",
},
{
name: "hello alex",
args: args{
name: "",
lng: language.Chinese,
},
want: "你好",
},
{
name: "hello alex",
args: args{
name: "alex",
lng: language.English,
},
want: "hello alex",
},
{
name: "hello alex german",
args: args{
name: "alex",
lng: language.Chinese,
},
want: "你好 alex",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := s.request(tt.args.lng, tt.args.name)
if got != tt.want {
t.Errorf("makeRequest() = %v, want %v", got, tt.want)
}
})
}
}