xref: /redis-3.2.3/tests/unit/scripting.tcl (revision f3fd58eb)
1start_server {tags {"scripting"}} {
2    test {EVAL - Does Lua interpreter replies to our requests?} {
3        r eval {return 'hello'} 0
4    } {hello}
5
6    test {EVAL - Lua integer -> Redis protocol type conversion} {
7        r eval {return 100.5} 0
8    } {100}
9
10    test {EVAL - Lua string -> Redis protocol type conversion} {
11        r eval {return 'hello world'} 0
12    } {hello world}
13
14    test {EVAL - Lua true boolean -> Redis protocol type conversion} {
15        r eval {return true} 0
16    } {1}
17
18    test {EVAL - Lua false boolean -> Redis protocol type conversion} {
19        r eval {return false} 0
20    } {}
21
22    test {EVAL - Lua status code reply -> Redis protocol type conversion} {
23        r eval {return {ok='fine'}} 0
24    } {fine}
25
26    test {EVAL - Lua error reply -> Redis protocol type conversion} {
27        catch {
28            r eval {return {err='this is an error'}} 0
29        } e
30        set _ $e
31    } {this is an error}
32
33    test {EVAL - Lua table -> Redis protocol type conversion} {
34        r eval {return {1,2,3,'ciao',{1,2}}} 0
35    } {1 2 3 ciao {1 2}}
36
37    test {EVAL - Are the KEYS and ARGV arrays populated correctly?} {
38        r eval {return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}} 2 a b c d
39    } {a b c d}
40
41    test {EVAL - is Lua able to call Redis API?} {
42        r set mykey myval
43        r eval {return redis.call('get',KEYS[1])} 1 mykey
44    } {myval}
45
46    test {EVALSHA - Can we call a SHA1 if already defined?} {
47        r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey
48    } {myval}
49
50    test {EVALSHA - Can we call a SHA1 in uppercase?} {
51        r evalsha FD758D1589D044DD850A6F05D52F2EEFD27F033F 1 mykey
52    } {myval}
53
54    test {EVALSHA - Do we get an error on invalid SHA1?} {
55        catch {r evalsha NotValidShaSUM 0} e
56        set _ $e
57    } {NOSCRIPT*}
58
59    test {EVALSHA - Do we get an error on non defined SHA1?} {
60        catch {r evalsha ffd632c7d33e571e9f24556ebed26c3479a87130 0} e
61        set _ $e
62    } {NOSCRIPT*}
63
64    test {EVAL - Redis integer -> Lua type conversion} {
65        r eval {
66            local foo = redis.pcall('incr','x')
67            return {type(foo),foo}
68        } 0
69    } {number 1}
70
71    test {EVAL - Redis bulk -> Lua type conversion} {
72        r set mykey myval
73        r eval {
74            local foo = redis.pcall('get','mykey')
75            return {type(foo),foo}
76        } 0
77    } {string myval}
78
79    test {EVAL - Redis multi bulk -> Lua type conversion} {
80        r del mylist
81        r rpush mylist a
82        r rpush mylist b
83        r rpush mylist c
84        r eval {
85            local foo = redis.pcall('lrange','mylist',0,-1)
86            return {type(foo),foo[1],foo[2],foo[3],# foo}
87        } 0
88    } {table a b c 3}
89
90    test {EVAL - Redis status reply -> Lua type conversion} {
91        r eval {
92            local foo = redis.pcall('set','mykey','myval')
93            return {type(foo),foo['ok']}
94        } 0
95    } {table OK}
96
97    test {EVAL - Redis error reply -> Lua type conversion} {
98        r set mykey myval
99        r eval {
100            local foo = redis.pcall('incr','mykey')
101            return {type(foo),foo['err']}
102        } 0
103    } {table {ERR value is not an integer or out of range}}
104
105    test {EVAL - Redis nil bulk reply -> Lua type conversion} {
106        r del mykey
107        r eval {
108            local foo = redis.pcall('get','mykey')
109            return {type(foo),foo == false}
110        } 0
111    } {boolean 1}
112
113    test {EVAL - Is the Lua client using the currently selected DB?} {
114        r set mykey "this is DB 9"
115        r select 10
116        r set mykey "this is DB 10"
117        r eval {return redis.pcall('get','mykey')} 0
118    } {this is DB 10}
119
120    test {EVAL - SELECT inside Lua should not affect the caller} {
121        # here we DB 10 is selected
122        r set mykey "original value"
123        r eval {return redis.pcall('select','9')} 0
124        set res [r get mykey]
125        r select 9
126        set res
127    } {original value}
128
129    if 0 {
130        test {EVAL - Script can't run more than configured time limit} {
131            r config set lua-time-limit 1
132            catch {
133                r eval {
134                    local i = 0
135                    while true do i=i+1 end
136                } 0
137            } e
138            set _ $e
139        } {*execution time*}
140    }
141
142    test {EVAL - Scripts can't run certain commands} {
143        set e {}
144        catch {r eval {return redis.pcall('spop','x')} 0} e
145        set e
146    } {*not allowed*}
147
148    test {EVAL - Scripts can't run certain commands} {
149        set e {}
150        catch {
151            r eval "redis.pcall('randomkey'); return redis.pcall('set','x','ciao')" 0
152        } e
153        set e
154    } {*not allowed after*}
155
156    test {EVAL - No arguments to redis.call/pcall is considered an error} {
157        set e {}
158        catch {r eval {return redis.call()} 0} e
159        set e
160    } {*one argument*}
161
162    test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
163        set e {}
164        catch {
165            r eval "redis.call('nosuchcommand')" 0
166        } e
167        set e
168    } {*Unknown Redis*}
169
170    test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
171        set e {}
172        catch {
173            r eval "redis.call('get','a','b','c')" 0
174        } e
175        set e
176    } {*number of args*}
177
178    test {EVAL - redis.call variant raises a Lua error on Redis cmd error (1)} {
179        set e {}
180        r set foo bar
181        catch {
182            r eval {redis.call('lpush',KEYS[1],'val')} 1 foo
183        } e
184        set e
185    } {*against a key*}
186
187    test {EVAL - JSON numeric decoding} {
188        # We must return the table as a string because otherwise
189        # Redis converts floats to ints and we get 0 and 1023 instead
190        # of 0.0003 and 1023.2 as the parsed output.
191        r eval {return
192                 table.concat(
193                   cjson.decode(
194                    "[0.0, -5e3, -1, 0.3e-3, 1023.2, 0e10]"), " ")
195        } 0
196    } {0 -5000 -1 0.0003 1023.2 0}
197
198    test {EVAL - JSON string decoding} {
199        r eval {local decoded = cjson.decode('{"keya": "a", "keyb": "b"}')
200                return {decoded.keya, decoded.keyb}
201        } 0
202    } {a b}
203
204    test {EVAL - cmsgpack can pack double?} {
205        r eval {local encoded = cmsgpack.pack(0.1)
206                local h = ""
207                for i = 1, #encoded do
208                    h = h .. string.format("%02x",string.byte(encoded,i))
209                end
210                return h
211        } 0
212    } {cb3fb999999999999a}
213
214    test {EVAL - cmsgpack can pack negative int64?} {
215        r eval {local encoded = cmsgpack.pack(-1099511627776)
216                local h = ""
217                for i = 1, #encoded do
218                    h = h .. string.format("%02x",string.byte(encoded,i))
219                end
220                return h
221        } 0
222    } {d3ffffff0000000000}
223
224    test {EVAL - cmsgpack can pack and unpack circular references?} {
225        r eval {local a = {x=nil,y=5}
226                local b = {x=a}
227                a['x'] = b
228                local encoded = cmsgpack.pack(a)
229                local h = ""
230                -- cmsgpack encodes to a depth of 16, but can't encode
231                -- references, so the encoded object has a deep copy recusive
232                -- depth of 16.
233                for i = 1, #encoded do
234                    h = h .. string.format("%02x",string.byte(encoded,i))
235                end
236                -- when unpacked, re.x.x != re because the unpack creates
237                -- individual tables down to a depth of 16.
238                -- (that's why the encoded output is so large)
239                local re = cmsgpack.unpack(encoded)
240                assert(re)
241                assert(re.x)
242                assert(re.x.x.y == re.y)
243                assert(re.x.x.x.x.y == re.y)
244                assert(re.x.x.x.x.x.x.y == re.y)
245                assert(re.x.x.x.x.x.x.x.x.x.x.y == re.y)
246                -- maximum working depth:
247                assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.y == re.y)
248                -- now the last x would be b above and has no y
249                assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x)
250                -- so, the final x.x is at the depth limit and was assigned nil
251                assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x == nil)
252                return {h, re.x.x.x.x.x.x.x.x.y == re.y, re.y == 5}
253        } 0
254    } {82a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a178c0 1 1}
255
256    test {EVAL - Numerical sanity check from bitop} {
257        r eval {assert(0x7fffffff == 2147483647, "broken hex literals");
258                assert(0xffffffff == -1 or 0xffffffff == 2^32-1,
259                    "broken hex literals");
260                assert(tostring(-1) == "-1", "broken tostring()");
261                assert(tostring(0xffffffff) == "-1" or
262                    tostring(0xffffffff) == "4294967295",
263                    "broken tostring()")
264        } 0
265    } {}
266
267    test {EVAL - Verify minimal bitop functionality} {
268        r eval {assert(bit.tobit(1) == 1);
269                assert(bit.band(1) == 1);
270                assert(bit.bxor(1,2) == 3);
271                assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
272        } 0
273    } {}
274
275    test {SCRIPTING FLUSH - is able to clear the scripts cache?} {
276        r set mykey myval
277        set v [r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey]
278        assert_equal $v myval
279        set e ""
280        r script flush
281        catch {r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey} e
282        set e
283    } {NOSCRIPT*}
284
285    test {SCRIPT EXISTS - can detect already defined scripts?} {
286        r eval "return 1+1" 0
287        r script exists a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bd9 a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bda
288    } {1 0}
289
290    test {SCRIPT LOAD - is able to register scripts in the scripting cache} {
291        list \
292            [r script load "return 'loaded'"] \
293            [r evalsha b534286061d4b9e4026607613b95c06c06015ae8 0]
294    } {b534286061d4b9e4026607613b95c06c06015ae8 loaded}
295
296    test "In the context of Lua the output of random commands gets ordered" {
297        r del myset
298        r sadd myset a b c d e f g h i l m n o p q r s t u v z aa aaa azz
299        r eval {return redis.call('smembers',KEYS[1])} 1 myset
300    } {a aa aaa azz b c d e f g h i l m n o p q r s t u v z}
301
302    test "SORT is normally not alpha re-ordered for the scripting engine" {
303        r del myset
304        r sadd myset 1 2 3 4 10
305        r eval {return redis.call('sort',KEYS[1],'desc')} 1 myset
306    } {10 4 3 2 1}
307
308    test "SORT BY <constant> output gets ordered for scripting" {
309        r del myset
310        r sadd myset a b c d e f g h i l m n o p q r s t u v z aa aaa azz
311        r eval {return redis.call('sort',KEYS[1],'by','_')} 1 myset
312    } {a aa aaa azz b c d e f g h i l m n o p q r s t u v z}
313
314    test "SORT BY <constant> with GET gets ordered for scripting" {
315        r del myset
316        r sadd myset a b c
317        r eval {return redis.call('sort',KEYS[1],'by','_','get','#','get','_:*')} 1 myset
318    } {a {} b {} c {}}
319
320    test "redis.sha1hex() implementation" {
321        list [r eval {return redis.sha1hex('')} 0] \
322             [r eval {return redis.sha1hex('Pizza & Mandolino')} 0]
323    } {da39a3ee5e6b4b0d3255bfef95601890afd80709 74822d82031af7493c20eefa13bd07ec4fada82f}
324
325    test {Globals protection reading an undeclared global variable} {
326        catch {r eval {return a} 0} e
327        set e
328    } {*ERR*attempted to access unexisting global*}
329
330    test {Globals protection setting an undeclared global*} {
331        catch {r eval {a=10} 0} e
332        set e
333    } {*ERR*attempted to create global*}
334
335    test {Test an example script DECR_IF_GT} {
336        set decr_if_gt {
337            local current
338
339            current = redis.call('get',KEYS[1])
340            if not current then return nil end
341            if current > ARGV[1] then
342                return redis.call('decr',KEYS[1])
343            else
344                return redis.call('get',KEYS[1])
345            end
346        }
347        r set foo 5
348        set res {}
349        lappend res [r eval $decr_if_gt 1 foo 2]
350        lappend res [r eval $decr_if_gt 1 foo 2]
351        lappend res [r eval $decr_if_gt 1 foo 2]
352        lappend res [r eval $decr_if_gt 1 foo 2]
353        lappend res [r eval $decr_if_gt 1 foo 2]
354        set res
355    } {4 3 2 2 2}
356
357    test {Scripting engine resets PRNG at every script execution} {
358        set rand1 [r eval {return tostring(math.random())} 0]
359        set rand2 [r eval {return tostring(math.random())} 0]
360        assert_equal $rand1 $rand2
361    }
362
363    test {Scripting engine PRNG can be seeded correctly} {
364        set rand1 [r eval {
365            math.randomseed(ARGV[1]); return tostring(math.random())
366        } 0 10]
367        set rand2 [r eval {
368            math.randomseed(ARGV[1]); return tostring(math.random())
369        } 0 10]
370        set rand3 [r eval {
371            math.randomseed(ARGV[1]); return tostring(math.random())
372        } 0 20]
373        assert_equal $rand1 $rand2
374        assert {$rand2 ne $rand3}
375    }
376
377    test {EVAL does not leak in the Lua stack} {
378        r set x 0
379        # Use a non blocking client to speedup the loop.
380        set rd [redis_deferring_client]
381        for {set j 0} {$j < 10000} {incr j} {
382            $rd eval {return redis.call("incr",KEYS[1])} 1 x
383        }
384        for {set j 0} {$j < 10000} {incr j} {
385            $rd read
386        }
387        assert {[s used_memory_lua] < 1024*100}
388        $rd close
389        r get x
390    } {10000}
391
392    test {EVAL processes writes from AOF in read-only slaves} {
393        r flushall
394        r config set appendonly yes
395        r eval {redis.call("set",KEYS[1],"100")} 1 foo
396        r eval {redis.call("incr",KEYS[1])} 1 foo
397        r eval {redis.call("incr",KEYS[1])} 1 foo
398        wait_for_condition 50 100 {
399            [s aof_rewrite_in_progress] == 0
400        } else {
401            fail "AOF rewrite can't complete after CONFIG SET appendonly yes."
402        }
403        r config set slave-read-only yes
404        r slaveof 127.0.0.1 0
405        r debug loadaof
406        set res [r get foo]
407        r slaveof no one
408        set res
409    } {102}
410
411    test {We can call scripts rewriting client->argv from Lua} {
412        r del myset
413        r sadd myset a b c
414        r mset a 1 b 2 c 3 d 4
415        assert {[r spop myset] ne {}}
416        assert {[r spop myset 1] ne {}}
417        assert {[r spop myset] ne {}}
418        assert {[r mget a b c d] eq {1 2 3 4}}
419        assert {[r spop myset] eq {}}
420    }
421
422    test {Call Redis command with many args from Lua (issue #1764)} {
423        r eval {
424            local i
425            local x={}
426            redis.call('del','mylist')
427            for i=1,100 do
428                table.insert(x,i)
429            end
430            redis.call('rpush','mylist',unpack(x))
431            return redis.call('lrange','mylist',0,-1)
432        } 0
433    } {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}
434
435    test {Number conversion precision test (issue #1118)} {
436        r eval {
437              local value = 9007199254740991
438              redis.call("set","foo",value)
439              return redis.call("get","foo")
440        } 0
441    } {9007199254740991}
442
443    test {String containing number precision test (regression of issue #1118)} {
444        r eval {
445            redis.call("set", "key", "12039611435714932082")
446            return redis.call("get", "key")
447        } 0
448    } {12039611435714932082}
449
450    test {Verify negative arg count is error instead of crash (issue #1842)} {
451        catch { r eval { return "hello" } -12 } e
452        set e
453    } {ERR Number of keys can't be negative}
454
455    test {Correct handling of reused argv (issue #1939)} {
456        r eval {
457              for i = 0, 10 do
458                  redis.call('SET', 'a', '1')
459                  redis.call('MGET', 'a', 'b', 'c')
460                  redis.call('EXPIRE', 'a', 0)
461                  redis.call('GET', 'a')
462                  redis.call('MGET', 'a', 'b', 'c')
463              end
464        } 0
465    }
466}
467
468# Start a new server since the last test in this stanza will kill the
469# instance at all.
470start_server {tags {"scripting"}} {
471    test {Timedout read-only scripts can be killed by SCRIPT KILL} {
472        set rd [redis_deferring_client]
473        r config set lua-time-limit 10
474        $rd eval {while true do end} 0
475        after 200
476        catch {r ping} e
477        assert_match {BUSY*} $e
478        r script kill
479        after 200 ; # Give some time to Lua to call the hook again...
480        assert_equal [r ping] "PONG"
481    }
482
483    test {Timedout script link is still usable after Lua returns} {
484        r config set lua-time-limit 10
485        r eval {for i=1,100000 do redis.call('ping') end return 'ok'} 0
486        r ping
487    } {PONG}
488
489    test {Timedout scripts that modified data can't be killed by SCRIPT KILL} {
490        set rd [redis_deferring_client]
491        r config set lua-time-limit 10
492        $rd eval {redis.call('set',KEYS[1],'y'); while true do end} 1 x
493        after 200
494        catch {r ping} e
495        assert_match {BUSY*} $e
496        catch {r script kill} e
497        assert_match {UNKILLABLE*} $e
498        catch {r ping} e
499        assert_match {BUSY*} $e
500    }
501
502    # Note: keep this test at the end of this server stanza because it
503    # kills the server.
504    test {SHUTDOWN NOSAVE can kill a timedout script anyway} {
505        # The server sould be still unresponding to normal commands.
506        catch {r ping} e
507        assert_match {BUSY*} $e
508        catch {r shutdown nosave}
509        # Make sure the server was killed
510        catch {set rd [redis_deferring_client]} e
511        assert_match {*connection refused*} $e
512    }
513}
514
515start_server {tags {"scripting repl"}} {
516    start_server {} {
517        test {Before the slave connects we issue two EVAL commands} {
518            # One with an error, but still executing a command.
519            # SHA is: 67164fc43fa971f76fd1aaeeaf60c1c178d25876
520            catch {
521                r eval {redis.call('incr',KEYS[1]); redis.call('nonexisting')} 1 x
522            }
523            # One command is correct:
524            # SHA is: 6f5ade10a69975e903c6d07b10ea44c6382381a5
525            r eval {return redis.call('incr',KEYS[1])} 1 x
526        } {2}
527
528        test {Connect a slave to the main instance} {
529            r -1 slaveof [srv 0 host] [srv 0 port]
530            wait_for_condition 50 100 {
531                [s -1 role] eq {slave} &&
532                [string match {*master_link_status:up*} [r -1 info replication]]
533            } else {
534                fail "Can't turn the instance into a slave"
535            }
536        }
537
538        test {Now use EVALSHA against the master, with both SHAs} {
539            # The server should replicate successful and unsuccessful
540            # commands as EVAL instead of EVALSHA.
541            catch {
542                r evalsha 67164fc43fa971f76fd1aaeeaf60c1c178d25876 1 x
543            }
544            r evalsha 6f5ade10a69975e903c6d07b10ea44c6382381a5 1 x
545        } {4}
546
547        test {If EVALSHA was replicated as EVAL, 'x' should be '4'} {
548            wait_for_condition 50 100 {
549                [r -1 get x] eq {4}
550            } else {
551                fail "Expected 4 in x, but value is '[r -1 get x]'"
552            }
553        }
554
555        test {Replication of script multiple pushes to list with BLPOP} {
556            set rd [redis_deferring_client]
557            $rd brpop a 0
558            r eval {
559                redis.call("lpush",KEYS[1],"1");
560                redis.call("lpush",KEYS[1],"2");
561            } 1 a
562            set res [$rd read]
563            $rd close
564            wait_for_condition 50 100 {
565                [r -1 lrange a 0 -1] eq [r lrange a 0 -1]
566            } else {
567                fail "Expected list 'a' in slave and master to be the same, but they are respectively '[r -1 lrange a 0 -1]' and '[r lrange a 0 -1]'"
568            }
569            set res
570        } {a 1}
571
572        test {EVALSHA replication when first call is readonly} {
573            r del x
574            r eval {if tonumber(ARGV[1]) > 0 then redis.call('incr', KEYS[1]) end} 1 x 0
575            r evalsha 6e0e2745aa546d0b50b801a20983b70710aef3ce 1 x 0
576            r evalsha 6e0e2745aa546d0b50b801a20983b70710aef3ce 1 x 1
577            wait_for_condition 50 100 {
578                [r -1 get x] eq {1}
579            } else {
580                fail "Expected 1 in x, but value is '[r -1 get x]'"
581            }
582        }
583
584        test {Lua scripts using SELECT are replicated correctly} {
585            r eval {
586                redis.call("set","foo1","bar1")
587                redis.call("select","10")
588                redis.call("incr","x")
589                redis.call("select","11")
590                redis.call("incr","z")
591            } 0
592            r eval {
593                redis.call("set","foo1","bar1")
594                redis.call("select","10")
595                redis.call("incr","x")
596                redis.call("select","11")
597                redis.call("incr","z")
598            } 0
599            wait_for_condition 50 100 {
600                [r -1 debug digest] eq [r debug digest]
601            } else {
602                fail "Master-Slave desync after Lua script using SELECT."
603            }
604        }
605    }
606}
607