summaryrefslogtreecommitdiffstats
path: root/tests/unit/functions.tcl
blob: 9e8ec08f32770f59fc1b94935d6080a97cc25566 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
proc get_function_code {args} {
    return [format "#!%s name=%s\nredis.register_function('%s', function(KEYS, ARGV)\n %s \nend)" [lindex $args 0] [lindex $args 1] [lindex $args 2] [lindex $args 3]]
}

proc get_no_writes_function_code {args} {
    return [format "#!%s name=%s\nredis.register_function{function_name='%s', callback=function(KEYS, ARGV)\n %s \nend, flags={'no-writes'}}" [lindex $args 0] [lindex $args 1] [lindex $args 2] [lindex $args 3]]
}

start_server {tags {"scripting"}} {
    test {FUNCTION - Basic usage} {
        r function load [get_function_code LUA test test {return 'hello'}]
        r fcall test 0
    } {hello}

    test {FUNCTION - Load with unknown argument} {
        catch {
            r function load foo bar [get_function_code LUA test test {return 'hello'}]
        } e
        set _ $e
    } {*Unknown option given*}

    test {FUNCTION - Create an already exiting library raise error} {
        catch {
            r function load [get_function_code LUA test test {return 'hello1'}]
        } e
        set _ $e
    } {*already exists*}

    test {FUNCTION - Create an already exiting library raise error (case insensitive)} {
        catch {
            r function load [get_function_code LUA test test {return 'hello1'}]
        } e
        set _ $e
    } {*already exists*}

    test {FUNCTION - Create a library with wrong name format} {
        catch {
            r function load [get_function_code LUA {bad\0foramat} test {return 'hello1'}]
        } e
        set _ $e
    } {*Library names can only contain letters, numbers, or underscores(_)*}

    test {FUNCTION - Create library with unexisting engine} {
        catch {
            r function load [get_function_code bad_engine test test {return 'hello1'}]
        } e
        set _ $e
    } {*Engine 'bad_engine' not found*}

    test {FUNCTION - Test uncompiled script} {
        catch {
            r function load replace [get_function_code LUA test test {bad script}]
        } e
        set _ $e
    } {*Error compiling function*}

    test {FUNCTION - test replace argument} {
        r function load REPLACE [get_function_code LUA test test {return 'hello1'}]
        r fcall test 0
    } {hello1}

    test {FUNCTION - test function case insensitive} {
        r fcall TEST 0
    } {hello1}

    test {FUNCTION - test replace argument with failure keeps old libraries} {
         catch {r function create LUA test REPLACE {error}}
        r fcall test 0
    } {hello1}

    test {FUNCTION - test function delete} {
        r function delete test
        catch {
            r fcall test 0
        } e
        set _ $e
    } {*Function not found*}

    test {FUNCTION - test fcall bad arguments} {
        r function load [get_function_code LUA test test {return 'hello'}]
        catch {
            r fcall test bad_arg
        } e
        set _ $e
    } {*Bad number of keys provided*}

    test {FUNCTION - test fcall bad number of keys arguments} {
        catch {
            r fcall test 10 key1
        } e
        set _ $e
    } {*Number of keys can't be greater than number of args*}

    test {FUNCTION - test fcall negative number of keys} {
        catch {
            r fcall test -1 key1
        } e
        set _ $e
    } {*Number of keys can't be negative*}

    test {FUNCTION - test delete on not exiting library} {
        catch {
            r function delete test1
        } e
        set _ $e
    } {*Library not found*}

    test {FUNCTION - test function kill when function is not running} {
        catch {
            r function kill
        } e
        set _ $e
    } {*No scripts in execution*}

    test {FUNCTION - test wrong subcommand} {
        catch {
            r function bad_subcommand
        } e
        set _ $e
    } {*unknown subcommand*}

    test {FUNCTION - test loading from rdb} {
        r debug reload
        r fcall test 0
    } {hello} {needs:debug}

    test {FUNCTION - test debug reload different options} {
        catch {r debug reload noflush} e
        assert_match "*Error trying to load the RDB*" $e
        r debug reload noflush merge
        r function list
    } {{library_name test engine LUA functions {{name test description {} flags {}}}}} {needs:debug}

    test {FUNCTION - test debug reload with nosave and noflush} {
        r function delete test
        r set x 1
        r function load [get_function_code LUA test1 test1 {return 'hello'}]
        r debug reload
        r function load [get_function_code LUA test2 test2 {return 'hello'}]
        r debug reload nosave noflush merge
        assert_equal [r fcall test1 0] {hello}
        assert_equal [r fcall test2 0] {hello}
    } {} {needs:debug}

    test {FUNCTION - test flushall and flushdb do not clean functions} {
        r function flush
        r function load REPLACE [get_function_code lua test test {return redis.call('set', 'x', '1')}]
        r flushall
        r flushdb
        r function list
    } {{library_name test engine LUA functions {{name test description {} flags {}}}}}

    test {FUNCTION - test function dump and restore} {
        r function flush
        r function load [get_function_code lua test test {return 'hello'}]
        set e [r function dump]
        r function delete test
        assert_match {} [r function list]
        r function restore $e
        r function list
    } {{library_name test engine LUA functions {{name test description {} flags {}}}}}

    test {FUNCTION - test function dump and restore with flush argument} {
        set e [r function dump]
        r function flush
        assert_match {} [r function list]
        r function restore $e FLUSH
        r function list
    } {{library_name test engine LUA functions {{name test description {} flags {}}}}}

    test {FUNCTION - test function dump and restore with append argument} {
        set e [r function dump]
        r function flush
        assert_match {} [r function list]
        r function load [get_function_code lua test test {return 'hello1'}]
        catch {r function restore $e APPEND} err
        assert_match {*already exists*} $err
        r function flush
        r function load [get_function_code lua test1 test1 {return 'hello1'}]
        r function restore $e APPEND
        assert_match {hello} [r fcall test 0]
        assert_match {hello1} [r fcall test1 0]
    }

    test {FUNCTION - test function dump and restore with replace argument} {
        r function flush
        r function load [get_function_code LUA test test {return 'hello'}]
        set e [r function dump]
        r function flush
        assert_match {} [r function list]
        r function load [get_function_code lua test test {return 'hello1'}]
        assert_match {hello1} [r fcall test 0]
        r function restore $e REPLACE
        assert_match {hello} [r fcall test 0]
    }

    test {FUNCTION - test function restore with bad payload do not drop existing functions} {
        r function flush
        r function load [get_function_code LUA test test {return 'hello'}]
        catch {r function restore bad_payload} e
        assert_match {*payload version or checksum are wrong*} $e
        r function list
    } {{library_name test engine LUA functions {{name test description {} flags {}}}}}

    test {FUNCTION - test function restore with wrong number of arguments} {
        catch {r function restore arg1 args2 arg3} e
        set _ $e
    } {*unknown subcommand or wrong number of arguments for 'restore'. Try FUNCTION HELP.}

    test {FUNCTION - test fcall_ro with write command} {
        r function load REPLACE [get_no_writes_function_code lua test test {return redis.call('set', 'x', '1')}]
        catch { r fcall_ro test 1 x } e
        set _ $e
    } {*Write commands are not allowed from read-only scripts*}

    test {FUNCTION - test fcall_ro with read only commands} {
        r function load REPLACE [get_no_writes_function_code lua test test {return redis.call('get', 'x')}]
        r set x 1
        r fcall_ro test 1 x
    } {1}

    test {FUNCTION - test keys and argv} {
        r function load REPLACE [get_function_code lua test test {return redis.call('set', KEYS[1], ARGV[1])}]
        r fcall test 1 x foo
        r get x
    } {foo}

    test {FUNCTION - test command get keys on fcall} {
        r COMMAND GETKEYS fcall test 1 x foo
    } {x}

    test {FUNCTION - test command get keys on fcall_ro} {
        r COMMAND GETKEYS fcall_ro test 1 x foo
    } {x}

    test {FUNCTION - test function kill} {
        set rd [redis_deferring_client]
        r config set busy-reply-threshold 10
        r function load REPLACE [get_function_code lua test test {local a = 1 while true do a = a + 1 end}]
        $rd fcall test 0
        after 200
        catch {r ping} e
        assert_match {BUSY*} $e
        assert_match {running_script {name test command {fcall test 0} duration_ms *} engines {*}} [r FUNCTION STATS]
        r function kill
        after 200 ; # Give some time to Lua to call the hook again...
        assert_equal [r ping] "PONG"
    }

    test {FUNCTION - test script kill not working on function} {
        set rd [redis_deferring_client]
        r config set busy-reply-threshold 10
        r function load REPLACE [get_function_code lua test test {local a = 1 while true do a = a + 1 end}]
        $rd fcall test 0
        after 200
        catch {r ping} e
        assert_match {BUSY*} $e
        catch {r script kill} e
        assert_match {BUSY*} $e
        r function kill
        after 200 ; # Give some time to Lua to call the hook again...
        assert_equal [r ping] "PONG"
    }

    test {FUNCTION - test function kill not working on eval} {
        set rd [redis_deferring_client]
        r config set busy-reply-threshold 10
        $rd eval {local a = 1 while true do a = a + 1 end} 0
        after 200
        catch {r ping} e
        assert_match {BUSY*} $e
        catch {r function kill} e
        assert_match {BUSY*} $e
        r script kill
        after 200 ; # Give some time to Lua to call the hook again...
        assert_equal [r ping] "PONG"
    }

    test {FUNCTION - test function flush} {
        r function load REPLACE [get_function_code lua test test {local a = 1 while true do a = a + 1 end}]
        assert_match {{library_name test engine LUA functions {{name test description {} flags {}}}}} [r function list]
        r function flush
        assert_match {} [r function list]

        r function load REPLACE [get_function_code lua test test {local a = 1 while true do a = a + 1 end}]
        assert_match {{library_name test engine LUA functions {{name test description {} flags {}}}}} [r function list]
        r function flush async
        assert_match {} [r function list]

        r function load REPLACE [get_function_code lua test test {local a = 1 while true do a = a + 1 end}]
        assert_match {{library_name test engine LUA functions {{name test description {} flags {}}}}} [r function list]
        r function flush sync
        assert_match {} [r function list]
    }

    test {FUNCTION - test function wrong argument} {
        catch {r function flush bad_arg} e
        assert_match {*only supports SYNC|ASYNC*} $e

        catch {r function flush sync extra_arg} e
        assert_match {*unknown subcommand or wrong number of arguments for 'flush'. Try FUNCTION HELP.} $e
    }
}

start_server {tags {"scripting repl external:skip"}} {
    start_server {} {
        test "Connect a replica to the master instance" {
            r -1 slaveof [srv 0 host] [srv 0 port]
            wait_for_condition 150 100 {
                [s -1 role] eq {slave} &&
                [string match {*master_link_status:up*} [r -1 info replication]]
            } else {
                fail "Can't turn the instance into a replica"
            }
        }

        test {FUNCTION - creation is replicated to replica} {
            r function load [get_no_writes_function_code LUA test test {return 'hello'}]
            wait_for_condition 150 100 {    
                [r -1 function list] eq {{library_name test engine LUA functions {{name test description {} flags no-writes}}}}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }
        }

        test {FUNCTION - call on replica} {
            r -1 fcall test 0
        } {hello}

        test {FUNCTION - restore is replicated to replica} {
            set e [r function dump]

            r function delete test
            wait_for_condition 150 100 {
                [r -1 function list] eq {}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }

            assert_equal [r function restore $e] {OK}

            wait_for_condition 150 100 {
                [r -1 function list] eq {{library_name test engine LUA functions {{name test description {} flags no-writes}}}}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }
        }

        test {FUNCTION - delete is replicated to replica} {
            r function delete test
            wait_for_condition 150 100 {
                [r -1 function list] eq {}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }
        }

        test {FUNCTION - flush is replicated to replica} {
            r function load [get_function_code LUA test test {return 'hello'}]
            wait_for_condition 150 100 {
                [r -1 function list] eq {{library_name test engine LUA functions {{name test description {} flags {}}}}}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }
            r function flush
            wait_for_condition 150 100 {
                [r -1 function list] eq {}
            } else {
                fail "Failed waiting for function to replicate to replica"
            }
        }

        test "Disconnecting the replica from master instance" {
            r -1 slaveof no one
            # creating a function after disconnect to make sure function
            # is replicated on rdb phase
            r function load [get_no_writes_function_code LUA test test {return 'hello'}]

            # reconnect the replica
            r -1 slaveof [srv 0 host] [srv 0 port]
            wait_for_condition 150 100 {
                [s -1 role] eq {slave} &&
                [string match {*master_link_status:up*} [r -1 info replication]]
            } else {
                fail "Can't turn the instance into a replica"
            }
        }

        test "FUNCTION - test replication to replica on rdb phase" {
            r -1 fcall test 0
        } {hello}

        test "FUNCTION - test replication to replica on rdb phase info command" {
            r -1 function list
        } {{library_name test engine LUA functions {{name test description {} flags no-writes}}}}

        test "FUNCTION - create on read only replica" {
            catch {
                r -1 function load [get_function_code LUA test test {return 'hello'}]
            } e
            set _ $e
        } {*can't write against a read only replica*}

        test "FUNCTION - delete on read only replica" {
            catch {
                r -1 function delete test
            } e
            set _ $e
        } {*can't write against a read only replica*}

        test "FUNCTION - function effect is replicated to replica" {
            r function load REPLACE [get_function_code LUA test test {return redis.call('set', 'x', '1')}]
            r fcall test 1 x
            assert {[r get x] eq {1}}
            wait_for_condition 150 100 {
                [r -1 get x] eq {1}
            } else {
                fail "Failed waiting function effect to be replicated to replica"
            }
        }

        test "FUNCTION - modify key space of read only replica" {
            catch {
                r -1 fcall test 1 x
            } e
            set _ $e
        } {READONLY You can't write against a read only replica.}
    }
}

test {FUNCTION can processes create, delete and flush commands in AOF when doing "debug loadaof" in read-only slaves} {
    start_server {} {
        r config set appendonly yes
        waitForBgrewriteaof r
        r FUNCTION LOAD "#!lua name=test\nredis.register_function('test', function() return 'hello' end)"
        r config set slave-read-only yes
        r slaveof 127.0.0.1 0
        r debug loadaof
        r slaveof no one
        assert_equal [r function list] {{library_name test engine LUA functions {{name test description {} flags {}}}}}

        r FUNCTION DELETE test

        r slaveof 127.0.0.1 0
        r debug loadaof
        r slaveof no one
        assert_equal [r function list] {}

        r FUNCTION LOAD "#!lua name=test\nredis.register_function('test', function() return 'hello' end)"
        r FUNCTION FLUSH

        r slaveof 127.0.0.1 0
        r debug loadaof
        r slaveof no one
        assert_equal [r function list] {}
    }
} {} {needs:debug external:skip}

start_server {tags {"scripting"}} {
    test {LIBRARIES - test shared function can access default globals} {
        r function load {#!lua name=lib1
            local function ping()
                return redis.call('ping')
            end
            redis.register_function(
                'f1',
                function(keys, args)
                    return ping()
                end
            )
        }
        r fcall f1 0
    } {PONG}

    test {LIBRARIES - usage and code sharing} {
        r function load REPLACE {#!lua name=lib1
            local function add1(a)
                return a + 1
            end
            redis.register_function(
                'f1',
                function(keys, args)
                    return add1(1)
                end
            )
            redis.register_function(
                'f2',
                function(keys, args)
                    return add1(2)
                end
            )
        }
        assert_equal [r fcall f1 0] {2}
        assert_equal [r fcall f2 0] {3}
        r function list
    } {{library_name lib1 engine LUA functions {*}}}

    test {LIBRARIES - test registration failure revert the entire load} {
        catch {
            r function load replace {#!lua name=lib1
                local function add1(a)
                    return a + 2
                end
                redis.register_function(
                    'f1',
                    function(keys, args)
                        return add1(1)
                    end
                )
                redis.register_function(
                    'f2',
                    'not a function'
                )
            }
        } e
        assert_match {*second argument to redis.register_function must be a function*} $e
        assert_equal [r fcall f1 0] {2}
        assert_equal [r fcall f2 0] {3}
    }

    test {LIBRARIES - test registration function name collision} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function(
                    'f1',
                    function(keys, args)
                        return 1
                    end
                )
            }
        } e
        assert_match {*Function f1 already exists*} $e
        assert_equal [r fcall f1 0] {2}
        assert_equal [r fcall f2 0] {3}
    }

    test {LIBRARIES - test registration function name collision on same library} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function(
                    'f1',
                    function(keys, args)
                        return 1
                    end
                )
                redis.register_function(
                    'f1',
                    function(keys, args)
                        return 1
                    end
                )
            }
        } e
        set _ $e
    } {*Function already exists in the library*}

    test {LIBRARIES - test registration with no argument} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function()
            }
        } e
        set _ $e
    } {*wrong number of arguments to redis.register_function*}

    test {LIBRARIES - test registration with only name} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function('f1')
            }
        } e
        set _ $e
    } {*calling redis.register_function with a single argument is only applicable to Lua table*}

    test {LIBRARIES - test registration with to many arguments} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function('f1', function() return 1 end, {}, 'description', 'extra arg')
            }
        } e
        set _ $e
    } {*wrong number of arguments to redis.register_function*}

    test {LIBRARIES - test registration with no string name} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function(nil, function() return 1 end)
            }
        } e
        set _ $e
    } {*first argument to redis.register_function must be a string*}

    test {LIBRARIES - test registration with wrong name format} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function('test\0test', function() return 1 end)
            }
        } e
        set _ $e
    } {*Library names can only contain letters, numbers, or underscores(_) and must be at least one character long*}

    test {LIBRARIES - test registration with empty name} {
        catch {
            r function load replace {#!lua name=lib2
                redis.register_function('', function() return 1 end)
            }
        } e
        set _ $e
    } {*Library names can only contain letters, numbers, or underscores(_) and must be at least one character long*}

    test {LIBRARIES - math.random from function load} {
        catch {
            r function load replace {#!lua name=lib2
                return math.random()
            }
        } e
        set _ $e
    } {*attempted to access nonexistent global variable 'math'*}

    test {LIBRARIES - redis.call from function load} {
        catch {
            r function load replace {#!lua name=lib2
                return redis.call('ping')
            }
        } e
        set _ $e
    } {*attempted to access nonexistent global variable 'call'*}

    test {LIBRARIES - redis.setresp from function load} {
        catch {
            r function load replace {#!lua name=lib2
                return redis.setresp(3)
            }
        } e
        set _ $e
    } {*attempted to access nonexistent global variable 'setresp'*}

    test {LIBRARIES - redis.set_repl from function load} {
        catch {
            r function load replace {#!lua name=lib2
                return redis.set_repl(redis.REPL_NONE)
            }
        } e
        set _ $e
    } {*attempted to access nonexistent global variable 'set_repl'*}

    test {LIBRARIES - redis.acl_check_cmd from function load} {
        catch {
            r function load replace {#!lua name=lib2
                return redis.acl_check_cmd('set','xx',1)
            }
        } e
        set _ $e
    } {*attempted to access nonexistent global variable 'acl_check_cmd'*}

    test {LIBRARIES - malicious access test} {
        # the 'library' API is not exposed inside a
        # function context and the 'redis' API is not
        # expose on the library registration context.
        # But a malicious user might find a way to hack it
        # (as demonstrated in this test). This is why we
        # have another level of protection on the C
        # code itself and we want to test it and verify
        # that it works properly.
        r function load replace {#!lua name=lib1
            local lib = redis
            lib.register_function('f1', function ()
                lib.redis = redis
                lib.math = math
                return {ok='OK'}
            end)

            lib.register_function('f2', function ()
                lib.register_function('f1', function ()
                    lib.redis = redis
                    lib.math = math
                    return {ok='OK'}
                end)
            end)
        }
        catch {[r fcall f1 0]} e
        assert_match {*Attempt to modify a readonly table*} $e

        catch {[r function load {#!lua name=lib2
            redis.math.random()
        }]} e
        assert_match {*Script attempted to access nonexistent global variable 'math'*} $e

        catch {[r function load {#!lua name=lib2
            redis.redis.call('ping')
        }]} e
        assert_match {*Script attempted to access nonexistent global variable 'redis'*} $e

        catch {[r fcall f2 0]} e
        assert_match {*can only be called on FUNCTION LOAD command*} $e
    }

    test {LIBRARIES - delete removed all functions on library} {
        r function delete lib1
        r function list
    } {}

    test {LIBRARIES - register function inside a function} {
        r function load {#!lua name=lib
            redis.register_function(
                'f1',
                function(keys, args)
                    redis.register_function(
                        'f2',
                        function(key, args)
                            return 2
                        end
                    )
                    return 1
                end
            )
        }
        catch {r fcall f1 0} e
        set _ $e
    } {*attempt to call field 'register_function' (a nil value)*}

    test {LIBRARIES - register library with no functions} {
        r function flush
        catch {
            r function load {#!lua name=lib
                return 1
            }
        } e
        set _ $e
    } {*No functions registered*}

    test {LIBRARIES - load timeout} {
        catch {
            r function load {#!lua name=lib
                local a = 1
                while 1 do a = a + 1 end
            }
        } e
        set _ $e
    } {*FUNCTION LOAD timeout*}

    test {LIBRARIES - verify global protection on the load run} {
        catch {
            r function load {#!lua name=lib
                a = 1
            }
        } e
        set _ $e
    } {*Attempt to modify a readonly table*}

    test {LIBRARIES - named arguments} {
        r function load {#!lua name=lib
            redis.register_function{
                function_name='f1',
                callback=function()
                    return 'hello'
                end,
                description='some desc'
            }
        }
        r function list
    } {{library_name lib engine LUA functions {{name f1 description {some desc} flags {}}}}}

    test {LIBRARIES - named arguments, bad function name} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    function_name=function() return 1 end,
                    callback=function()
                        return 'hello'
                    end,
                    description='some desc'
                }
            }
        } e
        set _ $e
    } {*function_name argument given to redis.register_function must be a string*}

    test {LIBRARIES - named arguments, bad callback type} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    function_name='f1',
                    callback='bad',
                    description='some desc'
                }
            }
        } e
        set _ $e
    } {*callback argument given to redis.register_function must be a function*}

    test {LIBRARIES - named arguments, bad description} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    function_name='f1',
                    callback=function()
                        return 'hello'
                    end,
                    description=function() return 1 end
                }
            }
        } e
        set _ $e
    } {*description argument given to redis.register_function must be a string*}

    test {LIBRARIES - named arguments, unknown argument} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    function_name='f1',
                    callback=function()
                        return 'hello'
                    end,
                    description='desc',
                    some_unknown='unknown'
                }
            }
        } e
        set _ $e
    } {*unknown argument given to redis.register_function*}

    test {LIBRARIES - named arguments, missing function name} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    callback=function()
                        return 'hello'
                    end,
                    description='desc'
                }
            }
        } e
        set _ $e
    } {*redis.register_function must get a function name argument*}

    test {LIBRARIES - named arguments, missing callback} {
        catch {
            r function load replace {#!lua name=lib
                redis.register_function{
                    function_name='f1',
                    description='desc'
                }
            }
        } e
        set _ $e
    } {*redis.register_function must get a callback argument*}

    test {FUNCTION - test function restore with function name collision} {
        r function flush
        r function load {#!lua name=lib1
            local function add1(a)
                return a + 1
            end
            redis.register_function(
                'f1',
                function(keys, args)
                    return add1(1)
                end
            )
            redis.register_function(
                'f2',
                function(keys, args)
                    return add1(2)
                end
            )
            redis.register_function(
                'f3',
                function(keys, args)
                    return add1(3)
                end
            )
        }
        set e [r function dump]
        r function flush

        # load a library with different name but with the same function name
        r function load {#!lua name=lib1
            redis.register_function(
                'f6',
                function(keys, args)
                    return 7
                end
            )
        }
        r function load {#!lua name=lib2
            local function add1(a)
                return a + 1
            end
            redis.register_function(
                'f4',
                function(keys, args)
                    return add1(4)
                end
            )
            redis.register_function(
                'f5',
                function(keys, args)
                    return add1(5)
                end
            )
            redis.register_function(
                'f3',
                function(keys, args)
                    return add1(3)
                end
            )
        }

        catch {r function restore $e} error
        assert_match {*Library lib1 already exists*} $error
        assert_equal [r fcall f3 0] {4}
        assert_equal [r fcall f4 0] {5}
        assert_equal [r fcall f5 0] {6}
        assert_equal [r fcall f6 0] {7}

        catch {r function restore $e replace} error
        assert_match {*Function f3 already exists*} $error
        assert_equal [r fcall f3 0] {4}
        assert_equal [r fcall f4 0] {5}
        assert_equal [r fcall f5 0] {6}
        assert_equal [r fcall f6 0] {7}
    }

    test {FUNCTION - test function list with code} {
        r function flush
        r function load {#!lua name=library1
            redis.register_function('f6', function(keys, args) return 7 end)
        }
        r function list withcode
    } {{library_name library1 engine LUA functions {{name f6 description {} flags {}}} library_code {*redis.register_function('f6', function(keys, args) return 7 end)*}}}

    test {FUNCTION - test function list with pattern} {
        r function load {#!lua name=lib1
            redis.register_function('f7', function(keys, args) return 7 end)
        }
        r function list libraryname library*
    } {{library_name library1 engine LUA functions {{name f6 description {} flags {}}}}}

    test {FUNCTION - test function list wrong argument} {
        catch {r function list bad_argument} e
        set _ $e
    } {*Unknown argument bad_argument*}

    test {FUNCTION - test function list with bad argument to library name} {
        catch {r function list libraryname} e
        set _ $e
    } {*library name argument was not given*}

    test {FUNCTION - test function list withcode multiple times} {
        catch {r function list withcode withcode} e
        set _ $e
    } {*Unknown argument withcode*}

    test {FUNCTION - test function list libraryname multiple times} {
        catch {r function list withcode libraryname foo libraryname foo} e
        set _ $e
    } {*Unknown argument libraryname*}

    test {FUNCTION - verify OOM on function load and function restore} {
        r function flush
        r function load replace {#!lua name=test
            redis.register_function('f1', function() return 1 end)
        }
        set payload [r function dump]
        r config set maxmemory 1

        r function flush
        catch {r function load replace {#!lua name=test
            redis.register_function('f1', function() return 1 end)
        }} e
        assert_match {*command not allowed when used memory*} $e

        r function flush
        catch {r function restore $payload} e
        assert_match {*command not allowed when used memory*} $e

        r config set maxmemory 0
    } {OK} {needs:config-maxmemory}

    test {FUNCTION - verify allow-omm allows running any command} {
        r FUNCTION load replace {#!lua name=f1
            redis.register_function{
                function_name='f1',
                callback=function() return redis.call('set', 'x', '1') end,
                flags={'allow-oom'}
            }
        }

        r config set maxmemory 1

        assert_match {OK} [r fcall f1 1 x]
        assert_match {1} [r get x]

        r config set maxmemory 0
    } {OK} {needs:config-maxmemory}
}

