forked from surrealdb/surrealdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_integration.rs
1454 lines (1266 loc) · 39.9 KB
/
ws_integration.rs
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// RUST_LOG=warn cargo make ci-ws-integration
mod common;
mod ws_integration {
use std::time::Duration;
use serde_json::json;
use test_log::test;
use super::common::{self, PASS, USER};
use crate::common::error::TestError;
#[test(tokio::test)]
async fn ping() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
// Send command
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "ping",
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res.is_object(), "result: {:?}", res);
let res = res.as_object().unwrap();
assert!(res.keys().all(|k| ["id", "result"].contains(&k.as_str())), "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn info() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
//
// Setup operations
//
let res = common::ws_query(socket, "DEFINE TABLE user PERMISSIONS FULL").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_query(
socket,
r#"
DEFINE SCOPE scope SESSION 24h
SIGNUP ( CREATE user SET user = $user, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE user = $user AND crypto::argon2::compare(pass, $pass) )
;
"#,
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_query(
socket,
r#"
CREATE user CONTENT {
user: 'user',
pass: crypto::argon2::generate('pass')
};
"#,
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Sign in
let res =
common::ws_signin(socket, "user", "pass", Some("N"), Some("D"), Some("scope")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Send the info command
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "info",
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the response contains the expected info
let res = res.unwrap();
assert!(res["result"].is_object(), "result: {:?}", res);
let res = res["result"].as_object().unwrap();
assert_eq!(res["user"], "user", "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn signup() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Setup scope
let res = common::ws_query(
socket,
r#"
DEFINE SCOPE scope SESSION 24h
SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) )
;"#,
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Signup
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "signup",
"params": [{
"ns": "N",
"db": "D",
"sc": "scope",
"email": "[email protected]",
"pass": "pass",
}],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res.is_object(), "result: {:?}", res);
let res = res.as_object().unwrap();
// Verify response contains no error
assert!(res.keys().all(|k| ["id", "result"].contains(&k.as_str())), "result: {:?}", res);
// Verify it returns a token
assert!(res["result"].is_string(), "result: {:?}", res);
let res = res["result"].as_str().unwrap();
assert!(res.starts_with("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9"), "result: {}", res);
Ok(())
}
#[test(tokio::test)]
async fn signin() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Setup scope
let res = common::ws_query(
socket,
r#"
DEFINE SCOPE scope SESSION 24h
SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) )
;"#,
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Signup
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "signup",
"params": [{
"ns": "N",
"db": "D",
"sc": "scope",
"email": "[email protected]",
"pass": "pass",
}],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Sign in
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "signin",
"params": [{
"ns": "N",
"db": "D",
"sc": "scope",
"email": "[email protected]",
"pass": "pass",
}],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res.is_object(), "result: {:?}", res);
let res = res.as_object().unwrap();
// Verify response contains no error
assert!(res.keys().all(|k| ["id", "result"].contains(&k.as_str())), "result: {:?}", res);
// Verify it returns a token
assert!(res["result"].is_string(), "result: {:?}", res);
let res = res["result"].as_str().unwrap();
assert!(res.starts_with("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9"), "result: {}", res);
Ok(())
}
#[test(tokio::test)]
async fn variable_auth_live_query() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Setup scope
let res = common::ws_query(socket, r#"
DEFINE SCOPE scope SESSION 2s
SIGNUP ( CREATE user SET user = $user, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE user = $user AND crypto::argon2::compare(pass, $pass) )
;"#).await;
assert!(res.is_ok(), "result: {:?}", res);
// Signup
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "signup",
"params": [{
"ns": "N",
"db": "D",
"sc": "scope",
"user": "user",
"pass": "pass",
}],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Sign in
let res =
common::ws_signin(socket, "user", "pass", Some("N"), Some("D"), Some("scope")).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
// Start Live Query
let table_name = "test_tableBB4B0A788C7E46E798720AEF938CBCF6";
let _live_query_response = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "66BB05C8-EF4B-4338-BCCD-8F8A19223CB1",
"method": "live",
"params": [
table_name
],
}))
.unwrap(),
)
.await
.unwrap_or_else(|e| panic!("Error sending message: {}", e))
.as_object()
.unwrap_or_else(|| panic!("Expected object, got {:?}", res));
// Wait 2 seconds for auth to expire
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Start second connection
let socket2 = &mut common::connect_ws(&addr).await?;
// Signin
let res =
common::ws_signin(socket2, "user", "pass", Some("N"), Some("D"), Some("scope")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Insert
let id = "A23A05ABC15C420E9A7E13D2C8657890";
let query = format!(r#"INSERT INTO {} {{"id": "{}", "name": "ok"}};"#, table_name, id);
let created = common::ws_query(socket2, query.as_str()).await.unwrap();
assert_eq!(created.len(), 1);
// Validate live query from first session didnt produce a result
let res = common::ws_recv_msg(socket).await;
match &res {
Err(e) => {
if let Some(TestError::NetworkError {
..
}) = e.downcast_ref::<TestError>()
{
} else {
panic!("Expected a network error, but got: {:?}", e)
}
}
Ok(v) => {
panic!("Expected a network error, but got: {:?}", v)
}
}
Ok(())
}
#[test(tokio::test)]
async fn invalidate() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify we have a ROOT session
let res = common::ws_query(socket, "DEFINE NAMESPACE NS").await;
assert!(res.is_ok(), "result: {:?}", res);
// Invalidate session
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "invalidate",
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify we invalidated the root session
let res = common::ws_query(socket, "DEFINE NAMESPACE NS2").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert_eq!(res[0]["status"], "ERR", "result: {:?}", res);
assert_eq!(
res[0]["result"], "IAM error: Not enough permissions to perform this action",
"result: {:?}",
res
);
Ok(())
}
#[test(tokio::test)]
async fn authenticate() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let token = res.unwrap();
// Reconnect so we start with an empty session
socket.close(None).await?;
let socket = &mut common::connect_ws(&addr).await?;
//
// Authenticate with the token
//
// Send command
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "authenticate",
"params": [
token,
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify we have a ROOT session
let res = common::ws_query(socket, "DEFINE NAMESPACE D2").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert_eq!(res[0]["status"], "OK", "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn kill_kill_endpoint() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let table_name = "table_D250F804BC244558982DB7D8712F6BE3".to_string();
let socket = &mut common::connect_ws(&addr).await?;
let ns = "DE4E65C08E7248FB851CBB4D939C13C7";
let db = "D7C40F656162434DB4888E334032B52C";
let _ = common::ws_signin(socket, USER, PASS, None, None, None).await?;
let _ = common::ws_use(socket, Some(ns), Some(db)).await?;
// LIVE query via live endpoint
let live_res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "live",
"params": [
table_name
],
}))
.unwrap(),
)
.await?;
let live_id = live_res["result"].as_str().unwrap();
// KILL query via kill endpoint
common::ws_send_msg(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "kill",
"params": [
live_id
],
}))
.unwrap(),
)
.await?;
// Verify we killed the query
let msgs = common::ws_recv_all_msgs(socket, 1, Duration::from_millis(1000)).await?;
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let msg = msgs.get(0).unwrap();
assert!(msg["status"].is_null(), "unexpected status: {:?}", msg);
// Create some data for notification
let id = "an-id-goes-here";
let query = format!(r#"INSERT INTO {} {{"id": "{}", "name": "ok"}};"#, table_name, id);
let _ = common::ws_query(socket, query.as_str()).await.unwrap();
let json = json!({
"id": "1",
"method": "query",
"params": [query],
});
common::ws_send_msg(socket, serde_json::to_string(&json).unwrap()).await?;
// Wait some time for all messages to arrive, and then verify we didn't get any notification
let msgs = common::ws_recv_all_msgs(socket, 1, Duration::from_millis(500)).await?;
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let lq_notif = msgs.iter().find(|v| common::ws_msg_is_notification_from_lq(v, live_id));
assert!(lq_notif.is_none(), "Expected to find no notifications, found 1: {:#?}", msgs);
Ok(())
}
#[test(tokio::test)]
async fn kill_query_endpoint() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let table_name = "table_8B5E5635869E4FF2A35C94E8FC2CAE9A".to_string();
let socket = &mut common::connect_ws(&addr).await?;
let ns = "3CB1D26373AF45F78D836EF2F78384A2";
let db = "622772B60DEB46958B6450EE43ED2515";
let _ = common::ws_signin(socket, USER, PASS, None, None, None).await?;
let _ = common::ws_use(socket, Some(ns), Some(db)).await?;
// LIVE query via live endpoint
let live_res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "live",
"params": [
table_name
],
}))
.unwrap(),
)
.await?;
let live_id = live_res["result"].as_str().unwrap();
// KILL query via kill endpoint
let kill_query = format!("KILL '{live_id}'");
common::ws_send_msg(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "query",
"params": [
kill_query
],
}))
.unwrap(),
)
.await?;
// Verify we killed the query
let msgs = common::ws_recv_all_msgs(socket, 1, Duration::from_millis(1000)).await?;
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let msg = msgs.get(0).unwrap();
assert!(msg["status"].is_null(), "unexpected status: {:?}", msg);
// Create some data for notification
let id = "an-id-goes-here";
let query = format!(r#"INSERT INTO {} {{"id": "{}", "name": "ok"}};"#, table_name, id);
let _ = common::ws_query(socket, query.as_str()).await.unwrap();
let json = json!({
"id": "1",
"method": "query",
"params": [query],
});
common::ws_send_msg(socket, serde_json::to_string(&json).unwrap()).await?;
// Wait some time for all messages to arrive, and then verify we didn't get any notification
let msgs = common::ws_recv_all_msgs(socket, 1, Duration::from_millis(500)).await?;
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let lq_notif = msgs.iter().find(|v| common::ws_msg_is_notification_from_lq(v, live_id));
assert!(lq_notif.is_none(), "Expected to find no notifications, found 1: {:#?}", msgs);
Ok(())
}
#[test(tokio::test)]
async fn live_live_endpoint() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_without_auth().await.unwrap();
let table_name = "table_FD40A9A361884C56B5908A934164884A".to_string();
let socket = &mut common::connect_ws(&addr).await?;
let ns = "3498b03b44b5452a9d3f15252b454db1";
let db = "2cf93e52ff0a42f39d271412404a01f6";
let _ = common::ws_signin(socket, USER, PASS, None, None, None).await?;
let _ = common::ws_use(socket, Some(ns), Some(db)).await?;
// LIVE query via live endpoint
let live_res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "live",
"params": [
table_name
],
}))
.unwrap(),
)
.await?;
let live_id = live_res["result"].as_str().unwrap();
// Create some data for notification
// Manually send the query and wait for multiple messages. Ordering of the messages is not guaranteed, so we could receive the notification before the query result.
let id = "an-id-goes-here";
let query = format!(r#"INSERT INTO {} {{"id": "{}", "name": "ok"}};"#, table_name, id);
let json = json!({
"id": "1",
"method": "query",
"params": [query],
});
common::ws_send_msg(socket, serde_json::to_string(&json).unwrap()).await?;
// Wait some time for all messages to arrive, and then search for the notification message
let msgs = common::ws_recv_all_msgs(socket, 2, Duration::from_millis(500)).await;
assert!(msgs.is_ok(), "Error waiting for messages: {:?}", msgs.err());
let msgs = msgs.unwrap();
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let lq_notif = msgs.iter().find(|v| common::ws_msg_is_notification_from_lq(v, live_id));
assert!(
lq_notif.is_some(),
"Expected to find a notification for LQ id {}: {:#?}",
live_id,
msgs
);
// Extract the notification object
let lq_notif = lq_notif.unwrap();
let lq_notif = lq_notif["result"].as_object().unwrap();
// Verify message on individual keys since the notification ID is random
let action = lq_notif["action"].as_str().unwrap();
let result = lq_notif["result"].as_object().unwrap();
assert_eq!(action, "CREATE", "expected notification to be `CREATE`: {:?}", lq_notif);
let expected_id = format!("{}:⟨{}⟩", table_name, id);
assert_eq!(
result["id"].as_str(),
Some(expected_id.as_str()),
"expected notification to have id {:?}: {:?}",
expected_id,
lq_notif
);
assert_eq!(
result["name"].as_str(),
Some("ok"),
"expected notification to have name `ok`: {:?}",
lq_notif
);
Ok(())
}
#[test(tokio::test)]
async fn live_query_endpoint() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_without_auth().await.unwrap();
let table_name = "table_FD40A9A361884C56B5908A934164884A".to_string();
let socket = &mut common::connect_ws(&addr).await?;
let ns = "3498b03b44b5452a9d3f15252b454db1";
let db = "2cf93e52ff0a42f39d271412404a01f6";
let _ = common::ws_signin(socket, USER, PASS, None, None, None).await?;
let _ = common::ws_use(socket, Some(ns), Some(db)).await?;
// LIVE query via query endpoint
let lq_res =
common::ws_query(socket, format!("LIVE SELECT * FROM {};", table_name).as_str())
.await?;
assert_eq!(lq_res.len(), 1, "Expected 1 result got: {:?}", lq_res);
let live_id = lq_res[0]["result"].as_str().unwrap();
// Create some data for notification
// Manually send the query and wait for multiple messages. Ordering of the messages is not guaranteed, so we could receive the notification before the query result.
let id = "an-id-goes-here";
let query = format!(r#"INSERT INTO {} {{"id": "{}", "name": "ok"}};"#, table_name, id);
let json = json!({
"id": "1",
"method": "query",
"params": [query],
});
common::ws_send_msg(socket, serde_json::to_string(&json).unwrap()).await?;
// Wait some time for all messages to arrive, and then search for the notification message
let msgs = common::ws_recv_all_msgs(socket, 2, Duration::from_millis(500)).await;
assert!(msgs.is_ok(), "Error waiting for messages: {:?}", msgs.err());
let msgs = msgs.unwrap();
assert!(
msgs.iter().all(|v| v["error"].is_null()),
"Unexpected error received: {:#?}",
msgs
);
let lq_notif = msgs.iter().find(|v| common::ws_msg_is_notification_from_lq(v, live_id));
assert!(
lq_notif.is_some(),
"Expected to find a notification for LQ id {}: {:#?}",
live_id,
msgs
);
// Extract the notification object
let lq_notif = lq_notif.unwrap();
let lq_notif = lq_notif["result"].as_object().unwrap();
// Verify message on individual keys since the notification ID is random
let action = lq_notif["action"].as_str().unwrap();
let result = lq_notif["result"].as_object().unwrap();
assert_eq!(action, "CREATE", "expected notification to be `CREATE`: {:?}", lq_notif);
let expected_id = format!("{}:⟨{}⟩", table_name, id);
assert_eq!(
result["id"].as_str(),
Some(expected_id.as_str()),
"expected notification to have id {:?}: {:?}",
expected_id,
lq_notif
);
assert_eq!(
result["name"].as_str(),
Some("ok"),
"expected notification to have name `ok`: {:?}",
lq_notif
);
Ok(())
}
#[test(tokio::test)]
async fn let_and_set() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Define variable using let
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "let",
"params": [
"let_var", "let_value",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Define variable using set
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "set",
"params": [
"set_var", "set_value",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the variables are set
let res = common::ws_query(socket, "SELECT * FROM $let_var, $set_var").await?;
assert_eq!(
res[0]["result"],
serde_json::to_value(["let_value", "set_value"]).unwrap(),
"result: {:?}",
res
);
Ok(())
}
#[test(tokio::test)]
async fn unset() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Define variable
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "let",
"params": [
"let_var", "let_value",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the variable is set
let res = common::ws_query(socket, "SELECT * FROM $let_var").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res[0]["result"].is_array(), "result: {:?}", res);
let res = res[0]["result"].as_array().unwrap();
assert_eq!(res[0], "let_value", "result: {:?}", res);
// Unset variable
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "unset",
"params": [
"let_var",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the variable is unset
let res = common::ws_query(socket, "SELECT * FROM $let_var").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res[0]["result"].is_array(), "result: {:?}", res);
let res = res[0]["result"].as_array().unwrap();
assert!(res[0].is_null(), "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn select() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
//
// Setup the database
//
let res = common::ws_query(socket, "CREATE foo").await;
assert!(res.is_ok(), "result: {:?}", res);
// Select data
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "select",
"params": [
"foo",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res["result"].is_array(), "result: {:?}", res);
let res = res["result"].as_array().unwrap();
// Verify the response contains the output of the select
assert_eq!(res.len(), 1, "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn insert() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Insert data
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "insert",
"params": [
"table",
{
"name": "foo",
"value": "bar",
}
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the data was inserted and can be queried
let res = common::ws_query(socket, "SELECT * FROM table").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res[0]["result"].is_array(), "result: {:?}", res);
let res = res[0]["result"].as_array().unwrap();
assert_eq!(res[0]["name"], "foo", "result: {:?}", res);
assert_eq!(res[0]["value"], "bar", "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn create() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
// Insert data
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "create",
"params": [
"table",
],
}))
.unwrap(),
)
.await;
assert!(res.is_ok(), "result: {:?}", res);
// Verify the data was created and can be queried
let res = common::ws_query(socket, "SELECT * FROM table").await;
assert!(res.is_ok(), "result: {:?}", res);
let res = res.unwrap();
assert!(res[0]["result"].is_array(), "result: {:?}", res);
let res = res[0]["result"].as_array().unwrap();
assert_eq!(res.len(), 1, "result: {:?}", res);
Ok(())
}
#[test(tokio::test)]
async fn update() -> Result<(), Box<dyn std::error::Error>> {
let (addr, _server) = common::start_server_with_defaults().await.unwrap();
let socket = &mut common::connect_ws(&addr).await?;
//
// Prepare the connection
//
let res = common::ws_signin(socket, USER, PASS, None, None, None).await;
assert!(res.is_ok(), "result: {:?}", res);
let res = common::ws_use(socket, Some("N"), Some("D")).await;
assert!(res.is_ok(), "result: {:?}", res);
//
// Setup the database
//
let res = common::ws_query(socket, r#"CREATE table SET name = "foo""#).await;
assert!(res.is_ok(), "result: {:?}", res);
// Insert data
let res = common::ws_send_msg_and_wait_response(
socket,
serde_json::to_string(&json!({
"id": "1",
"method": "update",
"params": [
"table",