forked from asternic/wuzapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdio_test.go
More file actions
827 lines (702 loc) · 23.3 KB
/
stdio_test.go
File metadata and controls
827 lines (702 loc) · 23.3 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
package main
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
_ "modernc.org/sqlite"
)
func TestStdioHealthRequest(t *testing.T) {
s := makeTestServer(t)
request := newRequest("test-001", "health", nil).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "test-001",
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's a success response (has result, no error)
if response["result"] == nil {
t.Errorf("Expected result field, got nil")
}
if response["error"] != nil {
t.Errorf("Expected no error, got: %v", response["error"])
}
}
func TestAdminUsersAddAndList(t *testing.T) {
s := makeTestServer(t)
// First, add a user
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "Alice",
"token": "alice-token-123",
}).toJSON(t)
addResponse := executeRequest(t, s, addRequest)
expectedAdd := map[string]interface{}{
"jsonrpc": "2.0",
"id": "1",
}
if diff := compareJSON(expectedAdd, addResponse); diff != "" {
t.Errorf("Add response mismatch:\n%s", diff)
}
if addResponse["error"] != nil {
t.Fatalf("Failed to add user: %v", addResponse["error"])
}
// Now list users to verify the user was added
listRequest := newRequest("2", "admin.users.list", map[string]interface{}{
"adminToken": "test-admin-token",
}).toJSON(t)
listResponse := executeRequest(t, s, listRequest)
expectedList := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedList, listResponse); diff != "" {
t.Errorf("List response mismatch:\n%s", diff)
}
if listResponse["error"] != nil {
t.Fatalf("List request failed: %v", listResponse["error"])
}
// Verify the user appears in the list with correct data
users := listResponse["result"].([]interface{})
if len(users) != 1 {
t.Fatalf("Expected 1 user, got %d", len(users))
}
user := users[0].(map[string]interface{})
expectedUser := map[string]interface{}{
"name": "Alice",
"token": "alice-token-123",
}
if diff := compareJSON(expectedUser, user); diff != "" {
t.Errorf("User data mismatch:\n%s", diff)
}
}
func TestAdminUsersGet(t *testing.T) {
s := makeTestServer(t)
// First add a user
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "Bob",
"token": "bob-token-456",
}).toJSON(t)
addResponse := executeRequest(t, s, addRequest)
expectedAdd := map[string]interface{}{
"jsonrpc": "2.0",
"id": "1",
}
if diff := compareJSON(expectedAdd, addResponse); diff != "" {
t.Errorf("Add response mismatch:\n%s", diff)
}
// Extract the userId from the add response
addData := addResponse["result"].(map[string]interface{})
userId := addData["id"].(string)
// Now get the specific user
getRequest := newRequest("2", "admin.users.get", map[string]interface{}{
"adminToken": "test-admin-token",
"userId": userId,
}).toJSON(t)
getResponse := executeRequest(t, s, getRequest)
expectedGet := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedGet, getResponse); diff != "" {
t.Errorf("Get response mismatch:\n%s", diff)
}
// Verify the user data
users := getResponse["result"].([]interface{})
if len(users) != 1 {
t.Fatalf("Expected 1 user, got %d", len(users))
}
user := users[0].(map[string]interface{})
expectedUser := map[string]interface{}{
"name": "Bob",
"token": "bob-token-456",
}
if diff := compareJSON(expectedUser, user); diff != "" {
t.Errorf("User data mismatch:\n%s", diff)
}
}
func TestAdminUsersDelete(t *testing.T) {
s := makeTestServer(t)
// First add a user
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "Charlie",
"token": "charlie-token-789",
}).toJSON(t)
addResponse := executeRequest(t, s, addRequest)
addData := addResponse["result"].(map[string]interface{})
userId := addData["id"].(string)
// Delete the user
deleteRequest := newRequest("2", "admin.users.delete", map[string]interface{}{
"adminToken": "test-admin-token",
"userId": userId,
}).toJSON(t)
deleteResponse := executeRequest(t, s, deleteRequest)
expectedDelete := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedDelete, deleteResponse); diff != "" {
t.Errorf("Delete response mismatch:\n%s", diff)
}
// Verify user is gone by listing
listRequest := newRequest("3", "admin.users.list", map[string]interface{}{
"adminToken": "test-admin-token",
}).toJSON(t)
listResponse := executeRequest(t, s, listRequest)
expectedList := map[string]interface{}{
"jsonrpc": "2.0",
"id": "3",
}
if diff := compareJSON(expectedList, listResponse); diff != "" {
t.Errorf("List response mismatch:\n%s", diff)
}
users := listResponse["result"].([]interface{})
if len(users) != 0 {
t.Errorf("Expected 0 users after deletion, got %d", len(users))
}
}
func TestSessionStatus(t *testing.T) {
s := makeTestServer(t)
// First create a user to get a valid token
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "TestUser",
"token": "test-user-token",
}).toJSON(t)
addResponse := executeRequest(t, s, addRequest)
expectedAdd := map[string]interface{}{
"jsonrpc": "2.0",
"id": "1",
}
if diff := compareJSON(expectedAdd, addResponse); diff != "" {
t.Errorf("Add response mismatch:\n%s", diff)
}
// Now check session status
statusRequest := newRequest("2", "session.status", map[string]interface{}{
"token": "test-user-token",
}).toJSON(t)
statusResponse := executeRequest(t, s, statusRequest)
expectedStatus := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedStatus, statusResponse); diff != "" {
t.Errorf("Status response mismatch:\n%s", diff)
}
// Verify response has expected fields
data := statusResponse["result"].(map[string]interface{})
if _, hasConnected := data["connected"]; !hasConnected {
t.Errorf("Status response missing 'connected' field")
}
if _, hasLoggedIn := data["loggedIn"]; !hasLoggedIn {
t.Errorf("Status response missing 'loggedIn' field")
}
}
// Note: session.connect, session.disconnect, session.logout tests are skipped
// because they require full WhatsApp/whatsmeow initialization which is complex
// to set up in unit tests. The routing is tested via session.status.
// Manual/integration testing should be used for these methods.
func TestChatSendText(t *testing.T) {
s := makeTestServer(t)
// Create a user first
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "MessageUser",
"token": "message-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Try to send a message (will fail because no WhatsApp session, but tests routing)
sendRequest := newRequest("2", "chat.send.text", map[string]interface{}{
"token": "message-token",
"Phone": "1234567890",
"Body": "Hello, World!",
}).toJSON(t)
sendResponse := executeRequest(t, s, sendRequest)
// Should fail with "no session" error since we don't have WhatsApp initialized
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expected, sendResponse); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's an error response
if sendResponse["error"] == nil {
t.Errorf("Expected error (no session), got success")
}
if sendResponse["result"] != nil {
t.Errorf("Expected no result on error, got: %v", sendResponse["result"])
}
errorObj := sendResponse["error"].(map[string]interface{})
if errorObj["code"].(float64) != 500 {
t.Errorf("Expected error code 500 (no session), got %v", errorObj["code"])
}
}
func TestChatHistory(t *testing.T) {
s := makeTestServer(t)
// Create a user with history enabled
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "HistoryUser",
"token": "history-token",
"history": 100,
}).toJSON(t)
executeRequest(t, s, addRequest)
// Try to get history (will fail because no WhatsApp session, but tests routing)
historyRequest := newRequest("2", "chat.history", map[string]interface{}{
"token": "history-token",
"chat_jid": "1234567890@s.whatsapp.net",
}).toJSON(t)
historyResponse := executeRequest(t, s, historyRequest)
// The routing should work even if the actual operation fails
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expected, historyResponse); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Either result or error should be present (check for key existence, not just value)
_, hasResult := historyResponse["result"]
_, hasError := historyResponse["error"]
if !hasResult && !hasError {
t.Errorf("Expected either result or error field. Got response: %+v", historyResponse)
}
}
// testRequest builds a JSON-RPC request with type safety
type testRequest struct {
ID interface{} // Can be string, int, or nil
Method string
Params interface{}
}
// newRequest creates a new request builder with string or numeric ID
func newRequest(id interface{}, method string, params interface{}) *testRequest {
return &testRequest{
ID: id,
Method: method,
Params: params,
}
}
// toJSON converts the request to a JSON string
func (r *testRequest) toJSON(t *testing.T) string {
t.Helper()
reqData := map[string]interface{}{
"id": r.ID,
"method": r.Method,
}
if r.Params != nil {
reqData["params"] = r.Params
}
jsonBytes, err := json.Marshal(reqData)
if err != nil {
t.Fatalf("Failed to marshal request: %v", err)
}
return string(jsonBytes)
}
// executeRequest is a helper that sends a JSON-RPC request and returns the parsed response
func executeRequest(t *testing.T, s *server, request string) map[string]interface{} {
t.Helper()
stdin := bytes.NewBufferString(request + "\n")
stdout := &bytes.Buffer{}
stdioServer := newStdioServerWithIO(s, stdin, stdout)
if err := stdioServer.Start(); err != nil {
t.Fatalf("Start() failed: %v", err)
}
var response map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response:\n%s\nError: %v", stdout.String(), err)
}
return response
}
func makeTestServer(t *testing.T) *server {
t.Helper()
// Set admin token for tests
testToken := "test-admin-token"
*adminToken = testToken
// Use in-memory database
db, err := sqlx.Open("sqlite", ":memory:")
if err != nil {
t.Fatalf("Failed to create test database: %v", err)
}
t.Cleanup(func() { db.Close() })
// Initialize schema using the same function as production
if err := initializeSchema(db); err != nil {
t.Fatalf("Failed to initialize schema: %v", err)
}
s := &server{
db: db,
router: mux.NewRouter(),
}
s.routes()
return s
}
// assertJSONRPC20Success checks that a response is a successful JSON-RPC 2.0 response
// and returns the result data for further assertions
func assertJSONRPC20Success(t *testing.T, response map[string]interface{}, expectedID interface{}) interface{} {
t.Helper()
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": expectedID,
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response structure mismatch:\n%s", diff)
}
if response["error"] != nil {
t.Fatalf("Expected no error, got: %v", response["error"])
}
if response["result"] == nil {
t.Fatalf("Expected result field, got nil")
}
return response["result"]
}
// assertJSONRPC20Error checks that a response is an error JSON-RPC 2.0 response
func assertJSONRPC20Error(t *testing.T, response map[string]interface{}, expectedID interface{}, expectedCode float64) map[string]interface{} {
t.Helper()
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": expectedID,
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response structure mismatch:\n%s", diff)
}
if response["result"] != nil {
t.Fatalf("Expected no result on error, got: %v", response["result"])
}
if response["error"] == nil {
t.Fatalf("Expected error field, got nil")
}
errorObj := response["error"].(map[string]interface{})
if errorObj["code"].(float64) != expectedCode {
t.Errorf("Expected error code %v, got: %v", expectedCode, errorObj["code"])
}
return errorObj
}
// compareJSON compares two JSON objects and returns a human-readable diff
func compareJSON(expected, actual map[string]interface{}) string {
var diffs []string
for key, expectedVal := range expected {
actualVal, exists := actual[key]
if !exists {
diffs = append(diffs, fmt.Sprintf(" Missing field: %q", key))
continue
}
if fmt.Sprintf("%v", expectedVal) != fmt.Sprintf("%v", actualVal) {
diffs = append(diffs, fmt.Sprintf(" Field %q: expected %v, got %v", key, expectedVal, actualVal))
}
}
if len(diffs) > 0 {
expectedJSON, _ := json.MarshalIndent(expected, " ", " ")
actualJSON, _ := json.MarshalIndent(actual, " ", " ")
return fmt.Sprintf("Expected:\n %s\n\n Actual:\n %s\n\n Differences:\n%s",
expectedJSON, actualJSON, strings.Join(diffs, "\n"))
}
return ""
}
func TestWebhookUpdate(t *testing.T) {
s := makeTestServer(t)
// Create a user first
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "WebhookUser",
"token": "webhook-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Update webhook to subscribe to events
updateRequest := newRequest("2", "webhook.update", map[string]interface{}{
"token": "webhook-token",
"events": []string{"Message", "Connected"},
"active": true,
}).toJSON(t)
updateResponse := executeRequest(t, s, updateRequest)
expectedUpdate := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedUpdate, updateResponse); diff != "" {
t.Errorf("Update response mismatch:\n%s", diff)
}
// Verify the update worked by getting webhook config
getRequest := newRequest("3", "webhook.get", map[string]interface{}{
"token": "webhook-token",
}).toJSON(t)
getResponse := executeRequest(t, s, getRequest)
expectedGet := map[string]interface{}{
"jsonrpc": "2.0",
"id": "3",
}
if diff := compareJSON(expectedGet, getResponse); diff != "" {
t.Errorf("Get response mismatch:\n%s", diff)
}
// Check events are set
data := getResponse["result"].(map[string]interface{})
subscribe := data["subscribe"].([]interface{})
if len(subscribe) != 2 {
t.Errorf("Expected 2 subscribed events, got %d: %v", len(subscribe), subscribe)
}
}
func TestWebhookSet(t *testing.T) {
s := makeTestServer(t)
// Create a user first
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "SetUser",
"token": "set-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Set webhook with events
setRequest := newRequest("2", "webhook.set", map[string]interface{}{
"token": "set-token",
"webhookurl": "http://example.com/webhook",
"events": []string{"Message", "Receipt"},
}).toJSON(t)
setResponse := executeRequest(t, s, setRequest)
expectedSet := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expectedSet, setResponse); diff != "" {
t.Errorf("Set response mismatch:\n%s", diff)
}
}
func TestWebhookDelete(t *testing.T) {
s := makeTestServer(t)
// Create a user with webhook configured
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "DeleteUser",
"token": "delete-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Set a webhook first
setRequest := newRequest("2", "webhook.set", map[string]interface{}{
"token": "delete-token",
"webhookurl": "http://example.com/webhook",
"events": []string{"Message"},
}).toJSON(t)
executeRequest(t, s, setRequest)
// Delete webhook
deleteRequest := newRequest("3", "webhook.delete", map[string]interface{}{
"token": "delete-token",
}).toJSON(t)
deleteResponse := executeRequest(t, s, deleteRequest)
expectedDelete := map[string]interface{}{
"jsonrpc": "2.0",
"id": "3",
}
if diff := compareJSON(expectedDelete, deleteResponse); diff != "" {
t.Errorf("Delete response mismatch:\n%s", diff)
}
// Verify webhook is cleared
getRequest := newRequest("4", "webhook.get", map[string]interface{}{
"token": "delete-token",
}).toJSON(t)
getResponse := executeRequest(t, s, getRequest)
expectedGet := map[string]interface{}{
"jsonrpc": "2.0",
"id": "4",
}
if diff := compareJSON(expectedGet, getResponse); diff != "" {
t.Errorf("Get response mismatch:\n%s", diff)
}
data := getResponse["result"].(map[string]interface{})
webhook := data["webhook"].(string)
if webhook != "" {
t.Errorf("Expected empty webhook after delete, got: %s", webhook)
}
}
func TestNumericRequestID(t *testing.T) {
s := makeTestServer(t)
// Send request with numeric ID (JSON-RPC 2.0 compliant)
request := newRequest(42, "health", nil).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": float64(42), // JSON unmarshals numbers as float64
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's a success response (has result, no error)
if response["result"] == nil {
t.Errorf("Expected result field, got nil")
}
if response["error"] != nil {
t.Errorf("Expected no error, got: %v", response["error"])
}
}
func TestNumericZeroRequestID(t *testing.T) {
s := makeTestServer(t)
// Send request with numeric ID 0 (valid per JSON-RPC 2.0 spec)
request := newRequest(0, "health", nil).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": float64(0), // JSON unmarshals numbers as float64
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's a success response (has result, no error)
if response["result"] == nil {
t.Errorf("Expected result field, got nil")
}
if response["error"] != nil {
t.Errorf("Expected no error, got: %v", response["error"])
}
}
func TestParseErrorReturnsNullID(t *testing.T) {
s := makeTestServer(t)
// Send invalid JSON to trigger parse error
request := `{invalid json`
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": nil, // null ID for parse errors
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's an error response (has error, no result)
if response["error"] == nil {
t.Errorf("Expected error field for parse error, got nil")
}
if response["result"] != nil {
t.Errorf("Expected no result for parse error, got: %v", response["result"])
}
}
func TestMissingUserIdParam(t *testing.T) {
s := makeTestServer(t)
// Test admin.users.get without userId parameter
request := newRequest("1", "admin.users.get", map[string]interface{}{
"adminToken": "test-admin-token",
// userId missing
}).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "1",
"error": map[string]interface{}{
"code": float64(400),
"message": "missing or invalid userId parameter",
},
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's an error response (has error, no result)
if response["error"] == nil {
t.Errorf("Expected error field, got nil")
}
if response["result"] != nil {
t.Errorf("Expected no result for error, got: %v", response["result"])
}
}
func TestInvalidUserIdParamType(t *testing.T) {
s := makeTestServer(t)
// Test with invalid userId type (number instead of string)
request := newRequest("1", "admin.users.get", map[string]interface{}{
"adminToken": "test-admin-token",
"userId": 12345, // number instead of string
}).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "1",
"error": map[string]interface{}{
"code": float64(400),
"message": "missing or invalid userId parameter",
},
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's an error response (has error, no result)
if response["error"] == nil {
t.Errorf("Expected error field, got nil")
}
if response["result"] != nil {
t.Errorf("Expected no result for error, got: %v", response["result"])
}
}
func TestStringRequestID(t *testing.T) {
s := makeTestServer(t)
// Send request with string ID (also JSON-RPC 2.0 compliant)
request := newRequest("test-123", "health", nil).toJSON(t)
response := executeRequest(t, s, request)
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "test-123",
}
if diff := compareJSON(expected, response); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Verify it's a success response (has result, no error)
if response["result"] == nil {
t.Errorf("Expected result field, got nil")
}
if response["error"] != nil {
t.Errorf("Expected no error, got: %v", response["error"])
}
}
func TestUserContacts(t *testing.T) {
s := makeTestServer(t)
// Create a user first
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "ContactsUser",
"token": "contacts-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Try to get contacts (will fail because no WhatsApp session, but tests routing)
contactsRequest := newRequest("2", "user.contacts", map[string]interface{}{
"token": "contacts-token",
}).toJSON(t)
contactsResponse := executeRequest(t, s, contactsRequest)
// The routing should work even if the actual operation fails
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expected, contactsResponse); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Either result or error should be present
if contactsResponse["result"] == nil && contactsResponse["error"] == nil {
t.Errorf("Expected either result or error field")
}
}
func TestGroupList(t *testing.T) {
s := makeTestServer(t)
// Create a user first
addRequest := newRequest("1", "admin.users.add", map[string]interface{}{
"adminToken": "test-admin-token",
"name": "GroupUser",
"token": "group-token",
}).toJSON(t)
executeRequest(t, s, addRequest)
// Try to list groups (will fail because no WhatsApp session, but tests routing)
groupListRequest := newRequest("2", "group.list", map[string]interface{}{
"token": "group-token",
}).toJSON(t)
groupListResponse := executeRequest(t, s, groupListRequest)
// The routing should work even if the actual operation fails
expected := map[string]interface{}{
"jsonrpc": "2.0",
"id": "2",
}
if diff := compareJSON(expected, groupListResponse); diff != "" {
t.Errorf("Response mismatch:\n%s", diff)
}
// Either result or error should be present
if groupListResponse["result"] == nil && groupListResponse["error"] == nil {
t.Errorf("Expected either result or error field")
}
}