From e82a0c47b4325aeb5e413b3e3c6d7499b3a5853a Mon Sep 17 00:00:00 2001 From: Achilleas Anagnostopoulos Date: Thu, 18 Feb 2016 20:41:47 +0000 Subject: [PATCH] Format all sources with dartfmt --- lib/dart_cassandra_cql.dart | 18 +- lib/src/client/client.dart | 105 +- lib/src/client/result_stream.dart | 70 +- lib/src/connection/async_queue.dart | 6 +- lib/src/connection/connection.dart | 157 +- lib/src/connection/connection_pool.dart | 13 +- lib/src/connection/pool_configuration.dart | 48 +- .../connection/simple_connection_pool.dart | 99 +- .../exception/authentication_exception.dart | 3 +- lib/src/exception/cassandra_exception.dart | 4 +- .../connection_failed_exception.dart | 3 +- .../exception/connection_lost_exception.dart | 3 +- .../exception/driver_exception_exception.dart | 2 +- .../no_healthy_connections_exception.dart | 4 +- .../stream_reservation_exception.dart | 3 +- .../authentication/authenticator.dart | 3 +- .../password_authenticator.dart | 6 +- .../protocol/frame/frame_decompressor.dart | 42 +- lib/src/protocol/frame/frame_parser.dart | 44 +- lib/src/protocol/frame/frame_reader.dart | 20 +- lib/src/protocol/frame/frame_writer.dart | 40 +- .../messages/internal/exception_message.dart | 4 +- lib/src/protocol/messages/message.dart | 2 +- .../requests/auth_response_message.dart | 3 +- .../messages/requests/batch_message.dart | 1 - .../messages/requests/execute_message.dart | 7 +- .../messages/requests/prepare_message.dart | 2 - .../messages/requests/query_message.dart | 8 +- .../messages/requests/register_message.dart | 1 - .../messages/requests/startup_message.dart | 5 +- .../responses/auth_challenge_message.dart | 6 +- .../responses/auth_success_message.dart | 5 +- .../responses/authenticate_message.dart | 5 +- .../messages/responses/error_message.dart | 17 +- .../messages/responses/event_message.dart | 12 +- .../responses/prepared_result_message.dart | 2 +- .../messages/responses/result_message.dart | 19 +- .../responses/rows_result_message.dart | 7 +- .../schema_change_result_message.dart | 4 +- .../set_keyspace_result_message.dart | 4 +- .../responses/void_result_message.dart | 3 +- lib/src/query/batch_query.dart | 11 +- lib/src/query/query.dart | 68 +- lib/src/query/query_interface.dart | 3 +- lib/src/stream/chunked_input_reader.dart | 13 +- lib/src/stream/chunked_output_writer.dart | 10 +- lib/src/stream/type_decoder.dart | 131 +- lib/src/stream/type_encoder.dart | 81 +- lib/src/types.dart | 2 +- lib/src/types/codec_registry.dart | 6 +- lib/src/types/custom_type.dart | 4 +- lib/src/types/enums/batch_type.dart | 1 - lib/src/types/enums/consistency.dart | 73 +- lib/src/types/enums/data_type.dart | 145 +- lib/src/types/enums/enum.dart | 4 +- lib/src/types/enums/error_code.dart | 56 +- .../types/enums/event_registration_type.dart | 25 +- lib/src/types/enums/event_type.dart | 43 +- lib/src/types/enums/header_version.dart | 14 +- lib/src/types/enums/opcode.dart | 112 +- lib/src/types/enums/result_type.dart | 18 +- lib/src/types/frame.dart | 9 +- lib/src/types/frame_header.dart | 1 - lib/src/types/tuple.dart | 1 - lib/src/types/type_spec.dart | 24 +- lib/src/types/uuid.dart | 7 +- test/lib/chunked_input_reader_test.dart | 6 +- test/lib/client_test.dart | 1584 +++++++++-------- test/lib/connection_test.dart | 361 ++-- test/lib/enum_test.dart | 78 +- test/lib/frame_parser_test.dart | 119 +- test/lib/frame_writer_test.dart | 25 +- test/lib/mocks/compression.dart | 10 +- test/lib/mocks/custom.dart | 15 +- test/lib/mocks/mocks.dart | 159 +- test/lib/pool_config_test.dart | 47 +- test/lib/query_test.dart | 543 +++--- test/lib/serialization_test.dart | 736 ++++---- test/lib/type_test.dart | 155 +- test/run_all.dart | 24 +- 80 files changed, 2831 insertions(+), 2703 deletions(-) diff --git a/lib/dart_cassandra_cql.dart b/lib/dart_cassandra_cql.dart index 6f20b7e..6a8dd1e 100644 --- a/lib/dart_cassandra_cql.dart +++ b/lib/dart_cassandra_cql.dart @@ -1,10 +1,24 @@ library dart_cassandra_cql; // Client API exports -export "src/exceptions.dart" show AuthenticationException, CassandraException, NoHealthyConnectionsException, DriverException; +export "src/exceptions.dart" + show + AuthenticationException, + CassandraException, + NoHealthyConnectionsException, + DriverException; export "src/types.dart"; export "src/query.dart"; -export "src/protocol.dart" show ResultMessage, RowsResultMessage, VoidResultMessage, SetKeyspaceResultMessage, SchemaChangeResultMessage, EventMessage, Authenticator, PasswordAuthenticator; +export "src/protocol.dart" + show + ResultMessage, + RowsResultMessage, + VoidResultMessage, + SetKeyspaceResultMessage, + SchemaChangeResultMessage, + EventMessage, + Authenticator, + PasswordAuthenticator; export "src/connection.dart" hide AsyncQueue; export "src/client.dart"; export "src/stream.dart"; diff --git a/lib/src/client/client.dart b/lib/src/client/client.dart index fe030f2..99d729e 100644 --- a/lib/src/client/client.dart +++ b/lib/src/client/client.dart @@ -1,9 +1,9 @@ part of dart_cassandra_cql.client; class Client { - ConnectionPool connectionPool; - final Map> preparedQueries = new Map>(); + final Map> preparedQueries = + new Map>(); /** * Create a new client and a [SimpleConnectionPool] to the supplied [hosts] optionally using @@ -11,14 +11,11 @@ class Client { * If a [defaultKeyspace] is provided, it will be autoselected during the handshake phase of each pool connection */ - Client.fromHostList(List hosts, {String defaultKeyspace, PoolConfiguration poolConfig}) { + Client.fromHostList(List hosts, + {String defaultKeyspace, PoolConfiguration poolConfig}) { connectionPool = new SimpleConnectionPool.fromHostList( - hosts - , poolConfig == null - ? new PoolConfiguration() - : poolConfig - , defaultKeyspace : defaultKeyspace - ); + hosts, poolConfig == null ? new PoolConfiguration() : poolConfig, + defaultKeyspace: defaultKeyspace); } /** @@ -33,10 +30,12 @@ class Client { * [SetKeyspaceResultMessage] or [SchemaChangeResultMessage]. The optional [pageSize] and [pagingState] * params may be supplied to enable pagination when performing single queries. */ - Future execute(QueryInterface query, {int pageSize : null, Uint8List pagingState : null}) { + Future execute(QueryInterface query, + {int pageSize: null, Uint8List pagingState: null}) { return (query is BatchQuery) - ? _executeBatch(query) - : _executeSingle(query as Query, pageSize : pageSize, pagingState : pagingState); + ? _executeBatch(query) + : _executeSingle(query as Query, + pageSize: pageSize, pagingState: pagingState); } /** @@ -53,7 +52,7 @@ class Client { * event per result row. The client uses cassandra's pagination API to load additional result pages on * demand. The result page size is controlled by the [pageSize] parameter (defaults to 100 rows). */ - Stream> stream(Query query, { int pageSize : 100}) { + Stream> stream(Query query, {int pageSize: 100}) { return new ResultStream(_executeSingle, query, pageSize).stream; } @@ -63,22 +62,24 @@ class Client { * that will complete when all connections are drained. If [drain] is false then the returned [Future] * will be already completed. */ - Future shutdown({ bool drain : true, Duration drainTimeout : const Duration( seconds : 5 )}) { - return connectionPool.disconnect(drain: drain, drainTimeout : drainTimeout); + Future shutdown( + {bool drain: true, Duration drainTimeout: const Duration(seconds: 5)}) { + return connectionPool.disconnect(drain: drain, drainTimeout: drainTimeout); } /** * Prepare the given query and return back a [Future] with a [PreparedResultMessage] */ Future _prepare(Query query) { - // If the query is preparing/already prepared, return its future if (preparedQueries.containsKey(query.query)) { return preparedQueries[query.query]; } // Queue for preparation and return back a future - Future deferred = connectionPool.getConnection().then((Connection conn) => conn.prepare(query)); + Future deferred = connectionPool + .getConnection() + .then((Connection conn) => conn.prepare(query)); preparedQueries[query.query] = deferred; return deferred; } @@ -87,22 +88,25 @@ class Client { * Execute a single [query] with optional [pageSize] and [pagingState] data * and return back a [Future] */ - Future _executeSingle(Query query, {int pageSize : null, Uint8List pagingState : null}) { + Future _executeSingle(Query query, + {int pageSize: null, Uint8List pagingState: null}) { Completer completer = new Completer(); // If this is a normal query, pick the next available pool connection and execute it if (!query.prepared) { void _execute() { - connectionPool.getConnection() - .then((Connection conn) => conn.execute( - query - , pageSize: pageSize - , pagingState : pagingState)) - .then(completer.complete) - // If we lose our connection OR we cannot reserve a connection stream, retry on another connection - .catchError((_) => _execute(), test: (e) => e is ConnectionLostException || e is StreamReservationException) - // Any other error will cause the future to fail - .catchError(completer.completeError); + connectionPool + .getConnection() + .then((Connection conn) => conn.execute(query, + pageSize: pageSize, pagingState: pagingState)) + .then(completer.complete) + // If we lose our connection OR we cannot reserve a connection stream, retry on another connection + .catchError((_) => _execute(), + test: (e) => + e is ConnectionLostException || + e is StreamReservationException) + // Any other error will cause the future to fail + .catchError(completer.completeError); } _execute(); @@ -112,26 +116,26 @@ class Client { void _prepareAndExecute() { // Prepare query; any error will make our returned future fail _prepare(query) - // Fetch a connection for the node this query was prepared at and execute it - .then((PreparedResultMessage preparedResult) => connectionPool.getConnectionToHost( - preparedResult.host - , preparedResult.port - ).then((Connection conn) => conn.execute( - query - , preparedResult : preparedResult - , pageSize: pageSize - , pagingState : pagingState - )) - .then(completer.complete) - // If we lose our connection OR we cannot reserve a connection stream, retry on another connection to the same host - .catchError((_) => _prepareAndExecute(), test: (e) => e is ConnectionLostException || e is StreamReservationException) - // We run out of connections to use this prepared result so we need to prepare it again on a new node - .catchError((_) { - preparedQueries.remove(query.query); - _prepareAndExecute(); - }, test : (e) => e is NoHealthyConnectionsException)) - // Any other error will cause the future to fail - .catchError(completer.completeError); + // Fetch a connection for the node this query was prepared at and execute it + .then((PreparedResultMessage preparedResult) => connectionPool + .getConnectionToHost(preparedResult.host, preparedResult.port) + .then((Connection conn) => conn.execute(query, + preparedResult: preparedResult, + pageSize: pageSize, + pagingState: pagingState)) + .then(completer.complete) + // If we lose our connection OR we cannot reserve a connection stream, retry on another connection to the same host + .catchError((_) => _prepareAndExecute(), + test: (e) => + e is ConnectionLostException || + e is StreamReservationException) + // We run out of connections to use this prepared result so we need to prepare it again on a new node + .catchError((_) { + preparedQueries.remove(query.query); + _prepareAndExecute(); + }, test: (e) => e is NoHealthyConnectionsException)) + // Any other error will cause the future to fail + .catchError(completer.completeError); } _prepareAndExecute(); return completer.future; @@ -141,7 +145,8 @@ class Client { * Execute a batch [query] and return back a [Future] */ Future _executeBatch(BatchQuery query) { - return connectionPool.getConnection().then((Connection conn) => conn.executeBatch(query)); + return connectionPool + .getConnection() + .then((Connection conn) => conn.executeBatch(query)); } - } diff --git a/lib/src/client/result_stream.dart b/lib/src/client/result_stream.dart index 3910303..6707c17 100644 --- a/lib/src/client/result_stream.dart +++ b/lib/src/client/result_stream.dart @@ -1,6 +1,7 @@ part of dart_cassandra_cql.client; -typedef Future PagedQueryExecutor(Query query, {int pageSize, Uint8List pagingState}); +typedef Future PagedQueryExecutor(Query query, + {int pageSize, Uint8List pagingState}); class ResultStream { PagedQueryExecutor _queryExecutor; @@ -17,35 +18,32 @@ class ResultStream { } _buffering = true; - _queryExecutor( - _query - , pageSize : _pageSize - , pagingState : _pagingState - ).then((RowsResultMessage data) { - // If the stream has been closed, clean up - if (_streamController.isClosed) { - return; - } - - _buffering = false; - - // Append incoming rows to current result list and update our paging state - _bufferedData = new Queue.from(data.rows); - data.rows = null; - _pagingState = data.metadata.pagingState; - - _emitRows(); - }) - .catchError(_streamController.addError, test : (e) => e is NoHealthyConnectionsException) - .catchError((_) { - // Treat any other kind of error as a 'connection lost' event and try to rebuffer again - _buffering = false; - _bufferNextPage(); - }); + _queryExecutor(_query, pageSize: _pageSize, pagingState: _pagingState) + .then((RowsResultMessage data) { + // If the stream has been closed, clean up + if (_streamController.isClosed) { + return; + } + + _buffering = false; + + // Append incoming rows to current result list and update our paging state + _bufferedData = new Queue.from(data.rows); + data.rows = null; + _pagingState = data.metadata.pagingState; + + _emitRows(); + }) + .catchError(_streamController.addError, + test: (e) => e is NoHealthyConnectionsException) + .catchError((_) { + // Treat any other kind of error as a 'connection lost' event and try to rebuffer again + _buffering = false; + _bufferNextPage(); + }); } void _emitRows() { - // If stream is paused, do not emit any events if (_streamController.isPaused) { return; @@ -53,7 +51,6 @@ class ResultStream { // Emit each available row while (_bufferedData != null && _bufferedData.isNotEmpty) { - Map row = _bufferedData.removeFirst(); _streamController.add(row); @@ -67,9 +64,7 @@ class ResultStream { // or close the stream if we are done if (!_streamController.isClosed && !_streamController.isPaused && - _bufferedData.isEmpty - ) { - + _bufferedData.isEmpty) { if (_pagingState == null) { _streamController.close(); } else { @@ -81,7 +76,6 @@ class ResultStream { void _cleanup() { _bufferedData = null; _pagingState = null; - } Stream> get stream => _streamController.stream; @@ -89,12 +83,12 @@ class ResultStream { /** * Create a new [ResultStream] by paging through [this._query] object with a page size of [this._pageSize]. */ - ResultStream(PagedQueryExecutor this._queryExecutor, Query this._query, int this._pageSize) { + ResultStream(PagedQueryExecutor this._queryExecutor, Query this._query, + int this._pageSize) { _streamController = new StreamController>( - onListen : _bufferNextPage - , onResume : _emitRows - , onCancel : _cleanup - , sync : true - ); + onListen: _bufferNextPage, + onResume: _emitRows, + onCancel: _cleanup, + sync: true); } } diff --git a/lib/src/connection/async_queue.dart b/lib/src/connection/async_queue.dart index efa8061..c269fb0 100644 --- a/lib/src/connection/async_queue.dart +++ b/lib/src/connection/async_queue.dart @@ -1,12 +1,11 @@ part of dart_cassandra_cql.connection; class AsyncQueue { - Queue _resources; Queue> _reservations = new Queue>(); Duration reservationTimeout; - AsyncQueue.from(Iterable resources){ + AsyncQueue.from(Iterable resources) { _resources = new Queue.from(resources); } @@ -24,7 +23,8 @@ class AsyncQueue { if (reservationTimeout != null && reservationTimeout.inMilliseconds > 0) { new Timer(reservationTimeout, () { if (!reservation.isCompleted) { - reservation.completeError(new StreamReservationException('Timed out waiting for stream reservation')); + reservation.completeError(new StreamReservationException( + 'Timed out waiting for stream reservation')); } }); } diff --git a/lib/src/connection/connection.dart b/lib/src/connection/connection.dart index 2cb00ab..f89e833 100644 --- a/lib/src/connection/connection.dart +++ b/lib/src/connection/connection.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.connection; class Connection { - // Configuration options PoolConfiguration _poolConfig; String defaultKeyspace; @@ -29,7 +28,8 @@ class Connection { Completer _drained; Future _socketFlushed; - Connection(String this.connId, String this.host, int this.port, {PoolConfiguration config, String this.defaultKeyspace}) { + Connection(String this.connId, String this.host, int this.port, + {PoolConfiguration config, String this.defaultKeyspace}) { // If no config is specified, use the default one _poolConfig = config == null ? new PoolConfiguration() : config; @@ -45,7 +45,6 @@ class Connection { */ Future _abortRequestsAndCleanup(reason) { - // Clear healthy flag healthy = false; @@ -61,9 +60,8 @@ class Connection { _connected = null; // Kill socket - Future socketClosed = _socket != null - ? _socket.close() - : new Future.value(); + Future socketClosed = + _socket != null ? _socket.close() : new Future.value(); _socket = null; return socketClosed; @@ -80,7 +78,8 @@ class Connection { _connected = new Completer(); } - connectionLogger.info("[${connId}] Trying to connect to ${host}:${port} [attempt ${_connectionAttempt + 1}/${_poolConfig.maxConnectionAttempts}]"); + connectionLogger.info( + "[${connId}] Trying to connect to ${host}:${port} [attempt ${_connectionAttempt + 1}/${_poolConfig.maxConnectionAttempts}]"); Socket.connect(host, port).then((Socket s) { _socket = s; _socketFlushed = new Future.value(true); @@ -88,38 +87,42 @@ class Connection { // Initialize our writer pool and set the reservation timeout _reservedFrameWriters.clear(); _frameWriterPool = new AsyncQueue.from( - new List.generate(_poolConfig.streamsPerConnection, (int id) => new FrameWriter(id, _poolConfig.protocolVersion, preferBiggerTcpPackets : _poolConfig.preferBiggerTcpPackets)) - ); - _frameWriterPool.reservationTimeout = _poolConfig.streamReservationTimeout; + new List.generate( + _poolConfig.streamsPerConnection, + (int id) => new FrameWriter(id, _poolConfig.protocolVersion, + preferBiggerTcpPackets: _poolConfig.preferBiggerTcpPackets))); + _frameWriterPool.reservationTimeout = + _poolConfig.streamReservationTimeout; // Bind processors and initiate handshake _socket - .transform(new FrameParser().transformer) - .transform(new FrameDecompressor(_poolConfig.compression).transformer) - .transform(new FrameReader().transformer) - .listen( - _onMessage - // Mute socket errors; they will be caught by _writeMessage - , onError : (_) { - } - , onDone : () { - connectionLogger.severe("[${connId}] Server has closed the connection"); - if (_socket != null) { - _socket.destroy(); - _socket = null; - } + .transform(new FrameParser().transformer) + .transform(new FrameDecompressor(_poolConfig.compression).transformer) + .transform(new FrameReader().transformer) + .listen( + _onMessage + // Mute socket errors; they will be caught by _writeMessage + , + onError: (_) {}, onDone: () { + connectionLogger.severe("[${connId}] Server has closed the connection"); + if (_socket != null) { + _socket.destroy(); + _socket = null; + } - _abortRequestsAndCleanup(new ConnectionLostException("Server closed the connection")); - } - ); + _abortRequestsAndCleanup( + new ConnectionLostException("Server closed the connection")); + }); // Handshake with the server _handshake(); }).catchError((err, trace) { if (++_connectionAttempt >= _poolConfig.maxConnectionAttempts) { - String errorMessage = "[${connId}] Could not connect to ${host}:${port} after ${_poolConfig.maxConnectionAttempts} attempts. Giving up"; + String errorMessage = + "[${connId}] Could not connect to ${host}:${port} after ${_poolConfig.maxConnectionAttempts} attempts. Giving up"; connectionLogger.severe(errorMessage); - _connected.completeError(new ConnectionFailedException(errorMessage, trace)); + _connected + .completeError(new ConnectionFailedException(errorMessage, trace)); // Clear _connected future so the client can invoke open() in the future _connected = null; @@ -135,9 +138,12 @@ class Connection { Future _authenticate(AuthenticateMessage authMessage) { // Check if an authenticator is specified if (_poolConfig.authenticator == null) { - throw new AuthenticationException("Server requested '${authMessage.authenticatorClass}' authenticator but no authenticator specified"); - } else if (authMessage.authenticatorClass != _poolConfig.authenticator.authenticatorClass) { - throw new AuthenticationException("Server requested '${authMessage.authenticatorClass}' authenticator but a '${_poolConfig.authenticator.authenticatorClass}' authenticator was specified instead"); + throw new AuthenticationException( + "Server requested '${authMessage.authenticatorClass}' authenticator but no authenticator specified"); + } else if (authMessage.authenticatorClass != + _poolConfig.authenticator.authenticatorClass) { + throw new AuthenticationException( + "Server requested '${authMessage.authenticatorClass}' authenticator but a '${_poolConfig.authenticator.authenticatorClass}' authenticator was specified instead"); } // Run through challenge response till we get back a ready message from the server @@ -147,20 +153,16 @@ class Connection { if (result is AuthenticateMessage || result is AuthChallengeMessage) { AuthResponseMessage response = new AuthResponseMessage() ..responsePayload = _poolConfig.authenticator.answerChallenge( - result is AuthenticateMessage - ? result.challengePayload - : (result as AuthChallengeMessage).challengePayload - ); - - _writeMessage(response) - .then(answerChallenge) - .catchError((e, trace) { + result is AuthenticateMessage + ? result.challengePayload + : (result as AuthChallengeMessage).challengePayload); + + _writeMessage(response).then(answerChallenge).catchError((e, trace) { completer.completeError( e is CassandraException - ? new AuthenticationException(e.message, trace) - : e - , trace - ); + ? new AuthenticationException(e.message, trace) + : e, + trace); }); } else if (result is AuthSuccessMessage) { completer.complete(result); @@ -177,21 +179,18 @@ class Connection { */ void _handshake() { - StartupMessage message = new StartupMessage() ..cqlVersion = _poolConfig.cqlVersion ..compression = _poolConfig.compression; - _writeMessage(message) - .then((Message response) { + _writeMessage(message).then((Message response) { // Authentication Required if (response is AuthenticateMessage) { return _authenticate(response); } else { return new Future.value(response); } - }) - .then((_) { + }).then((_) { // if default keyspace is specified, run a query here. // Note since the connection is not yet *open* we cannot invoke execute() here if (defaultKeyspace != null) { @@ -205,9 +204,9 @@ class Connection { return _writeMessage(message); } return true; - }) - .then((_) { - connectionLogger.info("[${connId}] Connected to ${host}:${port} [attempt ${_connectionAttempt + 1}/${_poolConfig.maxConnectionAttempts}]"); + }).then((_) { + connectionLogger.info( + "[${connId}] Connected to ${host}:${port} [attempt ${_connectionAttempt + 1}/${_poolConfig.maxConnectionAttempts}]"); healthy = true; inService = true; @@ -227,7 +226,6 @@ class Connection { */ Future _writeMessage(RequestMessage message) { - Completer reply = new Completer(); // Make sure we have flushed our socket data and then // block till we get back a frame writer @@ -243,11 +241,11 @@ class Connection { writer.writeMessage(message, _socket, compression: _poolConfig.compression); return _socket.flush(); - }) - .catchError((e, trace) { + }).catchError((e, trace) { // Wrap SocketExceptions if (e is SocketException) { - _abortRequestsAndCleanup(new ConnectionLostException('Lost connection')); + _abortRequestsAndCleanup( + new ConnectionLostException('Lost connection')); } else { reply.completeError(e); } @@ -261,10 +259,11 @@ class Connection { */ void _onMessage(Message message) { - connectionLogger.fine("[${connId}] [stream #${message.streamId}] Received message of type ${Opcode.nameOf(message.opcode)} (${message.opcode}) ${message}"); + connectionLogger.fine( + "[${connId}] [stream #${message.streamId}] Received message of type ${Opcode.nameOf(message.opcode)} (${message.opcode}) ${message}"); // Fetch our response completer - Completer responseCompleter = _pendingResponses[ message.streamId ]; + Completer responseCompleter = _pendingResponses[message.streamId]; // Release streamId back to the pool unless its -1 (server event message) if (message.streamId != -1) { @@ -320,7 +319,8 @@ class Connection { case Opcode.ERROR: ErrorMessage errorMessage = message as ErrorMessage; connectionLogger.severe(errorMessage.message); - responseCompleter.completeError(new CassandraException(errorMessage.message)); + responseCompleter + .completeError(new CassandraException(errorMessage.message)); break; } } @@ -367,7 +367,8 @@ class Connection { * This method returns a [Future] to be completed when the connection is shut down */ - Future close({bool drain : true, Duration drainTimeout : const Duration(seconds : 5)}) { + Future close( + {bool drain: true, Duration drainTimeout: const Duration(seconds: 5)}) { // Already closed if (_socket == null) { return new Future.value(); @@ -387,9 +388,10 @@ class Connection { if (drainTimeout != null) { new Future.delayed(drainTimeout).then((_) { if (_drained != null && !_drained.isCompleted) { - _abortRequestsAndCleanup(new ConnectionLostException('Connection drain timeout')) - .then((_) { - _drained .complete(); + _abortRequestsAndCleanup( + new ConnectionLostException('Connection drain timeout')) + .then((_) { + _drained.complete(); }); } }); @@ -398,7 +400,8 @@ class Connection { return _drained.future; } else { - return _abortRequestsAndCleanup(new ConnectionLostException('Connection closed')); + return _abortRequestsAndCleanup( + new ConnectionLostException('Connection closed')); } } @@ -408,8 +411,8 @@ class Connection { // to positional ones before preparing the statements PrepareMessage message = new PrepareMessage() ..query = _poolConfig.protocolVersion == ProtocolVersion.V2 - ? query.positionalQuery - : query.query; + ? query.positionalQuery + : query.query; return _writeMessage(message); }); @@ -424,7 +427,10 @@ class Connection { * This method will returns [ResultMessage] with the query result */ - Future execute(Query query, {PreparedResultMessage preparedResult : null, int pageSize : null, Uint8List pagingState : null}) { + Future execute(Query query, + {PreparedResultMessage preparedResult: null, + int pageSize: null, + Uint8List pagingState: null}) { return open().then((_) { // Simple unprepared query if (preparedResult == null) { @@ -443,8 +449,8 @@ class Connection { ExecuteMessage message = new ExecuteMessage() ..queryId = preparedResult.queryId ..bindings = _poolConfig.protocolVersion == ProtocolVersion.V2 - ? query.namedToPositionalBindings - : query.bindings + ? query.namedToPositionalBindings + : query.bindings ..bindingTypes = preparedResult.metadata.colSpec ..consistency = query.consistency ..serialConsistency = query.serialConsistency @@ -477,21 +483,24 @@ class Connection { * and return a [Stream] for handling incoming events */ - Stream listenForEvents(Iterable eventTypes) { - RegisterMessage message = new RegisterMessage() - ..eventTypes = eventTypes; + Stream listenForEvents( + Iterable eventTypes) { + RegisterMessage message = new RegisterMessage()..eventTypes = eventTypes; // Setup the stream controller if (_eventController == null) { _eventController = new StreamController(); } - open().then((_) => _writeMessage(message)).catchError(_eventController.addError); + open() + .then((_) => _writeMessage(message)) + .catchError(_eventController.addError); return _eventController.stream; } /** * Check if the connection has available stream slots for multiplexing additional queries */ - bool get hasAvailableStreams => _frameWriterPool != null && _frameWriterPool.hasAvailableSlots; + bool get hasAvailableStreams => + _frameWriterPool != null && _frameWriterPool.hasAvailableSlots; } diff --git a/lib/src/connection/connection_pool.dart b/lib/src/connection/connection_pool.dart index 1671929..e06357b 100644 --- a/lib/src/connection/connection_pool.dart +++ b/lib/src/connection/connection_pool.dart @@ -1,11 +1,11 @@ part of dart_cassandra_cql.connection; abstract class ConnectionPool { - static final int DEFAULT_PORT = 9042; PoolConfiguration poolConfig; - StreamController _eventStreamController = new StreamController.broadcast(); + StreamController _eventStreamController = + new StreamController.broadcast(); /** * Establish connections to the pool nodes and return a [Future] to be successfully completed when @@ -20,7 +20,8 @@ abstract class ConnectionPool { * when all connections are drained or when the [drainTimeout] expires. If [drain] is false then * the returned [Future] will already be completed. */ - Future disconnect({ bool drain : true, Duration drainTimeout : const Duration( seconds : 5 )}); + Future disconnect( + {bool drain: true, Duration drainTimeout: const Duration(seconds: 5)}); /** * Get back an active [Connection] from the pool. @@ -35,8 +36,10 @@ abstract class ConnectionPool { /** * Return a [Stream] where the application can listen for the requested [eventTypes]. */ - Stream listenForServerEvents(List eventTypes) { + Stream listenForServerEvents( + List eventTypes) { // Return back a stream filtered by the given event types - return _eventStreamController.stream.where((EventMessage e) => eventTypes.contains(e.type)); + return _eventStreamController.stream + .where((EventMessage e) => eventTypes.contains(e.type)); } } diff --git a/lib/src/connection/pool_configuration.dart b/lib/src/connection/pool_configuration.dart index b0d5277..17ad204 100644 --- a/lib/src/connection/pool_configuration.dart +++ b/lib/src/connection/pool_configuration.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.connection; class PoolConfiguration { - // The CQL version to use String cqlVersion; @@ -50,20 +49,18 @@ class PoolConfiguration { */ bool preferBiggerTcpPackets; - PoolConfiguration({ - String this.cqlVersion : "3.0.0" - , ProtocolVersion this.protocolVersion : ProtocolVersion.V2 - , int this.connectionsPerHost : 1 - , int this.streamsPerConnection : 128 - , int this.maxConnectionAttempts : 10 - , Duration this.reconnectWaitTime : const Duration(milliseconds : 1500) - , Duration this.streamReservationTimeout : const Duration(milliseconds: 0) - , bool this.autoDiscoverNodes : true - , Compression this.compression - , Authenticator this.authenticator - , bool this.preferBiggerTcpPackets : false - }) { - + PoolConfiguration( + {String this.cqlVersion: "3.0.0", + ProtocolVersion this.protocolVersion: ProtocolVersion.V2, + int this.connectionsPerHost: 1, + int this.streamsPerConnection: 128, + int this.maxConnectionAttempts: 10, + Duration this.reconnectWaitTime: const Duration(milliseconds: 1500), + Duration this.streamReservationTimeout: const Duration(milliseconds: 0), + bool this.autoDiscoverNodes: true, + Compression this.compression, + Authenticator this.authenticator, + bool this.preferBiggerTcpPackets: false}) { validate(); } @@ -74,22 +71,27 @@ class PoolConfiguration { void validate() { // We only support protocol version V2 and V3 - if (protocolVersion != ProtocolVersion.V2 && protocolVersion != ProtocolVersion.V3) { + if (protocolVersion != ProtocolVersion.V2 && + protocolVersion != ProtocolVersion.V3) { throw new ArgumentError("Driver only supports protocol versions 2 and 3"); } // According to the protocol spec, each connection can multiplex up to 128 streams (V2) or 32768 (V3) - if (protocolVersion == ProtocolVersion.V2 && (streamsPerConnection <= 0 || streamsPerConnection > 128)) { - throw new ArgumentError("Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 128 when using V2 prototcol"); + if (protocolVersion == ProtocolVersion.V2 && + (streamsPerConnection <= 0 || streamsPerConnection > 128)) { + throw new ArgumentError( + "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 128 when using V2 prototcol"); } - if (protocolVersion == ProtocolVersion.V3 && (streamsPerConnection <= 0 || streamsPerConnection > 32768)) { - throw new ArgumentError("Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 3768 when using V3 prototcol"); + if (protocolVersion == ProtocolVersion.V3 && + (streamsPerConnection <= 0 || streamsPerConnection > 32768)) { + throw new ArgumentError( + "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 3768 when using V3 prototcol"); } // If a compression algorithm is specified make sure the appropriate codec is registered if (compression != null && getCodec(compression.value) == null) { - throw new ArgumentError("A compression codec needs to be registered via registerCodec() for type '${compression}'"); + throw new ArgumentError( + "A compression codec needs to be registered via registerCodec() for type '${compression}'"); } } - -} \ No newline at end of file +} diff --git a/lib/src/connection/simple_connection_pool.dart b/lib/src/connection/simple_connection_pool.dart index c8a7d0b..71df138 100644 --- a/lib/src/connection/simple_connection_pool.dart +++ b/lib/src/connection/simple_connection_pool.dart @@ -1,12 +1,12 @@ part of dart_cassandra_cql.connection; class SimpleConnectionPool extends ConnectionPool { - // The list of all pool connections final List _pool = new List(); // The list of maintained connections per host:port combination - final Map> _poolPerHost = new HashMap>(); + final Map> _poolPerHost = + new HashMap>(); // Pending list of reconnect attempts final Map _pendingReconnects = new HashMap(); @@ -24,7 +24,9 @@ class SimpleConnectionPool extends ConnectionPool { * to the input list of [hosts] */ - SimpleConnectionPool.fromHostList(List hosts, PoolConfiguration poolConfig, { String this.defaultKeyspace}) { + SimpleConnectionPool.fromHostList( + List hosts, PoolConfiguration poolConfig, + {String this.defaultKeyspace}) { if (hosts == null || hosts.isEmpty) { throw new ArgumentError("Host list cannot be empty"); } @@ -35,11 +37,10 @@ class SimpleConnectionPool extends ConnectionPool { this.poolConfig = poolConfig; for (int hostIndex = 0; hostIndex < hosts.length; hostIndex++) { - List hostParts = hosts[hostIndex].split(':'); int port = hostParts.length > 1 - ? int.parse(hostParts[1]) - : ConnectionPool.DEFAULT_PORT; + ? int.parse(hostParts[1]) + : ConnectionPool.DEFAULT_PORT; _createPoolForHost(hostParts[0], port); } @@ -47,10 +48,9 @@ class SimpleConnectionPool extends ConnectionPool { // If node auto-discovery is enabled listen for those server events if (poolConfig.autoDiscoverNodes) { listenForServerEvents([ - EventRegistrationType.STATUS_CHANGE - , EventRegistrationType.TOPOLOGY_CHANGE - ]).listen(_handleEventMessage, onError : (_) { - }); + EventRegistrationType.STATUS_CHANGE, + EventRegistrationType.TOPOLOGY_CHANGE + ]).listen(_handleEventMessage, onError: (_) {}); } //poolLogger.info("Created ${_pool.length} connections to ${hosts.length} hosts"); } @@ -98,16 +98,16 @@ class SimpleConnectionPool extends ConnectionPool { } // No more connections remaining to be opened - if( remainingConnections == 0 && !_poolConnected.isCompleted){ + if (remainingConnections == 0 && !_poolConnected.isCompleted) { // All connections failed if (activeConnections == 0) { - _poolConnected.completeError(new NoHealthyConnectionsException("Could not connect to any of the supplied hosts")); - } else{ + _poolConnected.completeError(new NoHealthyConnectionsException( + "Could not connect to any of the supplied hosts")); + } else { // At least one connection has been established _poolConnected.complete(); } } - }); }); @@ -120,30 +120,38 @@ class SimpleConnectionPool extends ConnectionPool { * when all connections are drained or when the [drainTimeout] expires. If [drain] is false then * the returned [Future] will already be completed. */ - Future disconnect({ bool drain : true, Duration drainTimeout : const Duration( seconds : 5 )}) { - return Future.wait(_pool.map((Connection conn) => conn.close(drain : drain, drainTimeout : drainTimeout))); + Future disconnect( + {bool drain: true, Duration drainTimeout: const Duration(seconds: 5)}) { + return Future.wait(_pool.map((Connection conn) => + conn.close(drain: drain, drainTimeout: drainTimeout))); } /** * Get back an active [Connection] from the pool. */ Future getConnection() { - return _findOneMatchingFilter((Connection conn) => conn.healthy && conn.inService); + return _findOneMatchingFilter( + (Connection conn) => conn.healthy && conn.inService); } /** * Get back an active [Connection] from the pool to the specified [host] and [port]. */ Future getConnectionToHost(String host, int port) { - return _findOneMatchingFilter((Connection conn) => conn.healthy && conn.inService && conn.host == host && conn.port == port); + return _findOneMatchingFilter((Connection conn) => + conn.healthy && + conn.inService && + conn.host == host && + conn.port == port); } Future _findOneMatchingFilter(Function filter) { return connect().then((_) { - // Prefer healthry connections matching the filter predicate that have available // query multiplexing slots so we do not need to wait - Connection healthyConnection = _pool.firstWhere((Connection conn) => conn.hasAvailableStreams && filter(conn), orElse: () => null); + Connection healthyConnection = _pool.firstWhere( + (Connection conn) => conn.hasAvailableStreams && filter(conn), + orElse: () => null); // Otherwise try to fetch the first healthy connection from the pool matching the filter predicate if (healthyConnection == null) { @@ -151,7 +159,8 @@ class SimpleConnectionPool extends ConnectionPool { } if (healthyConnection == null) { - return new Future.error(new NoHealthyConnectionsException("No healhty connections available")); + return new Future.error(new NoHealthyConnectionsException( + "No healhty connections available")); } else { // Remove the connection and append it to the end of the list // so we can round-robin our connections @@ -167,24 +176,21 @@ class SimpleConnectionPool extends ConnectionPool { // List for server events and add them to the stream controller _eventSubscriber = conn; _eventSubscription = conn.listenForEvents([ - EventRegistrationType.STATUS_CHANGE, - EventRegistrationType.TOPOLOGY_CHANGE, - EventRegistrationType.SCHEMA_CHANGE - ]) - .listen(_eventStreamController.add, onError: (_) { - }); + EventRegistrationType.STATUS_CHANGE, + EventRegistrationType.TOPOLOGY_CHANGE, + EventRegistrationType.SCHEMA_CHANGE + ]).listen(_eventStreamController.add, onError: (_) {}); poolLogger.info("Listening for server events on [${conn.connId}]"); - } void _handleEventMessage(EventMessage message) { - poolLogger.fine("Received eventMessage ${EventRegistrationType.nameOf(message.type)}:${EventType.nameOf(message.subType)} ${message.type == EventRegistrationType.SCHEMA_CHANGE ? ("${message.keyspace}" + (!message.changedTable.isEmpty ? ".${message.changedTable}" : "")) : "${message.address}:${message.port}"}"); + poolLogger.fine( + "Received eventMessage ${EventRegistrationType.nameOf(message.type)}:${EventType.nameOf(message.subType)} ${message.type == EventRegistrationType.SCHEMA_CHANGE ? ("${message.keyspace}" + (!message.changedTable.isEmpty ? ".${message.changedTable}" : "")) : "${message.address}:${message.port}"}"); switch (message.subType) { case EventType.NODE_ADDED: case EventType.NODE_UP: - String hostKey = "${message.address.host}:${message.port}"; // If we are already processing an UP event for this host, ignore @@ -202,12 +208,14 @@ class SimpleConnectionPool extends ConnectionPool { poolLogger.info("Discovered new node [${hostKey}]. Adding to pool"); _createPoolForHost(message.address.host, message.port); } else { - poolLogger.info("Node [${hostKey}] went online. Attempting to reconnect"); + poolLogger + .info("Node [${hostKey}] went online. Attempting to reconnect"); } // According to the protocol spec, it might take some time for the node // to begin accepting connections so we need to defer our connection attempts. - _pendingReconnects[ hostKey ] = new Future.delayed(poolConfig.reconnectWaitTime, () { + _pendingReconnects[hostKey] = + new Future.delayed(poolConfig.reconnectWaitTime, () { _poolPerHost[hostKey].forEach((Connection conn) => conn.open()); _pendingReconnects.remove(hostKey); }); @@ -215,7 +223,6 @@ class SimpleConnectionPool extends ConnectionPool { break; case EventType.NODE_REMOVED: case EventType.NODE_DOWN: - String hostKey = "${message.address.host}:${message.port}"; Set hostConnections = _poolPerHost[hostKey]; @@ -223,26 +230,25 @@ class SimpleConnectionPool extends ConnectionPool { if (hostConnections == null) { return; } else if (message.subType == EventType.NODE_REMOVED) { - poolLogger.info("Node [${hostKey}] removed from cluster. Purging any existing open connections from pool"); + poolLogger.info( + "Node [${hostKey}] removed from cluster. Purging any existing open connections from pool"); _poolPerHost.remove(hostKey); _pendingReconnects.remove(hostKey); } else { - poolLogger.info("Node [${hostKey}] went offline. Closing any existing open connections"); + poolLogger.info( + "Node [${hostKey}] went offline. Closing any existing open connections"); _pendingReconnects.remove(hostKey); } // Force-close any existing connections - hostConnections.forEach((Connection conn) => conn.close(drain : false)); + hostConnections.forEach((Connection conn) => conn.close(drain: false)); // If we lost the connection registered for server events, pick a new one if (hostConnections.contains(_eventSubscriber)) { _eventSubscription.cancel(); _eventSubscription = null; _eventSubscriber = null; - getConnection() - .then(_registerEventListener) - .catchError((_) { - }); + getConnection().then(_registerEventListener).catchError((_) {}); } break; @@ -254,14 +260,11 @@ class SimpleConnectionPool extends ConnectionPool { _poolPerHost[hostKey] = new HashSet(); // Allocate poolConfig.connectionsPerHost connections - for (int poolIndex = 0; poolIndex < poolConfig.connectionsPerHost; poolIndex++) { - Connection conn = new Connection( - "${hostKey}-${poolIndex}" - , host - , port - , config : poolConfig - , defaultKeyspace : defaultKeyspace - ); + for (int poolIndex = 0; + poolIndex < poolConfig.connectionsPerHost; + poolIndex++) { + Connection conn = new Connection("${hostKey}-${poolIndex}", host, port, + config: poolConfig, defaultKeyspace: defaultKeyspace); _poolPerHost[hostKey].add(conn); _pool.add(conn); diff --git a/lib/src/exception/authentication_exception.dart b/lib/src/exception/authentication_exception.dart index 5f52184..54fe00d 100644 --- a/lib/src/exception/authentication_exception.dart +++ b/lib/src/exception/authentication_exception.dart @@ -1,7 +1,8 @@ part of dart_cassandra_cql.exception; class AuthenticationException extends DriverException { - AuthenticationException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + AuthenticationException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); String toString() { return "AuthenticationException: ${message}"; diff --git a/lib/src/exception/cassandra_exception.dart b/lib/src/exception/cassandra_exception.dart index 05748bc..f06d154 100644 --- a/lib/src/exception/cassandra_exception.dart +++ b/lib/src/exception/cassandra_exception.dart @@ -1,8 +1,8 @@ part of dart_cassandra_cql.exception; class CassandraException extends DriverException { - - CassandraException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + CassandraException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); String toString() { return "CassandraException: ${message}"; diff --git a/lib/src/exception/connection_failed_exception.dart b/lib/src/exception/connection_failed_exception.dart index 263c784..07dcdb4 100644 --- a/lib/src/exception/connection_failed_exception.dart +++ b/lib/src/exception/connection_failed_exception.dart @@ -1,7 +1,8 @@ part of dart_cassandra_cql.exception; class ConnectionFailedException extends DriverException { - ConnectionFailedException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + ConnectionFailedException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); String toString() { return "ConnectionFailedException: ${message}"; diff --git a/lib/src/exception/connection_lost_exception.dart b/lib/src/exception/connection_lost_exception.dart index a0a6749..dae9495 100644 --- a/lib/src/exception/connection_lost_exception.dart +++ b/lib/src/exception/connection_lost_exception.dart @@ -1,5 +1,6 @@ part of dart_cassandra_cql.exception; class ConnectionLostException extends DriverException { - ConnectionLostException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + ConnectionLostException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); } diff --git a/lib/src/exception/driver_exception_exception.dart b/lib/src/exception/driver_exception_exception.dart index a0a1c26..de4c7aa 100644 --- a/lib/src/exception/driver_exception_exception.dart +++ b/lib/src/exception/driver_exception_exception.dart @@ -4,7 +4,7 @@ class DriverException implements Exception { String message; StackTrace stackTrace; - DriverException(this.message, [ this.stackTrace = null]); + DriverException(this.message, [this.stackTrace = null]); String toString() { return "DriverException: ${message}"; diff --git a/lib/src/exception/no_healthy_connections_exception.dart b/lib/src/exception/no_healthy_connections_exception.dart index c48a0d3..22a6e4b 100644 --- a/lib/src/exception/no_healthy_connections_exception.dart +++ b/lib/src/exception/no_healthy_connections_exception.dart @@ -1,10 +1,10 @@ part of dart_cassandra_cql.exception; class NoHealthyConnectionsException extends DriverException { - NoHealthyConnectionsException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + NoHealthyConnectionsException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); String toString() { return "NoHealthyConnectionsException: ${message}"; } - } diff --git a/lib/src/exception/stream_reservation_exception.dart b/lib/src/exception/stream_reservation_exception.dart index bf146b3..126022a 100644 --- a/lib/src/exception/stream_reservation_exception.dart +++ b/lib/src/exception/stream_reservation_exception.dart @@ -1,7 +1,8 @@ part of dart_cassandra_cql.exception; class StreamReservationException extends DriverException { - StreamReservationException(String message, [ StackTrace stackTrace = null]) : super(message, stackTrace); + StreamReservationException(String message, [StackTrace stackTrace = null]) + : super(message, stackTrace); String toString() { return "StreamReservationException: ${message}"; diff --git a/lib/src/protocol/authentication/authenticator.dart b/lib/src/protocol/authentication/authenticator.dart index d7cea37..07484e5 100644 --- a/lib/src/protocol/authentication/authenticator.dart +++ b/lib/src/protocol/authentication/authenticator.dart @@ -10,5 +10,4 @@ abstract class Authenticator { * Process the [challenge] sent by the server and return a [Uint8List] response */ Uint8List answerChallenge(Uint8List challenge); - -} \ No newline at end of file +} diff --git a/lib/src/protocol/authentication/password_authenticator.dart b/lib/src/protocol/authentication/password_authenticator.dart index 3db2a07..567ddc9 100644 --- a/lib/src/protocol/authentication/password_authenticator.dart +++ b/lib/src/protocol/authentication/password_authenticator.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.protocol; class PasswordAuthenticator implements Authenticator { - String _userName; String _password; @@ -23,7 +22,8 @@ class PasswordAuthenticator implements Authenticator { /** * Get the class of this authenticator */ - String get authenticatorClass => "org.apache.cassandra.auth.PasswordAuthenticator"; + String get authenticatorClass => + "org.apache.cassandra.auth.PasswordAuthenticator"; /** * Process the [challenge] sent by the server and return a [Uint8List] response @@ -41,4 +41,4 @@ class PasswordAuthenticator implements Authenticator { return writer.joinChunks(); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/frame/frame_decompressor.dart b/lib/src/protocol/frame/frame_decompressor.dart index 975af64..6a04de6 100644 --- a/lib/src/protocol/frame/frame_decompressor.dart +++ b/lib/src/protocol/frame/frame_decompressor.dart @@ -1,42 +1,45 @@ part of dart_cassandra_cql.protocol; class FrameDecompressor { - Compression _compression; FrameDecompressor(this._compression); void handleData(Frame frame, EventSink sink) { - - if ((frame.header.flags & HeaderFlag.COMPRESSION.value) == HeaderFlag.COMPRESSION.value) { + if ((frame.header.flags & HeaderFlag.COMPRESSION.value) == + HeaderFlag.COMPRESSION.value) { // Fetch compression codec - Codec compressionCodec = _compression != null - ? getCodec(_compression.value) - : null; + Codec compressionCodec = + _compression != null ? getCodec(_compression.value) : null; try { if (compressionCodec == null && _compression == null) { - throw new DriverException("Server responded with an unexpected compressed frame"); + throw new DriverException( + "Server responded with an unexpected compressed frame"); } else if (compressionCodec == null) { - throw new DriverException("A compression codec needs to be registered via registerCodec() for type '${_compression}'"); + throw new DriverException( + "A compression codec needs to be registered via registerCodec() for type '${_compression}'"); } // Decompress and replace body data. According to the spec, if the compression algorithm is LZ4 // then the first four bytes of the payload should include its decompressed length so compliant // LZ4 codecs should expect this. - Uint8List bodyData = new Uint8List.view(frame.body.buffer, 0, frame.body.lengthInBytes); + Uint8List bodyData = + new Uint8List.view(frame.body.buffer, 0, frame.body.lengthInBytes); // Generate uncompressed frame bodyData = compressionCodec.decode(bodyData); - frame = new Frame.fromParts(frame.header, new ByteData.view(bodyData.buffer, 0, bodyData.lengthInBytes)); + frame = new Frame.fromParts(frame.header, + new ByteData.view(bodyData.buffer, 0, bodyData.lengthInBytes)); } catch (e, trace) { // Wrap non-driver exceptions ExceptionMessage message = new ExceptionMessage( e is DriverException - ? e - : new DriverException("An error occurred while invoking '${_compression}' codec (decompression): ${e}", trace) - , trace - ); + ? e + : new DriverException( + "An error occurred while invoking '${_compression}' codec (decompression): ${e}", + trace), + trace); message.streamId = frame.header.streamId; sink.addError(message); return; @@ -55,10 +58,9 @@ class FrameDecompressor { sink.addError(error, stackTrace); } - StreamTransformer get transformer => new StreamTransformer.fromHandlers( - handleData: handleData, - handleDone: handleDone, - handleError: handleError - ); - + StreamTransformer get transformer => + new StreamTransformer.fromHandlers( + handleData: handleData, + handleDone: handleDone, + handleError: handleError); } diff --git a/lib/src/protocol/frame/frame_parser.dart b/lib/src/protocol/frame/frame_parser.dart index 59d6b9e..274ea8b 100644 --- a/lib/src/protocol/frame/frame_parser.dart +++ b/lib/src/protocol/frame/frame_parser.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.protocol; class FrameParser { - final ChunkedInputReader _inputBuffer = new ChunkedInputReader(); FrameHeader _parsedHeader; Uint8List _bodyData; @@ -18,7 +17,6 @@ class FrameParser { // Are we extracting header bytes? if (_parsedHeader == null) { - if (_headerSizeInBytes == null) { // Peek the first byte to figure out the version int version = _inputBuffer.peekNextByte(); @@ -27,14 +25,15 @@ class FrameParser { _headerSizeInBytes = FrameHeader.SIZE_IN_BYTES_V2; _protocolVersion = ProtocolVersion.V2; } else if (version == HeaderVersion.RESPONSE_V3.value || - version == HeaderVersion.REQUEST_V3.value) { + version == HeaderVersion.REQUEST_V3.value) { _headerSizeInBytes = FrameHeader.SIZE_IN_BYTES_V3; _protocolVersion = ProtocolVersion.V3; } } // Not enough bytes to parse header; wait till we get more - if (_headerSizeInBytes == null || _inputBuffer.length < _headerSizeInBytes) { + if (_headerSizeInBytes == null || + _inputBuffer.length < _headerSizeInBytes) { return; } @@ -43,11 +42,14 @@ class FrameParser { _inputBuffer.read(headerBytes, _headerSizeInBytes); //dump = new File("${new DateTime.now()}.dump"); //dump.writeAsBytesSync(headerBytes); - _parsedHeader = new TypeDecoder.fromBuffer(new ByteData.view(headerBytes.buffer), _protocolVersion).readHeader(); + _parsedHeader = new TypeDecoder.fromBuffer( + new ByteData.view(headerBytes.buffer), _protocolVersion) + .readHeader(); headerBytes = null; if (_parsedHeader.length > FrameHeader.MAX_LENGTH_IN_BYTES) { - throw new DriverException("Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${_parsedHeader.length} bytes"); + throw new DriverException( + "Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${_parsedHeader.length} bytes"); } // Allocate buffer for body and reset write offset @@ -55,18 +57,20 @@ class FrameParser { _bodyWriteOffset = 0; } else { // Copy pending body data - _bodyWriteOffset += _inputBuffer.read(_bodyData, _parsedHeader.length - _bodyWriteOffset, _bodyWriteOffset); + _bodyWriteOffset += _inputBuffer.read(_bodyData, + _parsedHeader.length - _bodyWriteOffset, _bodyWriteOffset); } // If we are done emit the frame to the next pipeline stage and cleanup if (_bodyWriteOffset == _parsedHeader.length) { // Ignore messages with unknown opcodes if (_parsedHeader.opcode != null) { - //dump.writeAsBytesSync(_bodyData, mode : FileMode.APPEND); - sink.add(new Frame.fromParts(_parsedHeader, new ByteData.view(_bodyData.buffer))); + sink.add(new Frame.fromParts( + _parsedHeader, new ByteData.view(_bodyData.buffer))); } else { - throw new DriverException("Unknown frame with opcode 0x${_parsedHeader.unknownOpcodeValue.toRadixString(16)} and payload size 0x${_parsedHeader.length}"); + throw new DriverException( + "Unknown frame with opcode 0x${_parsedHeader.unknownOpcodeValue.toRadixString(16)} and payload size 0x${_parsedHeader.length}"); } _parsedHeader = null; _headerSizeInBytes = null; @@ -80,14 +84,9 @@ class FrameParser { handleData(null, sink); } } catch (e, trace) { - // / Emit an exception message - ExceptionMessage message = new ExceptionMessage( - e - , e is DriverException && e.stackTrace != null - ? e.stackTrace - : trace - ); + ExceptionMessage message = new ExceptionMessage(e, + e is DriverException && e.stackTrace != null ? e.stackTrace : trace); message.streamId = _parsedHeader.streamId; _parsedHeader = null; @@ -107,10 +106,9 @@ class FrameParser { sink.addError(error, stackTrace); } - StreamTransformer, Frame> get transformer => new StreamTransformer, Frame>.fromHandlers( - handleData: handleData, - handleDone: handleDone, - handleError: handleError - ); - + StreamTransformer, Frame> get transformer => + new StreamTransformer, Frame>.fromHandlers( + handleData: handleData, + handleDone: handleDone, + handleError: handleError); } diff --git a/lib/src/protocol/frame/frame_reader.dart b/lib/src/protocol/frame/frame_reader.dart index 552b226..31c4e5d 100644 --- a/lib/src/protocol/frame/frame_reader.dart +++ b/lib/src/protocol/frame/frame_reader.dart @@ -1,14 +1,14 @@ part of dart_cassandra_cql.protocol; class FrameReader { + StreamTransformer get transformer => + new StreamTransformer.fromHandlers( + handleData: handleData, + handleDone: handleDone, + handleError: handleError); - StreamTransformer get transformer => new StreamTransformer.fromHandlers( - handleData: handleData, - handleDone: handleDone, - handleError : handleError - ); - - void handleError(Object error, StackTrace stackTrace, EventSink sink) { + void handleError( + Object error, StackTrace stackTrace, EventSink sink) { // If this is a wrapped ExceptionMessage add it to the sink; otherwise add it as an error if (error is ExceptionMessage) { sink.add(error); @@ -23,7 +23,8 @@ class FrameReader { void handleData(Frame frame, EventSink sink) { try { - TypeDecoder decoder = new TypeDecoder.fromBuffer(frame.body, frame.getProtocolVersion()); + TypeDecoder decoder = + new TypeDecoder.fromBuffer(frame.body, frame.getProtocolVersion()); Message message = null; switch (frame.header.opcode) { case Opcode.AUTHENTICATE: @@ -63,5 +64,4 @@ class FrameReader { sink.add(message); } } - -} \ No newline at end of file +} diff --git a/lib/src/protocol/frame/frame_writer.dart b/lib/src/protocol/frame/frame_writer.dart index e8e7780..57a68ae 100644 --- a/lib/src/protocol/frame/frame_writer.dart +++ b/lib/src/protocol/frame/frame_writer.dart @@ -5,22 +5,26 @@ class FrameWriter { TypeEncoder _typeEncoder; FrameHeader _header = new FrameHeader(); - FrameWriter(int streamId, ProtocolVersion protocolVersion, {TypeEncoder withEncoder : null, bool this.preferBiggerTcpPackets : false}) { + FrameWriter(int streamId, ProtocolVersion protocolVersion, + {TypeEncoder withEncoder: null, + bool this.preferBiggerTcpPackets: false}) { _header - ..version = protocolVersion == ProtocolVersion.V2 ? HeaderVersion.REQUEST_V2 : HeaderVersion.REQUEST_V3 + ..version = protocolVersion == ProtocolVersion.V2 + ? HeaderVersion.REQUEST_V2 + : HeaderVersion.REQUEST_V3 ..flags = 0 ..streamId = streamId; - _typeEncoder = withEncoder == null - ? new TypeEncoder(protocolVersion) - : withEncoder; + _typeEncoder = + withEncoder == null ? new TypeEncoder(protocolVersion) : withEncoder; } int getStreamId() { return _header.streamId; } - void writeMessage(RequestMessage message, Sink targetSink, { Compression compression}) { + void writeMessage(RequestMessage message, Sink targetSink, + {Compression compression}) { // Buffer message so we can measure its length message.write(_typeEncoder); @@ -30,16 +34,20 @@ class FrameWriter { if (compression != null && message.opcode != Opcode.STARTUP) { Codec compressionCodec = getCodec(compression.value); if (compressionCodec == null) { - throw new DriverException("A compression codec needs to be registered via registerCodec() for type '${compression}'"); + throw new DriverException( + "A compression codec needs to be registered via registerCodec() for type '${compression}'"); } // Concatenate all writer blocks into a single chunk and then pass it through the compression codec // Catch and wrap any codec exceptions Uint8List compressedData; try { - compressedData = compressionCodec.encode(_typeEncoder.writer.joinChunks()); + compressedData = + compressionCodec.encode(_typeEncoder.writer.joinChunks()); } catch (e, trace) { - throw new DriverException("An error occurred while invoking '${compression}' codec (compression): ${e}", trace); + throw new DriverException( + "An error occurred while invoking '${compression}' codec (compression): ${e}", + trace); } // Replace writer blocks with compressed output and enable the compression flag for the header @@ -51,13 +59,15 @@ class FrameWriter { // Check for max payload size if (_typeEncoder.writer.lengthInBytes > FrameHeader.MAX_LENGTH_IN_BYTES) { _typeEncoder.writer.clear(); - throw new DriverException("Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to write ${_typeEncoder.writer.lengthInBytes} bytes"); + throw new DriverException( + "Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to write ${_typeEncoder.writer.lengthInBytes} bytes"); } // Allocate header buffer - Uint8List buf = new Uint8List(_typeEncoder.protocolVersion == ProtocolVersion.V2 - ? FrameHeader.SIZE_IN_BYTES_V2 - : FrameHeader.SIZE_IN_BYTES_V3); + Uint8List buf = new Uint8List( + _typeEncoder.protocolVersion == ProtocolVersion.V2 + ? FrameHeader.SIZE_IN_BYTES_V2 + : FrameHeader.SIZE_IN_BYTES_V3); ByteData headerBytes = new ByteData.view(buf.buffer); // Encode header @@ -86,7 +96,7 @@ class FrameWriter { //_typeEncoder.dumpToFile("frame-out.dump"); // Pipe everything to the sink - _typeEncoder.writer.pipe(targetSink, preferBiggerTcpPackets : preferBiggerTcpPackets); + _typeEncoder.writer + .pipe(targetSink, preferBiggerTcpPackets: preferBiggerTcpPackets); } } - diff --git a/lib/src/protocol/messages/internal/exception_message.dart b/lib/src/protocol/messages/internal/exception_message.dart index 7a29122..3f2d53c 100644 --- a/lib/src/protocol/messages/internal/exception_message.dart +++ b/lib/src/protocol/messages/internal/exception_message.dart @@ -8,5 +8,5 @@ class ExceptionMessage extends Message { dynamic exception; StackTrace stackTrace; - ExceptionMessage(this.exception, this.stackTrace) : super( Opcode.ERROR ); -} \ No newline at end of file + ExceptionMessage(this.exception, this.stackTrace) : super(Opcode.ERROR); +} diff --git a/lib/src/protocol/messages/message.dart b/lib/src/protocol/messages/message.dart index 3a1e507..12dc445 100644 --- a/lib/src/protocol/messages/message.dart +++ b/lib/src/protocol/messages/message.dart @@ -11,4 +11,4 @@ abstract class RequestMessage { Opcode opcode; void write(TypeEncoder encoder); -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/requests/auth_response_message.dart b/lib/src/protocol/messages/requests/auth_response_message.dart index f08439c..0c37147 100644 --- a/lib/src/protocol/messages/requests/auth_response_message.dart +++ b/lib/src/protocol/messages/requests/auth_response_message.dart @@ -6,7 +6,6 @@ class AuthResponseMessage extends Message implements RequestMessage { AuthResponseMessage() : super(Opcode.AUTH_RESPONSE); void write(TypeEncoder encoder) { - encoder.writeBytes(responsePayload, SizeType.LONG); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/requests/batch_message.dart b/lib/src/protocol/messages/requests/batch_message.dart index 10f1c7d..1656d34 100644 --- a/lib/src/protocol/messages/requests/batch_message.dart +++ b/lib/src/protocol/messages/requests/batch_message.dart @@ -9,7 +9,6 @@ class BatchMessage extends Message implements RequestMessage { BatchMessage() : super(Opcode.BATCH); void write(TypeEncoder encoder) { - // Write batch type and number of queries encoder.writeUint8(type.value); diff --git a/lib/src/protocol/messages/requests/execute_message.dart b/lib/src/protocol/messages/requests/execute_message.dart index 74e5287..22f43b5 100644 --- a/lib/src/protocol/messages/requests/execute_message.dart +++ b/lib/src/protocol/messages/requests/execute_message.dart @@ -15,12 +15,11 @@ class ExecuteMessage extends QueryMessage implements RequestMessage { */ void _writeBindings(TypeEncoder encoder) { - if (bindings is Map) { Map bindingsMap = bindings as Map; encoder.writeUInt16(bindingsMap.length); bindingsMap.forEach((String arg, Object value) { - encoder.writeTypedValue(arg, value, typeSpec : bindingTypes[arg]); + encoder.writeTypedValue(arg, value, typeSpec: bindingTypes[arg]); }); } else { Iterable bindingTypeList = bindingTypes.values; @@ -29,13 +28,13 @@ class ExecuteMessage extends QueryMessage implements RequestMessage { int arg = 0; bindingsList.forEach((Object value) { - encoder.writeTypedValue("$arg", value, typeSpec : bindingTypeList.elementAt(arg++)); + encoder.writeTypedValue("$arg", value, + typeSpec: bindingTypeList.elementAt(arg++)); }); } } void write(TypeEncoder encoder) { - // Write queryId encoder.writeBytes(queryId, SizeType.SHORT); diff --git a/lib/src/protocol/messages/requests/prepare_message.dart b/lib/src/protocol/messages/requests/prepare_message.dart index 6d49980..153d245 100644 --- a/lib/src/protocol/messages/requests/prepare_message.dart +++ b/lib/src/protocol/messages/requests/prepare_message.dart @@ -6,9 +6,7 @@ class PrepareMessage extends Message implements RequestMessage { PrepareMessage() : super(Opcode.PREPARE); void write(TypeEncoder encoder) { - // Send the query as a long string encoder.writeString(query, SizeType.LONG); } - } diff --git a/lib/src/protocol/messages/requests/query_message.dart b/lib/src/protocol/messages/requests/query_message.dart index 67b10e2..63ef06f 100644 --- a/lib/src/protocol/messages/requests/query_message.dart +++ b/lib/src/protocol/messages/requests/query_message.dart @@ -13,13 +13,12 @@ class QueryMessage extends Message implements RequestMessage { void _writeBindings(TypeEncoder encoder) { // Non-prepared query messages automatically expand their arguments inside the query // string so this is a NO-OP. - } void _writeQueryParameters(TypeEncoder encoder) { bool emptyBindings = (bindings == null) || - (bindings is Map && (bindings as Map).isEmpty) || - (bindings is List && (bindings as List).isEmpty); + (bindings is Map && (bindings as Map).isEmpty) || + (bindings is List && (bindings as List).isEmpty); int flags = 0; if (!emptyBindings) { @@ -53,16 +52,13 @@ class QueryMessage extends Message implements RequestMessage { if (serialConsistency != null) { encoder.writeUInt16(serialConsistency.value); } - } void write(TypeEncoder encoder) { - // Write query encoder.writeString(query, SizeType.LONG); // Write query parameters _writeQueryParameters(encoder); } - } diff --git a/lib/src/protocol/messages/requests/register_message.dart b/lib/src/protocol/messages/requests/register_message.dart index 6e22b78..63276c3 100644 --- a/lib/src/protocol/messages/requests/register_message.dart +++ b/lib/src/protocol/messages/requests/register_message.dart @@ -6,7 +6,6 @@ class RegisterMessage extends Message implements RequestMessage { RegisterMessage() : super(Opcode.REGISTER); void write(TypeEncoder encoder) { - encoder.writeStringList(eventTypes, SizeType.SHORT); } } diff --git a/lib/src/protocol/messages/requests/startup_message.dart b/lib/src/protocol/messages/requests/startup_message.dart index e554d78..624b13b 100644 --- a/lib/src/protocol/messages/requests/startup_message.dart +++ b/lib/src/protocol/messages/requests/startup_message.dart @@ -7,11 +7,8 @@ class StartupMessage extends Message implements RequestMessage { StartupMessage() : super(Opcode.STARTUP); void write(TypeEncoder encoder) { - // Write message contents - Map params = { - "CQL_VERSION" : cqlVersion - }; + Map params = {"CQL_VERSION": cqlVersion}; if (compression != null) { params["COMPRESSION"] = compression.value; } diff --git a/lib/src/protocol/messages/responses/auth_challenge_message.dart b/lib/src/protocol/messages/responses/auth_challenge_message.dart index 6502a8c..361186d 100644 --- a/lib/src/protocol/messages/responses/auth_challenge_message.dart +++ b/lib/src/protocol/messages/responses/auth_challenge_message.dart @@ -1,12 +1,10 @@ part of dart_cassandra_cql.protocol; class AuthChallengeMessage extends Message { - Uint8List challengePayload; - AuthChallengeMessage.parse(TypeDecoder decoder) : super(Opcode.AUTH_CHALLENGE){ - + AuthChallengeMessage.parse(TypeDecoder decoder) + : super(Opcode.AUTH_CHALLENGE) { challengePayload = decoder.readBytes(SizeType.LONG); - } } diff --git a/lib/src/protocol/messages/responses/auth_success_message.dart b/lib/src/protocol/messages/responses/auth_success_message.dart index c78dc56..fe6ce43 100644 --- a/lib/src/protocol/messages/responses/auth_success_message.dart +++ b/lib/src/protocol/messages/responses/auth_success_message.dart @@ -1,12 +1,9 @@ part of dart_cassandra_cql.protocol; class AuthSuccessMessage extends Message { - Uint8List token; - AuthSuccessMessage.parse(TypeDecoder decoder) : super(Opcode.AUTH_SUCCESS){ - + AuthSuccessMessage.parse(TypeDecoder decoder) : super(Opcode.AUTH_SUCCESS) { token = decoder.readBytes(SizeType.LONG); - } } diff --git a/lib/src/protocol/messages/responses/authenticate_message.dart b/lib/src/protocol/messages/responses/authenticate_message.dart index 7a5d9a7..21a3570 100644 --- a/lib/src/protocol/messages/responses/authenticate_message.dart +++ b/lib/src/protocol/messages/responses/authenticate_message.dart @@ -1,13 +1,10 @@ part of dart_cassandra_cql.protocol; class AuthenticateMessage extends Message { - String authenticatorClass; - AuthenticateMessage.parse(TypeDecoder decoder) : super(Opcode.AUTHENTICATE){ - + AuthenticateMessage.parse(TypeDecoder decoder) : super(Opcode.AUTHENTICATE) { authenticatorClass = decoder.readString(SizeType.SHORT); - } Uint8List get challengePayload => null; diff --git a/lib/src/protocol/messages/responses/error_message.dart b/lib/src/protocol/messages/responses/error_message.dart index 52e09c2..ece0020 100644 --- a/lib/src/protocol/messages/responses/error_message.dart +++ b/lib/src/protocol/messages/responses/error_message.dart @@ -1,12 +1,11 @@ part of dart_cassandra_cql.protocol; class ErrorMessage extends Message { - ErrorCode code; String message; - ErrorMessage.parse(TypeDecoder decoder) : super(Opcode.ERROR){ + ErrorMessage.parse(TypeDecoder decoder) : super(Opcode.ERROR) { // Parse message common code = ErrorCode.valueOf(decoder.readUInt()); message = decoder.readString(SizeType.SHORT); @@ -17,35 +16,37 @@ class ErrorMessage extends Message { String consistency = Consistency.nameOf(decoder.readConsistency()); int required = decoder.readUInt(); int alive = decoder.readUInt(); - message += "Not enough nodes available to answer the query with ${consistency} consistency. Required ${required} nodes but found ${alive} alive"; + message += + "Not enough nodes available to answer the query with ${consistency} consistency. Required ${required} nodes but found ${alive} alive"; break; case ErrorCode.WRITE_TIMEOUT: String consistency = Consistency.nameOf(decoder.readConsistency()); int received = decoder.readUInt(); int required = decoder.readUInt(); String writeType = decoder.readString(SizeType.SHORT); - message += "Timeout during a write request with ${consistency} consistency. Received ${received}/${required} ACK for a ${writeType} write"; + message += + "Timeout during a write request with ${consistency} consistency. Received ${received}/${required} ACK for a ${writeType} write"; break; case ErrorCode.READ_TIMEOUT: String consistency = Consistency.nameOf(decoder.readConsistency()); int received = decoder.readUInt(); int required = decoder.readUInt(); bool dataPresent = decoder.readByte() != 0; - message += "Timeout during a read request with ${consistency} consistency. Received ${received}/${required} responses. The replica asked for the data ${dataPresent ? "HAS" : "has NOT"} responded"; + message += + "Timeout during a read request with ${consistency} consistency. Received ${received}/${required} responses. The replica asked for the data ${dataPresent ? "HAS" : "has NOT"} responded"; break; case ErrorCode.ALREADY_EXISTS: String keyspace = decoder.readString(SizeType.SHORT); String table = decoder.readString(SizeType.SHORT); message += table.isEmpty - ? "Keyspace ${keyspace} already exists" - : "Table ${table} in keyspace ${keyspace} already exists"; + ? "Keyspace ${keyspace} already exists" + : "Table ${table} in keyspace ${keyspace} already exists"; break; case ErrorCode.UNPREPARED: int id = decoder.readShort(); message += "Unknown prepared query with id ${id}"; break; } - } } diff --git a/lib/src/protocol/messages/responses/event_message.dart b/lib/src/protocol/messages/responses/event_message.dart index 2b4c2da..e33c51e 100644 --- a/lib/src/protocol/messages/responses/event_message.dart +++ b/lib/src/protocol/messages/responses/event_message.dart @@ -15,31 +15,29 @@ class EventMessage extends Message { // V3-only String changedType; - EventMessage.parse(TypeDecoder decoder) : super(Opcode.EVENT){ + EventMessage.parse(TypeDecoder decoder) : super(Opcode.EVENT) { type = EventRegistrationType.valueOf(decoder.readString(SizeType.SHORT)); subType = EventType.valueOf(decoder.readString(SizeType.SHORT)); switch (type) { case EventRegistrationType.TOPOLOGY_CHANGE: case EventRegistrationType.STATUS_CHANGE: - address = decoder.readTypedValue(new TypeSpec(DataType.INET), size : SizeType.BYTE); + address = decoder.readTypedValue(new TypeSpec(DataType.INET), + size: SizeType.BYTE); port = decoder.readInt(); break; case EventRegistrationType.SCHEMA_CHANGE: switch (decoder.protocolVersion) { case ProtocolVersion.V2: - keyspace = decoder.readString(SizeType.SHORT); // According to the spec, this should be an empty string if only the keyspace changed String tableName = decoder.readString(SizeType.SHORT); - changedTable = tableName == null || tableName.isEmpty - ? null - : tableName; + changedTable = + tableName == null || tableName.isEmpty ? null : tableName; break; case ProtocolVersion.V3: - String target = decoder.readString(SizeType.SHORT); keyspace = decoder.readString(SizeType.SHORT); diff --git a/lib/src/protocol/messages/responses/prepared_result_message.dart b/lib/src/protocol/messages/responses/prepared_result_message.dart index 600a8b3..6430361 100644 --- a/lib/src/protocol/messages/responses/prepared_result_message.dart +++ b/lib/src/protocol/messages/responses/prepared_result_message.dart @@ -8,7 +8,7 @@ class PreparedResultMessage extends ResultMessage { String host; int port; - PreparedResultMessage.parse(TypeDecoder decoder){ + PreparedResultMessage.parse(TypeDecoder decoder) { queryId = decoder.readBytes(SizeType.SHORT); metadata = _parseMetadata(decoder); } diff --git a/lib/src/protocol/messages/responses/result_message.dart b/lib/src/protocol/messages/responses/result_message.dart index ae941cf..77f06b7 100644 --- a/lib/src/protocol/messages/responses/result_message.dart +++ b/lib/src/protocol/messages/responses/result_message.dart @@ -3,19 +3,19 @@ part of dart_cassandra_cql.protocol; abstract class ResultMessage extends Message { ResultMessage() : super(Opcode.RESULT); - factory ResultMessage.parse(TypeDecoder decoder){ + factory ResultMessage.parse(TypeDecoder decoder) { // Read message type ResultType type = ResultType.valueOf(decoder.readUInt()); switch (type) { case ResultType.VOID: return new VoidResultMessage(); case ResultType.ROWS: - //decoder.dumpToFile("frame-response-rows.dump"); + //decoder.dumpToFile("frame-response-rows.dump"); return new RowsResultMessage.parse(decoder); case ResultType.SET_KEYSPACE: return new SetKeyspaceResultMessage.parse(decoder); case ResultType.PREPARED: - //decoder.dumpToFile("frame-response-prepared.dump"); + //decoder.dumpToFile("frame-response-prepared.dump"); return new PreparedResultMessage.parse(decoder); case ResultType.SCHEMA_CHANGE: return new SchemaChangeResultMessage.parse(decoder); @@ -26,8 +26,10 @@ abstract class ResultMessage extends Message { ResultMetadata metadata = new ResultMetadata(); int flags = metadata.flags = decoder.readUInt(); - bool globalTableSpec = (flags & RowResultFlag.GLOBAL_TABLE_SPEC.value) == RowResultFlag.GLOBAL_TABLE_SPEC.value; - bool hasMorePages = (flags & RowResultFlag.HAS_MORE_PAGES.value) == RowResultFlag.HAS_MORE_PAGES.value; + bool globalTableSpec = (flags & RowResultFlag.GLOBAL_TABLE_SPEC.value) == + RowResultFlag.GLOBAL_TABLE_SPEC.value; + bool hasMorePages = (flags & RowResultFlag.HAS_MORE_PAGES.value) == + RowResultFlag.HAS_MORE_PAGES.value; //bool noMetadata = (flags & RowResultFlag.NO_METADATA.value) == RowResultFlag.NO_METADATA.value; int colCount = decoder.readUInt(); @@ -44,7 +46,7 @@ abstract class ResultMessage extends Message { // Parse column specs metadata.colSpec = new LinkedHashMap(); - for (int colIndex = colCount; colIndex > 0 ; colIndex--) { + for (int colIndex = colCount; colIndex > 0; colIndex--) { // Skip over col-specific table spec () if (!globalTableSpec) { decoder.skipString(SizeType.SHORT); @@ -52,9 +54,10 @@ abstract class ResultMessage extends Message { } // Parse column name and type - metadata.colSpec[ decoder.readString(SizeType.SHORT) ] = decoder.readTypeOption(); + metadata.colSpec[decoder.readString(SizeType.SHORT)] = + decoder.readTypeOption(); } return metadata; } -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/responses/rows_result_message.dart b/lib/src/protocol/messages/responses/rows_result_message.dart index bb340c1..7c3089d 100644 --- a/lib/src/protocol/messages/responses/rows_result_message.dart +++ b/lib/src/protocol/messages/responses/rows_result_message.dart @@ -4,8 +4,7 @@ class RowsResultMessage extends ResultMessage { ResultMetadata metadata; List> rows; - RowsResultMessage.parse(TypeDecoder decoder){ - + RowsResultMessage.parse(TypeDecoder decoder) { // Parse metadata metadata = _parseMetadata(decoder); @@ -14,9 +13,9 @@ class RowsResultMessage extends ResultMessage { rows = new List>.generate(rowCount, (int rowIndex) { Map row = new LinkedHashMap(); metadata.colSpec.forEach((String colName, TypeSpec typeSpec) { - row[ colName ] = decoder.readTypedValue(typeSpec, size : SizeType.LONG); + row[colName] = decoder.readTypedValue(typeSpec, size: SizeType.LONG); }); return row; }); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/responses/schema_change_result_message.dart b/lib/src/protocol/messages/responses/schema_change_result_message.dart index 463f7dd..ec40440 100644 --- a/lib/src/protocol/messages/responses/schema_change_result_message.dart +++ b/lib/src/protocol/messages/responses/schema_change_result_message.dart @@ -5,9 +5,9 @@ class SchemaChangeResultMessage extends ResultMessage { String keyspace; String table; - SchemaChangeResultMessage.parse(TypeDecoder decoder){ + SchemaChangeResultMessage.parse(TypeDecoder decoder) { change = decoder.readString(SizeType.SHORT); keyspace = decoder.readString(SizeType.SHORT); table = decoder.readString(SizeType.SHORT); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/responses/set_keyspace_result_message.dart b/lib/src/protocol/messages/responses/set_keyspace_result_message.dart index f643506..b93eb15 100644 --- a/lib/src/protocol/messages/responses/set_keyspace_result_message.dart +++ b/lib/src/protocol/messages/responses/set_keyspace_result_message.dart @@ -3,7 +3,7 @@ part of dart_cassandra_cql.protocol; class SetKeyspaceResultMessage extends ResultMessage { String keyspace; - SetKeyspaceResultMessage.parse(TypeDecoder decoder){ + SetKeyspaceResultMessage.parse(TypeDecoder decoder) { keyspace = decoder.readString(SizeType.SHORT); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/messages/responses/void_result_message.dart b/lib/src/protocol/messages/responses/void_result_message.dart index 52dacfc..040a11e 100644 --- a/lib/src/protocol/messages/responses/void_result_message.dart +++ b/lib/src/protocol/messages/responses/void_result_message.dart @@ -1,4 +1,3 @@ part of dart_cassandra_cql.protocol; -class VoidResultMessage extends ResultMessage { -} \ No newline at end of file +class VoidResultMessage extends ResultMessage {} diff --git a/lib/src/query/batch_query.dart b/lib/src/query/batch_query.dart index 38da323..3a3ab2e 100644 --- a/lib/src/query/batch_query.dart +++ b/lib/src/query/batch_query.dart @@ -1,18 +1,16 @@ part of dart_cassandra_cql.query; class BatchQuery extends QueryInterface { - List queryList = new List(); Consistency consistency; Consistency serialConsistency; BatchType type; - BatchQuery({ - Consistency this.consistency : Consistency.QUORUM - , Consistency this.serialConsistency - , BatchType this.type : BatchType.LOGGED - }); + BatchQuery( + {Consistency this.consistency: Consistency.QUORUM, + Consistency this.serialConsistency, + BatchType this.type: BatchType.LOGGED}); /** * Add a new [Query] to the batch @@ -21,5 +19,4 @@ class BatchQuery extends QueryInterface { void add(Query query) { queryList.add(query); } - } diff --git a/lib/src/query/query.dart b/lib/src/query/query.dart index 5f439ed..54b5c79 100644 --- a/lib/src/query/query.dart +++ b/lib/src/query/query.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.query; class Query extends QueryInterface { - bool prepared; String _query; String _positionalQuery; @@ -10,18 +9,29 @@ class Query extends QueryInterface { Consistency consistency; Consistency serialConsistency; static final List _byteToChar = [ - "0", "1", "2", "3", - "4", "5", "6", "7", - "8", "9", "a", "b", - "c", "d", "e", "f" + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "a", + "b", + "c", + "d", + "e", + "f" ]; - Query(String this._query, { - Object bindings : null - , Consistency this.consistency : Consistency.QUORUM - , Consistency this.serialConsistency - , bool this.prepared : false - }) { + Query(String this._query, + {Object bindings: null, + Consistency this.consistency: Consistency.QUORUM, + Consistency this.serialConsistency, + bool this.prepared: false}) { this.bindings = bindings; } @@ -56,7 +66,8 @@ class Query extends QueryInterface { int blockStart = 0; int offset = 0; bool insideLiteral = false; - RegExp placeholderRegex = new RegExp(":[a-zA-Z0-9_]+", caseSensitive: false); + RegExp placeholderRegex = + new RegExp(":[a-zA-Z0-9_]+", caseSensitive: false); for (; offset < _query.length; offset++) { if (_query[offset] == "'") { insideLiteral = !insideLiteral; @@ -73,7 +84,8 @@ class Query extends QueryInterface { // Capture placeholder name Match placeholderMatch = placeholderRegex.matchAsPrefix(_query, offset); if (placeholderMatch == null) { - throw new ArgumentError("Expected named placeholder to begin at offset $offset"); + throw new ArgumentError( + "Expected named placeholder to begin at offset $offset"); } String name = placeholderMatch.group(0).substring(1); @@ -120,9 +132,10 @@ class Query extends QueryInterface { return new List.generate(_namedToPositionalBindings.length, (argIndex) { String name = _namedToPositionalBindings[argIndex]; if (!bindingsMap.containsKey(name)) { - throw new ArgumentError("Missing binding for named placeholder '$name'"); + throw new ArgumentError( + "Missing binding for named placeholder '$name'"); } - return bindingsMap[ name ]; + return bindingsMap[name]; }); } @@ -146,12 +159,11 @@ class Query extends QueryInterface { } if (bindingList.length <= bindingIndex) { - throw new ArgumentError("Missing argument '${bindingIndex}' from bindings list"); + throw new ArgumentError( + "Missing argument '${bindingIndex}' from bindings list"); } - buffer.write( - _typeToString(bindingList[bindingIndex++]) - ); + buffer.write(_typeToString(bindingList[bindingIndex++])); // Begin capturing a new block after the placeholder char blockStart = offset + 1; @@ -169,7 +181,8 @@ class Query extends QueryInterface { int blockStart = 0; int offset = 0; bool insideLiteral = false; - RegExp placeholderRegex = new RegExp(":[a-zA-Z0-9_]+", caseSensitive: false); + RegExp placeholderRegex = + new RegExp(":[a-zA-Z0-9_]+", caseSensitive: false); for (; offset < _query.length; offset++) { if (_query[offset] == "'") { insideLiteral = !insideLiteral; @@ -186,11 +199,13 @@ class Query extends QueryInterface { // Capture placeholder name Match placeholderMatch = placeholderRegex.matchAsPrefix(_query, offset); if (placeholderMatch == null) { - throw new ArgumentError("Expected named placeholder to begin at offset $offset"); + throw new ArgumentError( + "Expected named placeholder to begin at offset $offset"); } String name = placeholderMatch.group(0).substring(1); if (!bindingMap.containsKey(name)) { - throw new ArgumentError("Missing binding for named placeholder '$name'"); + throw new ArgumentError( + "Missing binding for named placeholder '$name'"); } // Stringify binding value @@ -218,7 +233,7 @@ class Query extends QueryInterface { return buffer; } - Object _typeToString(Object value, {quoteStrings : true}) { + Object _typeToString(Object value, {quoteStrings: true}) { if (value == null) { return "null"; } else if (value is String) { @@ -241,7 +256,8 @@ class Query extends QueryInterface { Codec codec = getCodec(value.customTypeClass); if (codec == null) { - throw new ArgumentError("No custom type codec specified for type with class: ${value.customTypeClass}"); + throw new ArgumentError( + "No custom type codec specified for type with class: ${value.customTypeClass}"); } StringBuffer buffer = new StringBuffer(); @@ -251,7 +267,6 @@ class Query extends QueryInterface { ..write(r"'") ..write(buffer.toString().replaceAll(r"'", r"''")) ..write(r"'"); - } else if (value is TypedData) { Uint8List v = new Uint8List.view(value.buffer, 0, value.lengthInBytes); @@ -278,12 +293,11 @@ class Query extends QueryInterface { } else if (value is Map) { Map map = new LinkedHashMap(); value.forEach((Object k, Object v) { - map[ _typeToString(k) ] = _typeToString(v); + map[_typeToString(k)] = _typeToString(v); }); return map; } else { return value.toString(); } } - } diff --git a/lib/src/query/query_interface.dart b/lib/src/query/query_interface.dart index 8acfb2b..8760716 100644 --- a/lib/src/query/query_interface.dart +++ b/lib/src/query/query_interface.dart @@ -1,4 +1,3 @@ part of dart_cassandra_cql.query; -abstract class QueryInterface { -} +abstract class QueryInterface {} diff --git a/lib/src/stream/chunked_input_reader.dart b/lib/src/stream/chunked_input_reader.dart index d7d1bcc..3e0a785 100644 --- a/lib/src/stream/chunked_input_reader.dart +++ b/lib/src/stream/chunked_input_reader.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.stream; class ChunkedInputReader { - final _bufferedChunks = new ListQueue>(); int _usedHeadBytes = 0; @@ -22,9 +21,7 @@ class ChunkedInputReader { */ int get length => _bufferedChunks.fold( - -_usedHeadBytes, - (int count, List el) => count + el.length - ); + -_usedHeadBytes, (int count, List el) => count + el.length); /** * Return the next byte in the buffer without modifying the read pointer. @@ -47,7 +44,6 @@ class ChunkedInputReader { */ int read(List destination, int count, [int offset = 0]) { - int writeOffset = offset; while (count > 0) { // If we ran out of buffers we are done @@ -63,13 +59,15 @@ class ChunkedInputReader { // If the remaining head buffer can fill the destination entirely, copy it and de-queue head if (remainingHeadBytes <= count) { - destination.setRange(writeOffset, writeOffset + remainingHeadBytes, _bufferedChunks.removeFirst(), _usedHeadBytes); + destination.setRange(writeOffset, writeOffset + remainingHeadBytes, + _bufferedChunks.removeFirst(), _usedHeadBytes); _usedHeadBytes = 0; count -= remainingHeadBytes; writeOffset += remainingHeadBytes; } else { // Copy as much as we can skipping any already dequeued bytes - destination.setRange(writeOffset, writeOffset + count, _bufferedChunks.first, _usedHeadBytes); + destination.setRange(writeOffset, writeOffset + count, + _bufferedChunks.first, _usedHeadBytes); _usedHeadBytes += count; writeOffset += count; count = 0; @@ -86,7 +84,6 @@ class ChunkedInputReader { */ int skip(int count) { - int skippedBytesCount = 0; while (count > 0) { // If we ran out of buffers we are done diff --git a/lib/src/stream/chunked_output_writer.dart b/lib/src/stream/chunked_output_writer.dart index 86ac799..42f78fe 100644 --- a/lib/src/stream/chunked_output_writer.dart +++ b/lib/src/stream/chunked_output_writer.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.stream; class ChunkedOutputWriter { - final ListQueue _bufferedChunks = new ListQueue(); /** @@ -32,9 +31,8 @@ class ChunkedOutputWriter { * Get the total available bytes in all chunk buffers (excluding bytes already de-queued from head buffer). */ - int get lengthInBytes => _bufferedChunks.fold( - 0, (int count, el) => count + el.length - ); + int get lengthInBytes => + _bufferedChunks.fold(0, (int count, el) => count + el.length); /** * Get back the [ListQueue] of written chunks @@ -49,11 +47,11 @@ class ChunkedOutputWriter { * and should improve performance at the expense of a slightly higher memory usage */ - void pipe(Sink destination, {bool preferBiggerTcpPackets : false}) { + void pipe(Sink destination, {bool preferBiggerTcpPackets: false}) { if (destination == null) { return; } - if( preferBiggerTcpPackets ){ + if (preferBiggerTcpPackets) { destination.add(joinChunks()); } else { _bufferedChunks.forEach((Uint8List block) => destination.add(block)); diff --git a/lib/src/stream/type_decoder.dart b/lib/src/stream/type_decoder.dart index 574be15..4a7e8fb 100644 --- a/lib/src/stream/type_decoder.dart +++ b/lib/src/stream/type_decoder.dart @@ -6,7 +6,8 @@ class TypeDecoder { Endianness endianess = Endianness.BIG_ENDIAN; ProtocolVersion protocolVersion; - TypeDecoder.fromBuffer(ByteData this._buffer, ProtocolVersion this.protocolVersion); + TypeDecoder.fromBuffer( + ByteData this._buffer, ProtocolVersion this.protocolVersion); int readSignedByte() { return _buffer.getInt8(_offset++); @@ -67,8 +68,8 @@ class TypeDecoder { int readLength(SizeType size) { return size == SizeType.LONG - ? readInt() - : (size == SizeType.SHORT ? readShort() : readByte()); + ? readInt() + : (size == SizeType.SHORT ? readShort() : readByte()); } void skipBytes(int len) { @@ -125,20 +126,18 @@ class TypeDecoder { Map readStringMap(SizeType size) { int len = readLength(size); - Map map = { - }; + Map map = {}; while (len-- > 0) { - map[ readString(size) ] = readString(size); + map[readString(size)] = readString(size); } return map; } Map> readStringMultiMap(SizeType size) { int len = readLength(size); - Map map = { - }; + Map map = {}; while (len-- > 0) { - map[ readString(size) ] = readStringList(size); + map[readString(size)] = readStringList(size); } return map; } @@ -150,7 +149,6 @@ class TypeDecoder { */ FrameHeader readHeader() { - FrameHeader header = new FrameHeader(); // Parse and validate version @@ -166,24 +164,23 @@ class TypeDecoder { default: throw new ArgumentError("Unsupported version value"); } - } - on ArgumentError { - throw new ArgumentError("Unsupported server version value '0x${versionValue.toRadixString(16)}' while parsing frame header"); + } on ArgumentError { + throw new ArgumentError( + "Unsupported server version value '0x${versionValue.toRadixString(16)}' while parsing frame header"); } // Parse flags and stream id header.flags = readByte(); header.streamId = header.version == HeaderVersion.REQUEST_V2 || - header.version == HeaderVersion.RESPONSE_V2 - ? readSignedByte() - : readSignedShort(); + header.version == HeaderVersion.RESPONSE_V2 + ? readSignedByte() + : readSignedShort(); // Parse and validate opcode int opcodeValue = readByte(); try { header.opcode = Opcode.valueOf(opcodeValue); - } - on ArgumentError { + } on ArgumentError { header.unknownOpcodeValue = opcodeValue; } @@ -210,7 +207,8 @@ class TypeDecoder { if (len < 1) { _offset += len; - throw new ArgumentError("Could not parse varint value with length ${len}"); + throw new ArgumentError( + "Could not parse varint value with length ${len}"); } // Read bytes @@ -230,7 +228,8 @@ class TypeDecoder { } // Assemble final decoded number and apply sign - int value = decodeBuffer.fold(0, (int num, int byteValue) => (num << 8) | byteValue); + int value = decodeBuffer.fold( + 0, (int num, int byteValue) => (num << 8) | byteValue); return value.toSigned(8 * bytesToCopy); } @@ -254,7 +253,8 @@ class TypeDecoder { // If we have less than 5 bytes then we cannot parse this if (len < 5) { _offset += len; - throw new ArgumentError("Could not parse decimal value with length ${len}"); + throw new ArgumentError( + "Could not parse decimal value with length ${len}"); } // Read bytes @@ -274,14 +274,13 @@ class TypeDecoder { } // Assemble final decoded number and apply sign - int value = decodeBuffer.fold(0, (int num, int byteValue) => (num << 8) | byteValue); + int value = decodeBuffer.fold( + 0, (int num, int byteValue) => (num << 8) | byteValue); value = value.toSigned(8 * bytesToCopy); // Buf[3] specifies the number of fractional points. If it is 0 then this is just a wide int // Otherwise we need to convert it to a double and move the fractional point to the left - return buf[3] == 0 - ? value - : value.toDouble() * pow(10, -buf[3]); + return buf[3] == 0 ? value : value.toDouble() * pow(10, -buf[3]); } TypeSpec readTypeOption() { @@ -293,18 +292,19 @@ class TypeDecoder { // option parameters which we need to parse switch (type) { case DataType.CUSTOM: - // Custom type java FQ class - spec = new TypeSpec(type) - ..customTypeClass = readString(SizeType.SHORT); + // Custom type java FQ class + spec = new TypeSpec(type)..customTypeClass = readString(SizeType.SHORT); break; case DataType.LIST: case DataType.SET: - // Value is an option representing the list item type - spec = new TypeSpec(type, keySubType : keyType, valueSubType : readTypeOption()); + // Value is an option representing the list item type + spec = new TypeSpec(type, + keySubType: keyType, valueSubType: readTypeOption()); break; case DataType.MAP: - // We have two option values, one for the map key type and one for the value type - spec = new TypeSpec(type, keySubType : readTypeOption(), valueSubType : readTypeOption()); + // We have two option values, one for the map key type and one for the value type + spec = new TypeSpec(type, + keySubType: readTypeOption(), valueSubType: readTypeOption()); break; case DataType.UDT: spec = new TypeSpec(type); @@ -313,7 +313,7 @@ class TypeDecoder { // numFields tuples follow int numFields = readShort(); for (int fieldIndex = 0; fieldIndex < numFields; fieldIndex++) { - spec.udtFields[ readString(SizeType.SHORT) ] = readTypeOption(); + spec.udtFields[readString(SizeType.SHORT)] = readTypeOption(); } break; case DataType.TUPLE: @@ -331,7 +331,7 @@ class TypeDecoder { return spec; } - Object readTypedValue(TypeSpec typeSpec, { SizeType size }) { + Object readTypedValue(TypeSpec typeSpec, {SizeType size}) { // Read typed value length in bytes int lenInBytes = readLength(size); @@ -343,7 +343,6 @@ class TypeDecoder { } switch (typeSpec.valueType) { - case DataType.ASCII: return readAsciiString(size, lenInBytes); case DataType.TEXT: @@ -353,12 +352,12 @@ class TypeDecoder { case DataType.TIMEUUID: return new Uuid.fromBytes(readBytes(size, lenInBytes)); case DataType.CUSTOM: - // If a codec has been specified for this type, use that; otherwise return the - // serialized data as a Uint8 list + // If a codec has been specified for this type, use that; otherwise return the + // serialized data as a Uint8 list Codec typeCodec = getCodec(typeSpec.customTypeClass); return typeCodec != null - ? typeCodec.decode(readBytes(size, lenInBytes)) - : readBytes(size, lenInBytes); + ? typeCodec.decode(readBytes(size, lenInBytes)) + : readBytes(size, lenInBytes); case DataType.BLOB: return readBytes(size, lenInBytes); case DataType.INT: @@ -375,60 +374,56 @@ class TypeDecoder { case DataType.DOUBLE: return readDouble(); case DataType.INET: - // INET can be either 4 (ipv4) or 16 (ipv6) bytes long + // INET can be either 4 (ipv4) or 16 (ipv6) bytes long if (lenInBytes == 4) { Uint8List buf = readBytes(SizeType.BYTE, lenInBytes); return new InternetAddress(buf.join(".")); } else if (lenInBytes == 16) { return new InternetAddress( new List.generate(8, (_) => readShort().toRadixString(16)) - .join(":") - ); + .join(":")); } else { - throw new Exception("Could not decode INET type of length ${lenInBytes}"); + throw new Exception( + "Could not decode INET type of length ${lenInBytes}"); } break; case DataType.LIST: SizeType itemSize = protocolVersion == ProtocolVersion.V2 - ? SizeType.SHORT - : SizeType.LONG; + ? SizeType.SHORT + : SizeType.LONG; - int len = itemSize == SizeType.SHORT - ? readShort() - : readInt(); + int len = itemSize == SizeType.SHORT ? readShort() : readInt(); // The spec defines a list as a short (num of elements) followed by N typeSpec.value records. // Each record is a / length followed by M bytes. - return new List.generate(len, (_) => readTypedValue(typeSpec.valueSubType, size : itemSize)); + return new List.generate( + len, (_) => readTypedValue(typeSpec.valueSubType, size: itemSize)); case DataType.SET: SizeType itemSize = protocolVersion == ProtocolVersion.V2 - ? SizeType.SHORT - : SizeType.LONG; + ? SizeType.SHORT + : SizeType.LONG; - int entry = itemSize == SizeType.SHORT - ? readShort() - : readInt(); + int entry = itemSize == SizeType.SHORT ? readShort() : readInt(); // The spec defines a set as a short (num of elements) followed by N typeSpec.value records // Each record is a / length followed by M bytes. Set set = new Set(); for (; entry > 0; entry--) { - set.add(readTypedValue(typeSpec.valueSubType, size : itemSize)); + set.add(readTypedValue(typeSpec.valueSubType, size: itemSize)); } return set; case DataType.MAP: SizeType itemSize = protocolVersion == ProtocolVersion.V2 - ? SizeType.SHORT - : SizeType.LONG; + ? SizeType.SHORT + : SizeType.LONG; // The spec defines a map as a short (num of elements) followed by N record pairs. Map map = new LinkedHashMap(); - int pair = itemSize == SizeType.SHORT - ? readShort() - : readInt(); + int pair = itemSize == SizeType.SHORT ? readShort() : readInt(); for (; pair > 0; pair--) { - map[ readTypedValue(typeSpec.keySubType, size : itemSize) ] = readTypedValue(typeSpec.valueSubType, size : itemSize); + map[readTypedValue(typeSpec.keySubType, size: itemSize)] = + readTypedValue(typeSpec.valueSubType, size: itemSize); } return map; case DataType.DECIMAL: @@ -437,23 +432,23 @@ class TypeDecoder { return readVarInt(size, lenInBytes); case DataType.UDT: Map udt = new LinkedHashMap(); - typeSpec.udtFields.forEach((String name, TypeSpec udtSpec) => udt[ name ] = readTypedValue(udtSpec, size : size)); + typeSpec.udtFields.forEach((String name, TypeSpec udtSpec) => + udt[name] = readTypedValue(udtSpec, size: size)); return udt; case DataType.TUPLE: - Tuple tuple = new Tuple.fromIterable( - new List.generate(typeSpec.tupleFields.length, (int fieldIndex) => readTypedValue(typeSpec.tupleFields[fieldIndex], size : size)) - ); + Tuple tuple = new Tuple.fromIterable(new List.generate( + typeSpec.tupleFields.length, + (int fieldIndex) => + readTypedValue(typeSpec.tupleFields[fieldIndex], size: size))); return tuple; default: skipBytes(lenInBytes); return null; } - } void dumpToFile(String outputFile) { - new File(outputFile) - ..writeAsBytesSync(_buffer.buffer.asInt8List()); + new File(outputFile)..writeAsBytesSync(_buffer.buffer.asInt8List()); } get offset => _offset; diff --git a/lib/src/stream/type_encoder.dart b/lib/src/stream/type_encoder.dart index 29b995a..5605e68 100644 --- a/lib/src/stream/type_encoder.dart +++ b/lib/src/stream/type_encoder.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.stream; class SizeType extends Enum { - static const SizeType BYTE = const SizeType._(1); static const SizeType SHORT = const SizeType._(2); static const SizeType LONG = const SizeType._(4); @@ -12,7 +11,6 @@ class SizeType extends Enum { int DECIMAL_FRACTION_DIGITS = 6; class TypeEncoder { - // Cassandra spec specifies NULL as the short int value -1 static const int CASSANDRA_NULL = -1; @@ -22,10 +20,9 @@ class TypeEncoder { ProtocolVersion protocolVersion; - TypeEncoder(ProtocolVersion this.protocolVersion, {ChunkedOutputWriter withWriter : null}) { - _writer = withWriter == null - ? new ChunkedOutputWriter() - : withWriter; + TypeEncoder(ProtocolVersion this.protocolVersion, + {ChunkedOutputWriter withWriter: null}) { + _writer = withWriter == null ? new ChunkedOutputWriter() : withWriter; } void writeUint8(int value) { @@ -198,7 +195,9 @@ class TypeEncoder { int scaledValue = (value * pow(10, scale)).round(); // Encode scaled value - for (int bits = scaledValue.bitLength; bits > 0; bits -= 8, scaledValue >>= 8) { + for (int bits = scaledValue.bitLength; + bits > 0; + bits -= 8, scaledValue >>= 8) { bytes.add(scaledValue & 0xFF); } @@ -211,8 +210,10 @@ class TypeEncoder { writeBytes(new Uint8List.fromList(bytes.reversed.toList()), size); } - void writeTypedValue(String name, Object value, {TypeSpec typeSpec : null, DataType forceType : null, SizeType size: SizeType.LONG}) { - + void writeTypedValue(String name, Object value, + {TypeSpec typeSpec: null, + DataType forceType: null, + SizeType size: SizeType.LONG}) { DataType valueType = typeSpec != null ? typeSpec.valueType : forceType; //_logger.fine("[TypeEncoder::writeTypedValue] Attempting to write ${DataType.nameOf(valueType)} @ 0x${(encoder.writer.lengthInBytes + (encoder.protocolVersion == ProtocolVersion.V2 ? Header.SIZE_IN_BYTES_V2 : Header.SIZE_IN_BYTES_V3)).toRadixString(16)}"); @@ -232,13 +233,14 @@ class TypeEncoder { case DataType.UUID: case DataType.TIMEUUID: if (value is! Uuid) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uuid"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uuid"); } _writeUUID(value, size); break; case DataType.CUSTOM: - // If this is a Uint8List write is to the byte stream. - // Otherwise, check if this is a CustomType instance with a registered codec + // If this is a Uint8List write is to the byte stream. + // Otherwise, check if this is a CustomType instance with a registered codec if (value is Uint8List) { writeBytes(value, size); } else if (value is CustomType) { @@ -246,15 +248,18 @@ class TypeEncoder { if (codec != null) { writeBytes(codec.encode(value), size); } else { - throw new ArgumentError("No custom type handler codec registered for custom type: ${value.customTypeClass}"); + throw new ArgumentError( + "No custom type handler codec registered for custom type: ${value.customTypeClass}"); } } else { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uint8List OR an instance of CustomType with a registered type handler"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uint8List OR an instance of CustomType with a registered type handler"); } break; case DataType.BLOB: if (value is! Uint8List) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uint8List"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Uint8List"); } writeBytes(value as Uint8List, size); break; @@ -269,7 +274,8 @@ class TypeEncoder { break; case DataType.TIMESTAMP: if (value is! DateTime) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of DateTime"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of DateTime"); } writeLength(8, size); writeUInt64((value as DateTime).millisecondsSinceEpoch); @@ -288,24 +294,27 @@ class TypeEncoder { break; case DataType.INET: if (value is! InternetAddress) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of InternetAddress"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of InternetAddress"); } writeBytes((value as InternetAddress).rawAddress, size); break; case DataType.LIST: case DataType.SET: if (value is! Iterable) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Iterable"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Iterable"); } Iterable v = value as Iterable; // Encode list length and items into a separate buffer, then write the buffer length and buffer data SizeType itemSize = protocolVersion == ProtocolVersion.V2 - ? SizeType.SHORT - : SizeType.LONG; + ? SizeType.SHORT + : SizeType.LONG; TypeEncoder scopedEncoder = new TypeEncoder(protocolVersion); scopedEncoder.writeLength(v.length, itemSize); - v.forEach((Object elem) => scopedEncoder.writeTypedValue(name, elem, typeSpec : typeSpec.valueSubType, size: itemSize)); + v.forEach((Object elem) => scopedEncoder.writeTypedValue(name, elem, + typeSpec: typeSpec.valueSubType, size: itemSize)); // Write buffer size in bytes and the actual buffer data writeLength(scopedEncoder.writer.lengthInBytes, size); @@ -313,20 +322,23 @@ class TypeEncoder { break; case DataType.MAP: if (value is! Map) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Map"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Map"); } Map v = value as Map; // Encode list items into a separate buffer, then write the buffer length and buffer data SizeType itemSize = protocolVersion == ProtocolVersion.V2 - ? SizeType.SHORT - : SizeType.LONG; + ? SizeType.SHORT + : SizeType.LONG; TypeEncoder scopedEncoder = new TypeEncoder(protocolVersion); scopedEncoder.writeLength(v.length, itemSize); v.forEach((Object key, Object val) { scopedEncoder - ..writeTypedValue(name, key, typeSpec : typeSpec.keySubType, size: itemSize) - ..writeTypedValue(name, val, typeSpec : typeSpec.valueSubType, size: itemSize); + ..writeTypedValue(name, key, + typeSpec: typeSpec.keySubType, size: itemSize) + ..writeTypedValue(name, val, + typeSpec: typeSpec.valueSubType, size: itemSize); }); // Write buffer size in bytes and the actual buffer data @@ -342,7 +354,8 @@ class TypeEncoder { break; case DataType.UDT: if (value is! Map) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Map"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to implement Map"); } Map v = value as Map; @@ -350,7 +363,8 @@ class TypeEncoder { SizeType itemSize = SizeType.LONG; TypeEncoder scopedEncoder = new TypeEncoder(protocolVersion); typeSpec.udtFields.forEach((String name, TypeSpec udtType) { - scopedEncoder.writeTypedValue(name, v[name], typeSpec: udtType, size: itemSize); + scopedEncoder.writeTypedValue(name, v[name], + typeSpec: udtType, size: itemSize); }); // Write buffer size in bytes and the actual buffer data @@ -360,7 +374,8 @@ class TypeEncoder { break; case DataType.TUPLE: if (value is! Tuple) { - throw new ArgumentError("Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Tuple"); + throw new ArgumentError( + "Expected value for field '${name}' of type ${DataType.nameOf(valueType)} to be an instance of Tuple"); } Iterable v = (value as Tuple); @@ -369,9 +384,8 @@ class TypeEncoder { SizeType itemSize = SizeType.LONG; TypeEncoder scopedEncoder = new TypeEncoder(protocolVersion); for (int index = 0; index < v.length; index++) { - scopedEncoder.writeTypedValue(name, - v.elementAt(index), - typeSpec : typeSpec.tupleFields.elementAt(index), size: itemSize); + scopedEncoder.writeTypedValue(name, v.elementAt(index), + typeSpec: typeSpec.tupleFields.elementAt(index), size: itemSize); } // Write buffer size in bytes and the actual buffer data @@ -379,7 +393,8 @@ class TypeEncoder { writer.addAll(scopedEncoder.writer.chunks); break; default: - throw new ArgumentError("Unsupported type ${DataType.nameOf(valueType)} for arg '${name}' with value ${value}"); + throw new ArgumentError( + "Unsupported type ${DataType.nameOf(valueType)} for arg '${name}' with value ${value}"); } } diff --git a/lib/src/types.dart b/lib/src/types.dart index 2223bd0..fd43fc1 100644 --- a/lib/src/types.dart +++ b/lib/src/types.dart @@ -37,4 +37,4 @@ part "types/frame.dart"; part "types/frame_header.dart"; // Codec registry -part "types/codec_registry.dart"; \ No newline at end of file +part "types/codec_registry.dart"; diff --git a/lib/src/types/codec_registry.dart b/lib/src/types/codec_registry.dart index b33b68f..826a0f3 100644 --- a/lib/src/types/codec_registry.dart +++ b/lib/src/types/codec_registry.dart @@ -1,8 +1,7 @@ part of dart_cassandra_cql.types; // Cassandra custom type codec registry -Map> _customTypeCodecs = { -}; +Map> _customTypeCodecs = {}; /** * Register a [Codec getCodec(String typeClassName) => _customTypeCodecs[ typeClassName ]; \ No newline at end of file +Codec getCodec(String typeClassName) => + _customTypeCodecs[typeClassName]; diff --git a/lib/src/types/custom_type.dart b/lib/src/types/custom_type.dart index ad964cc..9d92bf5 100644 --- a/lib/src/types/custom_type.dart +++ b/lib/src/types/custom_type.dart @@ -1,7 +1,5 @@ part of dart_cassandra_cql.types; abstract class CustomType { - String get customTypeClass; - -} \ No newline at end of file +} diff --git a/lib/src/types/enums/batch_type.dart b/lib/src/types/enums/batch_type.dart index c282e36..68f3d8d 100644 --- a/lib/src/types/enums/batch_type.dart +++ b/lib/src/types/enums/batch_type.dart @@ -8,5 +8,4 @@ class BatchType extends Enum { const BatchType._(int value) : super(value); String toString() => "0x${value.toRadixString(16)}"; - } diff --git a/lib/src/types/enums/consistency.dart b/lib/src/types/enums/consistency.dart index da3209e..4f5c55d 100644 --- a/lib/src/types/enums/consistency.dart +++ b/lib/src/types/enums/consistency.dart @@ -18,37 +18,62 @@ class Consistency extends Enum { String toString() => "0x${value.toRadixString(16)}"; static Consistency valueOf(int value) { - Consistency fromValue = value == ANY._value ? ANY : - value == ONE._value ? ONE : - value == TWO._value ? TWO : - value == THREE._value ? THREE : - value == QUORUM._value ? QUORUM : - value == ALL._value ? ALL : - value == LOCAL_QUORUM._value ? LOCAL_QUORUM : - value == EACH_QUORUM._value ? EACH_QUORUM : - value == SERIAL._value ? SERIAL : - value == LOCAL_SERIAL._value ? LOCAL_SERIAL : - value == LOCAL_ONE._value ? LOCAL_ONE : null; + Consistency fromValue = value == ANY._value + ? ANY + : value == ONE._value + ? ONE + : value == TWO._value + ? TWO + : value == THREE._value + ? THREE + : value == QUORUM._value + ? QUORUM + : value == ALL._value + ? ALL + : value == LOCAL_QUORUM._value + ? LOCAL_QUORUM + : value == EACH_QUORUM._value + ? EACH_QUORUM + : value == SERIAL._value + ? SERIAL + : value == LOCAL_SERIAL._value + ? LOCAL_SERIAL + : value == LOCAL_ONE._value + ? LOCAL_ONE + : null; if (fromValue == null) { - throw new ArgumentError("Invalid consistency value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid consistency value 0x${value.toRadixString(16)}"); } return fromValue; } static String nameOf(Consistency value) { - String name = value == ANY ? "ANY" : - value == ONE ? "ONE" : - value == TWO ? "TWO" : - value == THREE ? "THREE" : - value == QUORUM ? "QUORUM" : - value == ALL ? "ALL" : - value == LOCAL_QUORUM ? "LOCAL_QUORUM" : - value == EACH_QUORUM ? "EACH_QUORUM" : - value == SERIAL ? "SERIAL" : - value == LOCAL_SERIAL ? "LOCAL_SERIAL" : - value == LOCAL_ONE ? "LOCAL_ONE" : null; + String name = value == ANY + ? "ANY" + : value == ONE + ? "ONE" + : value == TWO + ? "TWO" + : value == THREE + ? "THREE" + : value == QUORUM + ? "QUORUM" + : value == ALL + ? "ALL" + : value == LOCAL_QUORUM + ? "LOCAL_QUORUM" + : value == EACH_QUORUM + ? "EACH_QUORUM" + : value == SERIAL + ? "SERIAL" + : value == LOCAL_SERIAL + ? "LOCAL_SERIAL" + : value == LOCAL_ONE + ? "LOCAL_ONE" + : null; return name; } -} \ No newline at end of file +} diff --git a/lib/src/types/enums/data_type.dart b/lib/src/types/enums/data_type.dart index 87cc703..491e6bb 100644 --- a/lib/src/types/enums/data_type.dart +++ b/lib/src/types/enums/data_type.dart @@ -1,7 +1,9 @@ part of dart_cassandra_cql.types; class DataType extends Enum { - static final RegExp _UUID_REGEX = new RegExp(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", caseSensitive : false); + static final RegExp _UUID_REGEX = new RegExp( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + caseSensitive: false); static const DataType CUSTOM = const DataType._(0x0000); static const DataType ASCII = const DataType._(0x0001); @@ -35,58 +37,102 @@ class DataType extends Enum { get isCollection => this == LIST || this == SET || this == MAP; static DataType valueOf(int value) { - DataType fromValue = value == CUSTOM._value ? CUSTOM : - value == ASCII._value ? ASCII : - value == BIGINT._value ? BIGINT : - value == BLOB._value ? BLOB : - value == BOOLEAN._value ? BOOLEAN : - value == COUNTER._value ? COUNTER : - value == DECIMAL._value ? DECIMAL : - value == DOUBLE._value ? DOUBLE : - value == FLOAT._value ? FLOAT : - value == INT._value ? INT : - value == TEXT._value ? TEXT : - value == TIMESTAMP._value ? TIMESTAMP : - value == UUID._value ? UUID : - value == VARCHAR._value ? VARCHAR : - value == VARINT._value ? VARINT : - value == TIMEUUID._value ? TIMEUUID : - value == INET._value ? INET : - value == LIST._value ? LIST : - value == MAP._value ? MAP : - value == SET._value ? SET : - value == UDT._value ? UDT : - value == TUPLE._value ? TUPLE : null; + DataType fromValue = value == CUSTOM._value + ? CUSTOM + : value == ASCII._value + ? ASCII + : value == BIGINT._value + ? BIGINT + : value == BLOB._value + ? BLOB + : value == BOOLEAN._value + ? BOOLEAN + : value == COUNTER._value + ? COUNTER + : value == DECIMAL._value + ? DECIMAL + : value == DOUBLE._value + ? DOUBLE + : value == FLOAT._value + ? FLOAT + : value == INT._value + ? INT + : value == TEXT._value + ? TEXT + : value == TIMESTAMP._value + ? TIMESTAMP + : value == UUID._value + ? UUID + : value == VARCHAR._value + ? VARCHAR + : value == + VARINT + ._value + ? VARINT + : value == + TIMEUUID + ._value + ? TIMEUUID + : value == + INET._value + ? INET + : value == + LIST._value + ? LIST + : value == MAP._value + ? MAP + : value == SET._value ? SET : value == UDT._value ? UDT : value == TUPLE._value ? TUPLE : null; if (fromValue == null) { - throw new ArgumentError("Invalid datatype value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid datatype value 0x${value.toRadixString(16)}"); } return fromValue; } static String nameOf(DataType value) { - String name = value == CUSTOM ? "CUSTOM" : - value == ASCII ? "ASCII" : - value == BIGINT ? "BIGINT" : - value == BLOB ? "BLOB" : - value == BOOLEAN ? "BOOLEAN" : - value == COUNTER ? "COUNTER" : - value == DECIMAL ? "DECIMAL" : - value == DOUBLE ? "DOUBLE" : - value == FLOAT ? "FLOAT" : - value == INT ? "INT" : - value == TEXT ? "TEXT" : - value == TIMESTAMP ? "TIMESTAMP" : - value == UUID ? "UUID" : - value == VARCHAR ? "VARCHAR" : - value == VARINT ? "VARINT" : - value == TIMEUUID ? "TIMEUUID" : - value == INET ? "INET" : - value == LIST ? "LIST" : - value == MAP ? "MAP" : - value == SET ? "SET" : - value == UDT ? "UDT" : - value == TUPLE ? "TUPLE" : null; + String name = value == CUSTOM + ? "CUSTOM" + : value == ASCII + ? "ASCII" + : value == BIGINT + ? "BIGINT" + : value == BLOB + ? "BLOB" + : value == BOOLEAN + ? "BOOLEAN" + : value == COUNTER + ? "COUNTER" + : value == DECIMAL + ? "DECIMAL" + : value == DOUBLE + ? "DOUBLE" + : value == FLOAT + ? "FLOAT" + : value == INT + ? "INT" + : value == TEXT + ? "TEXT" + : value == TIMESTAMP + ? "TIMESTAMP" + : value == UUID + ? "UUID" + : value == VARCHAR + ? "VARCHAR" + : value == VARINT + ? "VARINT" + : value == + TIMEUUID + ? "TIMEUUID" + : value == + INET + ? "INET" + : value == + LIST + ? "LIST" + : value == MAP + ? "MAP" + : value == SET ? "SET" : value == UDT ? "UDT" : value == TUPLE ? "TUPLE" : null; return name; } @@ -100,11 +146,11 @@ class DataType extends Enum { return BOOLEAN; } else if (value is int) { int v = value; - return v.bitLength <= 32 ? INT : - v.bitLength <= 64 ? BIGINT : VARINT; + return v.bitLength <= 32 ? INT : v.bitLength <= 64 ? BIGINT : VARINT; } else if (value is num) { return DOUBLE; - } else if (value is Uuid || (value is String && _UUID_REGEX.hasMatch(value))) { + } else if (value is Uuid || + (value is String && _UUID_REGEX.hasMatch(value))) { return UUID; } else if (value is String) { return VARCHAR; @@ -126,5 +172,4 @@ class DataType extends Enum { return null; } - } diff --git a/lib/src/types/enums/enum.dart b/lib/src/types/enums/enum.dart index 566efa0..0c07a19 100644 --- a/lib/src/types/enums/enum.dart +++ b/lib/src/types/enums/enum.dart @@ -4,11 +4,9 @@ part of dart_cassandra_cql.types; * An abstract class for modeling enums */ abstract class Enum { - final T _value; const Enum(this._value); T get value => _value; - -} \ No newline at end of file +} diff --git a/lib/src/types/enums/error_code.dart b/lib/src/types/enums/error_code.dart index a22112a..8d3a2df 100644 --- a/lib/src/types/enums/error_code.dart +++ b/lib/src/types/enums/error_code.dart @@ -22,25 +22,47 @@ class ErrorCode extends Enum { String toString() => "0x${value.toRadixString(16)}"; static ErrorCode valueOf(int value) { - ErrorCode fromValue = value == SERVER_ERROR._value ? SERVER_ERROR : - value == PROTOCOL_ERROR._value ? PROTOCOL_ERROR : - value == BAD_CREDENTIALS._value ? BAD_CREDENTIALS : - value == UNAVAILABLE._value ? UNAVAILABLE : - value == OVERLOADED._value ? OVERLOADED : - value == IS_BOOTSTRAPPING._value ? IS_BOOTSTRAPPING : - value == TRUNCATE_ERROR._value ? TRUNCATE_ERROR : - value == WRITE_TIMEOUT._value ? WRITE_TIMEOUT : - value == READ_TIMEOUT._value ? READ_TIMEOUT : - value == SYNTAX_ERROR._value ? SYNTAX_ERROR : - value == UNAUTHORIZED._value ? UNAUTHORIZED : - value == INVALID._value ? INVALID : - value == CONFIG_ERROR._value ? CONFIG_ERROR : - value == ALREADY_EXISTS._value ? ALREADY_EXISTS : - value == UNPREPARED._value ? UNPREPARED : null; + ErrorCode fromValue = value == SERVER_ERROR._value + ? SERVER_ERROR + : value == PROTOCOL_ERROR._value + ? PROTOCOL_ERROR + : value == BAD_CREDENTIALS._value + ? BAD_CREDENTIALS + : value == UNAVAILABLE._value + ? UNAVAILABLE + : value == OVERLOADED._value + ? OVERLOADED + : value == IS_BOOTSTRAPPING._value + ? IS_BOOTSTRAPPING + : value == TRUNCATE_ERROR._value + ? TRUNCATE_ERROR + : value == WRITE_TIMEOUT._value + ? WRITE_TIMEOUT + : value == READ_TIMEOUT._value + ? READ_TIMEOUT + : value == SYNTAX_ERROR._value + ? SYNTAX_ERROR + : value == UNAUTHORIZED._value + ? UNAUTHORIZED + : value == INVALID._value + ? INVALID + : value == + CONFIG_ERROR._value + ? CONFIG_ERROR + : value == + ALREADY_EXISTS + ._value + ? ALREADY_EXISTS + : value == + UNPREPARED + ._value + ? UNPREPARED + : null; if (fromValue == null) { - throw new ArgumentError("Invalid error code value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid error code value 0x${value.toRadixString(16)}"); } return fromValue; } -} \ No newline at end of file +} diff --git a/lib/src/types/enums/event_registration_type.dart b/lib/src/types/enums/event_registration_type.dart index 7a569c8..0b1aebe 100644 --- a/lib/src/types/enums/event_registration_type.dart +++ b/lib/src/types/enums/event_registration_type.dart @@ -1,18 +1,23 @@ part of dart_cassandra_cql.types; class EventRegistrationType extends Enum { - static const EventRegistrationType TOPOLOGY_CHANGE = const EventRegistrationType._("TOPOLOGY_CHANGE"); - static const EventRegistrationType STATUS_CHANGE = const EventRegistrationType._("STATUS_CHANGE"); - static const EventRegistrationType SCHEMA_CHANGE = const EventRegistrationType._("SCHEMA_CHANGE"); + static const EventRegistrationType TOPOLOGY_CHANGE = + const EventRegistrationType._("TOPOLOGY_CHANGE"); + static const EventRegistrationType STATUS_CHANGE = + const EventRegistrationType._("STATUS_CHANGE"); + static const EventRegistrationType SCHEMA_CHANGE = + const EventRegistrationType._("SCHEMA_CHANGE"); const EventRegistrationType._(String value) : super(value); String toString() => value; static EventRegistrationType valueOf(String value) { - EventRegistrationType fromValue = value == TOPOLOGY_CHANGE._value ? TOPOLOGY_CHANGE : - value == STATUS_CHANGE._value ? STATUS_CHANGE : - value == SCHEMA_CHANGE._value ? SCHEMA_CHANGE : null; + EventRegistrationType fromValue = value == TOPOLOGY_CHANGE._value + ? TOPOLOGY_CHANGE + : value == STATUS_CHANGE._value + ? STATUS_CHANGE + : value == SCHEMA_CHANGE._value ? SCHEMA_CHANGE : null; if (fromValue == null) { throw new ArgumentError("Invalid event registration value ${value}"); @@ -21,9 +26,11 @@ class EventRegistrationType extends Enum { } static String nameOf(EventRegistrationType value) { - String nameValue = value == TOPOLOGY_CHANGE ? "TOPOLOGY_CHANGE" : - value == STATUS_CHANGE ? "STATUS_CHANGE" : - value == SCHEMA_CHANGE ? "SCHEMA_CHANGE" : null; + String nameValue = value == TOPOLOGY_CHANGE + ? "TOPOLOGY_CHANGE" + : value == STATUS_CHANGE + ? "STATUS_CHANGE" + : value == SCHEMA_CHANGE ? "SCHEMA_CHANGE" : null; return nameValue; } diff --git a/lib/src/types/enums/event_type.dart b/lib/src/types/enums/event_type.dart index 5197d45..44a2029 100644 --- a/lib/src/types/enums/event_type.dart +++ b/lib/src/types/enums/event_type.dart @@ -14,13 +14,21 @@ class EventType extends Enum { String toString() => value; static EventType valueOf(String value) { - EventType fromValue = value == NODE_ADDED.value ? NODE_ADDED : - value == NODE_REMOVED.value ? NODE_REMOVED : - value == NODE_UP.value ? NODE_UP : - value == NODE_DOWN.value ? NODE_DOWN : - value == SCHEMA_CREATED.value ? SCHEMA_CREATED : - value == SCHEMA_UPDATED.value ? SCHEMA_UPDATED : - value == SCHEMA_DROPPED.value ? SCHEMA_DROPPED : null; + EventType fromValue = value == NODE_ADDED.value + ? NODE_ADDED + : value == NODE_REMOVED.value + ? NODE_REMOVED + : value == NODE_UP.value + ? NODE_UP + : value == NODE_DOWN.value + ? NODE_DOWN + : value == SCHEMA_CREATED.value + ? SCHEMA_CREATED + : value == SCHEMA_UPDATED.value + ? SCHEMA_UPDATED + : value == SCHEMA_DROPPED.value + ? SCHEMA_DROPPED + : null; if (fromValue == null) { throw new ArgumentError("Invalid event value ${value}"); @@ -29,15 +37,20 @@ class EventType extends Enum { } static String nameOf(EventType value) { - String nameValue = value == NODE_ADDED ? "NODE_ADDED" : - value == NODE_REMOVED ? "NODE_REMOVED" : - value == NODE_UP ? "NODE_UP" : - value == NODE_DOWN ? "NODE_DOWN" : - value == SCHEMA_CREATED ? "SCHEMA_CREATED" : - value == SCHEMA_UPDATED ? "SCHEMA_UPDATED" : - value == SCHEMA_DROPPED ? "SCHEMA_DROPPED" : null; + String nameValue = value == NODE_ADDED + ? "NODE_ADDED" + : value == NODE_REMOVED + ? "NODE_REMOVED" + : value == NODE_UP + ? "NODE_UP" + : value == NODE_DOWN + ? "NODE_DOWN" + : value == SCHEMA_CREATED + ? "SCHEMA_CREATED" + : value == SCHEMA_UPDATED + ? "SCHEMA_UPDATED" + : value == SCHEMA_DROPPED ? "SCHEMA_DROPPED" : null; return nameValue; } - } diff --git a/lib/src/types/enums/header_version.dart b/lib/src/types/enums/header_version.dart index 7ab52b2..589ae0b 100644 --- a/lib/src/types/enums/header_version.dart +++ b/lib/src/types/enums/header_version.dart @@ -11,13 +11,17 @@ class HeaderVersion extends Enum { String toString() => "0x${value.toRadixString(16)}"; static HeaderVersion valueOf(int value) { - HeaderVersion fromValue = value == REQUEST_V2._value ? REQUEST_V2 : - value == RESPONSE_V2._value ? RESPONSE_V2 : - value == REQUEST_V3._value ? REQUEST_V3 : - value == RESPONSE_V3._value ? RESPONSE_V3 : null; + HeaderVersion fromValue = value == REQUEST_V2._value + ? REQUEST_V2 + : value == RESPONSE_V2._value + ? RESPONSE_V2 + : value == REQUEST_V3._value + ? REQUEST_V3 + : value == RESPONSE_V3._value ? RESPONSE_V3 : null; if (fromValue == null) { - throw new ArgumentError("Invalid version value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid version value 0x${value.toRadixString(16)}"); } return fromValue; } diff --git a/lib/src/types/enums/opcode.dart b/lib/src/types/enums/opcode.dart index f47bba7..8e50f65 100644 --- a/lib/src/types/enums/opcode.dart +++ b/lib/src/types/enums/opcode.dart @@ -23,47 +23,91 @@ class Opcode extends Enum { String toString() => "0x${value.toRadixString(16)}"; static Opcode valueOf(int value) { - Opcode fromValue = value == ERROR._value ? ERROR : - value == STARTUP._value ? STARTUP : - value == READY._value ? READY : - value == AUTHENTICATE._value ? AUTHENTICATE : - value == OPTIONS._value ? OPTIONS : - value == SUPPORTED._value ? SUPPORTED : - value == QUERY._value ? QUERY : - value == RESULT._value ? RESULT : - value == PREPARE._value ? PREPARE : - value == EXECUTE._value ? EXECUTE : - value == REGISTER._value ? REGISTER : - value == EVENT._value ? EVENT : - value == BATCH._value ? BATCH : - value == AUTH_CHALLENGE._value ? AUTH_CHALLENGE : - value == AUTH_RESPONSE._value ? AUTH_RESPONSE : - value == AUTH_SUCCESS._value ? AUTH_SUCCESS : null; + Opcode fromValue = value == ERROR._value + ? ERROR + : value == STARTUP._value + ? STARTUP + : value == READY._value + ? READY + : value == AUTHENTICATE._value + ? AUTHENTICATE + : value == OPTIONS._value + ? OPTIONS + : value == SUPPORTED._value + ? SUPPORTED + : value == QUERY._value + ? QUERY + : value == RESULT._value + ? RESULT + : value == PREPARE._value + ? PREPARE + : value == EXECUTE._value + ? EXECUTE + : value == REGISTER._value + ? REGISTER + : value == EVENT._value + ? EVENT + : value == BATCH._value + ? BATCH + : value == + AUTH_CHALLENGE + ._value + ? AUTH_CHALLENGE + : value == + AUTH_RESPONSE + ._value + ? AUTH_RESPONSE + : value == + AUTH_SUCCESS + ._value + ? AUTH_SUCCESS + : null; if (fromValue == null) { - throw new ArgumentError("Invalid opcode value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid opcode value 0x${value.toRadixString(16)}"); } return fromValue; } static String nameOf(Opcode value) { - String nameValue = value == ERROR ? "ERROR" : - value == STARTUP ? "STARTUP" : - value == READY ? "READY" : - value == AUTHENTICATE ? "AUTHENTICATE" : - value == OPTIONS ? "OPTIONS" : - value == SUPPORTED ? "SUPPORTED" : - value == QUERY ? "QUERY" : - value == RESULT ? "RESULT" : - value == PREPARE ? "PREPARE" : - value == EXECUTE ? "EXECUTE" : - value == REGISTER ? "REGISTER" : - value == EVENT ? "EVENT" : - value == BATCH ? "BATCH" : - value == AUTH_CHALLENGE ? "AUTH_CHALLENGE" : - value == AUTH_RESPONSE ? "AUTH_RESPONSE" : - value == AUTH_SUCCESS ? "AUTH_SUCCESS" : null; + String nameValue = value == ERROR + ? "ERROR" + : value == STARTUP + ? "STARTUP" + : value == READY + ? "READY" + : value == AUTHENTICATE + ? "AUTHENTICATE" + : value == OPTIONS + ? "OPTIONS" + : value == SUPPORTED + ? "SUPPORTED" + : value == QUERY + ? "QUERY" + : value == RESULT + ? "RESULT" + : value == PREPARE + ? "PREPARE" + : value == EXECUTE + ? "EXECUTE" + : value == REGISTER + ? "REGISTER" + : value == EVENT + ? "EVENT" + : value == BATCH + ? "BATCH" + : value == + AUTH_CHALLENGE + ? "AUTH_CHALLENGE" + : value == + AUTH_RESPONSE + ? "AUTH_RESPONSE" + : value == + AUTH_SUCCESS + ? "AUTH_SUCCESS" + : null; return nameValue; } -} \ No newline at end of file +} diff --git a/lib/src/types/enums/result_type.dart b/lib/src/types/enums/result_type.dart index c9b4470..6ec377d 100644 --- a/lib/src/types/enums/result_type.dart +++ b/lib/src/types/enums/result_type.dart @@ -12,16 +12,20 @@ class ResultType extends Enum { String toString() => "0x${value.toRadixString(16)}"; static ResultType valueOf(int value) { - ResultType fromValue = value == VOID._value ? VOID : - value == ROWS._value ? ROWS : - value == SET_KEYSPACE._value ? SET_KEYSPACE : - value == PREPARED._value ? PREPARED : - value == SCHEMA_CHANGE._value ? SCHEMA_CHANGE : null; + ResultType fromValue = value == VOID._value + ? VOID + : value == ROWS._value + ? ROWS + : value == SET_KEYSPACE._value + ? SET_KEYSPACE + : value == PREPARED._value + ? PREPARED + : value == SCHEMA_CHANGE._value ? SCHEMA_CHANGE : null; if (fromValue == null) { - throw new ArgumentError("Invalid result type value 0x${value.toRadixString(16)}"); + throw new ArgumentError( + "Invalid result type value 0x${value.toRadixString(16)}"); } return fromValue; } - } diff --git a/lib/src/types/frame.dart b/lib/src/types/frame.dart index 922d517..dccf6b3 100644 --- a/lib/src/types/frame.dart +++ b/lib/src/types/frame.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.types; class Frame { - final FrameHeader header; final ByteData body; @@ -12,14 +11,14 @@ class Frame { return null; } - if (header.version == HeaderVersion.REQUEST_V2 || header.version == HeaderVersion.RESPONSE_V2) { + if (header.version == HeaderVersion.REQUEST_V2 || + header.version == HeaderVersion.RESPONSE_V2) { return ProtocolVersion.V2; - } else if (header.version == HeaderVersion.REQUEST_V3 || header.version == HeaderVersion.RESPONSE_V3) { + } else if (header.version == HeaderVersion.REQUEST_V3 || + header.version == HeaderVersion.RESPONSE_V3) { return ProtocolVersion.V3; } return null; } - } - diff --git a/lib/src/types/frame_header.dart b/lib/src/types/frame_header.dart index 7ab2aaf..261a8c8 100644 --- a/lib/src/types/frame_header.dart +++ b/lib/src/types/frame_header.dart @@ -1,7 +1,6 @@ part of dart_cassandra_cql.types; class FrameHeader { - static const int SIZE_IN_BYTES_V2 = 8; static const int SIZE_IN_BYTES_V3 = 9; static const int MAX_LENGTH_IN_BYTES = 268435456; // 256MB (see spec) diff --git a/lib/src/types/tuple.dart b/lib/src/types/tuple.dart index ceb9987..d1c8c01 100644 --- a/lib/src/types/tuple.dart +++ b/lib/src/types/tuple.dart @@ -6,6 +6,5 @@ part of dart_cassandra_cql.types; * during serialization */ class Tuple extends _wrappers.DelegatingList { - Tuple.fromIterable(Iterable iterable) : super(iterable); } diff --git a/lib/src/types/type_spec.dart b/lib/src/types/type_spec.dart index 48ecade..ae1037c 100644 --- a/lib/src/types/type_spec.dart +++ b/lib/src/types/type_spec.dart @@ -16,13 +16,23 @@ class TypeSpec { // V3 protocol: TUPLE List tupleFields; - TypeSpec(DataType this.valueType, {TypeSpec this.keySubType, TypeSpec this.valueSubType}) { - if (valueType == DataType.LIST && (valueSubType == null || valueSubType is! TypeSpec) ) { - throw new ArgumentError("LIST type should specify a TypeSpec instance for its values"); - } else if (valueType == DataType.SET && (valueSubType == null || valueSubType is! TypeSpec) ) { - throw new ArgumentError("SET type should specify a TypeSpec instance for its values"); - } else if (valueType == DataType.MAP && (keySubType == null || keySubType is! TypeSpec || valueSubType == null || valueSubType is! TypeSpec) ) { - throw new ArgumentError("MAP type should specify TypeSpec instances for both its keys and values"); + TypeSpec(DataType this.valueType, + {TypeSpec this.keySubType, TypeSpec this.valueSubType}) { + if (valueType == DataType.LIST && + (valueSubType == null || valueSubType is! TypeSpec)) { + throw new ArgumentError( + "LIST type should specify a TypeSpec instance for its values"); + } else if (valueType == DataType.SET && + (valueSubType == null || valueSubType is! TypeSpec)) { + throw new ArgumentError( + "SET type should specify a TypeSpec instance for its values"); + } else if (valueType == DataType.MAP && + (keySubType == null || + keySubType is! TypeSpec || + valueSubType == null || + valueSubType is! TypeSpec)) { + throw new ArgumentError( + "MAP type should specify TypeSpec instances for both its keys and values"); } else if (valueType == DataType.UDT) { udtFields = new LinkedHashMap(); } else if (valueType == DataType.TUPLE) { diff --git a/lib/src/types/uuid.dart b/lib/src/types/uuid.dart index dbd415f..7c40e2d 100644 --- a/lib/src/types/uuid.dart +++ b/lib/src/types/uuid.dart @@ -1,4 +1,4 @@ - part of dart_cassandra_cql.types; +part of dart_cassandra_cql.types; // Helpers _uuidImpl.Uuid _uuidFactory = new _uuidImpl.Uuid(); @@ -16,14 +16,14 @@ class Uuid { /** * Create a V4 (randomised) uuid */ - factory Uuid.simple(){ + factory Uuid.simple() { return new Uuid(_uuidFactory.v4()); } /** * Create a V1 (time-based) uuid */ - factory Uuid.timeBased(){ + factory Uuid.timeBased() { return new Uuid(_uuidFactory.v1()); } @@ -41,5 +41,4 @@ class Uuid { */ get bytes => new Uint8List.fromList(_uuidFactory.parse(value)); - } diff --git a/test/lib/chunked_input_reader_test.dart b/test/lib/chunked_input_reader_test.dart index 069193a..0d4afea 100644 --- a/test/lib/chunked_input_reader_test.dart +++ b/test/lib/chunked_input_reader_test.dart @@ -4,8 +4,7 @@ import "package:unittest/unittest.dart"; import '../../lib/src/stream.dart'; -main({bool enableLogger : true}) { - +main({bool enableLogger: true}) { group("Chunked input reader:", () { test("add chunks", () { ChunkedInputReader reader = new ChunkedInputReader(); @@ -62,7 +61,6 @@ main({bool enableLogger : true}) { reader.read(buffer, 2); expect(reader.length, equals(0)); expect(buffer, equals([4, 5])); - }); }); -} \ No newline at end of file +} diff --git a/test/lib/client_test.dart b/test/lib/client_test.dart index 9d5a3a3..dcc832f 100644 --- a/test/lib/client_test.dart +++ b/test/lib/client_test.dart @@ -8,8 +8,8 @@ import "mocks/mocks.dart" as mock; import "mocks/custom.dart" as custom; import '../../lib/dart_cassandra_cql.dart' as cql; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } @@ -31,24 +31,20 @@ main({bool enableLogger : true}) { }); group("Simple connection pool:", () { - cql.Client client; setUp(() { return Future.wait([ - server.listen(SERVER_HOST, SERVER_PORT) - , server2.listen(SERVER_HOST, SERVER2_PORT) + server.listen(SERVER_HOST, SERVER_PORT), + server2.listen(SERVER_HOST, SERVER2_PORT) ]); }); tearDown(() { - List cleanupFutures = [ - server.shutdown() - , server2.shutdown() - ]; + List cleanupFutures = [server.shutdown(), server2.shutdown()]; if (client != null) { - cleanupFutures.add(client.shutdown(drain : true)); + cleanupFutures.add(client.shutdown(drain: true)); client = null; } @@ -57,31 +53,33 @@ main({bool enableLogger : true}) { group("misc:", () { test("empty hosts exception", () { - expect(() => new cql.SimpleConnectionPool.fromHostList( - [] - , new cql.PoolConfiguration() - ), throwsA((e) => e is ArgumentError && e.message == "Host list cannot be empty")); + expect( + () => new cql.SimpleConnectionPool.fromHostList( + [], new cql.PoolConfiguration()), + throwsA((e) => + e is ArgumentError && + e.message == "Host list cannot be empty")); }); test("no connection pool exception", () { - expect(() => new cql.SimpleConnectionPool.fromHostList( - ['foo:123'] - , null - ), throwsA((e) => e is ArgumentError && e.message == "A valid pool configuration is required")); + expect( + () => new cql.SimpleConnectionPool.fromHostList(['foo:123'], null), + throwsA((e) => + e is ArgumentError && + e.message == "A valid pool configuration is required")); }); test("Client with default pool conf", () { - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"]); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"]); expect(client.connectionPool.poolConfig.connectionsPerHost, equals(1)); }); test("Fail to connect to any pool host", () { client = new cql.Client.fromHostList( - [ "${SERVER_HOST}:${SERVER_PORT + 3}"] - , poolConfig : new cql.PoolConfiguration( - reconnectWaitTime : new Duration(milliseconds : 1) - , maxConnectionAttempts : 5 - )); + ["${SERVER_HOST}:${SERVER_PORT + 3}"], + poolConfig: new cql.PoolConfiguration( + reconnectWaitTime: new Duration(milliseconds: 1), + maxConnectionAttempts: 5)); void handleError(e) { expect(e, new isInstanceOf()); @@ -91,87 +89,84 @@ main({bool enableLogger : true}) { }); test("Connection to at least one node in the pool", () { - client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}", - "${SERVER_HOST}:${SERVER_PORT + 3000}" - ] - , poolConfig : new cql.PoolConfiguration( - reconnectWaitTime : new Duration(milliseconds : 1) - , maxConnectionAttempts : 5 - )); - - void connected(_) { - } + client = new cql.Client.fromHostList([ + "${SERVER_HOST}:${SERVER_PORT}", + "${SERVER_HOST}:${SERVER_PORT + 3000}" + ], + poolConfig: new cql.PoolConfiguration( + reconnectWaitTime: new Duration(milliseconds: 1), + maxConnectionAttempts: 5)); - client.connectionPool.connect() - .then(expectAsync(connected)) - .catchError((e) => fail(e)); - }); + void connected(_) {} + client.connectionPool + .connect() + .then(expectAsync(connected)) + .catchError((e) => fail(e)); + }); }); group("authentication:", () { group("password authenticator exceptions", () { test("empty username", () { - expect(() => new cql.PasswordAuthenticator("", "foo"), throwsArgumentError); + expect(() => new cql.PasswordAuthenticator("", "foo"), + throwsArgumentError); }); test("empty password", () { - expect(() => new cql.PasswordAuthenticator("foo", ""), throwsArgumentError); + expect(() => new cql.PasswordAuthenticator("foo", ""), + throwsArgumentError); }); - }); test("Authentication provider exception", () { server.setAuthReplayList(["authenticate_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration( - autoDiscoverNodes : false - , protocolVersion : cql.ProtocolVersion.V3 - )); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3)); void handleError(e) { expect(e, new isInstanceOf()); - expect(e.message, equals("Server requested 'org.apache.cassandra.auth.PasswordAuthenticator' authenticator but no authenticator specified")); + expect( + e.message, + equals( + "Server requested 'org.apache.cassandra.auth.PasswordAuthenticator' authenticator but no authenticator specified")); } client.connectionPool.connect().catchError(expectAsync(handleError)); - }); test("Different authenticator exception", () { server.setAuthReplayList(["authenticate_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration( - autoDiscoverNodes : false - , protocolVersion : cql.ProtocolVersion.V3 - , authenticator : new mock.MockAuthenticator() - )); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3, + authenticator: new mock.MockAuthenticator())); void handleError(e) { expect(e, new isInstanceOf()); - expect(e.message, equals("Server requested 'org.apache.cassandra.auth.PasswordAuthenticator' authenticator but a '${client.connectionPool.poolConfig.authenticator.authenticatorClass}' authenticator was specified instead")); + expect( + e.message, + equals( + "Server requested 'org.apache.cassandra.auth.PasswordAuthenticator' authenticator but a '${client.connectionPool.poolConfig.authenticator.authenticatorClass}' authenticator was specified instead")); } client.connectionPool.connect().catchError(expectAsync(handleError)); - }); test("User/pass mismatch exception", () { - server.setAuthReplayList([ - "authenticate_v3.dump" - , "auth_error_v3.dump" - ]); + server + .setAuthReplayList(["authenticate_v3.dump", "auth_error_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration( - autoDiscoverNodes : false - , protocolVersion : cql.ProtocolVersion.V3 - , authenticator : new cql.PasswordAuthenticator("foo", "bar") - )); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3, + authenticator: new cql.PasswordAuthenticator("foo", "bar"))); void handleError(e) { expect(e, new isInstanceOf()); @@ -179,123 +174,118 @@ main({bool enableLogger : true}) { } client.connectionPool.connect().catchError(expectAsync(handleError)); - }); test("Auth success (multi challenge-response)", () { server.setAuthReplayList([ - "authenticate_v3.dump" - , "auth_challenge_v3.dump" - , "auth_challenge_v3.dump" - , "auth_challenge_v3.dump" - , "auth_success_v3.dump" + "authenticate_v3.dump", + "auth_challenge_v3.dump", + "auth_challenge_v3.dump", + "auth_challenge_v3.dump", + "auth_success_v3.dump" ]); server.setReplayList(["select_tuple_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration( - autoDiscoverNodes : false - , protocolVersion : cql.ProtocolVersion.V3 - , authenticator : new cql.PasswordAuthenticator("foo", "bar") - )); - - void handleSuccess(_) { - } + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3, + authenticator: new cql.PasswordAuthenticator("foo", "bar"))); - client.query(new cql.Query("SELECT * FROM test.test_type")).then(expectAsync(handleSuccess)); + void handleSuccess(_) {} + client + .query(new cql.Query("SELECT * FROM test.test_type")) + .then(expectAsync(handleSuccess)); }); }); group("execute:", () { - test("select from invalid collection (V3)", () { server.setReplayList(["error_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration( - autoDiscoverNodes : false - , protocolVersion : cql.ProtocolVersion.V3 - )); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3)); void handleError(e) { expect(e, new isInstanceOf()); expect(e.message, equals("unconfigured columnfamily foo")); } - client.execute(new cql.Query("SELECT * from test.foo", consistency : cql.Consistency.LOCAL_ONE)) - .catchError(expectAsync(handleError)); + client + .execute(new cql.Query("SELECT * from test.foo", + consistency: cql.Consistency.LOCAL_ONE)) + .catchError(expectAsync(handleError)); }); test("set keyspace", () { server.setReplayList(["set_keyspace_v2.dump"]); - cql.ConnectionPool pool = new cql.SimpleConnectionPool.fromHostList([ - "${SERVER_HOST}:${SERVER_PORT}" - ], new cql.PoolConfiguration(autoDiscoverNodes : false)); + cql.ConnectionPool pool = new cql.SimpleConnectionPool.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + new cql.PoolConfiguration(autoDiscoverNodes: false)); client = new cql.Client.withPool(pool); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); - expect((message as cql.SetKeyspaceResultMessage).keyspace, equals("test")); + expect((message as cql.SetKeyspaceResultMessage).keyspace, + equals("test")); } - client.execute(new cql.Query("USE test")).then(expectAsync(handleResult)); + client + .execute(new cql.Query("USE test")) + .then(expectAsync(handleResult)); }); test("query and process raw RowsResultMessage", () { server.setReplayList(["select_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); - expect( - client.execute(new cql.Query("SELECT * from test.type_test")), + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); + expect(client.execute(new cql.Query("SELECT * from test.type_test")), completion((cql.ResultMessage message) { - expect(message, new isInstanceOf()); - cql.RowsResultMessage res = message as cql.RowsResultMessage; - expect(res.rows.length, equals(1)); - Map row = res.rows.first; - Map expectedValues = { - "ascii_type" : "text4" - , "bigint_type" : 9223372036854775807 - , "bool_type" : true - , "inet_type" : new InternetAddress("192.168.169.102") - , "int_type" : 32238493 - , "list_type" : [100, 200] - , "map_type" : { - 100 : "the test" - , 200 : "the result" - } - , "set_type" : [100, 200] - , "text_type" : "This is a long UTF8 κείμενο" - , "uuid_type" : new cql.Uuid("550e8400-e29b-41d4-a716-446655440000") - , "varchar_type" : "Arbitary long text goes here" - , "varint_type" : -3123091212904812093120938120938120312890 - }; - expectedValues.forEach((String fieldName, Object fieldValue) { - expect(row[fieldName], equals(fieldValue)); - }); - return true; - }) - ); + expect(message, new isInstanceOf()); + cql.RowsResultMessage res = message as cql.RowsResultMessage; + expect(res.rows.length, equals(1)); + Map row = res.rows.first; + Map expectedValues = { + "ascii_type": "text4", + "bigint_type": 9223372036854775807, + "bool_type": true, + "inet_type": new InternetAddress("192.168.169.102"), + "int_type": 32238493, + "list_type": [100, 200], + "map_type": {100: "the test", 200: "the result"}, + "set_type": [100, 200], + "text_type": "This is a long UTF8 κείμενο", + "uuid_type": new cql.Uuid("550e8400-e29b-41d4-a716-446655440000"), + "varchar_type": "Arbitary long text goes here", + "varint_type": -3123091212904812093120938120938120312890 + }; + expectedValues.forEach((String fieldName, Object fieldValue) { + expect(row[fieldName], equals(fieldValue)); + }); + return true; + })); }); test("alter statement and process raw RowsResultMessage", () { server.setReplayList(["schema_change_result_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); expect( - client.execute(new cql.Query("ALTER TABLE test.type_test ADD new_field int")), + client.execute( + new cql.Query("ALTER TABLE test.type_test ADD new_field int")), completion((cql.ResultMessage message) { - expect(message, new isInstanceOf()); - cql.SchemaChangeResultMessage res = message as cql.SchemaChangeResultMessage; - expect(res.keyspace, equals("test")); - expect(res.table, equals("type_test")); - expect(res.change, equals("UPDATED")); - return true; - }) - ); + expect(message, new isInstanceOf()); + cql.SchemaChangeResultMessage res = + message as cql.SchemaChangeResultMessage; + expect(res.keyspace, equals("test")); + expect(res.table, equals("type_test")); + expect(res.change, equals("UPDATED")); + return true; + })); }); test( @@ -313,17 +303,14 @@ main({bool enableLogger : true}) { }); group("query:", () { - group("SELECT:", () { - group("custom types:", () { - test("without custom type handler", () { cql.unregisterCodec('com.achilleasa.cassandra.cqltypes.Json'); server.setReplayList(["select_custom_type_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList([ + "${SERVER_HOST}:${SERVER_PORT}" + ], poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); void onResult(Iterable> rows) { expect(rows.length, equals(1)); @@ -334,18 +321,20 @@ main({bool enableLogger : true}) { expect(row["custom"], new isInstanceOf()); } - client.query(new cql.Query("SELECT * from test.custom_types")) - .then(expectAsync(onResult)); + client + .query(new cql.Query("SELECT * from test.custom_types")) + .then(expectAsync(onResult)); }); test("with custom type handler", () { // Register custom type handler - cql.registerCodec('com.achilleasa.cassandra.cqltypes.Json', new custom.CustomJsonCodec()); + cql.registerCodec('com.achilleasa.cassandra.cqltypes.Json', + new custom.CustomJsonCodec()); server.setReplayList(["select_custom_type_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList([ + "${SERVER_HOST}:${SERVER_PORT}" + ], poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); void onResult(Iterable> rows) { expect(rows.length, equals(1)); @@ -355,43 +344,45 @@ main({bool enableLogger : true}) { expect(row["login"], equals("test")); expect(row["custom"], new isInstanceOf()); - custom.CustomJson customJson = (row["custom"] as custom.CustomJson); + custom.CustomJson customJson = + (row["custom"] as custom.CustomJson); expect(customJson.payload.containsKey("foo"), isTrue); expect(customJson.payload["foo"], equals("bar")); } - client.query(new cql.Query("SELECT * from test.custom_types")) - .then(expectAsync(onResult)); + client + .query(new cql.Query("SELECT * from test.custom_types")) + .then(expectAsync(onResult)); }); }); test("tuple type", () { server.setReplayList(["select_tuple_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, protocolVersion : cql.ProtocolVersion.V3) - ); - expect( - client.query(new cql.Query("SELECT * from test.tuple_test")), + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3)); + expect(client.query(new cql.Query("SELECT * from test.tuple_test")), completion((Iterable> rows) { - expect(rows.length, equals(1)); - Map row = rows.first; - Map expectedValues = { - "the_key" : 1 - , "the_tuple" : new cql.Tuple.fromIterable([10, "foo", true]) - }; - expectedValues.forEach((String fieldName, Object fieldValue) { - expect(row[fieldName], equals(fieldValue)); - }); - return true; - }) - ); + expect(rows.length, equals(1)); + Map row = rows.first; + Map expectedValues = { + "the_key": 1, + "the_tuple": new cql.Tuple.fromIterable([10, "foo", true]) + }; + expectedValues.forEach((String fieldName, Object fieldValue) { + expect(row[fieldName], equals(fieldValue)); + }); + return true; + })); }); test("from unknown collection (V2)", () { server.setReplayList(["error_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); void handleError(e) { expect(e, new isInstanceOf()); @@ -399,139 +390,138 @@ main({bool enableLogger : true}) { expect(e.toString(), equals('CassandraException: ${e.message}')); } - client.query(new cql.Query("SELECT * from test.foo")) - .catchError(expectAsync(handleError)); + client + .query(new cql.Query("SELECT * from test.foo")) + .catchError(expectAsync(handleError)); }); test("normal", () { server.setReplayList(["select_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); - expect( - client.query(new cql.Query("SELECT * from test.type_test")), + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); + expect(client.query(new cql.Query("SELECT * from test.type_test")), completion((Iterable> rows) { - expect(rows.length, equals(1)); - Map row = rows.first; - Map expectedValues = { - "ascii_type" : "text4" - , "bigint_type" : 9223372036854775807 - , "bool_type" : true - , "inet_type" : new InternetAddress("192.168.169.102") - , "int_type" : 32238493 - , "list_type" : [100, 200] - , "map_type" : { - 100 : "the test" - , 200 : "the result" - } - , "set_type" : [100, 200] - , "text_type" : "This is a long UTF8 κείμενο" - , "uuid_type" : new cql.Uuid("550e8400-e29b-41d4-a716-446655440000") - , "varchar_type" : "Arbitary long text goes here" - , "varint_type" : -3123091212904812093120938120938120312890 - }; - expectedValues.forEach((String fieldName, Object fieldValue) { - expect(row[fieldName], equals(fieldValue)); - }); - return true; - }) - ); + expect(rows.length, equals(1)); + Map row = rows.first; + Map expectedValues = { + "ascii_type": "text4", + "bigint_type": 9223372036854775807, + "bool_type": true, + "inet_type": new InternetAddress("192.168.169.102"), + "int_type": 32238493, + "list_type": [100, 200], + "map_type": {100: "the test", 200: "the result"}, + "set_type": [100, 200], + "text_type": "This is a long UTF8 κείμενο", + "uuid_type": new cql.Uuid("550e8400-e29b-41d4-a716-446655440000"), + "varchar_type": "Arbitary long text goes here", + "varint_type": -3123091212904812093120938120938120312890 + }; + expectedValues.forEach((String fieldName, Object fieldValue) { + expect(row[fieldName], equals(fieldValue)); + }); + return true; + })); }); }); group("INSERT:", () { - test("batch insert", () { server.setReplayList(["void_result_v2.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); } - String query = "INSERT INTO page_view_counts (url_name, page_name, counter_value) VALUES (?, ?, ?)"; - client.execute( - new cql.BatchQuery() - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "front_page", 1])) - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "login_page", 2])) - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "main_page", 3])) - ).then(expectAsync(handleResult)); + String query = + "INSERT INTO page_view_counts (url_name, page_name, counter_value) VALUES (?, ?, ?)"; + client + .execute(new cql.BatchQuery() + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "front_page", 1])) + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "login_page", 2])) + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "main_page", 3]))) + .then(expectAsync(handleResult)); }); test("batch insert with serial consistency (V3)", () { server.setReplayList(["void_result_v3.dump"]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, protocolVersion : cql.ProtocolVersion.V3) - ); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3)); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); } - String query = "INSERT INTO page_view_counts (url_name, page_name, counter_value) VALUES (?, ?, ?)"; - client.execute( - new cql.BatchQuery() + String query = + "INSERT INTO page_view_counts (url_name, page_name, counter_value) VALUES (?, ?, ?)"; + client + .execute(new cql.BatchQuery() ..serialConsistency = cql.Consistency.LOCAL_SERIAL - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "front_page", 1])) - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "login_page", 2])) - ..add(new cql.Query(query, bindings : [ "http://www.test.com", "main_page", 3])) - ).then(expectAsync(handleResult)); + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "front_page", 1])) + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "login_page", 2])) + ..add(new cql.Query(query, + bindings: ["http://www.test.com", "main_page", 3]))) + .then(expectAsync(handleResult)); }); - }); }); group("stream:", () { - test("process streamed rows", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); - void streamCallback(Map row) { - } + void streamCallback(Map row) {} - client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen(expectAsync(streamCallback, count : 10, max : 10)); + client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(expectAsync(streamCallback, count: 10, max: 10)); }); test("process streamed rows (preferBiggerTcpPackets)", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, preferBiggerTcpPackets : true) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, preferBiggerTcpPackets: true)); - void streamCallback(Map row) { - } + void streamCallback(Map row) {} - client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen(expectAsync(streamCallback, count : 10, max : 10)); + client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(expectAsync(streamCallback, count: 10, max: 10)); }); test("pause/resume", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); StreamSubscription streamSubscription; int rowCount = 0; @@ -540,26 +530,25 @@ main({bool enableLogger : true}) { rowCount++; if (rowCount == 5) { streamSubscription.pause(); - new Future.delayed(new Duration(milliseconds : 100), () => streamSubscription.resume()); + new Future.delayed(new Duration(milliseconds: 100), + () => streamSubscription.resume()); } } - streamSubscription = client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen(expectAsync(streamCallback, count : 10, max : 10)); - + streamSubscription = client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(expectAsync(streamCallback, count: 10, max: 10)); }); test("close", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); StreamSubscription streamSubscription; int rowCount = 0; @@ -571,21 +560,20 @@ main({bool enableLogger : true}) { } } - streamSubscription = client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen(expectAsync(streamCallback, count : 5, max : 5)); + streamSubscription = client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(expectAsync(streamCallback, count: 5, max: 5)); }); test("connection lost", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); StreamSubscription subscription; @@ -596,32 +584,30 @@ main({bool enableLogger : true}) { firstInvocation = false; subscription.pause(); server.shutdown().then((_) { - new Future.delayed(new Duration(milliseconds: 10), () => subscription.resume()); + new Future.delayed( + new Duration(milliseconds: 10), () => subscription.resume()); }); } } - subscription = client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen( - streamCallback - , onError : expectAsync((e) { - expect(e, new isInstanceOf()); - expect(e.toString(), startsWith("NoHealthyConnectionsException")); - }) - ); + subscription = client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(streamCallback, onError: expectAsync((e) { + expect(e, new isInstanceOf()); + expect(e.toString(), startsWith("NoHealthyConnectionsException")); + })); }); test("connection lost; fallback to alt connection", () { server.setReplayList([ - "stream_v2_1of3.dump" - , "stream_v2_2of3.dump" - , "stream_v2_3of3.dump" + "stream_v2_1of3.dump", + "stream_v2_2of3.dump", + "stream_v2_3of3.dump" ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, connectionsPerHost : 2) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, connectionsPerHost: 2)); bool firstRun = true; @@ -632,24 +618,22 @@ main({bool enableLogger : true}) { } } - client.stream( - new cql.Query("SELECT * FROM test.page_view_counts") - , pageSize: 4 - ).listen(expectAsync(streamCallback, count : 10, max : 10), onError : (e) => print(e)); + client + .stream(new cql.Query("SELECT * FROM test.page_view_counts"), + pageSize: 4) + .listen(expectAsync(streamCallback, count: 10, max: 10), + onError: (e) => print(e)); }); }); group("prepared queries:", () { test("prepare and execute query (V2)", () { - server.setReplayList([ - "prepare_v2.dump" - , "void_result_v2.dump" - ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false) - ); + server.setReplayList(["prepare_v2.dump", "void_result_v2.dump"]); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration(autoDiscoverNodes: false)); - cql.Query query = new cql.Query(""" + cql.Query query = new cql.Query( + """ INSERT INTO test.type_test ( ascii_type, bigint_type, decimal_type, bool_type, double_type, float_type, inet_type, int_type, list_type, map_type, @@ -660,48 +644,61 @@ INSERT INTO test.type_test ( :double_type, :float_type, :inet_type, :int_type, :list_type, :map_type, :set_type, :text_type, :timestamp_type, :uuid_type, :timeuuid_type, :varchar_type, :varint_type, :blob_type -)""", consistency : cql.Consistency.ONE, prepared : true); +)""", + consistency: cql.Consistency.ONE, + prepared: true); query.bindings = { - "ascii_type" : "123" - , "bigint_type" : 123451234 - , "decimal_type" : 3.14 - , "bool_type" : true - , "double_type" : 3.14 - , "float_type" : 3.14 - , "inet_type" : new InternetAddress("192.168.169.101") - , "int_type" : 10 - , "list_type" : [1, 2, 3] - , "map_type" : { - 1 : "A" - , 2 : "BC" - } - , "set_type" : [1, 2, 3] - , "text_type" : "Long text" - , "timestamp_type" : new DateTime.now() - , "uuid_type" : new cql.Uuid.simple() - , "timeuuid_type" : new cql.Uuid.timeBased() - , "varchar_type" : "test 123" - , "varint_type" : 123456 - , "blob_type" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x00, 0x0D, 0xF0, 0x00, 0x0C, 0x00, 0x0F, 0xF3, 0x0E]) + "ascii_type": "123", + "bigint_type": 123451234, + "decimal_type": 3.14, + "bool_type": true, + "double_type": 3.14, + "float_type": 3.14, + "inet_type": new InternetAddress("192.168.169.101"), + "int_type": 10, + "list_type": [1, 2, 3], + "map_type": {1: "A", 2: "BC"}, + "set_type": [1, 2, 3], + "text_type": "Long text", + "timestamp_type": new DateTime.now(), + "uuid_type": new cql.Uuid.simple(), + "timeuuid_type": new cql.Uuid.timeBased(), + "varchar_type": "test 123", + "varint_type": 123456, + "blob_type": new Uint8List.fromList([ + 0x8B, + 0xAD, + 0xF0, + 0x00, + 0x0D, + 0xF0, + 0x00, + 0x0C, + 0x00, + 0x0F, + 0xF3, + 0x0E + ]) }; - void done(cql.VoidResultMessage msg) { - } + void done(cql.VoidResultMessage msg) {} client.execute(query).then(expectAsync(done)); }); - test("prepare and execute query; fallback to other connection on same host (V2)", () { + test( + "prepare and execute query; fallback to other connection on same host (V2)", + () { server.setReplayList([ - "prepare_v2.dump" - , "void_result_v2.dump" - , "void_result_v2.dump" // 2nd attempt + "prepare_v2.dump", "void_result_v2.dump", + "void_result_v2.dump" // 2nd attempt ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, connectionsPerHost: 2) - ); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, connectionsPerHost: 2)); - cql.Query query = new cql.Query(""" + cql.Query query = new cql.Query( + """ INSERT INTO test.type_test ( ascii_type, bigint_type, decimal_type, bool_type, double_type, float_type, inet_type, int_type, list_type, map_type, @@ -712,37 +709,47 @@ INSERT INTO test.type_test ( :double_type, :float_type, :inet_type, :int_type, :list_type, :map_type, :set_type, :text_type, :timestamp_type, :uuid_type, :timeuuid_type, :varchar_type, :varint_type, :blob_type -)""", consistency : cql.Consistency.ONE, prepared : true); +)""", + consistency: cql.Consistency.ONE, + prepared: true); query.bindings = { - "ascii_type" : "123" - , "bigint_type" : 123451234 - , "decimal_type" : 3.14 - , "bool_type" : true - , "double_type" : 3.14 - , "float_type" : 3.14 - , "inet_type" : new InternetAddress("192.168.169.101") - , "int_type" : 10 - , "list_type" : [1, 2, 3] - , "map_type" : { - 1 : "A" - , 2 : "BC" - } - , "set_type" : [1, 2, 3] - , "text_type" : "Long text" - , "timestamp_type" : new DateTime.now() - , "uuid_type" : new cql.Uuid.simple() - , "timeuuid_type" : new cql.Uuid.timeBased() - , "varchar_type" : "test 123" - , "varint_type" : 123456 - , "blob_type" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x00, 0x0D, 0xF0, 0x00, 0x0C, 0x00, 0x0F, 0xF3, 0x0E]) + "ascii_type": "123", + "bigint_type": 123451234, + "decimal_type": 3.14, + "bool_type": true, + "double_type": 3.14, + "float_type": 3.14, + "inet_type": new InternetAddress("192.168.169.101"), + "int_type": 10, + "list_type": [1, 2, 3], + "map_type": {1: "A", 2: "BC"}, + "set_type": [1, 2, 3], + "text_type": "Long text", + "timestamp_type": new DateTime.now(), + "uuid_type": new cql.Uuid.simple(), + "timeuuid_type": new cql.Uuid.timeBased(), + "varchar_type": "test 123", + "varint_type": 123456, + "blob_type": new Uint8List.fromList([ + 0x8B, + 0xAD, + 0xF0, + 0x00, + 0x0D, + 0xF0, + 0x00, + 0x0C, + 0x00, + 0x0F, + 0xF3, + 0x0E + ]) }; - Function done = expectAsync((_) { - }); + Function done = expectAsync((_) {}); - client.execute(query) - .then((_) { + client.execute(query).then((_) { // Kill 1st connection so we run the next prepared statement attempt // on the second connection server.disconnectClient(0); @@ -753,23 +760,18 @@ INSERT INTO test.type_test ( }); }); - test("prepare and execute query; prepare on new host after server1 dies (V2)", () { - server.setReplayList([ - "prepare_v2.dump" - , "void_result_v2.dump" - ]); - server2.setReplayList([ - "prepare_v2.dump" - , "void_result_v2.dump" - ]); - client = new cql.Client.fromHostList([ - "${SERVER_HOST}:${SERVER_PORT}" - , "${SERVER_HOST}:${SERVER2_PORT}" - ] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, connectionsPerHost: 2) - ); + test( + "prepare and execute query; prepare on new host after server1 dies (V2)", + () { + server.setReplayList(["prepare_v2.dump", "void_result_v2.dump"]); + server2.setReplayList(["prepare_v2.dump", "void_result_v2.dump"]); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}", "${SERVER_HOST}:${SERVER2_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, connectionsPerHost: 2)); - cql.Query query = new cql.Query(""" + cql.Query query = new cql.Query( + """ INSERT INTO test.type_test ( ascii_type, bigint_type, decimal_type, bool_type, double_type, float_type, inet_type, int_type, list_type, map_type, @@ -780,30 +782,42 @@ INSERT INTO test.type_test ( :double_type, :float_type, :inet_type, :int_type, :list_type, :map_type, :set_type, :text_type, :timestamp_type, :uuid_type, :timeuuid_type, :varchar_type, :varint_type, :blob_type -)""", consistency : cql.Consistency.ONE, prepared : true); +)""", + consistency: cql.Consistency.ONE, + prepared: true); query.bindings = { - "ascii_type" : "123" - , "bigint_type" : 123451234 - , "decimal_type" : 3.14 - , "bool_type" : true - , "double_type" : 3.14 - , "float_type" : 3.14 - , "inet_type" : new InternetAddress("192.168.169.101") - , "int_type" : 10 - , "list_type" : [1, 2, 3] - , "map_type" : { - 1 : "A" - , 2 : "BC" - } - , "set_type" : [1, 2, 3] - , "text_type" : "Long text" - , "timestamp_type" : new DateTime.now() - , "uuid_type" : new cql.Uuid.simple() - , "timeuuid_type" : new cql.Uuid.timeBased() - , "varchar_type" : "test 123" - , "varint_type" : 123456 - , "blob_type" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x00, 0x0D, 0xF0, 0x00, 0x0C, 0x00, 0x0F, 0xF3, 0x0E]) + "ascii_type": "123", + "bigint_type": 123451234, + "decimal_type": 3.14, + "bool_type": true, + "double_type": 3.14, + "float_type": 3.14, + "inet_type": new InternetAddress("192.168.169.101"), + "int_type": 10, + "list_type": [1, 2, 3], + "map_type": {1: "A", 2: "BC"}, + "set_type": [1, 2, 3], + "text_type": "Long text", + "timestamp_type": new DateTime.now(), + "uuid_type": new cql.Uuid.simple(), + "timeuuid_type": new cql.Uuid.timeBased(), + "varchar_type": "test 123", + "varint_type": 123456, + "blob_type": new Uint8List.fromList([ + 0x8B, + 0xAD, + 0xF0, + 0x00, + 0x0D, + 0xF0, + 0x00, + 0x0C, + 0x00, + 0x0F, + 0xF3, + 0x0E + ]) }; bool firstResponse = true; @@ -819,25 +833,24 @@ INSERT INTO test.type_test ( return new Future.value(); } - client.execute(query) - .then(done) - // 2nd statement should trigger a prepare on server2 - .then((_) => client.execute(query)) - .then(expectAsync(done)); + client + .execute(query) + .then(done) + // 2nd statement should trigger a prepare on server2 + .then((_) => client.execute(query)) + .then(expectAsync(done)); }); - test("prepare and execute query; NoHealthyConnections exception after server1 dies (V2)", () { - server.setReplayList([ - "prepare_v2.dump" - , "void_result_v2.dump" - ]); - client = new cql.Client.fromHostList([ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, connectionsPerHost: 2) - ); + test( + "prepare and execute query; NoHealthyConnections exception after server1 dies (V2)", + () { + server.setReplayList(["prepare_v2.dump", "void_result_v2.dump"]); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, connectionsPerHost: 2)); - cql.Query query = new cql.Query(""" + cql.Query query = new cql.Query( + """ INSERT INTO test.type_test ( ascii_type, bigint_type, decimal_type, bool_type, double_type, float_type, inet_type, int_type, list_type, map_type, @@ -848,55 +861,65 @@ INSERT INTO test.type_test ( :double_type, :float_type, :inet_type, :int_type, :list_type, :map_type, :set_type, :text_type, :timestamp_type, :uuid_type, :timeuuid_type, :varchar_type, :varint_type, :blob_type -)""", consistency : cql.Consistency.ONE - , serialConsistency : cql.Consistency.LOCAL_SERIAL - , prepared : true - ); +)""", + consistency: cql.Consistency.ONE, + serialConsistency: cql.Consistency.LOCAL_SERIAL, + prepared: true); query.bindings = { - "ascii_type" : "123" - , "bigint_type" : 123451234 - , "decimal_type" : 3.14 - , "bool_type" : true - , "double_type" : 3.14 - , "float_type" : 3.14 - , "inet_type" : new InternetAddress("192.168.169.101") - , "int_type" : 10 - , "list_type" : [1, 2, 3] - , "map_type" : { - 1 : "A" - , 2 : "BC" - } - , "set_type" : [1, 2, 3] - , "text_type" : "Long text" - , "timestamp_type" : new DateTime.now() - , "uuid_type" : new cql.Uuid.simple() - , "timeuuid_type" : new cql.Uuid.timeBased() - , "varchar_type" : "test 123" - , "varint_type" : 123456 - , "blob_type" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x00, 0x0D, 0xF0, 0x00, 0x0C, 0x00, 0x0F, 0xF3, 0x0E]) + "ascii_type": "123", + "bigint_type": 123451234, + "decimal_type": 3.14, + "bool_type": true, + "double_type": 3.14, + "float_type": 3.14, + "inet_type": new InternetAddress("192.168.169.101"), + "int_type": 10, + "list_type": [1, 2, 3], + "map_type": {1: "A", 2: "BC"}, + "set_type": [1, 2, 3], + "text_type": "Long text", + "timestamp_type": new DateTime.now(), + "uuid_type": new cql.Uuid.simple(), + "timeuuid_type": new cql.Uuid.timeBased(), + "varchar_type": "test 123", + "varint_type": 123456, + "blob_type": new Uint8List.fromList([ + 0x8B, + 0xAD, + 0xF0, + 0x00, + 0x0D, + 0xF0, + 0x00, + 0x0C, + 0x00, + 0x0F, + 0xF3, + 0x0E + ]) }; Function fail = expectAsync((e) { expect(e, new isInstanceOf()); }, count: 1); - client.execute(query) - .then((_) => server.shutdown()) - .then((_) => client.execute(query)) - .catchError(fail); + client + .execute(query) + .then((_) => server.shutdown()) + .then((_) => client.execute(query)) + .catchError(fail); }); test("prepare and execute query (V3)", () { - server.setReplayList([ - "prepare_v3.dump" - , "void_result_v3.dump" - ]); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : new cql.PoolConfiguration(autoDiscoverNodes : false, protocolVersion : cql.ProtocolVersion.V3) - ); - - cql.Query query = new cql.Query(""" + server.setReplayList(["prepare_v3.dump", "void_result_v3.dump"]); + client = new cql.Client.fromHostList(["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: new cql.PoolConfiguration( + autoDiscoverNodes: false, + protocolVersion: cql.ProtocolVersion.V3)); + + cql.Query query = new cql.Query( + """ INSERT INTO test.type_test ( ascii_type, bigint_type, decimal_type, bool_type, double_type, float_type, inet_type, int_type, list_type, map_type, @@ -907,187 +930,204 @@ INSERT INTO test.type_test ( :double_type, :float_type, :inet_type, :int_type, :list_type, :map_type, :set_type, :text_type, :timestamp_type, :uuid_type, :timeuuid_type, :varchar_type, :varint_type, :blob_type -)""", consistency : cql.Consistency.ONE, prepared : true); +)""", + consistency: cql.Consistency.ONE, + prepared: true); query.bindings = { - "ascii_type" : "123" - , "bigint_type" : 123451234 - , "decimal_type" : 3.14 - , "bool_type" : true - , "double_type" : 3.14 - , "float_type" : 3.14 - , "inet_type" : new InternetAddress("192.168.169.101") - , "int_type" : 10 - , "list_type" : [1, 2, 3] - , "map_type" : { - 1 : "A" - , 2 : "BC" - } - , "set_type" : [1, 2, 3] - , "text_type" : "Long text" - , "timestamp_type" : new DateTime.now() - , "uuid_type" : new cql.Uuid.simple() - , "timeuuid_type" : new cql.Uuid.timeBased() - , "varchar_type" : "test 123" - , "varint_type" : 123456 - , "blob_type" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x00, 0x0D, 0xF0, 0x00, 0x0C, 0x00, 0x0F, 0xF3, 0x0E]) + "ascii_type": "123", + "bigint_type": 123451234, + "decimal_type": 3.14, + "bool_type": true, + "double_type": 3.14, + "float_type": 3.14, + "inet_type": new InternetAddress("192.168.169.101"), + "int_type": 10, + "list_type": [1, 2, 3], + "map_type": {1: "A", 2: "BC"}, + "set_type": [1, 2, 3], + "text_type": "Long text", + "timestamp_type": new DateTime.now(), + "uuid_type": new cql.Uuid.simple(), + "timeuuid_type": new cql.Uuid.timeBased(), + "varchar_type": "test 123", + "varint_type": 123456, + "blob_type": new Uint8List.fromList([ + 0x8B, + 0xAD, + 0xF0, + 0x00, + 0x0D, + 0xF0, + 0x00, + 0x0C, + 0x00, + 0x0F, + 0xF3, + 0x0E + ]) }; - void done(cql.VoidResultMessage msg) { - } + void done(cql.VoidResultMessage msg) {} client.execute(query).then(expectAsync(done)); }); }); group("server events:", () { group("STATUS_CHANGE (V2):", () { - test("server2 host up event while server1 suddenly dies; automatically connect to server2", () { - server2.setReplayList([ - "set_keyspace_v2.dump" - ]); + test( + "server2 host up event while server1 suddenly dies; automatically connect to server2", + () { + server2.setReplayList(["set_keyspace_v2.dump"]); cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - ); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER_PORT}"] - , poolConfig : poolConfig - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + ); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); - expect((message as cql.SetKeyspaceResultMessage).keyspace, equals("test")); + expect((message as cql.SetKeyspaceResultMessage).keyspace, + equals("test")); } client.connectionPool - .connect() - // Wait for event registration message to be received and then reply the event message - .then((_) => new Future.delayed(new Duration(milliseconds:100), () => server.replayFile(0, "event_status_up_v2.dump"))) - .then((_) => new Future.delayed(new Duration(milliseconds:100), () => server.shutdown())) - // Wait for the client to connect to discovered node and try executing a query - .then((_) => new Future.delayed(new Duration(milliseconds : 200), () => client.execute(new cql.Query("USE test")))) - .then(expectAsync(handleResult)); + .connect() + // Wait for event registration message to be received and then reply the event message + .then((_) => new Future.delayed(new Duration(milliseconds: 100), + () => server.replayFile(0, "event_status_up_v2.dump"))) + .then((_) => new Future.delayed( + new Duration(milliseconds: 100), () => server.shutdown())) + // Wait for the client to connect to discovered node and try executing a query + .then((_) => new Future.delayed(new Duration(milliseconds: 200), + () => client.execute(new cql.Query("USE test")))) + .then(expectAsync(handleResult)); }); - test("server2 host down event; pending queries to server2 should automatically fail", () { + test( + "server2 host down event; pending queries to server2 should automatically fail", + () { server2.setReplayList([ - // Intentionally empty so the client gets stuck waiting for the server to reply + // Intentionally empty so the client gets stuck waiting for the server to reply ]); cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 1) // Keep reconnect time low for our test - ); - client = new cql.Client.fromHostList([ "${SERVER_HOST}:${SERVER2_PORT}"] - , poolConfig : poolConfig - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 1) // Keep reconnect time low for our test + ); + client = new cql.Client.fromHostList( + ["${SERVER_HOST}:${SERVER2_PORT}"], + poolConfig: poolConfig); void handleError(e) { expect(e, new isInstanceOf()); } client.connectionPool - .connect() - // Wait for the event registration ready event to arrive and then shut server 2 down - .then((_) => new Future.delayed(new Duration(milliseconds: 20), () => server2.replayFile(0, "event_status_down_v2.dump"))) - // Wait for the node down message to be processed and attempt a query that should fail - .then((_) => new Future.delayed(new Duration(milliseconds: 100), () => client.execute(new cql.Query("USE test")))) - .catchError(expectAsync(handleError)); + .connect() + // Wait for the event registration ready event to arrive and then shut server 2 down + .then((_) => new Future.delayed(new Duration(milliseconds: 20), + () => server2.replayFile(0, "event_status_down_v2.dump"))) + // Wait for the node down message to be processed and attempt a query that should fail + .then((_) => new Future.delayed(new Duration(milliseconds: 100), + () => client.execute(new cql.Query("USE test")))) + .catchError(expectAsync(handleError)); }); test("server2 host down then host up event", () { - server2.setReplayList([ - "set_keyspace_v2.dump" - ]); + server2.setReplayList(["set_keyspace_v2.dump"]); cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - ); - client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - , "${SERVER_HOST}:${SERVER2_PORT}" - ] - , poolConfig : poolConfig - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + ); + client = new cql.Client.fromHostList([ + "${SERVER_HOST}:${SERVER_PORT}", + "${SERVER_HOST}:${SERVER2_PORT}" + ], poolConfig: poolConfig); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); - expect((message as cql.SetKeyspaceResultMessage).keyspace, equals("test")); + expect((message as cql.SetKeyspaceResultMessage).keyspace, + equals("test")); } client.connectionPool - .connect() - .then((_) { - // Wait for event registration message to be received and then reply the event message - new Timer(new Duration(milliseconds: 100), () => server.replayFile(0, "event_status_down_v2.dump")); - new Timer(new Duration(milliseconds: 200), () => server.replayFile(0, "event_status_up_v2.dump")); - return new Future.delayed(new Duration(milliseconds:400), () => server.shutdown()); - }) - .then((_) => client.execute(new cql.Query("USE test"))) - .then(expectAsync(handleResult)); + .connect() + .then((_) { + // Wait for event registration message to be received and then reply the event message + new Timer(new Duration(milliseconds: 100), + () => server.replayFile(0, "event_status_down_v2.dump")); + new Timer(new Duration(milliseconds: 200), + () => server.replayFile(0, "event_status_up_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 400), () => server.shutdown()); + }) + .then((_) => client.execute(new cql.Query("USE test"))) + .then(expectAsync(handleResult)); }); - }); group("TOPOLOGY CHANGE (V3):", () { test("server2 leaves cluster then re-joins", () { - server2.setReplayList([ - "set_keyspace_v2.dump" - ]); + server2.setReplayList(["set_keyspace_v2.dump"]); cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); - client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - , "${SERVER_HOST}:${SERVER2_PORT}" - ] - , poolConfig : poolConfig - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); + client = new cql.Client.fromHostList([ + "${SERVER_HOST}:${SERVER_PORT}", + "${SERVER_HOST}:${SERVER2_PORT}" + ], poolConfig: poolConfig); void handleResult(cql.ResultMessage message) { expect(message, new isInstanceOf()); - expect((message as cql.SetKeyspaceResultMessage).keyspace, equals("test")); + expect((message as cql.SetKeyspaceResultMessage).keyspace, + equals("test")); } client.connectionPool - .connect() - .then((_) { - // Wait for event registration message to be received and then reply the event message - new Timer(new Duration(milliseconds: 100), () => server.replayFile(0, "event_removed_node_v3.dump")); - new Timer(new Duration(milliseconds: 200), () => server.replayFile(0, "event_new_node_v3.dump")); - return new Future.delayed(new Duration(milliseconds:300), () => server.shutdown()); - }) - .then((_) => client.execute(new cql.Query("USE test"))) - .then(expectAsync(handleResult)); + .connect() + .then((_) { + // Wait for event registration message to be received and then reply the event message + new Timer(new Duration(milliseconds: 100), + () => server.replayFile(0, "event_removed_node_v3.dump")); + new Timer(new Duration(milliseconds: 200), + () => server.replayFile(0, "event_new_node_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 300), () => server.shutdown()); + }) + .then((_) => client.execute(new cql.Query("USE test"))) + .then(expectAsync(handleResult)); }); }); group("SCHEMA CHANGE:", () { group("V2:", () { group("KEYSPACE:", () { - test("created", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V2 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V2); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_CREATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1097,33 +1137,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_created_keyspace_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_created_keyspace_v2.dump")); }); }); test("dropped", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V2 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V2); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_DROPPED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1133,36 +1172,34 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_dropped_keyspace_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_dropped_keyspace_v2.dump")); }); }); }); group("TABLE:", () { - test("created", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V2 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V2); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_CREATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1172,33 +1209,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_created_table_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_created_table_v2.dump")); }); }); test("dropped", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_DROPPED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1208,33 +1244,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_dropped_table_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_dropped_table_v2.dump")); }); }); test("updated", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V2 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V2); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_UPDATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1244,14 +1279,15 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_updated_table_v2.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_updated_table_v2.dump")); }); }); }); @@ -1260,23 +1296,20 @@ INSERT INTO test.type_test ( group("V3:", () { group("KEYSPACE:", () { - test("created", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_CREATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1286,33 +1319,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_created_keyspace_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_created_keyspace_v3.dump")); }); }); test("dropped", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_DROPPED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1322,36 +1354,34 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_dropped_keyspace_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_dropped_keyspace_v3.dump")); }); }); }); group("TABLE:", () { - test("created", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_CREATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1361,33 +1391,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_created_table_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_created_table_v3.dump")); }); }); test("dropped", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_DROPPED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1397,33 +1426,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_dropped_table_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_dropped_table_v3.dump")); }); }); test("updated", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_UPDATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, "type_test"); @@ -1433,36 +1461,34 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_updated_table_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_updated_table_v3.dump")); }); }); }); group("TYPE:", () { - test("created", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_CREATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1472,33 +1498,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_created_type_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_created_type_v3.dump")); }); }); test("dropped", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_DROPPED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1508,33 +1533,32 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_dropped_type_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_dropped_type_v3.dump")); }); }); test("updated", () { - cql.PoolConfiguration poolConfig = new cql.PoolConfiguration( - autoDiscoverNodes : true - , reconnectWaitTime : new Duration(milliseconds : 0) // Keep reconnect time low for our test - , protocolVersion : cql.ProtocolVersion.V3 - ); + autoDiscoverNodes: true, + reconnectWaitTime: new Duration( + milliseconds: 0) // Keep reconnect time low for our test + , + protocolVersion: cql.ProtocolVersion.V3); client = new cql.Client.fromHostList( - [ - "${SERVER_HOST}:${SERVER_PORT}" - ] - , poolConfig : poolConfig - ); + ["${SERVER_HOST}:${SERVER_PORT}"], + poolConfig: poolConfig); void handleMessage(cql.EventMessage message) { - expect(message.type, equals(cql.EventRegistrationType.SCHEMA_CHANGE)); + expect(message.type, + equals(cql.EventRegistrationType.SCHEMA_CHANGE)); expect(message.subType, equals(cql.EventType.SCHEMA_UPDATED)); expect(message.keyspace, equals("test")); expect(message.changedTable, isNull); @@ -1544,18 +1568,18 @@ INSERT INTO test.type_test ( } client.connectionPool.listenForServerEvents([ - cql.EventRegistrationType.SCHEMA_CHANGE + cql.EventRegistrationType.SCHEMA_CHANGE ]).listen(expectAsync(handleMessage)); - client.connectionPool - .connect() - .then((_) { + client.connectionPool.connect().then((_) { // Wait for event registration message to be received and then reply the event message - return new Future.delayed(new Duration(milliseconds: 100), () => server.replayFile(0, "event_schema_updated_type_v3.dump")); + return new Future.delayed( + new Duration(milliseconds: 100), + () => server.replayFile( + 0, "event_schema_updated_type_v3.dump")); }); }); }); - }); }); }); diff --git a/test/lib/connection_test.dart b/test/lib/connection_test.dart index ae28521..6c42163 100644 --- a/test/lib/connection_test.dart +++ b/test/lib/connection_test.dart @@ -8,8 +8,8 @@ import "mocks/compression.dart" as compress; import '../../lib/dart_cassandra_cql.dart' as cql; import '../../lib/src/exceptions.dart' as cqlEx; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } @@ -19,7 +19,6 @@ main({bool enableLogger : true}) { cql.Connection conn; group("Connection", () { - setUp(() { conn = null; return server.listen(SERVER_HOST, SERVER_PORT); @@ -27,42 +26,41 @@ main({bool enableLogger : true}) { tearDown(() { server.setCompression(null); - List cleanupFutures = [ - server.shutdown() - ]; + List cleanupFutures = [server.shutdown()]; if (conn != null) { - cleanupFutures.add(conn.close(drain : false)); + cleanupFutures.add(conn.close(drain: false)); } return Future.wait(cleanupFutures); }); - test("frame parsing exception should be wrapped in an ExceptionMessage", () { - cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V3 - ); + test("frame parsing exception should be wrapped in an ExceptionMessage", + () { + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V3); // We have modified this event message to use stream id 0 and // include a malformed INET field. This should trigger an exception when we try to parse it server.setReplayList(["malformed_frame_v3.dump"]); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e, trace) { expect(e, new isInstanceOf()); expect(e.message, equals("Could not decode INET type of length 6")); expect(trace, isNotNull); } - conn.open() - .then((_) => conn.execute(new cql.Query("SELECT * FROM test"))) - .catchError(expectAsync(handleError)); + conn + .open() + .then((_) => conn.execute(new cql.Query("SELECT * FROM test"))) + .catchError(expectAsync(handleError)); }); test("failure with reconnect attempts", () { cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , maxConnectionAttempts : 2 - , reconnectWaitTime : new Duration(milliseconds : 1) - ); - conn = new cql.Connection("conn-0", SERVER_HOST, 123, config : config); + protocolVersion: cql.ProtocolVersion.V2, + maxConnectionAttempts: 2, + reconnectWaitTime: new Duration(milliseconds: 1)); + conn = new cql.Connection("conn-0", SERVER_HOST, 123, config: config); void handleError(e) { expect(e, new isInstanceOf()); @@ -72,29 +70,30 @@ main({bool enableLogger : true}) { test("stream reservation timeout exception", () { cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , streamReservationTimeout : new Duration(milliseconds : 10) - , streamsPerConnection : 1 - ); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + protocolVersion: cql.ProtocolVersion.V2, + streamReservationTimeout: new Duration(milliseconds: 10), + streamsPerConnection: 1); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e) { expect(e, new isInstanceOf()); expect(e.toString(), startsWith("StreamReservationException")); } - conn.open() - .then((_) { + conn.open().then((_) { // Future f1 will grab our stream writer and wait for a server connection - conn.execute(new cql.Query("SELECT * FROM test")).catchError((_) { - }); + conn.execute(new cql.Query("SELECT * FROM test")).catchError((_) {}); // With a small delay, try a second query which should fail with a reservation timeout exception - return new Future.delayed(new Duration(milliseconds:10), () => conn.execute(new cql.Query("SELECT * FROM test"))); + return new Future.delayed(new Duration(milliseconds: 10), + () => conn.execute(new cql.Query("SELECT * FROM test"))); }).catchError(expectAsync(handleError)); }); test("Multiple connection attempts", () { - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V2); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V2); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); Future f1 = conn.open(); Future f2 = conn.open(); expect(f1, equals(f2)); @@ -103,8 +102,10 @@ main({bool enableLogger : true}) { }); test("V2 handshake", () { - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V2); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V2); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); return conn.open(); }); @@ -115,122 +116,121 @@ main({bool enableLogger : true}) { test("V2 handshake and keyspace selection", () { server.setReplayList(["void_result_v2.dump"]); - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V2); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V2); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); return conn.open(); }); test("V3 handshake", () { - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V3); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V3); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); return conn.open(); }); test("lost exception", () { cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V3 - , maxConnectionAttempts : 1 - ); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + protocolVersion: cql.ProtocolVersion.V3, maxConnectionAttempts: 1); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e) { expect(e, new isInstanceOf()); } - conn.open() - .then((_) => server.shutdown()) - .then((_) => conn.execute(new cql.Query("SELECT * FROM foo"))) - .catchError(expectAsync(handleError)); + conn + .open() + .then((_) => server.shutdown()) + .then((_) => conn.execute(new cql.Query("SELECT * FROM foo"))) + .catchError(expectAsync(handleError)); }); test("default keyspace (V2)", () { server.setReplayList(["set_keyspace_v2.dump"]); - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V3); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config, defaultKeyspace : "test"); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V3); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config, defaultKeyspace: "test"); expect(conn.open(), completes); }); test("query (V2)", () { server.setReplayList(["select_v2.dump"]); - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V3); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V3); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); expect( conn.open().then((_) { - return conn.execute(new cql.Query("SELECT * from test.type_test")); - }), - completion((cql.RowsResultMessage res) { - expect(res.rows.length, equals(1)); - Map row = res.rows.first; - Map expectedValues = { - "ascii_type" : "text4" - , "bigint_type" : 9223372036854775807 - , "bool_type" : true - , "inet_type" : new InternetAddress("192.168.169.102") - , "int_type" : 32238493 - , "list_type" : [100, 200] - , "map_type" : { - 100 : "the test" - , 200 : "the result" - } - , "set_type" : [100, 200] - , "text_type" : "This is a long UTF8 κείμενο" - , "uuid_type" : new cql.Uuid("550e8400-e29b-41d4-a716-446655440000") - , "varchar_type" : "Arbitary long text goes here" - , "varint_type" : -3123091212904812093120938120938120312890 - }; - expectedValues.forEach((String fieldName, Object fieldValue) { - expect(row[fieldName], equals(fieldValue)); - }); - return true; - }) - ); + return conn.execute(new cql.Query("SELECT * from test.type_test")); + }), completion((cql.RowsResultMessage res) { + expect(res.rows.length, equals(1)); + Map row = res.rows.first; + Map expectedValues = { + "ascii_type": "text4", + "bigint_type": 9223372036854775807, + "bool_type": true, + "inet_type": new InternetAddress("192.168.169.102"), + "int_type": 32238493, + "list_type": [100, 200], + "map_type": {100: "the test", 200: "the result"}, + "set_type": [100, 200], + "text_type": "This is a long UTF8 κείμενο", + "uuid_type": new cql.Uuid("550e8400-e29b-41d4-a716-446655440000"), + "varchar_type": "Arbitary long text goes here", + "varint_type": -3123091212904812093120938120938120312890 + }; + expectedValues.forEach((String fieldName, Object fieldValue) { + expect(row[fieldName], equals(fieldValue)); + }); + return true; + })); }); test("query (V3)", () { server.setReplayList(["select_v3.dump"]); - cql.PoolConfiguration config = new cql.PoolConfiguration(protocolVersion : cql.ProtocolVersion.V3); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + cql.PoolConfiguration config = + new cql.PoolConfiguration(protocolVersion: cql.ProtocolVersion.V3); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); expect( conn.open().then((_) { - return conn.execute(new cql.Query("SELECT * FROM test.user_profiles")); - }), - completion((cql.RowsResultMessage res) { - expect(res.rows.length, equals(1)); - Map row = res.rows.first; - Map expectedValues = { - "login": "test_user" - , "addresses": { - "home": { - "street": "123 Test Str." - , "city": "San Fransisco" - , "zip": 94110 - , "phones":[ - { - "number": "123 444 5555" - , "tags": [ - "direct line" - , "preferred" - ] - }, - { - "number": "123 444 6666" - , "tags": ["fax"] - } - ] - } + return conn.execute(new cql.Query("SELECT * FROM test.user_profiles")); + }), completion((cql.RowsResultMessage res) { + expect(res.rows.length, equals(1)); + Map row = res.rows.first; + Map expectedValues = { + "login": "test_user", + "addresses": { + "home": { + "street": "123 Test Str.", + "city": "San Fransisco", + "zip": 94110, + "phones": [ + { + "number": "123 444 5555", + "tags": ["direct line", "preferred"] + }, + { + "number": "123 444 6666", + "tags": ["fax"] } - , "email": "tuser@test.com" - , "first_name": "Test" - , "last_name": "User" - }; - expectedValues.forEach((String fieldName, Object fieldValue) { - expect(row[fieldName], equals(fieldValue)); - }); - return true; - }) - ); - + ] + } + }, + "email": "tuser@test.com", + "first_name": "Test", + "last_name": "User" + }; + expectedValues.forEach((String fieldName, Object fieldValue) { + expect(row[fieldName], equals(fieldValue)); + }); + return true; + })); }); group("with compression:", () { @@ -246,71 +246,79 @@ main({bool enableLogger : true}) { test("Codec encode exception handling", () { // Register codec for the mock server - cql.registerCodec(cql.Compression.SNAPPY.value, new compress.MockCompressionCodec(true)); + cql.registerCodec(cql.Compression.SNAPPY.value, + new compress.MockCompressionCodec(true)); cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , compression : cql.Compression.SNAPPY - ); + protocolVersion: cql.ProtocolVersion.V2, + compression: cql.Compression.SNAPPY); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e) { - expect(e.message, startsWith("An error occurred while invoking '${cql.Compression.SNAPPY}' codec (compression)")); + expect( + e.message, + startsWith( + "An error occurred while invoking '${cql.Compression.SNAPPY}' codec (compression)")); } - conn.open() - .then((_) => conn.execute(new cql.Query("SELECT * from test.type_test"))) - .catchError(expectAsync(handleError)); + conn + .open() + .then((_) => + conn.execute(new cql.Query("SELECT * from test.type_test"))) + .catchError(expectAsync(handleError)); }); test("server responds with unexpected compressed frame", () { server.setReplayList(["void_result_v2.dump"]); // Register codec for the mock server - cql.registerCodec(cql.Compression.SNAPPY.value, new compress.MockCompressionCodec()); + cql.registerCodec(cql.Compression.SNAPPY.value, + new compress.MockCompressionCodec()); cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - ); + protocolVersion: cql.ProtocolVersion.V2); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e) { - expect(e.message, equals("Server responded with an unexpected compressed frame")); + expect(e.message, + equals("Server responded with an unexpected compressed frame")); } - conn.open() - .then((_) => conn.execute(new cql.Query("SELECT * from test.type_test"))) - .catchError(expectAsync(handleError)); + conn + .open() + .then((_) => + conn.execute(new cql.Query("SELECT * from test.type_test"))) + .catchError(expectAsync(handleError)); }); test("Using a compression codec", () { server.setReplayList(["void_result_v2.dump"]); // Register codec - cql.registerCodec(cql.Compression.SNAPPY.value, new compress.MockCompressionCodec()); + cql.registerCodec(cql.Compression.SNAPPY.value, + new compress.MockCompressionCodec()); cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , compression : cql.Compression.SNAPPY - ); + protocolVersion: cql.ProtocolVersion.V2, + compression: cql.Compression.SNAPPY); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); expect( conn.open().then((_) { - return conn.execute(new cql.Query("SELECT * from test.type_test")); - }), - completion((cql.ResultMessage res) { - return res is cql.VoidResultMessage; - }) - ); + return conn.execute(new cql.Query("SELECT * from test.type_test")); + }), completion((cql.ResultMessage res) { + return res is cql.VoidResultMessage; + })); }); }); group("mock-LZ4:", () { - setUp(() { server.setCompression(cql.Compression.LZ4); }); @@ -325,23 +333,22 @@ main({bool enableLogger : true}) { server.setReplayList(["void_result_v2.dump"]); // Register codec - cql.registerCodec(cql.Compression.LZ4.value, new compress.MockCompressionCodec()); + cql.registerCodec( + cql.Compression.LZ4.value, new compress.MockCompressionCodec()); cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , compression : cql.Compression.LZ4 - ); + protocolVersion: cql.ProtocolVersion.V2, + compression: cql.Compression.LZ4); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); expect( conn.open().then((_) { - return conn.execute(new cql.Query("SELECT * from test.type_test")); - }), - completion((cql.ResultMessage res) { - return res is cql.VoidResultMessage; - }) - ); + return conn.execute(new cql.Query("SELECT * from test.type_test")); + }), completion((cql.ResultMessage res) { + return res is cql.VoidResultMessage; + })); }); test("Codec decode exception handling", () { @@ -350,33 +357,41 @@ main({bool enableLogger : true}) { // Register a mock codec for the mock server (pretend its LV4) and the SNAPPY codec // with throw on decode for our client. When we receive the server response a decode exception // will be thrown - cql.registerCodec(cql.Compression.LZ4.value, new compress.MockCompressionCodec()); - cql.registerCodec(cql.Compression.SNAPPY.value, new compress.MockCompressionCodec(false, true)); + cql.registerCodec( + cql.Compression.LZ4.value, new compress.MockCompressionCodec()); + cql.registerCodec(cql.Compression.SNAPPY.value, + new compress.MockCompressionCodec(false, true)); cql.PoolConfiguration config = new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , compression : cql.Compression.SNAPPY - ); + protocolVersion: cql.ProtocolVersion.V2, + compression: cql.Compression.SNAPPY); - conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, config : config); + conn = new cql.Connection("conn-0", SERVER_HOST, SERVER_PORT, + config: config); void handleError(e) { - expect(e.message, startsWith("An error occurred while invoking '${cql.Compression.SNAPPY}' codec (decompression)")); + expect( + e.message, + startsWith( + "An error occurred while invoking '${cql.Compression.SNAPPY}' codec (decompression)")); } - conn.open() - .then((_) => conn.execute(new cql.Query("SELECT * from test.type_test"))) - .catchError(expectAsync(handleError)); + conn + .open() + .then((_) => + conn.execute(new cql.Query("SELECT * from test.type_test"))) + .catchError(expectAsync(handleError)); }); test("Missing compression codec exception", () { expect( - () => new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , compression : cql.Compression.SNAPPY - ) - , throwsA((e) => e is ArgumentError && e.message == "A compression codec needs to be registered via registerCodec() for type 'snappy'") - ); + () => new cql.PoolConfiguration( + protocolVersion: cql.ProtocolVersion.V2, + compression: cql.Compression.SNAPPY), + throwsA((e) => + e is ArgumentError && + e.message == + "A compression codec needs to be registered via registerCodec() for type 'snappy'")); }); }); }); diff --git a/test/lib/enum_test.dart b/test/lib/enum_test.dart index 0d02934..b9b5b7c 100644 --- a/test/lib/enum_test.dart +++ b/test/lib/enum_test.dart @@ -13,23 +13,22 @@ Type _getGenericType(ClassMirror classMirror) { return classMirror.superclass.typeArguments.first.reflectedType; } -main({bool enableLogger : true}) { - +main({bool enableLogger: true}) { List enumClasses = [ - BatchType - , Consistency - , DataType - , ErrorCode - , EventRegistrationType - , EventType - , HeaderFlag - , HeaderVersion - , Opcode - , ProtocolVersion - , QueryFlag - , ResultType - , RowResultFlag - , Compression + BatchType, + Consistency, + DataType, + ErrorCode, + EventRegistrationType, + EventType, + HeaderFlag, + HeaderVersion, + Opcode, + ProtocolVersion, + QueryFlag, + ResultType, + RowResultFlag, + Compression ]; for (Type enumClass in enumClasses) { @@ -41,7 +40,10 @@ main({bool enableLogger : true}) { // Run a first pass to detect which methods we can use cm.declarations.forEach((Symbol enumSymbol, declarationMirror) { - String declName = enumSymbol.toString().replaceAll("Symbol(\"", "").replaceAll("\")", ""); + String declName = enumSymbol + .toString() + .replaceAll("Symbol(\"", "") + .replaceAll("\")", ""); if (declarationMirror is MethodMirror) { if (declName == "valueOf") { valueOfMirror = declarationMirror; @@ -54,33 +56,36 @@ main({bool enableLogger : true}) { }); // Nothing to test here... - if (nameOfMirror == null && valueOfMirror == null && toStringMirror == null) { + if (nameOfMirror == null && + valueOfMirror == null && + toStringMirror == null) { continue; } group("${enumClass.toString()}:", () { - // Generate tests for exceptions if (valueOfMirror != null) { group("Exceptions:", () { Object junkValue = _getMethodArgType(valueOfMirror) == String - ? "BADFOOD" - : 0xBADF00D; + ? "BADFOOD" + : 0xBADF00D; - Object formattedJunkValue = junkValue is String - ? "\"BADFOOD\"" - : "0xBADF00D"; + Object formattedJunkValue = + junkValue is String ? "\"BADFOOD\"" : "0xBADF00D"; test("valueOf(${formattedJunkValue}) throws ArgumentError", () { - expect(() => cm.invoke(#valueOf, [ junkValue ]).reflectee, throwsArgumentError); + expect(() => cm.invoke(#valueOf, [junkValue]).reflectee, + throwsArgumentError); }); }); } // Generate tests depending on which methods are available cm.declarations.forEach((Symbol enumSymbol, declarationMirror) { - - String declName = enumSymbol.toString().replaceAll("Symbol(\"", "").replaceAll("\")", ""); + String declName = enumSymbol + .toString() + .replaceAll("Symbol(\"", "") + .replaceAll("\")", ""); // Only process public Enum instances if (declarationMirror is MethodMirror || declarationMirror.isPrivate) { @@ -93,8 +98,10 @@ main({bool enableLogger : true}) { if (valueOfMirror != null) { test("valueOf(${declName}.value) == ${declName}", () { dynamic staticEnumInstance = cm.getField(enumSymbol).reflectee; - dynamic enumValue = cm.getField(enumSymbol).getField(#value).reflectee; - expect(cm.invoke(#valueOf, [ enumValue ]).reflectee, equals(staticEnumInstance)); + dynamic enumValue = + cm.getField(enumSymbol).getField(#value).reflectee; + expect(cm.invoke(#valueOf, [enumValue]).reflectee, + equals(staticEnumInstance)); }); } @@ -102,26 +109,27 @@ main({bool enableLogger : true}) { if (nameOfMirror != null) { test("nameOf(${declName}) == \"${declName}\"", () { dynamic staticEnumInstance = cm.getField(enumSymbol).reflectee; - expect(cm.invoke(#nameOf, [ staticEnumInstance ]).reflectee, equals(declName)); + expect(cm.invoke(#nameOf, [staticEnumInstance]).reflectee, + equals(declName)); }); } // Generate toString tests if (toStringMirror != null) { test("${declName}.toString()", () { - Enum staticEnumInstance = cm.getField(enumSymbol).reflectee; + Enum staticEnumInstance = + cm.getField(enumSymbol).reflectee; Object enumValue = staticEnumInstance.value; Object expectedValue = _getGenericType(cm) == String - ? enumValue - : "0x${(enumValue as int).toRadixString(16)}"; + ? enumValue + : "0x${(enumValue as int).toRadixString(16)}"; expect(staticEnumInstance.toString(), equals(expectedValue)); }); } - }); }); }); } -} \ No newline at end of file +} diff --git a/test/lib/frame_parser_test.dart b/test/lib/frame_parser_test.dart index 1f0e718..26ceb35 100644 --- a/test/lib/frame_parser_test.dart +++ b/test/lib/frame_parser_test.dart @@ -8,8 +8,8 @@ import '../../lib/src/types.dart'; import '../../lib/src/protocol.dart'; import '../../lib/src/exceptions.dart'; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } @@ -18,39 +18,31 @@ main({bool enableLogger : true}) { Stream frameGrabber; group("Frame parser (V2):", () { - setUp(() { writer = new FrameWriter(0, ProtocolVersion.V2); - streamController = new StreamController(sync : false); - frameGrabber = streamController.stream.transform(new FrameParser().transformer); + streamController = new StreamController(sync: false); + frameGrabber = + streamController.stream.transform(new FrameParser().transformer); }); test("READY message", () { - frameGrabber.listen(expectAsync((Frame frame) { expect(frame.header.opcode, equals(Opcode.READY)); })); - mock.writeMessage( - streamController - , Opcode.READY.value - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, Opcode.READY.value, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }); test("EVENT message (-1 streamId)", () { - frameGrabber.listen(expectAsync((Frame frame) { expect(frame.header.opcode, equals(Opcode.EVENT)); expect(frame.header.streamId, equals(-1)); })); - mock.writeMessage( - streamController - , Opcode.EVENT.value - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - , streamId : -1 - ); + mock.writeMessage(streamController, Opcode.EVENT.value, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2, + streamId: -1); }); test("InvalidFrame exception (illegal opcode)", () { @@ -59,20 +51,17 @@ main({bool enableLogger : true}) { expect(error, new isInstanceOf()); expect( (error.exception as DriverException).message, - equals("Unknown frame with opcode 0x${0xFF.toRadixString(16)} and payload size 0x0") - ); + equals( + "Unknown frame with opcode 0x${0xFF.toRadixString(16)} and payload size 0x0")); })); runZoned(() { frameGrabber.listen(((Frame frame) { throw new Exception("Should not have parsed ${frame}"); })); - mock.writeMessage( - streamController - , 0xFF - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, 0xFF, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }, onError: (e) { error = e; }); @@ -84,21 +73,18 @@ main({bool enableLogger : true}) { expect(error, new isInstanceOf()); expect( (error.exception as DriverException).message, - equals("Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes") - ); + equals( + "Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes")); })); runZoned(() { frameGrabber.listen(((Frame frame) { throw new Exception("Should not have parsed ${frame}"); })); - mock.writeMessage( - streamController - , Opcode.READY.value - , overrideLength : FrameHeader.MAX_LENGTH_IN_BYTES + 1 - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, Opcode.READY.value, + overrideLength: FrameHeader.MAX_LENGTH_IN_BYTES + 1, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }, onError: (e) { error = e; }); @@ -106,39 +92,31 @@ main({bool enableLogger : true}) { }); group("Frame parser (V3):", () { - setUp(() { writer = new FrameWriter(0, ProtocolVersion.V3); - streamController = new StreamController(sync : false); - frameGrabber = streamController.stream.transform(new FrameParser().transformer); + streamController = new StreamController(sync: false); + frameGrabber = + streamController.stream.transform(new FrameParser().transformer); }); test("READY message", () { - frameGrabber.listen(expectAsync((Frame frame) { expect(frame.header.opcode, equals(Opcode.READY)); })); - mock.writeMessage( - streamController - , Opcode.READY.value - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, Opcode.READY.value, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }); test("EVENT message (-1 streamId)", () { - frameGrabber.listen(expectAsync((Frame frame) { expect(frame.header.opcode, equals(Opcode.EVENT)); expect(frame.header.streamId, equals(-1)); })); - mock.writeMessage( - streamController - , Opcode.EVENT.value - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - , streamId : -1 - ); + mock.writeMessage(streamController, Opcode.EVENT.value, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2, + streamId: -1); }); test("InvalidFrame exception (illegal opcode)", () { @@ -147,20 +125,17 @@ main({bool enableLogger : true}) { expect(error, new isInstanceOf()); expect( (error.exception as DriverException).message, - equals("Unknown frame with opcode 0x${0xFF.toRadixString(16)} and payload size 0x0") - ); + equals( + "Unknown frame with opcode 0x${0xFF.toRadixString(16)} and payload size 0x0")); })); runZoned(() { frameGrabber.listen(((Frame frame) { throw new Exception("Should not have parsed ${frame}"); })); - mock.writeMessage( - streamController - , 0xFF - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, 0xFF, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }, onError: (e) { error = e; }); @@ -172,25 +147,21 @@ main({bool enableLogger : true}) { expect(error, new isInstanceOf()); expect( (error.exception as DriverException).message, - equals("Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes") - ); + equals( + "Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to read ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes")); })); runZoned(() { frameGrabber.listen(((Frame frame) { throw new Exception("Should not have parsed ${frame}"); })); - mock.writeMessage( - streamController - , Opcode.READY.value - , overrideLength : FrameHeader.MAX_LENGTH_IN_BYTES + 1 - , protocolVersion: ProtocolVersion.V2 - , headerVersion : HeaderVersion.RESPONSE_V2 - ); + mock.writeMessage(streamController, Opcode.READY.value, + overrideLength: FrameHeader.MAX_LENGTH_IN_BYTES + 1, + protocolVersion: ProtocolVersion.V2, + headerVersion: HeaderVersion.RESPONSE_V2); }, onError: (e) { error = e; }); }); }); - -} \ No newline at end of file +} diff --git a/test/lib/frame_writer_test.dart b/test/lib/frame_writer_test.dart index 7f81d43..bb65581 100644 --- a/test/lib/frame_writer_test.dart +++ b/test/lib/frame_writer_test.dart @@ -8,27 +8,27 @@ import '../../lib/src/protocol.dart'; import '../../lib/src/stream.dart'; import '../../lib/src/exceptions.dart'; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } FrameWriter frameWriter; - mock.MockChunkedOutputWriter mockOutputWriter = new mock.MockChunkedOutputWriter(); + mock.MockChunkedOutputWriter mockOutputWriter = + new mock.MockChunkedOutputWriter(); group("Frame writer:", () { - setUp(() { - frameWriter = new FrameWriter(0 - , ProtocolVersion.V2 - , withEncoder : new TypeEncoder(ProtocolVersion.V2, withWriter : mockOutputWriter) - ); + frameWriter = new FrameWriter(0, ProtocolVersion.V2, + withEncoder: new TypeEncoder(ProtocolVersion.V2, + withWriter: mockOutputWriter)); }); test("InvalidFrame exception (illegal length)", () { var error; try { - mockOutputWriter.forcedLengthInBytes = FrameHeader.MAX_LENGTH_IN_BYTES + 1; + mockOutputWriter.forcedLengthInBytes = + FrameHeader.MAX_LENGTH_IN_BYTES + 1; frameWriter.writeMessage(new StartupMessage(), null); } on Exception catch (e) { error = e; @@ -36,9 +36,8 @@ main({bool enableLogger : true}) { expect(error, new isInstanceOf()); expect( (error as DriverException).message, - equals("Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to write ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes") - ); + equals( + "Frame size cannot be larger than ${FrameHeader.MAX_LENGTH_IN_BYTES} bytes. Attempted to write ${FrameHeader.MAX_LENGTH_IN_BYTES + 1} bytes")); }); }); - -} \ No newline at end of file +} diff --git a/test/lib/mocks/compression.dart b/test/lib/mocks/compression.dart index f25241b..1c7c8be 100644 --- a/test/lib/mocks/compression.dart +++ b/test/lib/mocks/compression.dart @@ -4,14 +4,13 @@ import "dart:typed_data"; import "dart:convert"; class RotConverter extends Converter { - final bool throwOnConvert; final int _key; const RotConverter(this._key, this.throwOnConvert); Uint8List convert(Uint8List input) { - if( throwOnConvert ){ + if (throwOnConvert) { throw new Exception("Something has gone awfully wrong..."); } Uint8List result = new Uint8List(input.length); @@ -25,7 +24,6 @@ class RotConverter extends Converter { } class MockCompressionCodec extends Codec { - bool throwOnEncode; bool throwOnDecode; @@ -33,7 +31,8 @@ class MockCompressionCodec extends Codec { RotConverter _encoder; RotConverter _decoder; - MockCompressionCodec([this.throwOnEncode = false, this.throwOnDecode = false]) { + MockCompressionCodec( + [this.throwOnEncode = false, this.throwOnDecode = false]) { _encoder = new RotConverter(13, throwOnEncode); _decoder = new RotConverter(-13, throwOnDecode); } @@ -45,5 +44,4 @@ class MockCompressionCodec extends Codec { Converter get decoder { return _decoder; } - -} \ No newline at end of file +} diff --git a/test/lib/mocks/custom.dart b/test/lib/mocks/custom.dart index e6c090d..72b5930 100644 --- a/test/lib/mocks/custom.dart +++ b/test/lib/mocks/custom.dart @@ -13,27 +13,23 @@ class CustomJson implements CustomType { } class CustomJsonEncoder extends Converter { - Uint8List convert(CustomJson input) { return input.payload == null - ? null - : new Uint8List.fromList(JSON.encode(input.payload).codeUnits); + ? null + : new Uint8List.fromList(JSON.encode(input.payload).codeUnits); } } class CustomJsonDecoder extends Converter { - CustomJson convert(Uint8List input) { - Map payload = input == null - ? null - : new JsonDecoder().convert(UTF8.decode(input)); + Map payload = + input == null ? null : new JsonDecoder().convert(UTF8.decode(input)); return new CustomJson(payload); } } class CustomJsonCodec extends Codec { - final CustomJsonEncoder _encoder = new CustomJsonEncoder(); final CustomJsonDecoder _decoder = new CustomJsonDecoder(); @@ -44,5 +40,4 @@ class CustomJsonCodec extends Codec { Converter get decoder { return _decoder; } - -} \ No newline at end of file +} diff --git a/test/lib/mocks/mocks.dart b/test/lib/mocks/mocks.dart index 5aa4f68..5b95551 100644 --- a/test/lib/mocks/mocks.dart +++ b/test/lib/mocks/mocks.dart @@ -12,31 +12,31 @@ final Logger mockLogger = new Logger("MockLogger"); bool initializedLogger = false; void initLogger() { - if( initializedLogger == true ){ + if (initializedLogger == true) { return; } initializedLogger = true; hierarchicalLoggingEnabled = true; Logger.root.level = Level.ALL; Logger.root.onRecord.listen((LogRecord rec) { - print("[${rec.level.name}]\t[${rec.time}]\t[${rec.loggerName}]:\t${rec.message}"); + print( + "[${rec.level.name}]\t[${rec.time}]\t[${rec.loggerName}]:\t${rec.message}"); }); } -void writeMessage(Sink targetSink, int opcode, { -ProtocolVersion protocolVersion : ProtocolVersion.V2 -, HeaderVersion headerVersion : HeaderVersion.REQUEST_V2 -, int streamId : 0 -, int flags : 0 -, int overrideLength -, List data : const [] -}) { +void writeMessage(Sink targetSink, int opcode, + {ProtocolVersion protocolVersion: ProtocolVersion.V2, + HeaderVersion headerVersion: HeaderVersion.REQUEST_V2, + int streamId: 0, + int flags: 0, + int overrideLength, + List data: const []}) { TypeEncoder typeEncoder = new TypeEncoder(protocolVersion); // Allocate header buffer Uint8List buf = new Uint8List(protocolVersion == ProtocolVersion.V2 - ? FrameHeader.SIZE_IN_BYTES_V2 - : FrameHeader.SIZE_IN_BYTES_V3); + ? FrameHeader.SIZE_IN_BYTES_V2 + : FrameHeader.SIZE_IN_BYTES_V3); ByteData headerBytes = new ByteData.view(buf.buffer); // Encode header @@ -56,9 +56,8 @@ ProtocolVersion protocolVersion : ProtocolVersion.V2 // Encode remaining frame data headerBytes ..setUint8(offset++, opcode) - ..setUint32(offset++, overrideLength != null - ? overrideLength - : data.length); + ..setUint32( + offset++, overrideLength != null ? overrideLength : data.length); // Prepend the header to the writer buffer queue typeEncoder.writer.addFirst(buf); @@ -79,13 +78,10 @@ TypeDecoder createDecoder(TypeEncoder fromEncoder) { // Return decoder return new TypeDecoder.fromBuffer( - new ByteData.view(buffer.buffer), - fromEncoder.protocolVersion - ); + new ByteData.view(buffer.buffer), fromEncoder.protocolVersion); } class MockServer { - Compression _compression; ServerSocket _server; List clients = []; @@ -96,13 +92,16 @@ class MockServer { Future _replayFuture = new Future.value(); MockServer() { - List pathSegments = Platform.script.pathSegments.getRange(0, Platform.script.pathSegments.length - 1).toList(); + List pathSegments = Platform.script.pathSegments + .getRange(0, Platform.script.pathSegments.length - 1) + .toList(); // Hack: make sure we can find our dump files from the main test or from individual tests if (!pathSegments.contains("lib")) { pathSegments = new List.from(pathSegments); pathSegments.add("lib"); } - _pathToDumps = "${Platform.pathSeparator}${pathSegments.join(Platform.pathSeparator)}${Platform.pathSeparator}frame_dumps${Platform.pathSeparator}"; + _pathToDumps = + "${Platform.pathSeparator}${pathSegments.join(Platform.pathSeparator)}${Platform.pathSeparator}frame_dumps${Platform.pathSeparator}"; } Future shutdown() { @@ -110,12 +109,15 @@ class MockServer { _replayAuthDumpFileList = null; if (_server != null) { - mockLogger.info("Shutting down server [${_server.address}:${_server.port}]"); + mockLogger + .info("Shutting down server [${_server.address}:${_server.port}]"); List cleanupFutures = [] - ..add(_replayFuture) - ..addAll(clients.map((Socket client) => new Future.value(client.destroy()))) - ..add(_server.close().then((_) => new Future.delayed(new Duration(milliseconds:20), () => true))); + ..add(_replayFuture) + ..addAll( + clients.map((Socket client) => new Future.value(client.destroy()))) + ..add(_server.close().then((_) => + new Future.delayed(new Duration(milliseconds: 20), () => true))); clients.clear(); _server = null; @@ -129,7 +131,8 @@ class MockServer { void disconnectClient(int clientIndex) { if (clients.length > clientIndex) { Socket client = clients.removeAt(clientIndex); - mockLogger.info("Disconnecting client [${client.remoteAddress.host}:${client.remotePort}]"); + mockLogger.info( + "Disconnecting client [${client.remoteAddress.host}:${client.remotePort}]"); client.destroy(); } } @@ -139,19 +142,27 @@ class MockServer { Uint8List payload = new Uint8List.fromList(originalPayload); // Detect version - ProtocolVersion version = ( - payload[0] == HeaderVersion.REQUEST_V2.value || - payload[0] == HeaderVersion.RESPONSE_V2.value - ) - ? ProtocolVersion.V2 - : ProtocolVersion.V3; + ProtocolVersion version = (payload[0] == HeaderVersion.REQUEST_V2.value || + payload[0] == HeaderVersion.RESPONSE_V2.value) + ? ProtocolVersion.V2 + : ProtocolVersion.V3; // Create encoder for assembling compressed output TypeEncoder encoder = new TypeEncoder(version); // Create header and body views - ByteData headerView = new ByteData.view(payload.buffer, 0, version == ProtocolVersion.V2 ? FrameHeader.SIZE_IN_BYTES_V2 : FrameHeader.SIZE_IN_BYTES_V3); - Uint8List bodyView = new Uint8List.view(payload.buffer, version == ProtocolVersion.V2 ? FrameHeader.SIZE_IN_BYTES_V2 : FrameHeader.SIZE_IN_BYTES_V3, payload.lengthInBytes - headerView.lengthInBytes); + ByteData headerView = new ByteData.view( + payload.buffer, + 0, + version == ProtocolVersion.V2 + ? FrameHeader.SIZE_IN_BYTES_V2 + : FrameHeader.SIZE_IN_BYTES_V3); + Uint8List bodyView = new Uint8List.view( + payload.buffer, + version == ProtocolVersion.V2 + ? FrameHeader.SIZE_IN_BYTES_V2 + : FrameHeader.SIZE_IN_BYTES_V3, + payload.lengthInBytes - headerView.lengthInBytes); // Compress body Uint8List compressedBody = getCodec(_compression.value).encode(bodyView); @@ -160,11 +171,14 @@ class MockServer { encoder.writer.addLast(compressedBody); // Toggle header compression flag and update body size - headerView.setUint8(1, headerView.getUint8(1) | HeaderFlag.COMPRESSION.value); - headerView.setUint32(version == ProtocolVersion.V2 ? 4 : 5, encoder.writer.lengthInBytes); + headerView.setUint8( + 1, headerView.getUint8(1) | HeaderFlag.COMPRESSION.value); + headerView.setUint32( + version == ProtocolVersion.V2 ? 4 : 5, encoder.writer.lengthInBytes); // Prepend header to writer blocks - encoder.writer.addFirst(new Uint8List.view(headerView.buffer, 0, headerView.lengthInBytes)); + encoder.writer.addFirst( + new Uint8List.view(headerView.buffer, 0, headerView.lengthInBytes)); // concat everything together and cleanup Uint8List compressedOutput = encoder.writer.joinChunks(); @@ -179,15 +193,18 @@ class MockServer { Uint8List payload = new Uint8List.fromList(originalPayload); // Detect version - ProtocolVersion version = ( - payload[0] == HeaderVersion.REQUEST_V2.value || - payload[0] == HeaderVersion.RESPONSE_V2.value - ) - ? ProtocolVersion.V2 - : ProtocolVersion.V3; + ProtocolVersion version = (payload[0] == HeaderVersion.REQUEST_V2.value || + payload[0] == HeaderVersion.RESPONSE_V2.value) + ? ProtocolVersion.V2 + : ProtocolVersion.V3; // Path stream id - ByteData headerView = new ByteData.view(payload.buffer, 0, version == ProtocolVersion.V2 ? FrameHeader.SIZE_IN_BYTES_V2 : FrameHeader.SIZE_IN_BYTES_V3); + ByteData headerView = new ByteData.view( + payload.buffer, + 0, + version == ProtocolVersion.V2 + ? FrameHeader.SIZE_IN_BYTES_V2 + : FrameHeader.SIZE_IN_BYTES_V3); if (version == ProtocolVersion.V2) { headerView.setInt8(2, streamId); @@ -205,18 +222,18 @@ class MockServer { } File dumpFile = new File("${_pathToDumps}${filename}"); List response = _compression == null - ? _patchStreamId(dumpFile.readAsBytesSync(), streamId) - : _applyCompression(_patchStreamId(dumpFile.readAsBytesSync(), streamId)); + ? _patchStreamId(dumpFile.readAsBytesSync(), streamId) + : _applyCompression( + _patchStreamId(dumpFile.readAsBytesSync(), streamId)); clients[clientIndex].add(response); return clients[clientIndex].flush(); - } - return _replayFuture.then((_){ - return responseDelay != null - ? new Future.delayed(responseDelay, onReplay) - : onReplay(); - }); + return _replayFuture.then((_) { + return responseDelay != null + ? new Future.delayed(responseDelay, onReplay) + : onReplay(); + }); } Future listen(String host, int port) { @@ -231,7 +248,6 @@ class MockServer { }); return completer.future; - } void setCompression(Compression compressionAlgo) { @@ -239,52 +255,53 @@ class MockServer { } void setReplayList(Iterable list) { - _replayDumpFileList = new List.from(list); } void setAuthReplayList(Iterable list) { - _replayAuthDumpFileList = new List.from(list); } void _handleClientFrame(Socket client, Frame frame) { //mockLogger.fine("Client [${client.remoteAddress.host}:${client.remotePort}][SID: ${frame.header.streamId}] sent ${Opcode.nameOf(frame.header.opcode)} frame with len 0x${frame.header.length.toRadixString(16)}]"); // Complete handshake and event registration messages - if (frame.header.opcode == Opcode.STARTUP && (_replayAuthDumpFileList == null || _replayAuthDumpFileList.isEmpty)) { - writeMessage(client, Opcode.READY.value, streamId : frame.header.streamId); + if (frame.header.opcode == Opcode.STARTUP && + (_replayAuthDumpFileList == null || _replayAuthDumpFileList.isEmpty)) { + writeMessage(client, Opcode.READY.value, streamId: frame.header.streamId); } else if (frame.header.opcode == Opcode.REGISTER) { - writeMessage(client, Opcode.READY.value, streamId : frame.header.streamId); - } else if (_replayAuthDumpFileList != null && !_replayAuthDumpFileList.isEmpty) { + writeMessage(client, Opcode.READY.value, streamId: frame.header.streamId); + } else if (_replayAuthDumpFileList != null && + !_replayAuthDumpFileList.isEmpty) { // Respond with the next payload in replay list - _replayFuture = replayFile(clients.indexOf(client), _replayAuthDumpFileList.removeAt(0), frame.header.streamId); + _replayFuture = replayFile(clients.indexOf(client), + _replayAuthDumpFileList.removeAt(0), frame.header.streamId); } else if (_replayDumpFileList != null && !_replayDumpFileList.isEmpty) { // Respond with the next payload in replay list - _replayFuture = replayFile(clients.indexOf(client), _replayDumpFileList.removeAt(0), frame.header.streamId); + _replayFuture = replayFile(clients.indexOf(client), + _replayDumpFileList.removeAt(0), frame.header.streamId); } } void _handleClientError(Socket client, err, trace) { - mockLogger.info("Client [${client.remoteAddress.host}:${client.remotePort}] error ${err.exception.message}"); + mockLogger.info( + "Client [${client.remoteAddress.host}:${client.remotePort}] error ${err.exception.message}"); mockLogger.info("${err.stackTrace}"); } void _handleConnection(Socket client) { clients.add(client); - mockLogger.info("Client [${client.remoteAddress.host}:${client.remotePort}] connected"); + mockLogger.info( + "Client [${client.remoteAddress.host}:${client.remotePort}] connected"); client - .transform(new FrameParser().transformer) - .transform(new FrameDecompressor(_compression).transformer) - .listen( - (frame) => _handleClientFrame(client, frame) - , onError : (err, trace) => _handleClientError(client, err, trace) - ); + .transform(new FrameParser().transformer) + .transform(new FrameDecompressor(_compression).transformer) + .listen((frame) => _handleClientFrame(client, frame), + onError: (err, trace) => _handleClientError(client, err, trace)); } } class MockChunkedOutputWriter extends ChunkedOutputWriter { - int _forcedLengthInBytes = 0; set forcedLengthInBytes(int value) => _forcedLengthInBytes = value; @@ -293,7 +310,6 @@ class MockChunkedOutputWriter extends ChunkedOutputWriter { } class MockAuthenticator extends Authenticator { - String get authenticatorClass { return "com.achilleasa.FooAuthenticator"; } @@ -301,5 +317,4 @@ class MockAuthenticator extends Authenticator { Uint8List answerChallenge(Uint8List challenge) { return null; } - } diff --git a/test/lib/pool_config_test.dart b/test/lib/pool_config_test.dart index 1b6c080..7bb2962 100644 --- a/test/lib/pool_config_test.dart +++ b/test/lib/pool_config_test.dart @@ -4,43 +4,36 @@ import "package:unittest/unittest.dart"; import '../../lib/dart_cassandra_cql.dart' as cql; -main({bool enableLogger : true}) { - +main({bool enableLogger: true}) { group("Pool config:", () { test("invalid protocol", () { expect( - () => new cql.PoolConfiguration( - protocolVersion : null - ) - , throwsA( - predicate((ex) => ex is ArgumentError && ex.message == "Driver only supports protocol versions 2 and 3") - ) - ); + () => new cql.PoolConfiguration(protocolVersion: null), + throwsA(predicate((ex) => + ex is ArgumentError && + ex.message == "Driver only supports protocol versions 2 and 3"))); }); test("invalid streams per connection (V2 protocol)", () { expect( - () => new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V2 - , streamsPerConnection : 1024 - ) - , throwsA( - predicate((ex) => ex is ArgumentError && ex.message == "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 128 when using V2 prototcol") - ) - ); + () => new cql.PoolConfiguration( + protocolVersion: cql.ProtocolVersion.V2, + streamsPerConnection: 1024), + throwsA(predicate((ex) => + ex is ArgumentError && + ex.message == + "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 128 when using V2 prototcol"))); }); test("invalid protocol", () { expect( - () => new cql.PoolConfiguration( - protocolVersion : cql.ProtocolVersion.V3 - , streamsPerConnection : 65536 - ) - , throwsA( - predicate((ex) => ex is ArgumentError && ex.message == "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 3768 when using V3 prototcol") - ) - ); + () => new cql.PoolConfiguration( + protocolVersion: cql.ProtocolVersion.V3, + streamsPerConnection: 65536), + throwsA(predicate((ex) => + ex is ArgumentError && + ex.message == + "Invalid value for option 'streamsPerConnection'. Expected a value between 1 and 3768 when using V3 prototcol"))); }); - }); -} \ No newline at end of file +} diff --git a/test/lib/query_test.dart b/test/lib/query_test.dart index 7e351fc..5348175 100644 --- a/test/lib/query_test.dart +++ b/test/lib/query_test.dart @@ -8,49 +8,50 @@ import '../../lib/dart_cassandra_cql.dart' as cql; import "mocks/mocks.dart" as mock; import "mocks/custom.dart" as custom; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } group("Single query:", () { - test("invalid binding type exception", () { - expect(() => new cql.Query("SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", bindings : 'boo'), - throwsArgumentError - ); + expect( + () => new cql.Query("SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", + bindings: 'boo'), + throwsArgumentError); }); test("invalid placeholder exception for named2positionalQuery", () { - expect(() => new cql.Query("SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", bindings : ['boo']).positionalQuery, - throwsArgumentError - ); + expect( + () => new cql.Query("SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", + bindings: ['boo']).positionalQuery, + throwsArgumentError); }); test("missing custom type codec exception", () { - custom.CustomJson customJson = new custom.CustomJson({ - "foo" : "bar" - }); + custom.CustomJson customJson = new custom.CustomJson({"foo": "bar"}); cql.unregisterCodec(customJson.customTypeClass); expect( - () => new cql.Query("INSERT INTO test.custom_type (login, custom) VALUES ('bar', :baz )", bindings : { - 'baz' : customJson - }).expandedQuery, - throwsA((e) => e is ArgumentError && e.message == "No custom type codec specified for type with class: ${customJson.customTypeClass}") - ); - + () => new cql.Query( + "INSERT INTO test.custom_type (login, custom) VALUES ('bar', :baz )", + bindings: {'baz': customJson}).expandedQuery, + throwsA((e) => + e is ArgumentError && + e.message == + "No custom type codec specified for type with class: ${customJson.customTypeClass}")); }); test("named to positional query missing bindings exception", () { - cql.Query query = new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); + cql.Query query = new cql.Query( + "SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); expect(query, new isInstanceOf()); query.positionalQuery; - query.bindings = { - 'baz' : true - }; - expect(() => query.namedToPositionalBindings, - throwsA((e) => e is ArgumentError && e.message == "Missing binding for named placeholder 'boo'") - ); + query.bindings = {'baz': true}; + expect( + () => query.namedToPositionalBindings, + throwsA((e) => + e is ArgumentError && + e.message == "Missing binding for named placeholder 'boo'")); }); }); @@ -58,115 +59,117 @@ main({bool enableLogger : true}) { // test("with empty bindings", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1").expandedQuery, - "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - ); + new cql.Query("SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1") + .expandedQuery, + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1"); }); // group("of positional args:", () { test("ASCII/TEXT", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=? LIMIT 1", bindings : [ 'Simple string' ]).expandedQuery, - "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=? LIMIT 1", + bindings: ['Simple string']).expandedQuery, + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ 'Simple string' ]).expandedQuery, - "SELECT foo FROM bar WHERE baz='Simple string'" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", + bindings: ['Simple string']).expandedQuery, + "SELECT foo FROM bar WHERE baz='Simple string'"); expect( - new cql.Query("SELECT foo FROM bar WHERE skip='this?' AND baz=? OR boo=?", bindings : [ r"'Quoted' string", r"Yet \''Another'\' string" ]).expandedQuery, - r"SELECT foo FROM bar WHERE skip='this?' AND baz='''Quoted'' string' OR boo='Yet \''''Another''\'' string'" - ); + new cql.Query( + "SELECT foo FROM bar WHERE skip='this?' AND baz=? OR boo=?", + bindings: [r"'Quoted' string", r"Yet \''Another'\' string"]) + .expandedQuery, + r"SELECT foo FROM bar WHERE skip='this?' AND baz='''Quoted'' string' OR boo='Yet \''''Another''\'' string'"); }); test("INT/BIGINT/COUNTER", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ 1 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=1" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [1]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=1"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ -3812 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=-3812" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [-3812]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=-3812"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ 9223372036854775807 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=9223372036854775807" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", + bindings: [9223372036854775807]).expandedQuery, + "SELECT foo FROM bar WHERE baz=9223372036854775807"); }); test("BLOB", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ new Uint8List.fromList([0xFE, 0xed, 0xfA, 0xCe]) ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=0xfeedface" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + new Uint8List.fromList([0xFE, 0xed, 0xfA, 0xCe]) + ]).expandedQuery, + "SELECT foo FROM bar WHERE baz=0xfeedface"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ - new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x0D, 0xF0, 0x0C, 0x0F, 0xFE]) + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + new Uint8List.fromList( + [0x8B, 0xAD, 0xF0, 0x0D, 0xF0, 0x0C, 0x0F, 0xFE]) ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=0x8badf00df00c0ffe" - ); - + "SELECT foo FROM bar WHERE baz=0x8badf00df00c0ffe"); }); test("BOOLEAN", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=?", bindings : [ true, false ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=true AND boo=false" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=?", + bindings: [true, false]).expandedQuery, + "SELECT foo FROM bar WHERE baz=true AND boo=false"); }); test("DECIMAL/FLOAT/DOUBLE", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ 12.31415161718 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=12.31415161718" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", + bindings: [12.31415161718]).expandedQuery, + "SELECT foo FROM bar WHERE baz=12.31415161718"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ -12314151617.18 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=-12314151617.18" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", + bindings: [-12314151617.18]).expandedQuery, + "SELECT foo FROM bar WHERE baz=-12314151617.18"); }); test("TIMESTAMP", () { DateTime now = new DateTime.now(); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ now ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=${now.millisecondsSinceEpoch}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [now]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=${now.millisecondsSinceEpoch}"); }); test("INET", () { InternetAddress ipv4 = new InternetAddress("192.168.169.101"); InternetAddress ipv6 = new InternetAddress("2607:f0d0:1002:51::4"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=?", bindings : [ ipv4, ipv6 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz='${ipv4.address}' AND boo='${ipv6.address}'" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=?", + bindings: [ipv4, ipv6]).expandedQuery, + "SELECT foo FROM bar WHERE baz='${ipv4.address}' AND boo='${ipv6.address}'"); }); test("UUID", () { cql.Uuid uuid = new cql.Uuid.simple(); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ uuid ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=${uuid.value}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [uuid]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=${uuid.value}"); }); test("LIST", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ [3, 2, 1] ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=[3,2,1]" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + [3, 2, 1] + ]).expandedQuery, + "SELECT foo FROM bar WHERE baz=[3,2,1]"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ [r'lorem', r"Ips'um", null] ]).expandedQuery, - r"SELECT foo FROM bar WHERE baz=['lorem','Ips''um',null]" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + [r'lorem', r"Ips'um", null] + ]).expandedQuery, + r"SELECT foo FROM bar WHERE baz=['lorem','Ips''um',null]"); }); test("MAP", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ { - 'a' : 'abc', 'b' : "fe'f" - } ]).expandedQuery, - "SELECT foo FROM bar WHERE baz={'a': 'abc', 'b': 'fe''f'}" - ); - expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ { - 'a' : 1, 'b' : 2, 'c' : null - } ]).expandedQuery, - r"SELECT foo FROM bar WHERE baz={'a': 1, 'b': 2, 'c': null}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + {'a': 'abc', 'b': "fe'f"} + ]).expandedQuery, + "SELECT foo FROM bar WHERE baz={'a': 'abc', 'b': 'fe''f'}"); + expect( + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [ + {'a': 1, 'b': 2, 'c': null} + ]).expandedQuery, + r"SELECT foo FROM bar WHERE baz={'a': 1, 'b': 2, 'c': null}"); }); test("SET", () { Set set1 = new Set(); @@ -178,207 +181,169 @@ main({bool enableLogger : true}) { set2.add(2); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ set1 ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=['abc','fe''f']" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [set1]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=['abc','fe''f']"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ set2 ]).expandedQuery, - r"SELECT foo FROM bar WHERE baz=[1,2]" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [set2]) + .expandedQuery, + r"SELECT foo FROM bar WHERE baz=[1,2]"); }); test("TUPLE", () { cql.Tuple tuple = new cql.Tuple.fromIterable(['abc', "fe'f"]); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ tuple ]).expandedQuery, - "SELECT foo FROM bar WHERE baz=('abc','fe''f')" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [tuple]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz=('abc','fe''f')"); }); test("UDT", () { Map udt = { - 'a' : 1, - 'b' : "fe'f", - 'c' : [ - { - 'foo' : 'bar' - }, - { - 'foo' : 'baz' - } - ] + 'a': 1, + 'b': "fe'f", + 'c': [ + {'foo': 'bar'}, + {'foo': 'baz'} + ] }; expect( - new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings : [ udt ]).expandedQuery, - "SELECT foo FROM bar WHERE baz={'a': 1, 'b': 'fe''f', 'c': [{'foo': 'bar'},{'foo': 'baz'}]}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=?", bindings: [udt]) + .expandedQuery, + "SELECT foo FROM bar WHERE baz={'a': 1, 'b': 'fe''f', 'c': [{'foo': 'bar'},{'foo': 'baz'}]}"); }); test("Missing args exception", () { - expect(() => new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo = ?", bindings : [ 1 ]).expandedQuery - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Missing argument '1' from bindings list" - ) - )); + expect( + () => new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo = ?", + bindings: [1]).expandedQuery, + throwsA(predicate((e) => + e is ArgumentError && + e.message == "Missing argument '1' from bindings list"))); }); }); // group("of named args:", () { test("ASCII/TEXT", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz LIMIT 1", bindings : { - 'baz':'Simple string' - }).expandedQuery, - "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz LIMIT 1", + bindings: {'baz': 'Simple string'}).expandedQuery, + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz':'Simple string' - }).expandedQuery, - "SELECT foo FROM bar WHERE baz='Simple string'" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': 'Simple string'}).expandedQuery, + "SELECT foo FROM bar WHERE baz='Simple string'"); expect( - new cql.Query("SELECT foo FROM bar WHERE skip=':baz' AND baz=:baz OR boo=:boo", bindings : { - 'baz' : r"'Quoted' string", 'boo' : r"Yet \''Another'\' string" - }).expandedQuery, - r"SELECT foo FROM bar WHERE skip=':baz' AND baz='''Quoted'' string' OR boo='Yet \''''Another''\'' string'" - ); + new cql.Query("SELECT foo FROM bar WHERE skip=':baz' AND baz=:baz OR boo=:boo", + bindings: { + 'baz': r"'Quoted' string", + 'boo': r"Yet \''Another'\' string" + }).expandedQuery, + r"SELECT foo FROM bar WHERE skip=':baz' AND baz='''Quoted'' string' OR boo='Yet \''''Another''\'' string'"); }); test("INT/BIGINT/COUNTER", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' :1 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=1" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': 1}).expandedQuery, + "SELECT foo FROM bar WHERE baz=1"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : -3812 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=-3812" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': -3812}).expandedQuery, + "SELECT foo FROM bar WHERE baz=-3812"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : 9223372036854775807 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=9223372036854775807" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': 9223372036854775807}).expandedQuery, + "SELECT foo FROM bar WHERE baz=9223372036854775807"); }); test("CUSTOM", () { - custom.CustomJson customJson = new custom.CustomJson({ - "foo" : "bar" - }); + custom.CustomJson customJson = new custom.CustomJson({"foo": "bar"}); // Register custom type handler - cql.registerCodec(customJson.customTypeClass, new custom.CustomJsonCodec()); + cql.registerCodec( + customJson.customTypeClass, new custom.CustomJsonCodec()); expect( - new cql.Query("INSERT INTO test.custom_type (login, custom) VALUES ('bar', :baz )", bindings : { - 'baz' : customJson - }).expandedQuery, - "INSERT INTO test.custom_type (login, custom) VALUES ('bar', '{\"foo\":\"bar\"}' )" - ); - + new cql.Query( + "INSERT INTO test.custom_type (login, custom) VALUES ('bar', :baz )", + bindings: {'baz': customJson}).expandedQuery, + "INSERT INTO test.custom_type (login, custom) VALUES ('bar', '{\"foo\":\"bar\"}' )"); }); test("BLOB", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : new Uint8List.fromList([0xFE, 0xed, 0xfA, 0xCe]) + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + 'baz': new Uint8List.fromList([0xFE, 0xed, 0xfA, 0xCe]) }).expandedQuery, - "SELECT foo FROM bar WHERE baz=0xfeedface" - ); + "SELECT foo FROM bar WHERE baz=0xfeedface"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - "baz" : new Uint8List.fromList([0x8B, 0xAD, 0xF0, 0x0D, 0xF0, 0x0C, 0x0F, 0xFE]) + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + "baz": new Uint8List.fromList( + [0x8B, 0xAD, 0xF0, 0x0D, 0xF0, 0x0C, 0x0F, 0xFE]) }).expandedQuery, - "SELECT foo FROM bar WHERE baz=0x8badf00df00c0ffe" - ); - + "SELECT foo FROM bar WHERE baz=0x8badf00df00c0ffe"); }); test("BOOLEAN", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo", bindings : { - 'baz' : true, 'boo' : false - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=true AND boo=false" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo", + bindings: {'baz': true, 'boo': false}).expandedQuery, + "SELECT foo FROM bar WHERE baz=true AND boo=false"); }); test("DECIMAL/FLOAT/DOUBLE", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : 12.31415161718 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=12.31415161718" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': 12.31415161718}).expandedQuery, + "SELECT foo FROM bar WHERE baz=12.31415161718"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : -12314151617.18 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=-12314151617.18" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': -12314151617.18}).expandedQuery, + "SELECT foo FROM bar WHERE baz=-12314151617.18"); }); test("TIMESTAMP", () { DateTime now = new DateTime.now(); expect( - new cql.Query("SELECT foo FROM bar WHERE baz= :test", bindings : { - 'test' : now - }).expandedQuery, - "SELECT foo FROM bar WHERE baz= ${now.millisecondsSinceEpoch}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz= :test", + bindings: {'test': now}).expandedQuery, + "SELECT foo FROM bar WHERE baz= ${now.millisecondsSinceEpoch}"); }); test("INET", () { InternetAddress ipv4 = new InternetAddress("192.168.169.101"); InternetAddress ipv6 = new InternetAddress("2607:f0d0:1002:51::4"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo", bindings : { - 'boo': ipv6, 'baz': ipv4 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz='${ipv4.address}' AND boo='${ipv6.address}'" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo", + bindings: {'boo': ipv6, 'baz': ipv4}).expandedQuery, + "SELECT foo FROM bar WHERE baz='${ipv4.address}' AND boo='${ipv6.address}'"); }); test("UUID", () { cql.Uuid uuid = new cql.Uuid.simple(); expect(uuid.value, equals(uuid.toString())); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:uuid", bindings : { - 'uuid': uuid - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=${uuid.value}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:uuid", + bindings: {'uuid': uuid}).expandedQuery, + "SELECT foo FROM bar WHERE baz=${uuid.value}"); }); test("LIST", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : [3, 2, 1] + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + 'baz': [3, 2, 1] }).expandedQuery, - "SELECT foo FROM bar WHERE baz=[3,2,1]" - ); + "SELECT foo FROM bar WHERE baz=[3,2,1]"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : [r'lorem', r"Ips'um", null] + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + 'baz': [r'lorem', r"Ips'um", null] }).expandedQuery, - r"SELECT foo FROM bar WHERE baz=['lorem','Ips''um',null]" - ); + r"SELECT foo FROM bar WHERE baz=['lorem','Ips''um',null]"); }); test("MAP", () { expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : { - 'a' : 'abc', 'b' : "fe'f" - } + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + 'baz': {'a': 'abc', 'b': "fe'f"} }).expandedQuery, - "SELECT foo FROM bar WHERE baz={'a': 'abc', 'b': 'fe''f'}" - ); + "SELECT foo FROM bar WHERE baz={'a': 'abc', 'b': 'fe''f'}"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : { - 'a' : 1, 'b' : 2, 'c' : null - } + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings: { + 'baz': {'a': 1, 'b': 2, 'c': null} }).expandedQuery, - r"SELECT foo FROM bar WHERE baz={'a': 1, 'b': 2, 'c': null}" - ); + r"SELECT foo FROM bar WHERE baz={'a': 1, 'b': 2, 'c': null}"); }); test("SET", () { Set set1 = new Set(); @@ -390,70 +355,57 @@ main({bool enableLogger : true}) { set2.add(2); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : set1 - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=['abc','fe''f']" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': set1}).expandedQuery, + "SELECT foo FROM bar WHERE baz=['abc','fe''f']"); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : set2 - }).expandedQuery, - r"SELECT foo FROM bar WHERE baz=[1,2]" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': set2}).expandedQuery, + r"SELECT foo FROM bar WHERE baz=[1,2]"); }); test("TUPLE", () { cql.Tuple tuple = new cql.Tuple.fromIterable(['abc', "fe'f"]); expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : tuple - }).expandedQuery, - "SELECT foo FROM bar WHERE baz=('abc','fe''f')" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': tuple}).expandedQuery, + "SELECT foo FROM bar WHERE baz=('abc','fe''f')"); }); test("UDT", () { Map udt = { - 'a' : 1, - 'b' : "fe'f", - 'c' : [ - { - 'foo' : 'bar' - }, - { - 'foo' : 'baz' - } - ] + 'a': 1, + 'b': "fe'f", + 'c': [ + {'foo': 'bar'}, + {'foo': 'baz'} + ] }; expect( - new cql.Query("SELECT foo FROM bar WHERE baz=:baz", bindings : { - 'baz' : udt - }).expandedQuery, - "SELECT foo FROM bar WHERE baz={'a': 1, 'b': 'fe''f', 'c': [{'foo': 'bar'},{'foo': 'baz'}]}" - ); + new cql.Query("SELECT foo FROM bar WHERE baz=:baz", + bindings: {'baz': udt}).expandedQuery, + "SELECT foo FROM bar WHERE baz={'a': 1, 'b': 'fe''f', 'c': [{'foo': 'bar'},{'foo': 'baz'}]}"); }); group("Exceptions:", () { test("Missing args exception", () { - expect(() => new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo =:boo", bindings : { - 'boo' : 1 - }).expandedQuery - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Missing binding for named placeholder 'baz'" - ) - )); + expect( + () => new cql.Query( + "SELECT foo FROM bar WHERE baz=:baz AND boo =:boo", + bindings: {'boo': 1}).expandedQuery, + throwsA(predicate((e) => + e is ArgumentError && + e.message == "Missing binding for named placeholder 'baz'"))); }); test("Invalid placeholder exception", () { - expect(() => new cql.Query("SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", bindings : { - 'boo' : 1 - }).expandedQuery - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == 'Expected named placeholder to begin at offset 30' - ) - )); + expect( + () => new cql.Query( + "SELECT foo FROM bar WHERE baz=:\$ AND boo =:boo", + bindings: {'boo': 1}).expandedQuery, + throwsA(predicate((e) => + e is ArgumentError && + e.message == + 'Expected named placeholder to begin at offset 30'))); }); }); }); @@ -463,59 +415,48 @@ main({bool enableLogger : true}) { // test("mixed bindings", () { cql.BatchQuery batch = new cql.BatchQuery() - ..add(new cql.Query("SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1")) - ..add(new cql.Query("SELECT foo FROM bar WHERE baz=? LIMIT 1", bindings : [ 'Simple string' ])) - ..add(new cql.Query("SELECT foo FROM bar WHERE baz=:baz LIMIT 1", bindings : { - 'baz' : 'Simple string' - })); + ..add(new cql.Query( + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1")) + ..add(new cql.Query("SELECT foo FROM bar WHERE baz=? LIMIT 1", + bindings: ['Simple string'])) + ..add(new cql.Query("SELECT foo FROM bar WHERE baz=:baz LIMIT 1", + bindings: {'baz': 'Simple string'})); expect(batch, new isInstanceOf()); - expect( - batch.queryList.map((cql.Query q) => q.expandedQuery), - [ - "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - , "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - , "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" - ] - ); + expect(batch.queryList.map((cql.Query q) => q.expandedQuery), [ + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1", + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1", + "SELECT foo FROM bar WHERE baz='Simple string' LIMIT 1" + ]); }); }); group("V2, V3 compatibility:", () { test("named to positional query", () { - cql.Query query = new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); - expect( - query.positionalQuery, - "SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?" - ); + cql.Query query = new cql.Query( + "SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); + expect(query.positionalQuery, + "SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?"); }); test("positional to positional query", () { - cql.Query query = new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?"); - expect( - query.positionalQuery, - "SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?" - ); + cql.Query query = + new cql.Query("SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?"); + expect(query.positionalQuery, + "SELECT foo FROM bar WHERE baz=? AND boo=? AND baz2=?"); }); test("named to positional bindings", () { - cql.Query query = new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); + cql.Query query = new cql.Query( + "SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); query.positionalQuery; - query.bindings = { - 'baz' : true - , 'boo' : false - }; - expect( - query.namedToPositionalBindings, - [true, false, true] - ); + query.bindings = {'baz': true, 'boo': false}; + expect(query.namedToPositionalBindings, [true, false, true]); }); test("named to positional bindings (original bindings as a list)", () { - cql.Query query = new cql.Query("SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); + cql.Query query = new cql.Query( + "SELECT foo FROM bar WHERE baz=:baz AND boo=:boo AND baz2=:baz"); query.positionalQuery; - query.bindings = [ true, false, true ]; - expect( - query.namedToPositionalBindings, - [true, false, true] - ); + query.bindings = [true, false, true]; + expect(query.namedToPositionalBindings, [true, false, true]); }); }); -} \ No newline at end of file +} diff --git a/test/lib/serialization_test.dart b/test/lib/serialization_test.dart index dcdbd6c..e33def9 100644 --- a/test/lib/serialization_test.dart +++ b/test/lib/serialization_test.dart @@ -10,13 +10,12 @@ import '../../lib/src/types.dart'; import "mocks/mocks.dart" as mock; import 'mocks/custom.dart' as custom; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } - final custom.CustomJson customJsonInstance = new custom.CustomJson({ - }); + final custom.CustomJson customJsonInstance = new custom.CustomJson({}); group("Serialization", () { TypeEncoder encoder; @@ -33,157 +32,165 @@ main({bool enableLogger : true}) { }); group("TypeSpec:", () { - test("Missing key/valueSubTYpe", () { - expect(() => new TypeSpec(DataType.MAP) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "MAP type should specify TypeSpec instances for both its keys and values" - ) - )); - - expect(() => new TypeSpec(DataType.MAP, keySubType : new TypeSpec(DataType.ASCII)) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "MAP type should specify TypeSpec instances for both its keys and values" - ) - )); - - expect(() => new TypeSpec(DataType.MAP, valueSubType : new TypeSpec(DataType.ASCII)) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "MAP type should specify TypeSpec instances for both its keys and values" - ) - )); - + expect( + () => new TypeSpec(DataType.MAP), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "MAP type should specify TypeSpec instances for both its keys and values"))); + + expect( + () => new TypeSpec(DataType.MAP, + keySubType: new TypeSpec(DataType.ASCII)), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "MAP type should specify TypeSpec instances for both its keys and values"))); + + expect( + () => new TypeSpec(DataType.MAP, + valueSubType: new TypeSpec(DataType.ASCII)), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "MAP type should specify TypeSpec instances for both its keys and values"))); }); test("Missing valueSubType", () { - expect(() => new TypeSpec(DataType.LIST) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "LIST type should specify a TypeSpec instance for its values" - ) - )); - - expect(() => new TypeSpec(DataType.SET) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "SET type should specify a TypeSpec instance for its values" - ) - )); + expect( + () => new TypeSpec(DataType.LIST), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "LIST type should specify a TypeSpec instance for its values"))); + expect( + () => new TypeSpec(DataType.SET), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "SET type should specify a TypeSpec instance for its values"))); }); - }); test("Not instance of DateTime", () { Object input = "foo"; TypeSpec type = new TypeSpec(DataType.TIMESTAMP); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type TIMESTAMP to be an instance of DateTime" - ) - )); - + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type TIMESTAMP to be an instance of DateTime"))); }); test("Not instance of Uint8List or CustomType", () { Object input = "foo"; TypeSpec type = new TypeSpec(DataType.CUSTOM); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type CUSTOM to be an instance of Uint8List OR an instance of CustomType with a registered type handler" - ) - )); - - expect(() => encoder.writeTypedValue('test', new Uint16List.fromList([]), typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type CUSTOM to be an instance of Uint8List OR an instance of CustomType with a registered type handler" - ) - )); + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type CUSTOM to be an instance of Uint8List OR an instance of CustomType with a registered type handler"))); + + expect( + () => encoder.writeTypedValue('test', new Uint16List.fromList([]), + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type CUSTOM to be an instance of Uint8List OR an instance of CustomType with a registered type handler"))); unregisterCodec(customJsonInstance.customTypeClass); - expect(() => encoder.writeTypedValue('test', customJsonInstance, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "No custom type handler codec registered for custom type: ${customJsonInstance.customTypeClass}" - ) - )); + expect( + () => encoder.writeTypedValue('test', customJsonInstance, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "No custom type handler codec registered for custom type: ${customJsonInstance.customTypeClass}"))); type = new TypeSpec(DataType.BLOB); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type BLOB to be an instance of Uint8List" - ) - )); - + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type BLOB to be an instance of Uint8List"))); }); test("Not instance of InternetAddress", () { Object input = "foo"; TypeSpec type = new TypeSpec(DataType.INET); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type INET to be an instance of InternetAddress" - ) - )); - + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type INET to be an instance of InternetAddress"))); }); test("Not instance of Iterable", () { Object input = "foo"; - TypeSpec type = new TypeSpec(DataType.LIST, valueSubType : new TypeSpec(DataType.ASCII)); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type LIST to implement Iterable" - ) - )); - type = new TypeSpec(DataType.SET, valueSubType : new TypeSpec(DataType.ASCII)); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type SET to implement Iterable" - ) - )); - + TypeSpec type = new TypeSpec(DataType.LIST, + valueSubType: new TypeSpec(DataType.ASCII)); + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type LIST to implement Iterable"))); + type = new TypeSpec(DataType.SET, + valueSubType: new TypeSpec(DataType.ASCII)); + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type SET to implement Iterable"))); }); test("Not instance of Map", () { Object input = "foo"; - TypeSpec type = new TypeSpec(DataType.MAP, keySubType : new TypeSpec(DataType.ASCII), valueSubType : new TypeSpec(DataType.ASCII)); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type MAP to implement Map" - ) - )); + TypeSpec type = new TypeSpec(DataType.MAP, + keySubType: new TypeSpec(DataType.ASCII), + valueSubType: new TypeSpec(DataType.ASCII)); + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type MAP to implement Map"))); type = new TypeSpec(DataType.UDT); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type UDT to implement Map" - ) - )); + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type UDT to implement Map"))); }); test("Not instance of Tuple", () { Object input = ["foo"]; TypeSpec type = new TypeSpec(DataType.TUPLE); - expect(() => encoder.writeTypedValue('test', input, typeSpec : type, size : size) - , throwsA( - predicate( - (e) => e is ArgumentError && e.message == "Expected value for field 'test' of type TUPLE to be an instance of Tuple" - ) - )); - + expect( + () => encoder.writeTypedValue('test', input, + typeSpec: type, size: size), + throwsA(predicate((e) => + e is ArgumentError && + e.message == + "Expected value for field 'test' of type TUPLE to be an instance of Tuple"))); }); }); @@ -195,24 +202,21 @@ main({bool enableLogger : true}) { test("Consistency", () { Consistency input = Consistency.LOCAL_ONE; - encoder.writer.addLast(new Uint8List.fromList([ 0x00, input.value ])); + encoder.writer.addLast(new Uint8List.fromList([0x00, input.value])); Object output = mock.createDecoder(encoder).readConsistency(); expect(output, equals(input)); }); test("String list", () { - List input = [ "a", "foo", "f33dfAce"]; + List input = ["a", "foo", "f33dfAce"]; encoder.writeStringList(input, size); Object output = mock.createDecoder(encoder).readStringList(size); expect(output, equals(input)); }); test("String map", () { - Map input = { - "foo" : "bar" - , "baz00ka" : "f33df4ce" - }; + Map input = {"foo": "bar", "baz00ka": "f33df4ce"}; encoder.writeStringMap(input, size); Object output = mock.createDecoder(encoder).readStringMap(size); expect(output, equals(input)); @@ -220,14 +224,13 @@ main({bool enableLogger : true}) { test("String multimap", () { Map> input = { - "foo" : ["bar", "baz"] - , "baz00ka" : ["f33df4ce"] + "foo": ["bar", "baz"], + "baz00ka": ["f33df4ce"] }; encoder.writeStringMultiMap(input, size); Object output = mock.createDecoder(encoder).readStringMultiMap(size); expect(output, equals(input)); }); - }); group("(protocol V2):", () { @@ -239,8 +242,9 @@ main({bool enableLogger : true}) { test("UTF-8 STRING", () { Object input = "Test 123 AbC !@#ΤΕΣΤ"; TypeSpec type = new TypeSpec(DataType.TEXT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -248,8 +252,9 @@ main({bool enableLogger : true}) { test("ASCII STRING", () { Object input = "Test 123 AbC"; TypeSpec type = new TypeSpec(DataType.ASCII); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -257,8 +262,9 @@ main({bool enableLogger : true}) { test("UUID", () { Object input = new Uuid.simple(); TypeSpec type = new TypeSpec(DataType.UUID); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -266,61 +272,66 @@ main({bool enableLogger : true}) { test("TIMEUUID", () { Object input = new Uuid.timeBased(); TypeSpec type = new TypeSpec(DataType.TIMEUUID); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); group("CUSTOM:", () { - test("without type handler", () { - Object input = new Uint8List.fromList(new List.generate(10, (int index) => index * 2)); + Object input = new Uint8List.fromList( + new List.generate(10, (int index) => index * 2)); TypeSpec type = new TypeSpec(DataType.CUSTOM) ..customTypeClass = customJsonInstance.customTypeClass; - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("with type handler", () { // Register custom type handler - registerCodec('com.achilleasa.cassandra.cqltypes.Json', new custom.CustomJsonCodec()); + registerCodec('com.achilleasa.cassandra.cqltypes.Json', + new custom.CustomJsonCodec()); customJsonInstance.payload = { - "foo" : { - "bar" : "baz" - } + "foo": {"bar": "baz"} }; TypeSpec type = new TypeSpec(DataType.CUSTOM) ..customTypeClass = customJsonInstance.customTypeClass; - encoder.writeTypedValue('test', customJsonInstance, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', customJsonInstance, + typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, new isInstanceOf()); - expect((output as custom.CustomJson).payload, equals(customJsonInstance.payload)); + expect((output as custom.CustomJson).payload, + equals(customJsonInstance.payload)); }); - }); test("BLOB", () { - Object input = new Uint8List.fromList(new List.generate(10, (int index) => index * 2)); + Object input = new Uint8List.fromList( + new List.generate(10, (int index) => index * 2)); TypeSpec type = new TypeSpec(DataType.BLOB); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); group("COUNTER", () { - test("(positive)", () { Object input = 9223372036854775807; TypeSpec type = new TypeSpec(DataType.COUNTER); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -328,85 +339,86 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -1; TypeSpec type = new TypeSpec(DataType.COUNTER); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); test("TIMESTAMP", () { - Object input = new DateTime.fromMillisecondsSinceEpoch(1455746327000); TypeSpec type = new TypeSpec(DataType.TIMESTAMP); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); group("BOOLEAN", () { test("(true)", () { - Object input = true; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(false)", () { - Object input = false; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("BOOLEAN", () { test("(true)", () { - Object input = true; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(false)", () { - Object input = false; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("INET:", () { test("(ipv4)", () { Object input = new InternetAddress("192.168.169.101"); TypeSpec type = new TypeSpec(DataType.INET); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(ipv6)", () { - Object input = new InternetAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); + Object input = + new InternetAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); TypeSpec type = new TypeSpec(DataType.INET); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -417,8 +429,9 @@ main({bool enableLogger : true}) { test("(positive)", () { Object input = 2147483647; TypeSpec type = new TypeSpec(DataType.INT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -426,21 +439,21 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -21474836; TypeSpec type = new TypeSpec(DataType.INT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("BIGINT", () { - test("(positive)", () { Object input = 9223372036854775807; TypeSpec type = new TypeSpec(DataType.BIGINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -448,21 +461,21 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -922036854775807; TypeSpec type = new TypeSpec(DataType.BIGINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("FLOAT", () { - test("(positive)", () { Object input = 3.141516; TypeSpec type = new TypeSpec(DataType.FLOAT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); @@ -470,120 +483,122 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -3.12345; TypeSpec type = new TypeSpec(DataType.FLOAT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); - }); group("DOUBLE", () { - test("(positive)", () { Object input = 3.141516; TypeSpec type = new TypeSpec(DataType.DOUBLE); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); - }); test("(negative)", () { Object input = -3.12345; TypeSpec type = new TypeSpec(DataType.DOUBLE); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); - }); group("DECIMAL [fraction digits = ${DECIMAL_FRACTION_DIGITS}]", () { - test("(positive)", () { Object input = 3.123451234512345; TypeSpec type = new TypeSpec(DataType.DECIMAL); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, pow(10, -DECIMAL_FRACTION_DIGITS))); - }); test("(negative)", () { Object input = -3.123451234512345; TypeSpec type = new TypeSpec(DataType.DECIMAL); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, pow(10, -DECIMAL_FRACTION_DIGITS))); }); - }); group("VARINT", () { - test("(positive)", () { Object input = 12345678901234567890123; TypeSpec type = new TypeSpec(DataType.VARINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); - }); test("(negative)", () { Object input = -987677654324167384628746291873912873; TypeSpec type = new TypeSpec(DataType.VARINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); }); group("COLLECTIONS:", () { test("SET", () { - Object input = new Set.from([ -2, -1, 0, 1, 2 ]); - TypeSpec type = new TypeSpec(DataType.SET, valueSubType : new TypeSpec(DataType.INT)); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + Object input = new Set.from([-2, -1, 0, 1, 2]); + TypeSpec type = new TypeSpec(DataType.SET, + valueSubType: new TypeSpec(DataType.INT)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("LIST", () { - Object input = [ new DateTime.fromMillisecondsSinceEpoch(1455746327000), new DateTime.fromMillisecondsSinceEpoch(1455746327000) ]; - TypeSpec type = new TypeSpec(DataType.LIST, valueSubType : new TypeSpec(DataType.TIMESTAMP)); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + Object input = [ + new DateTime.fromMillisecondsSinceEpoch(1455746327000), + new DateTime.fromMillisecondsSinceEpoch(1455746327000) + ]; + TypeSpec type = new TypeSpec(DataType.LIST, + valueSubType: new TypeSpec(DataType.TIMESTAMP)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("MAP", () { Object input = { - "foo" : new DateTime.fromMillisecondsSinceEpoch(1455746327000), - "bar" : new DateTime.fromMillisecondsSinceEpoch(1455746327000) + "foo": new DateTime.fromMillisecondsSinceEpoch(1455746327000), + "bar": new DateTime.fromMillisecondsSinceEpoch(1455746327000) }; - TypeSpec type = new TypeSpec( - DataType.MAP - , keySubType : new TypeSpec(DataType.TEXT) - , valueSubType : new TypeSpec(DataType.TIMESTAMP) - ); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + TypeSpec type = new TypeSpec(DataType.MAP, + keySubType: new TypeSpec(DataType.TEXT), + valueSubType: new TypeSpec(DataType.TIMESTAMP)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); }); - }); group("(protocol V3):", () { @@ -594,8 +609,9 @@ main({bool enableLogger : true}) { test("UTF-8 STRING", () { Object input = "Test 123 AbC !@#ΤΕΣΤ"; TypeSpec type = new TypeSpec(DataType.TEXT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -603,8 +619,9 @@ main({bool enableLogger : true}) { test("ASCII STRING", () { Object input = "Test 123 AbC"; TypeSpec type = new TypeSpec(DataType.ASCII); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -612,8 +629,9 @@ main({bool enableLogger : true}) { test("UUID", () { Object input = new Uuid.simple(); TypeSpec type = new TypeSpec(DataType.UUID); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -621,37 +639,42 @@ main({bool enableLogger : true}) { test("TIMEUUID", () { Object input = new Uuid.timeBased(); TypeSpec type = new TypeSpec(DataType.TIMEUUID); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("CUSTOM", () { - Object input = new Uint8List.fromList(new List.generate(10, (int index) => index * 2)); + Object input = new Uint8List.fromList( + new List.generate(10, (int index) => index * 2)); TypeSpec type = new TypeSpec(DataType.CUSTOM); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("BLOB", () { - Object input = new Uint8List.fromList(new List.generate(10, (int index) => index * 2)); + Object input = new Uint8List.fromList( + new List.generate(10, (int index) => index * 2)); TypeSpec type = new TypeSpec(DataType.BLOB); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); group("COUNTER", () { - test("(positive)", () { Object input = 9223372036854775807; TypeSpec type = new TypeSpec(DataType.COUNTER); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -659,85 +682,86 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -1; TypeSpec type = new TypeSpec(DataType.COUNTER); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); test("TIMESTAMP", () { - Object input = new DateTime.fromMillisecondsSinceEpoch(1455746327000); TypeSpec type = new TypeSpec(DataType.TIMESTAMP); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); group("BOOLEAN", () { test("(true)", () { - Object input = true; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(false)", () { - Object input = false; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("BOOLEAN", () { test("(true)", () { - Object input = true; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(false)", () { - Object input = false; TypeSpec type = new TypeSpec(DataType.BOOLEAN); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("INET:", () { test("(ipv4)", () { Object input = new InternetAddress("192.168.169.101"); TypeSpec type = new TypeSpec(DataType.INET); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("(ipv6)", () { - Object input = new InternetAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); + Object input = + new InternetAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); TypeSpec type = new TypeSpec(DataType.INET); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -748,8 +772,9 @@ main({bool enableLogger : true}) { test("(positive)", () { Object input = 2147483647; TypeSpec type = new TypeSpec(DataType.INT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -757,21 +782,21 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -21474836; TypeSpec type = new TypeSpec(DataType.INT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("BIGINT", () { - test("(positive)", () { Object input = 9223372036854775807; TypeSpec type = new TypeSpec(DataType.BIGINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -779,21 +804,21 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -922036854775807; TypeSpec type = new TypeSpec(DataType.BIGINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); group("FLOAT", () { - test("(positive)", () { Object input = 3.141516; TypeSpec type = new TypeSpec(DataType.FLOAT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); @@ -801,115 +826,118 @@ main({bool enableLogger : true}) { test("(negative)", () { Object input = -3.12345; TypeSpec type = new TypeSpec(DataType.FLOAT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); - }); group("DOUBLE", () { - test("(positive)", () { Object input = 3.141516; TypeSpec type = new TypeSpec(DataType.DOUBLE); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); - }); test("(negative)", () { Object input = -3.12345; TypeSpec type = new TypeSpec(DataType.DOUBLE); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, 0.000001)); }); - }); group("DECIMAL [fraction digits = ${DECIMAL_FRACTION_DIGITS}]", () { - test("(positive)", () { Object input = 3.123451234512345; TypeSpec type = new TypeSpec(DataType.DECIMAL); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, pow(10, -DECIMAL_FRACTION_DIGITS))); - }); test("(negative)", () { Object input = -3.123451234512345; TypeSpec type = new TypeSpec(DataType.DECIMAL); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, closeTo(input, pow(10, -DECIMAL_FRACTION_DIGITS))); }); - }); group("VARINT", () { - test("(positive)", () { Object input = 12345678901234567890123; TypeSpec type = new TypeSpec(DataType.VARINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); - }); test("(negative)", () { Object input = -987677654324167384628746291873912873; TypeSpec type = new TypeSpec(DataType.VARINT); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); }); group("COLLECTIONS:", () { test("SET", () { - Object input = new Set.from([ -2, -1, 0, 1, 2 ]); - TypeSpec type = new TypeSpec(DataType.SET, valueSubType : new TypeSpec(DataType.INT)); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + Object input = new Set.from([-2, -1, 0, 1, 2]); + TypeSpec type = new TypeSpec(DataType.SET, + valueSubType: new TypeSpec(DataType.INT)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("LIST", () { - Object input = [ new DateTime.fromMillisecondsSinceEpoch(1455746327000), new DateTime.fromMillisecondsSinceEpoch(1455746327000) ]; - TypeSpec type = new TypeSpec(DataType.LIST, valueSubType : new TypeSpec(DataType.TIMESTAMP)); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + Object input = [ + new DateTime.fromMillisecondsSinceEpoch(1455746327000), + new DateTime.fromMillisecondsSinceEpoch(1455746327000) + ]; + TypeSpec type = new TypeSpec(DataType.LIST, + valueSubType: new TypeSpec(DataType.TIMESTAMP)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("MAP", () { Object input = { - "foo" : new DateTime.fromMillisecondsSinceEpoch(1455746327000), - "bar" : new DateTime.fromMillisecondsSinceEpoch(1455746327000) + "foo": new DateTime.fromMillisecondsSinceEpoch(1455746327000), + "bar": new DateTime.fromMillisecondsSinceEpoch(1455746327000) }; - TypeSpec type = new TypeSpec( - DataType.MAP - , keySubType : new TypeSpec(DataType.TEXT) - , valueSubType : new TypeSpec(DataType.TIMESTAMP) - ); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + TypeSpec type = new TypeSpec(DataType.MAP, + keySubType: new TypeSpec(DataType.TEXT), + valueSubType: new TypeSpec(DataType.TIMESTAMP)); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); @@ -917,23 +945,17 @@ main({bool enableLogger : true}) { test("UDT (nested)", () { Object input = { - "address" : "Elm street" - , "phones" : [ - { - "prefix" : 30 - , "phone" : "123456789" - }, - { - "prefix" : 1 - , "phone" : "800180023" - } - ] - , "tags" : { - "home" : { - "when" : new DateTime.fromMillisecondsSinceEpoch(1455746327000) - , "labels" : [ "red", "green", "blue" ] - } + "address": "Elm street", + "phones": [ + {"prefix": 30, "phone": "123456789"}, + {"prefix": 1, "phone": "800180023"} + ], + "tags": { + "home": { + "when": new DateTime.fromMillisecondsSinceEpoch(1455746327000), + "labels": ["red", "green", "blue"] } + } }; TypeSpec intType = new TypeSpec(DataType.INT); TypeSpec dateType = new TypeSpec(DataType.TIMESTAMP); @@ -943,32 +965,40 @@ main({bool enableLogger : true}) { ..udtFields["phone"] = stringType; TypeSpec tagType = new TypeSpec(DataType.UDT) ..udtFields["when"] = dateType - ..udtFields["labels"] = new TypeSpec(DataType.LIST, valueSubType : stringType); + ..udtFields["labels"] = + new TypeSpec(DataType.LIST, valueSubType: stringType); TypeSpec type = new TypeSpec(DataType.UDT) ..udtFields["address"] = stringType - ..udtFields["phones"] = new TypeSpec(DataType.LIST, valueSubType : phoneType) - ..udtFields["tags"] = new TypeSpec(DataType.MAP, keySubType : stringType, valueSubType : tagType); + ..udtFields["phones"] = + new TypeSpec(DataType.LIST, valueSubType: phoneType) + ..udtFields["tags"] = new TypeSpec(DataType.MAP, + keySubType: stringType, valueSubType: tagType); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); test("TUPLE", () { - Object input = new Tuple.fromIterable(["Test", 3.14, new DateTime.fromMillisecondsSinceEpoch(1455746327000)]); + Object input = new Tuple.fromIterable([ + "Test", + 3.14, + new DateTime.fromMillisecondsSinceEpoch(1455746327000) + ]); TypeSpec type = new TypeSpec(DataType.TUPLE) ..tupleFields.add(new TypeSpec(DataType.TEXT)) ..tupleFields.add(new TypeSpec(DataType.DOUBLE)) ..tupleFields.add(new TypeSpec(DataType.TIMESTAMP)); - encoder.writeTypedValue('test', input, typeSpec : type, size : size); - Object output = mock.createDecoder(encoder).readTypedValue(type, size : size); + encoder.writeTypedValue('test', input, typeSpec: type, size: size); + Object output = + mock.createDecoder(encoder).readTypedValue(type, size: size); expect(output, equals(input)); }); - }); }); } diff --git a/test/lib/type_test.dart b/test/lib/type_test.dart index b05667f..1932e5e 100644 --- a/test/lib/type_test.dart +++ b/test/lib/type_test.dart @@ -8,8 +8,8 @@ import '../../lib/src/types.dart'; import 'mocks/mocks.dart' as mock; import "mocks/custom.dart" as custom; -main({bool enableLogger : true}) { - if( enableLogger ){ +main({bool enableLogger: true}) { + if (enableLogger) { mock.initLogger(); } @@ -37,185 +37,126 @@ main({bool enableLogger : true}) { test("CUSTOM", () { custom.CustomJson customJson = new custom.CustomJson({}); TypeSpec ts = new TypeSpec(DataType.CUSTOM) - ..customTypeClass = customJson.customTypeClass; - expect(ts.toString(), equals("CustomType<${customJson.customTypeClass}>")); + ..customTypeClass = customJson.customTypeClass; + expect( + ts.toString(), equals("CustomType<${customJson.customTypeClass}>")); }); test("LIST", () { - TypeSpec ts = new TypeSpec( - DataType.LIST - , valueSubType : new TypeSpec(DataType.INET) - ); + TypeSpec ts = new TypeSpec(DataType.LIST, + valueSubType: new TypeSpec(DataType.INET)); expect(ts.toString(), equals("List")); }); test("SET", () { - TypeSpec ts = new TypeSpec( - DataType.SET - , valueSubType : new TypeSpec(DataType.TIMESTAMP) - ); + TypeSpec ts = new TypeSpec(DataType.SET, + valueSubType: new TypeSpec(DataType.TIMESTAMP)); expect(ts.toString(), equals("Set")); }); test("MAP", () { - TypeSpec ts = new TypeSpec( - DataType.MAP - , keySubType : new TypeSpec(DataType.TIMESTAMP) - , valueSubType : new TypeSpec(DataType.INT) - ); + TypeSpec ts = new TypeSpec(DataType.MAP, + keySubType: new TypeSpec(DataType.TIMESTAMP), + valueSubType: new TypeSpec(DataType.INT)); expect(ts.toString(), equals("Map")); }); test("UDT", () { - TypeSpec ts = new TypeSpec( - DataType.UDT - ) + TypeSpec ts = new TypeSpec(DataType.UDT) ..keyspace = "test" ..udtName = "phone" ..udtFields = { - "tags" : new TypeSpec( - DataType.LIST - , valueSubType : new TypeSpec(DataType.ASCII) - ) - }; + "tags": new TypeSpec(DataType.LIST, + valueSubType: new TypeSpec(DataType.ASCII)) + }; expect(ts.toString(), equals('{test.phone: {tags: List}}')); }); test("TUPLE", () { - TypeSpec ts = new TypeSpec( - DataType.TUPLE - ) + TypeSpec ts = new TypeSpec(DataType.TUPLE) ..tupleFields = [ - new TypeSpec(DataType.INT) - , new TypeSpec(DataType.ASCII) - , new TypeSpec(DataType.TIMESTAMP) - ]; + new TypeSpec(DataType.INT), + new TypeSpec(DataType.ASCII), + new TypeSpec(DataType.TIMESTAMP) + ]; expect(ts.toString(), equals('([INT, ASCII, TIMESTAMP])')); }); }); group("Type guess:", () { - test("BOOL", () { - expect( - DataType.guessForValue(true) - , equals(DataType.BOOLEAN) - ); - expect( - DataType.guessForValue(false) - , equals(DataType.BOOLEAN) - ); + expect(DataType.guessForValue(true), equals(DataType.BOOLEAN)); + expect(DataType.guessForValue(false), equals(DataType.BOOLEAN)); }); test("DOUBLE", () { - expect( - DataType.guessForValue(3.145) - , equals(DataType.DOUBLE) - ); + expect(DataType.guessForValue(3.145), equals(DataType.DOUBLE)); }); test("INT", () { - expect( - DataType.guessForValue(3) - , equals(DataType.INT) - ); + expect(DataType.guessForValue(3), equals(DataType.INT)); }); test("BIGINT", () { expect( - DataType.guessForValue(9223372036854775807) - , equals(DataType.BIGINT) - ); + DataType.guessForValue(9223372036854775807), equals(DataType.BIGINT)); }); test("VARINT", () { - expect( - DataType.guessForValue(9223372036854775807000000) - , equals(DataType.VARINT) - ); + expect(DataType.guessForValue(9223372036854775807000000), + equals(DataType.VARINT)); }); test("VARCHAR", () { - expect( - DataType.guessForValue("test123 123") - , equals(DataType.VARCHAR) - ); + expect(DataType.guessForValue("test123 123"), equals(DataType.VARCHAR)); }); test("UUID", () { - expect( - DataType.guessForValue(new Uuid.simple()) - , equals(DataType.UUID) - ); + expect(DataType.guessForValue(new Uuid.simple()), equals(DataType.UUID)); expect( - DataType.guessForValue(new Uuid.timeBased()) - , equals(DataType.UUID) - ); + DataType.guessForValue(new Uuid.timeBased()), equals(DataType.UUID)); - expect( - DataType.guessForValue(new Uuid.timeBased().toString()) - , equals(DataType.UUID) - ); + expect(DataType.guessForValue(new Uuid.timeBased().toString()), + equals(DataType.UUID)); }); test("BLOB", () { - expect( - DataType.guessForValue(new Uint8List.fromList([0xff])) - , equals(DataType.BLOB) - ); + expect(DataType.guessForValue(new Uint8List.fromList([0xff])), + equals(DataType.BLOB)); }); test("TIMESTAMP", () { - expect( - DataType.guessForValue(new DateTime.now()) - , equals(DataType.TIMESTAMP) - ); + expect(DataType.guessForValue(new DateTime.now()), + equals(DataType.TIMESTAMP)); }); test("INET", () { - expect( - DataType.guessForValue(new InternetAddress("127.0.0.1")) - , equals(DataType.INET) - ); + expect(DataType.guessForValue(new InternetAddress("127.0.0.1")), + equals(DataType.INET)); }); test("LIST", () { - expect( - DataType.guessForValue(["test123 123", 1, 2, 3.14]) - , equals(DataType.LIST) - ); + expect(DataType.guessForValue(["test123 123", 1, 2, 3.14]), + equals(DataType.LIST)); }); test("SET", () { - expect( - DataType.guessForValue(new Set.from(["a", "a", "b"])) - , equals(DataType.SET) - ); + expect(DataType.guessForValue(new Set.from(["a", "a", "b"])), + equals(DataType.SET)); }); test("MAP", () { - expect( - DataType.guessForValue({ - "foo" : "bar" - }) - , equals(DataType.MAP) - ); + expect(DataType.guessForValue({"foo": "bar"}), equals(DataType.MAP)); }); test("TUPLE", () { - expect( - DataType.guessForValue(new Tuple.fromIterable([1, 2, 3])) - , equals(DataType.TUPLE) - ); + expect(DataType.guessForValue(new Tuple.fromIterable([1, 2, 3])), + equals(DataType.TUPLE)); }); test("No guess", () { - expect( - DataType.guessForValue(new SocketException("foo")) - , isNull - ); + expect(DataType.guessForValue(new SocketException("foo")), isNull); }); - }); -} \ No newline at end of file +} diff --git a/test/run_all.dart b/test/run_all.dart index dc2b4be..a0f6ae2 100644 --- a/test/run_all.dart +++ b/test/run_all.dart @@ -12,7 +12,6 @@ import "lib/pool_config_test.dart" as poolConfig; import "lib/client_test.dart" as client; void main(List args) { - // Check if we need to disable our loggers bool enableLogger = args.indexOf('--enable-logger') != -1; @@ -22,43 +21,42 @@ void main(List args) { //useCompactVMConfiguration(); if (runAll || (new RegExp("enums")).hasMatch(allArgs)) { - enums.main(enableLogger : enableLogger); + enums.main(enableLogger: enableLogger); } if (runAll || (new RegExp("chunked-input-reader")).hasMatch(allArgs)) { - chunkedInputReader.main(enableLogger : enableLogger); + chunkedInputReader.main(enableLogger: enableLogger); } if (runAll || (new RegExp("serialization")).hasMatch(allArgs)) { - serialization.main(enableLogger : enableLogger); + serialization.main(enableLogger: enableLogger); } if (runAll || (new RegExp("frame-parser")).hasMatch(allArgs)) { - frameParser.main(enableLogger : enableLogger); + frameParser.main(enableLogger: enableLogger); } if (runAll || (new RegExp("frame-writer")).hasMatch(allArgs)) { - frameWriter.main(enableLogger : enableLogger); + frameWriter.main(enableLogger: enableLogger); } if (runAll || (new RegExp("connection")).hasMatch(allArgs)) { - connection.main(enableLogger : enableLogger); + connection.main(enableLogger: enableLogger); } if (runAll || (new RegExp("type-test")).hasMatch(allArgs)) { - typeTest.main(enableLogger : enableLogger); + typeTest.main(enableLogger: enableLogger); } if (runAll || (new RegExp("pool-config")).hasMatch(allArgs)) { - poolConfig.main(enableLogger : enableLogger); + poolConfig.main(enableLogger: enableLogger); } if (runAll || (new RegExp("query")).hasMatch(allArgs)) { - query.main(enableLogger : enableLogger); + query.main(enableLogger: enableLogger); } if (runAll || (new RegExp("client")).hasMatch(allArgs)) { - client.main(enableLogger : enableLogger); + client.main(enableLogger: enableLogger); } - -} \ No newline at end of file +}