Ejemplo n.º 1
0
def test_raises_error_if_password_is_wrong(keyspace):
    config.set('requirepass', 'test')
    k = Keyspace()
    with pytest.raises(DredisError) as exc:
        k.auth('wrongpass')

    assert str(exc.value) == 'ERR invalid password'
Ejemplo n.º 2
0
def test_eval_with_error_call():
    k = Keyspace()

    with pytest.raises(RedisScriptError) as exc:
        k.eval("""return redis.call('cmd_not_found')""", [], [])
    assert str(
        exc.value
    ) == '@user_script: Unknown Redis command called from Lua script'
Ejemplo n.º 3
0
def test_eval_with_error_pcall():
    k = Keyspace()

    with pytest.raises(
            RedisScriptError,
            message=
            'Error running script: @user_script: Unknown Redis command called from Lua script'
    ):
        k.eval("""return redis.pcall('cmd_not_found')""", [], [])
Ejemplo n.º 4
0
def test_redislua_with_error_pcall():
    k = Keyspace()
    lua_runtime = LuaRuntime(unpack_returned_tuples=True)
    redis_lua = RedisLua(k, lua_runtime)
    table = redis_lua.pcall('GET')

    assert table['err'] == "wrong number of arguments for 'get' command"
Ejemplo n.º 5
0
def test_redislua_with_command_error_pcall():
    k = Keyspace()
    lua_runtime = LuaRuntime(unpack_returned_tuples=True)
    redis_lua = RedisLua(k, lua_runtime)
    table = redis_lua.pcall('cmd_not_found')

    assert table[
        'err'] == '@user_script: Unknown Redis command called from Lua script'
Ejemplo n.º 6
0
def test_lua_table_with_error_run():
    k = Keyspace()
    runner = LuaRunner(k)
    lua_script_err = """return {err='This is an error'}"""

    with pytest.raises(RedisScriptError) as e:
        runner.run(lua_script_err, [], [])

    assert str(e.value) == 'This is an error'
Ejemplo n.º 7
0
def test_redislua_with_error_call():
    k = Keyspace()
    lua_runtime = LuaRuntime(unpack_returned_tuples=True)
    redis_lua = RedisLua(k, lua_runtime)

    with pytest.raises(RedisScriptError) as exc:
        redis_lua.call('GET')

    assert str(exc.value) == "wrong number of arguments for 'get' command"
Ejemplo n.º 8
0
def test_redislua_with_command_error_call():
    k = Keyspace()
    lua_runtime = LuaRuntime(unpack_returned_tuples=True)
    redis_lua = RedisLua(k, lua_runtime)

    with pytest.raises(RedisScriptError) as exc:
        redis_lua.call('cmd_not_found')

    assert str(
        exc.value
    ) == '@user_script: Unknown Redis command called from Lua script'
Ejemplo n.º 9
0
def test_bad_authentication_when_authenticated_should_invalidate_the_session(keyspace):
    config.set('requirepass', 'secret')
    k = Keyspace()

    assert run_command(k, 'auth', ('secret',))
    try:
        run_command(k, 'auth', ('wrongpass',))
    except DredisError:
        pass

    with pytest.raises(AuthenticationRequiredError) as exc:
        run_command(k, 'incrby', ('counter', '1'))

    assert str(exc.value) == 'NOAUTH Authentication required.'
Ejemplo n.º 10
0
def test_redislua_return_lua_types_pcall():
    k = Keyspace()
    lua_runtime = LuaRuntime(unpack_returned_tuples=True)
    redis_lua = RedisLua(k, lua_runtime)
    lua_script = """return {'test', true, false, 10, 20.3, {'another string'}, redis.call('ping')}"""
    table = redis_lua.pcall('EVAL', lua_script, 0, [])

    assert table[1] == 'test'
    assert table[2] == 1
    assert table[3] is False
    assert table[4] == 10
    assert table[5] == 20
    assert table[6][1] == 'another string'
    assert table[7] == 'PONG'
Ejemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser(version=__version__)
    parser.add_argument('--host',
                        default='127.0.0.1',
                        help='server host (defaults to %(default)s)')
    parser.add_argument('--port',
                        default='6377',
                        type=int,
                        help='server port (defaults to %(default)s)')
    parser.add_argument(
        '--dir',
        default=None,
        help='directory to save data (defaults to a temporary directory)')
    parser.add_argument(
        '--backend',
        default=db.DEFAULT_DB_BACKEND,
        choices=db.DB_BACKENDS.keys(),
        help='key/value database backend (defaults to %(default)s)')
    parser.add_argument(
        '--backend-option',
        action='append',
        help='database backend options (e.g., --backend-option map_size=BYTES)'
    )
    parser.add_argument('--rdb', default=None, help='RDB file to seed dredis')
    # boolean arguments
    parser.add_argument('--debug',
                        action='store_true',
                        help='enable debug logs')
    parser.add_argument('--flushall',
                        action='store_true',
                        default=False,
                        help='run FLUSHALL on startup')
    parser.add_argument('--readonly',
                        action='store_true',
                        help='accept read-only commands')
    parser.add_argument(
        '--requirepass',
        default='',
        help=
        'require clients to issue AUTH <password> before processing any other commands'
    )
    parser.add_argument(
        '--gc-interval',
        default=gc.DEFAULT_GC_INTERVAL,
        type=float,
        help='key gc interval in milliseconds (defaults to %(default)s)')
    parser.add_argument('--gc-batch-size',
                        default=gc.DEFAULT_GC_BATCH_SIZE,
                        type=float,
                        help='key gc batch size (defaults to %(default)s)')
    args = parser.parse_args()

    global ROOT_DIR
    if args.dir:
        ROOT_DIR = Path(args.dir)
        ROOT_DIR.makedirs(ignore_if_exists=True)

    else:
        ROOT_DIR = tempfile.mkdtemp(prefix="redis-test-")

    setup_logging(logging.INFO)

    config.set('debug', config.TRUE if args.debug else config.FALSE)
    config.set('readonly', config.TRUE if args.readonly else config.FALSE)
    config.set('requirepass',
               args.requirepass if args.requirepass else config.EMPTY)

    db_backend_options = {}
    if args.backend_option:
        for option in args.backend_option:
            if '=' not in option:
                logger.error(
                    'Expected `key=value` pairs for --backend-option parameter'
                )
                sys.exit(1)
            key, value = map(str.strip, option.split('='))
            db_backend_options[key] = json.loads(value)
    db.DB_MANAGER.setup_dbs(ROOT_DIR, args.backend, db_backend_options)

    keyspace = Keyspace()
    if args.flushall:
        keyspace.flushall()

    if args.rdb:
        logger.info("Loading %s..." % args.rdb)
        start_time = time.time()
        with open(args.rdb, 'rb') as f:
            rdb.load_rdb(keyspace, f)
        logger.info("Finished loading (%.2f seconds)." %
                    (time.time() - start_time))

    RedisServer(args.host, args.port)
    gc_thread = gc.KeyGarbageCollector(args.gc_interval, args.gc_batch_size)
    gc_thread.daemon = True
    gc_thread.start()

    logger.info("Backend: {}".format(args.backend))
    logger.info("Port: {}".format(args.port))
    logger.info("Root directory: {}".format(ROOT_DIR))
    logger.info('PID: {}'.format(os.getpid()))
    logger.info('Readonly: {}'.format(config.get('readonly')))
    logger.info('Ready to accept connections')

    try:
        asyncore.loop(use_poll=True)
    except KeyboardInterrupt:
        logger.info("Shutting down...")
Ejemplo n.º 12
0
def test_delete():
    tempdir = tempfile.mkdtemp(prefix="redis-test-")
    DB_MANAGER.setup_dbs(tempdir, backend='leveldb', backend_options={})
    keyspace = Keyspace()

    keyspace.select('0')
    keyspace.set('mystr', 'test')
    keyspace.sadd('myset', 'elem1')
    keyspace.zadd('myzset', 0, 'elem1')
    keyspace.hset('myhash', 'testkey', 'testvalue')

    keyspace.delete('mystr', 'myset', 'myzset', 'myhash', 'notfound')

    KeyGarbageCollector().collect()

    assert list(DB_MANAGER.get_db('0').iterator()) == []
Ejemplo n.º 13
0
def save_rdb(output_dir, db_backend_options):
    db.DB_MANAGER.setup_dbs(output_dir, BACKEND, db_backend_options)
    keyspace = Keyspace()
    keyspace.save()
Ejemplo n.º 14
0
def test_allows_commands_when_password_is_valid(keyspace):
    config.set('requirepass', 'secret')
    k = Keyspace()

    assert run_command(k, 'auth', ('secret',))
    assert run_command(k, 'incrby', ('counter', '1')) == 1
Ejemplo n.º 15
0
def test_lua_return_redis_types_run():
    k = Keyspace()
    runner = LuaRunner(k)
    lua_script = """return {'test', true, false, 10, 20.3, {4}}"""

    assert runner.run(lua_script, [], []) == ['test', 1, None, 10, 20, [4]]
Ejemplo n.º 16
0
def test_raises_error_if_not_authenticated(keyspace):
    config.set('requirepass', 'test')
    with pytest.raises(AuthenticationRequiredError) as exc:
        run_command(Keyspace(), 'get', ('test',))

    assert str(exc.value) == 'NOAUTH Authentication required.'
Ejemplo n.º 17
0
 def __init__(self, *args, **kwargs):
     asyncore.dispatcher.__init__(self, *args, **kwargs)
     self._parser = Parser(self.recv)  # contains client message buffer
     self.keyspace = Keyspace()
     self.out_buffer = bytearray(
     )  # asyncore.py uses `str` instead of `bytearray`
Ejemplo n.º 18
0
def test_lua_table_with_ok_run():
    k = Keyspace()
    runner = LuaRunner(k)
    lua_script_ok = """return {ok='Everything is OK'}"""

    assert runner.run(lua_script_ok, [], []) == 'Everything is OK'
Ejemplo n.º 19
0
def test_rdb_load(keyspace):
    rdb.load_rdb(keyspace, open(FIXTURE_DUMP, 'rb'))

    new_keyspace = Keyspace()
    new_keyspace.select(1)
    reproduce_dump.run(new_keyspace)

    assert new_keyspace.keys('*') == keyspace.keys('*')

    for key in new_keyspace.keys('string_*'):
        assert new_keyspace.get(key) == keyspace.get(key)

    for key in new_keyspace.keys('set_*'):
        assert new_keyspace.smembers(key) == keyspace.smembers(key)

    for key in new_keyspace.keys('zset_*'):
        assert new_keyspace.zrange(
            key, 0, -1, with_scores=True) == keyspace.zrange(key,
                                                             0,
                                                             -1,
                                                             with_scores=True)

    for key in new_keyspace.keys('hash_*'):
        assert new_keyspace.hgetall(key) == keyspace.hgetall(key)
Ejemplo n.º 20
0
def keyspace():
    DB_MANAGER.setup_dbs('', backend='memory', backend_options={})
    original_configs = config.get_all('*')
    yield Keyspace()
    for option, value in zip(original_configs[0::2], original_configs[1::2]):
        config.set(option, value)