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'
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.'
def cmd_config(keyspace, action, *params): if action.lower() == 'help': # copied from # https://github.com/antirez/redis/blob/cb51bb4320d2240001e8fc4a522d59fb28259703/src/config.c#L2244-L2245 help = [ "GET <pattern> -- Return parameters matching the glob-like <pattern> and their values.", "SET <parameter> <value> -- Set parameter to value.", ] return help elif action.lower() == 'get' and len(params) == 1: return config.get_all(params[0]) elif action.lower() == 'set' and len(params) == 2: config.set(params[0], params[1]) return SimpleString('OK') else: raise DredisError( "Unknown subcommand or wrong number of arguments for '{}'. Try CONFIG HELP." .format(action))
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...")
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.'
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
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)