-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpublic_api_test.go
More file actions
353 lines (316 loc) · 9.1 KB
/
Copy pathpublic_api_test.go
File metadata and controls
353 lines (316 loc) · 9.1 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package channel
import (
"context"
"errors"
"go/ast"
"go/parser"
"go/token"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
)
type mockAssertionProvider struct{}
func (mockAssertionProvider) RetrieveToken(ctx context.Context, aud string) (*larkcore.Token, error) {
if aud == "" {
return nil, errors.New("aud is required")
}
return &larkcore.Token{Value: "assertion"}, nil
}
type mockCache struct{}
func (mockCache) Set(ctx context.Context, key string, value string, expireTime time.Duration) error {
return nil
}
func (mockCache) Get(ctx context.Context, key string) (string, error) {
return "", nil
}
type mockLogger struct{}
func (mockLogger) Debug(context.Context, ...interface{}) {}
func (mockLogger) Info(context.Context, ...interface{}) {}
func (mockLogger) Warn(context.Context, ...interface{}) {}
func (mockLogger) Error(context.Context, ...interface{}) {}
func TestNewRejectsEmptyAppID(t *testing.T) {
_, err := New("", "secret")
if err == nil {
t.Fatal("expected appID error")
}
}
func TestNewRejectsEmptyAppSecretWithoutAssertion(t *testing.T) {
_, err := New("cli_a", "")
if err == nil {
t.Fatal("expected appSecret error")
}
}
func TestNewAcceptsClientAssertionWithoutAppSecret(t *testing.T) {
ch, err := New("cli_a", "", WithClientAssertionProvider(mockAssertionProvider{}))
if err != nil {
t.Fatalf("New returned error: %v", err)
}
if ch == nil {
t.Fatal("New returned nil channel")
}
}
func TestNewExposesRawClient(t *testing.T) {
ch, err := New("cli_a", "secret")
if err != nil {
t.Fatalf("New returned error: %v", err)
}
if ch.RawClient() == nil {
t.Fatal("raw client should be available")
}
if _, ok := any(ch).(interface{ RawWSClient() any }); ok {
t.Fatal("RawWSClient must not be exposed")
}
}
func TestNewAllowsHandlerRegistration(t *testing.T) {
ch, err := New("cli_a", "secret")
if err != nil {
t.Fatalf("New returned error: %v", err)
}
ch.OnReady(func() {})
ch.OnError(func(err error) {})
ch.OnMessage(func(ctx context.Context, msg *NormalizedMessage) error {
return nil
})
}
func TestRootTypeAliasesCompile(t *testing.T) {
var _ Channel = nil
var _ *SendInput = &SendInput{}
var _ *SendResult = &SendResult{}
var _ *NormalizedMessage = &NormalizedMessage{}
var _ *ReactionEvent = &ReactionEvent{}
var _ *CommentEvent = &CommentEvent{}
var _ *CardActionEvent = &CardActionEvent{}
var _ *RejectEvent = &RejectEvent{}
input := SendInput{
ReceiveID: "oc_test",
MsgType: "text",
Text: "hello",
}
if input.ReceiveID == "" {
t.Fatal("ReceiveID should be set")
}
input.Media = &UploadInput{Kind: MediaKindImage, SourcePath: "test.png"}
rateErr := &FeishuChannelError{Code: ErrCodeRateLimited}
if ClassifyError(rateErr) == nil || !IsRetryable(rateErr) {
t.Fatal("error helpers should be usable from root package")
}
if !IsFormatError(&FeishuChannelError{Code: ErrCodeFormatError}) {
t.Fatal("IsFormatError should be usable from root package")
}
msg := NormalizedMessage{
MessageID: "om_test",
ChatID: "oc_test",
}
if msg.MessageID == "" {
t.Fatal("MessageID should be set")
}
evt := CardActionEvent{
Action: CardActionPayload{Name: "approve"},
}
if evt.Action.Name == "" {
t.Fatal("CardActionEvent should be usable from root package")
}
}
func TestRootChannelOptionsCompile(t *testing.T) {
_, err := New("cli_a", "secret", WithSafetyConfig(SafetyConfig{}))
if err != nil {
t.Fatalf("New returned error: %v", err)
}
}
func TestOptionsMapToClientConfig(t *testing.T) {
mockHTTP := &mockHTTPClient{}
cache := mockCache{}
logger := mockLogger{}
headers := http.Header{"X-Test": []string{"channel"}}
provider := mockAssertionProvider{}
timeout := 7 * time.Second
cfg := config{}
for _, opt := range []Option{
WithLogger(logger),
WithLogLevel(larkcore.LogLevelWarn),
WithDomain("https://open.example.com"),
WithOAuthBaseURL("https://accounts.example.com"),
WithHTTPClient(mockHTTP),
WithReqTimeout(timeout),
WithTokenCache(cache),
WithEnableTokenCache(false),
WithHeaders(headers),
WithSource("channel-sdk-go-test"),
WithClientAssertionProvider(provider),
} {
opt(&cfg)
}
clientConfig := &larkcore.Config{}
for _, opt := range cfg.clientOptions {
opt(clientConfig)
}
if clientConfig.Logger != logger {
t.Fatal("WithLogger did not map to lark client config")
}
if clientConfig.LogLevel != larkcore.LogLevelWarn {
t.Fatal("WithLogLevel did not map to lark client config")
}
if clientConfig.BaseUrl != "https://open.example.com" {
t.Fatalf("WithDomain mapped BaseUrl to %q", clientConfig.BaseUrl)
}
if clientConfig.OAuthBaseUrl != "https://accounts.example.com" {
t.Fatalf("WithOAuthBaseURL mapped OAuthBaseUrl to %q", clientConfig.OAuthBaseUrl)
}
if clientConfig.HttpClient != mockHTTP {
t.Fatal("WithHTTPClient did not map to lark client config")
}
if clientConfig.ReqTimeout != timeout {
t.Fatalf("WithReqTimeout mapped ReqTimeout to %v", clientConfig.ReqTimeout)
}
if clientConfig.TokenCache != cache {
t.Fatal("WithTokenCache did not map to lark client config")
}
if clientConfig.EnableTokenCache {
t.Fatal("WithEnableTokenCache(false) did not map to lark client config")
}
if clientConfig.Header.Get("X-Test") != "channel" {
t.Fatal("WithHeaders did not map to lark client config")
}
if clientConfig.Source != "channel-sdk-go-test" {
t.Fatal("WithSource did not map to lark client config")
}
if clientConfig.ClientAssertionProvider != provider {
t.Fatal("WithClientAssertionProvider did not map to lark client config")
}
if !cfg.hasAssertion {
t.Fatal("WithClientAssertionProvider should mark assertion mode")
}
if len(cfg.wsOptions) != 6 {
t.Fatalf("expected logger, log level, domain, headers, source, and assertion ws options, got %d", len(cfg.wsOptions))
}
if len(cfg.eventOptions) != 2 {
t.Fatalf("expected logger and log level event options, got %d", len(cfg.eventOptions))
}
}
func TestSeparateEndpointOptionsCompile(t *testing.T) {
cfg := config{}
for _, opt := range []Option{
WithOpenBaseURL("https://open-only.example.com"),
WithWebSocketDomain("https://ws-only.example.com"),
} {
opt(&cfg)
}
clientConfig := &larkcore.Config{}
for _, opt := range cfg.clientOptions {
opt(clientConfig)
}
if clientConfig.BaseUrl != "https://open-only.example.com" {
t.Fatalf("WithOpenBaseURL mapped BaseUrl to %q", clientConfig.BaseUrl)
}
if len(cfg.wsOptions) != 1 {
t.Fatalf("expected one ws option from WithWebSocketDomain, got %d", len(cfg.wsOptions))
}
}
func TestNewWithHTTPClientSupportsShortLivedSend(t *testing.T) {
mockHTTP := &mockHTTPClient{
DoFunc: func(req *http.Request) (*http.Response, error) {
respBody := `{"code":0,"msg":"success","data":{"message_id":"om_short","chat_id":"oc_short"}}`
header := make(http.Header)
header.Set("Content-Type", "application/json")
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(respBody)),
Header: header,
}, nil
},
}
ch, err := New("cli_a", "secret", WithHTTPClient(mockHTTP))
if err != nil {
t.Fatalf("New returned error: %v", err)
}
t.Cleanup(func() {
if err := ch.Stop(context.Background()); err != nil {
t.Fatalf("Stop returned error: %v", err)
}
})
res, err := ch.Send(context.Background(), &SendInput{
ReceiveID: "oc_short",
MsgType: "text",
Text: "hello",
})
if err != nil {
t.Fatalf("Send returned error: %v", err)
}
if res.MessageID != "om_short" {
t.Fatalf("message id = %q", res.MessageID)
}
}
func TestNoLegacyConstructorsInRootPackage(t *testing.T) {
for _, name := range []string{
"NewChannel",
"NewWithClient",
"NewWithClients",
} {
if rootPackageHasExportedSymbol(t, name) {
t.Fatalf("root package must not expose %s", name)
}
}
}
func TestNoInternalRuntimeConstructorsInRootPackage(t *testing.T) {
for _, name := range []string{
"NewUpdateQueue",
"NewCardStreamController",
"NewMarkdownStreamController",
} {
if rootPackageHasExportedSymbol(t, name) {
t.Fatalf("root package must not expose %s", name)
}
}
}
func rootPackageHasExportedSymbol(t *testing.T, name string) bool {
t.Helper()
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatalf("glob root go files: %v", err)
}
fset := token.NewFileSet()
for _, file := range files {
if filepath.Ext(file) != ".go" || strings.HasSuffix(filepath.Base(file), "_test.go") {
continue
}
src, err := os.ReadFile(file)
if err != nil {
t.Fatalf("read %s: %v", file, err)
}
parsed, err := parser.ParseFile(fset, file, src, 0)
if err != nil {
t.Fatalf("parse %s: %v", file, err)
}
for _, decl := range parsed.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
if d.Recv == nil && d.Name.Name == name {
return true
}
case *ast.GenDecl:
for _, spec := range d.Specs {
switch s := spec.(type) {
case *ast.TypeSpec:
if s.Name.Name == name {
return true
}
case *ast.ValueSpec:
for _, ident := range s.Names {
if ident.Name == name {
return true
}
}
}
}
}
}
}
return false
}