start_server {tags {"scripting"}} {
    test {FUNCTION - wrong flags type named arguments} {
        catch {r function load replace {#!lua name=test
            redis.register_function{
                function_name = 'f1',
                callback = function() return 1 end,
                flags = 'bad flags type'
            }
        }} e
        set _ $e
    } {*flags argument to redis.register_function must be a table representing function flags*}

    test {FUNCTION - wrong flag type} {
        catch {r function load replace {#!lua name=test
            redis.register_function{
                function_name = 'f1',
                callback = function() return 1 end,
                flags = {function() return 1 end}
            }
        }} e
        set _ $e
    } {*unknown flag given*}

    test {FUNCTION - unknown flag} {
        catch {r function load replace {#!lua name=test
            redis.register_function{
                function_name = 'f1',
                callback = function() return 1 end,
                flags = {'unknown'}
            }
        }} e
        set _ $e
    } {*unknown flag given*}

    test {FUNCTION - write script on fcall_ro} {
        r function load replace {#!lua name=test
            redis.register_function{
                function_name = 'f1',
                callback = function() return redis.call('set', 'x', 1) end
            }
        }
        catch {r fcall_ro f1 1 x} e
        set _ $e
    } {*Can not execute a script with write flag using \*_ro command*}

    test {FUNCTION - write script with no-writes flag} {
        r function load replace {#!lua name=test
            redis.register_function{
                function_name = 'f1',
                callback = function() return redis.call('set', 'x', 1) end,
                flags = {'no-writes'}
            }
        }
        catch {r fcall f1 1 x} e
        set _ $e
    } {*Write commands are not allowed from read-only scripts*}

    test {FUNCTION - deny oom} {
        r FUNCTION load replace {#!lua name=test
            redis.register_function('f1', function() return redis.call('set', 'x', '1') end) 
        }

        r config set maxmemory 1

        catch {[r fcall f1 1 x]} e
        assert_match {OOM *when used memory > 'maxmemory'*} $e

        r config set maxmemory 0
    } {OK} {needs:config-maxmemory}

    test {FUNCTION - deny oom on no-writes function} {
        r FUNCTION load replace {#!lua name=test
            redis.register_function{function_name='f1', callback=function() return 'hello' end, flags={'no-writes'}}
        }

        r config set maxmemory 1

        assert_equal [r fcall f1 1 k] hello
        assert_equal [r fcall_ro f1 1 k] hello

        r config set maxmemory 0
    } {OK} {needs:config-maxmemory}

    test {FUNCTION - allow stale} {
        r FUNCTION load replace {#!lua name=test
            redis.register_function{function_name='f1', callback=function() return 'hello' end, flags={'no-writes'}}
            redis.register_function{function_name='f2', callback=function() return 'hello' end, flags={'allow-stale', 'no-writes'}}
            redis.register_function{function_name='f3', callback=function() return redis.call('get', 'x') end, flags={'allow-stale', 'no-writes'}}
            redis.register_function{function_name='f4', callback=function() return redis.call('info', 'server') end, flags={'allow-stale', 'no-writes'}}
        }
        
        r config set replica-serve-stale-data no
        r replicaof 127.0.0.1 1

        catch {[r fcall f1 0]} e
        assert_match {MASTERDOWN *} $e

        assert_equal {hello} [r fcall f2 0]

        catch {[r fcall f3 1 x]} e
        assert_match {ERR *Can not execute the command on a stale replica*} $e

        assert_match {*redis_version*} [r fcall f4 0]

        r replicaof no one
        r config set replica-serve-stale-data yes
        set _ {}
    } {} {external:skip}

    test {FUNCTION - redis version api} {
        r FUNCTION load replace {#!lua name=test
            local version = redis.REDIS_VERSION_NUM

            redis.register_function{function_name='get_version_v1', callback=function()
              return string.format('%s.%s.%s',
                                    bit.band(bit.rshift(version, 16), 0x000000ff),
                                    bit.band(bit.rshift(version, 8), 0x000000ff),
                                    bit.band(version, 0x000000ff))
            end}
            redis.register_function{function_name='get_version_v2', callback=function() return redis.REDIS_VERSION end}
        }

        catch {[r fcall f1 0]} e
        assert_equal  [r fcall get_version_v1 0] [r fcall get_version_v2 0]
    }

    test {FUNCTION - function stats} {
        r FUNCTION FLUSH

        r FUNCTION load {#!lua name=test1
            redis.register_function('f1', function() return 1 end)
            redis.register_function('f2', function() return 1 end)
        }

        r FUNCTION load {#!lua name=test2
            redis.register_function('f3', function() return 1 end)
        }

        r function stats
    } {running_script {} engines {LUA {libraries_count 2 functions_count 3}}}

    test {FUNCTION - function stats reloaded correctly from rdb} {
        r debug reload
        r function stats
    } {running_script {} engines {LUA {libraries_count 2 functions_count 3}}} {needs:debug}

    test {FUNCTION - function stats delete library} {
        r function delete test1
        r function stats
    } {running_script {} engines {LUA {libraries_count 1 functions_count 1}}}

    test {FUNCTION - test function stats on loading failure} {
        r FUNCTION FLUSH

        r FUNCTION load {#!lua name=test1
            redis.register_function('f1', function() return 1 end)
            redis.register_function('f2', function() return 1 end)
        }

        catch {r FUNCTION load {#!lua name=test1
            redis.register_function('f3', function() return 1 end)
        }} e
        assert_match "*Library 'test1' already exists*" $e
        

        r function stats
    } {running_script {} engines {LUA {libraries_count 1 functions_count 2}}}

    test {FUNCTION - function stats cleaned after flush} {
        r function flush
        r function stats
    } {running_script {} engines {LUA {libraries_count 0 functions_count 0}}}

    test {FUNCTION - function test empty engine} {
         catch {r function load replace {#! name=test
            redis.register_function('foo', function() return 1 end)
        }} e
        set _ $e
    } {ERR Engine '' not found}

    test {FUNCTION - function test unknown metadata value} {
         catch {r function load replace {#!lua name=test foo=bar
            redis.register_function('foo', function() return 1 end)
        }} e
        set _ $e
    } {ERR Invalid metadata value given: foo=bar}

    test {FUNCTION - function test no name} {
         catch {r function load replace {#!lua
            redis.register_function('foo', function() return 1 end)
        }} e
        set _ $e
    } {ERR Library name was not given}

    test {FUNCTION - function test multiple names} {
         catch {r function load replace {#!lua name=foo name=bar
            redis.register_function('foo', function() return 1 end)
        }} e
        set _ $e
    } {ERR Invalid metadata value, name argument was given multiple times}

    test {FUNCTION - function test name with quotes} {
        r function load replace {#!lua name="foo"
            redis.register_function('foo', function() return 1 end)
        }
    } {foo}

    test {FUNCTION - trick global protection 1} {
        r FUNCTION FLUSH

        r FUNCTION load {#!lua name=test1
            redis.register_function('f1', function() 
                mt = getmetatable(_G)
                original_globals = mt.__index
                original_globals['redis'] = function() return 1 end
            end)
        }

        catch {[r fcall f1 0]} e
        set _ $e
    } {*Attempt to modify a readonly table*}

    test {FUNCTION - test getmetatable on script load} {
        r FUNCTION FLUSH

        catch {
            r FUNCTION load {#!lua name=test1
                mt = getmetatable(_G)
            }
        } e

        set _ $e
    } {*Script attempted to access nonexistent global variable 'getmetatable'*}

}