From 9ec4c83cfcef68c95ed446a84746028d4da1775f Mon Sep 17 00:00:00 2001 From: Deven Joshi Date: Mon, 12 Apr 2021 18:44:30 +0530 Subject: [PATCH] fixed tests, null errors --- packages/stream_chat/lib/src/api/channel.dart | 93 +++++++++---------- .../stream_chat/lib/src/api/responses.g.dart | 4 +- .../stream_chat/lib/src/api/retry_policy.dart | 1 - .../stream_chat/lib/src/api/retry_queue.dart | 1 - .../stream_chat/lib/src/api/websocket.dart | 4 +- .../lib/src/attachment_file_uploader.dart | 4 +- packages/stream_chat/lib/src/client.dart | 35 ++++--- .../lib/src/db/chat_persistence_client.dart | 2 +- .../lib/src/extensions/rate_limit.dart | 2 +- .../lib/src/models/attachment_file.dart | 2 +- .../lib/src/models/channel_state.dart | 4 +- .../lib/src/models/serialization.dart | 2 +- packages/stream_chat/pubspec.yaml | 2 +- .../test/src/api/channel_test.dart | 18 ++-- .../test/src/api/requests_test.dart | 4 +- .../test/src/api/responses_test.dart | 42 ++++++--- .../stream_chat/test/src/client_test.dart | 6 +- packages/stream_chat/test/version_test.dart | 4 +- 18 files changed, 124 insertions(+), 106 deletions(-) diff --git a/packages/stream_chat/lib/src/api/channel.dart b/packages/stream_chat/lib/src/api/channel.dart index 7606bc9a..3782b4b9 100644 --- a/packages/stream_chat/lib/src/api/channel.dart +++ b/packages/stream_chat/lib/src/api/channel.dart @@ -78,63 +78,63 @@ class Channel { /// Channel configuration as a stream Stream? get configStream => - state?.channelStateStream?.map((cs) => cs!.channel?.config); + state?.channelStateStream.map((cs) => cs!.channel?.config); /// Channel user creator User? get createdBy => state?._channelState?.channel?.createdBy; /// Channel user creator as a stream Stream? get createdByStream => - state?.channelStateStream?.map((cs) => cs!.channel?.createdBy); + state?.channelStateStream.map((cs) => cs!.channel?.createdBy); /// Channel frozen status bool? get frozen => state?._channelState?.channel?.frozen; /// Channel frozen status as a stream Stream? get frozenStream => - state?.channelStateStream?.map((cs) => cs!.channel?.frozen); + state?.channelStateStream.map((cs) => cs!.channel?.frozen); /// Channel creation date DateTime? get createdAt => state?._channelState?.channel?.createdAt; /// Channel creation date as a stream Stream? get createdAtStream => - state?.channelStateStream?.map((cs) => cs!.channel?.createdAt); + state?.channelStateStream.map((cs) => cs!.channel?.createdAt); /// Channel last message date DateTime? get lastMessageAt => state?._channelState?.channel?.lastMessageAt; /// Channel last message date as a stream Stream? get lastMessageAtStream => - state?.channelStateStream?.map((cs) => cs!.channel?.lastMessageAt); + state?.channelStateStream.map((cs) => cs!.channel?.lastMessageAt); /// Channel updated date DateTime? get updatedAt => state?._channelState?.channel?.updatedAt; /// Channel updated date as a stream Stream? get updatedAtStream => - state?.channelStateStream?.map((cs) => cs!.channel?.updatedAt); + state?.channelStateStream.map((cs) => cs!.channel?.updatedAt); /// Channel deletion date DateTime? get deletedAt => state?._channelState?.channel?.deletedAt; /// Channel deletion date as a stream Stream? get deletedAtStream => - state?.channelStateStream?.map((cs) => cs!.channel?.deletedAt); + state?.channelStateStream.map((cs) => cs!.channel?.deletedAt); /// Channel member count int? get memberCount => state?._channelState?.channel?.memberCount; /// Channel member count as a stream Stream? get memberCountStream => - state?.channelStateStream?.map((cs) => cs!.channel?.memberCount); + state?.channelStateStream.map((cs) => cs!.channel?.memberCount); /// Channel id String? get id => state?._channelState?.channel?.id ?? _id; /// Channel id as a stream Stream? get idStream => - state?.channelStateStream?.map((cs) => cs!.channel?.id ?? _id); + state?.channelStateStream.map((cs) => cs!.channel?.id ?? _id); /// Channel cid String? get cid => state?._channelState?.channel?.cid ?? _cid; @@ -144,7 +144,7 @@ class Channel { /// Channel cid as a stream Stream? get cidStream => - state?.channelStateStream?.map((cs) => cs!.channel?.cid ?? _cid); + state?.channelStateStream.map((cs) => cs!.channel?.cid ?? _cid); /// Channel extra data Map? get extraData => @@ -152,7 +152,7 @@ class Channel { /// Channel extra data as a stream Stream?>? get extraDataStream => - state?.channelStateStream?.map((cs) => cs!.channel?.extraData); + state?.channelStateStream.map((cs) => cs!.channel?.extraData); /// The main Stream chat client StreamChatClient get client => _client; @@ -284,7 +284,7 @@ class Channel { it.copyWith(uploadState: UploadState.failed(error: e.toString())), ); }).whenComplete(() { - throttledUpdateAttachment?.cancel(); + throttledUpdateAttachment.cancel(); _cancelableAttachmentUploadRequest.remove(it.id); }); })).whenComplete(() { @@ -297,7 +297,7 @@ class Channel { /// Send a [message] to this channel. /// Waits for a [_messageAttachmentsUploadCompleter] to complete /// before actually sending the message. - Future sendMessage(Message message) async { + Future sendMessage(Message message) async { // Cancelling previous completer in case it's called again in the process // Eg. Updating the message while the previous call is in progress. _messageAttachmentsUploadCompleter @@ -305,7 +305,7 @@ class Channel { ?.completeError('Message Cancelled'); final quotedMessage = state?.messages?.firstWhereOrNull( - (m) => m.id == message?.quotedMessageId, + (m) => m.id == message.quotedMessageId, ); // ignore: parameter_assignments message = message.copyWith( @@ -318,7 +318,7 @@ class Channel { if (it.uploadState.isSuccess) return it; return it.copyWith(uploadState: const UploadState.preparing()); }, - )?.toList(), + ).toList(), ); if (message.parentId != null && message.id == null) { @@ -348,9 +348,8 @@ class Channel { message = await attachmentsUploadCompleter.future; } - final response = await (_client.sendMessage(message, id, type) - as FutureOr); - state?.addMessage(response.message!); + final response = await (_client.sendMessage(message, id, type)); + state?.addMessage(response!.message!); return response; } catch (error) { if (error is DioError && error.type != DioErrorType.response) { @@ -379,7 +378,7 @@ class Channel { if (it.uploadState.isSuccess) return it; return it.copyWith(uploadState: const UploadState.preparing()); }, - )?.toList(), + ).toList(), ); state?.addMessage(message); @@ -596,7 +595,7 @@ class Channel { ..removeWhere((it) => it.userId != user!.id); final newMessage = message.copyWith( - reactionCounts: {...message?.reactionCounts ?? {}} + reactionCounts: {...message.reactionCounts ?? {}} ..update(type, (value) { if (enforceUnique) return value; return value + 1; @@ -660,7 +659,7 @@ class Channel { r.type == reaction.type && r.messageId == reaction.messageId); - final ownReactions = [...latestReactions ?? []] + final ownReactions = [...latestReactions] ..removeWhere((it) => it.userId != user!.id); final newMessage = message.copyWith( @@ -867,7 +866,7 @@ class Channel { '$_channelURL/stop-watching', data: {}, ); - return _client.decode(response?.data, EmptyResponse.fromJson); + return _client.decode(response.data, EmptyResponse.fromJson); } /// List the message replies for a parent message @@ -878,10 +877,10 @@ class Channel { PaginationParams options, { bool preferOffline = false, }) async { - final cachedReplies = (await _client.chatPersistenceClient?.getReplies( + final cachedReplies = await _client.chatPersistenceClient?.getReplies( parentId, options: options, - ))!; + ); if (cachedReplies != null && cachedReplies.isNotEmpty) { state?.updateThreadInfo(parentId, cachedReplies); if (preferOffline) { @@ -1049,7 +1048,7 @@ class Channel { if (id != null) { payload['id'] = id; - } else if (state?.members?.isNotEmpty == true) { + } else if (state?.members.isNotEmpty == true) { payload['members'] = state!.members; } @@ -1222,7 +1221,7 @@ class ChannelClientState { ChannelState channelState, //ignore: unnecessary_parenthesis ) : _debouncedUpdatePersistenceChannelState = ((ChannelState state) => - _channel?._client?.chatPersistenceClient + _channel._client.chatPersistenceClient ?.updateChannelState(state)) .debounced(const Duration(seconds: 1)) { retryQueue = RetryQueue( @@ -1264,12 +1263,12 @@ class ChannelClientState { _channel._client.chatPersistenceClient ?.getChannelThreads(_channel.cid) - ?.then((threads) { + .then((threads) { _threads = threads; - })?.then((_) { + }).then((_) { _channel._client.chatPersistenceClient ?.getChannelStateByCid(_channel.cid) - ?.then((state) { + .then((state) { // Replacing the persistence state members with the latest // `channelState.members` as they may have changes over the time. updateChannelState(state.copyWith(members: channelState.members)); @@ -1309,8 +1308,8 @@ class ChannelClientState { return expiration.isBefore(DateTime.now()); }) == true) - ?.map((e) => e.id) - ?.toList(); + .map((e) => e.id) + .toList(); if (expiredAttachmentMessagesId?.isNotEmpty == true) { _channel.getMessagesById(expiredAttachmentMessagesId!); _updatedMessagesIds.addAll(expiredAttachmentMessagesId); @@ -1560,7 +1559,7 @@ class ChannelClientState { /// Channel members list List get members => _channelState!.members! - .map((e) => e!.copyWith(user: _channel.client.state!.users![e.user!.id!])) + .map((e) => e!.copyWith(user: _channel.client.state!.users[e.user!.id!])) .toList(); /// Channel members list as a stream @@ -1581,7 +1580,7 @@ class ChannelClientState { /// Channel watchers list List get watchers => _channelState!.watchers! - .map((e) => _channel.client.state!.users![e.id!] ?? e) + .map((e) => _channel.client.state!.users[e.id!] ?? e) .toList(); /// Channel watchers list as a stream @@ -1628,7 +1627,7 @@ class ChannelClientState { ...newThreads[parentId] ?.where((newMessage) => !messages!.any((m) => m.id == newMessage.id)) - ?.toList() ?? + .toList() ?? [], ...messages!, ]; @@ -1654,39 +1653,39 @@ class ChannelClientState { /// Update channelState with updated information void updateChannelState(ChannelState updatedState) { final newMessages = [ - ...updatedState?.messages ?? [], + ...updatedState.messages ?? [], ..._channelState?.messages ?.where((m) => updatedState.messages ?.any((newMessage) => newMessage.id == m.id) != true) - ?.toList() ?? + .toList() ?? [], ]..sort(_sortByCreatedAt as int Function(Message, Message)?); final newWatchers = [ - ...updatedState?.watchers ?? [], + ...updatedState.watchers ?? [], ..._channelState?.watchers ?.where((w) => updatedState.watchers ?.any((newWatcher) => newWatcher.id == w.id) != true) - ?.toList() ?? + .toList() ?? [], ]; final newMembers = [ - ...updatedState?.members ?? [], + ...updatedState.members ?? [], ]; final newReads = [ - ...updatedState?.read ?? [], + ...updatedState.read ?? [], ..._channelState?.read ?.where((r) => updatedState.read ?.any((newRead) => newRead.user!.id == r.user!.id) != true) - ?.toList() ?? + .toList() ?? [], ]; @@ -1730,12 +1729,12 @@ class ChannelClientState { set _channelState(ChannelState? v) { _channelStateController.add(v); - _debouncedUpdatePersistenceChannelState?.call([v]); + _debouncedUpdatePersistenceChannelState.call([v]); } /// The channel threads related to this channel - Map>? get threads => - _threadsController.value as Map>?; + Map>? get threads => _threadsController.value + ?.map((key, value) => MapEntry(key ?? '', value ?? [])); /// The channel threads related to this channel as a stream Stream?>> get threadsStream => @@ -1793,7 +1792,7 @@ class ChannelClientState { .on() .where((event) => event.user != null && - members?.any((m) => m.userId == event.user!.id) == true) + members.any((m) => m.userId == event.user!.id) == true) .listen( (event) { final newMembers = List.from(members); @@ -1841,7 +1840,7 @@ class ChannelClientState { final now = DateTime.now(); var expiredMessages = channelState!.pinnedMessages ?.where((m) => m.pinExpires?.isBefore(now) == true) - ?.toList() ?? + .toList() ?? []; if (expiredMessages.isNotEmpty) { expiredMessages = expiredMessages @@ -1876,7 +1875,7 @@ class ChannelClientState { /// Call this method to dispose this object void dispose() { - _debouncedUpdatePersistenceChannelState?.cancel(); + _debouncedUpdatePersistenceChannelState.cancel(); _unreadCountController.close(); retryQueue!.dispose(); _subscriptions.forEach((s) => s.cancel()); diff --git a/packages/stream_chat/lib/src/api/responses.g.dart b/packages/stream_chat/lib/src/api/responses.g.dart index 141534a5..849b6d1a 100644 --- a/packages/stream_chat/lib/src/api/responses.g.dart +++ b/packages/stream_chat/lib/src/api/responses.g.dart @@ -20,7 +20,7 @@ QueryChannelsResponse _$QueryChannelsResponseFromJson(Map json) { return QueryChannelsResponse() ..duration = json['duration'] as String? ..channels = (json['channels'] as List?) - ?.map((e) => ChannelState.fromJson(e as Map)) + ?.map((e) => ChannelState.fromJson(e as Map)) .toList(); } @@ -169,7 +169,7 @@ SearchMessagesResponse _$SearchMessagesResponseFromJson(Map json) { return SearchMessagesResponse() ..duration = json['duration'] as String? ..results = (json['results'] as List?) - ?.map((e) => GetMessageResponse.fromJson(e as Map)) + ?.map((e) => GetMessageResponse.fromJson(e as Map)) .toList(); } diff --git a/packages/stream_chat/lib/src/api/retry_policy.dart b/packages/stream_chat/lib/src/api/retry_policy.dart index 2eaf6ab5..f0f2c67b 100644 --- a/packages/stream_chat/lib/src/api/retry_policy.dart +++ b/packages/stream_chat/lib/src/api/retry_policy.dart @@ -1,4 +1,3 @@ -import 'package:meta/meta.dart'; import 'package:stream_chat/src/client.dart'; import 'package:stream_chat/src/exceptions.dart'; diff --git a/packages/stream_chat/lib/src/api/retry_queue.dart b/packages/stream_chat/lib/src/api/retry_queue.dart index a63a7d3a..e09c367b 100644 --- a/packages/stream_chat/lib/src/api/retry_queue.dart +++ b/packages/stream_chat/lib/src/api/retry_queue.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; -import 'package:meta/meta.dart'; import 'package:stream_chat/src/api/channel.dart'; import 'package:stream_chat/src/api/retry_policy.dart'; import 'package:stream_chat/src/event_type.dart'; diff --git a/packages/stream_chat/lib/src/api/websocket.dart b/packages/stream_chat/lib/src/api/websocket.dart index ba4d4271..b2208a13 100644 --- a/packages/stream_chat/lib/src/api/websocket.dart +++ b/packages/stream_chat/lib/src/api/websocket.dart @@ -153,9 +153,7 @@ class WebSocket { onError: (error, stacktrace) { _onConnectionError(error, stacktrace); }, - onDone: () { - _onDone(); - }, + onDone: _onDone, ); return _connectionCompleter.future; } diff --git a/packages/stream_chat/lib/src/attachment_file_uploader.dart b/packages/stream_chat/lib/src/attachment_file_uploader.dart index 42fab498..42df3fb2 100644 --- a/packages/stream_chat/lib/src/attachment_file_uploader.dart +++ b/packages/stream_chat/lib/src/attachment_file_uploader.dart @@ -70,7 +70,7 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) async { - final filename = file!.path?.split('/')?.last ?? file.name; + final filename = file!.path?.split('/').last ?? file.name; final mimeType = filename.mimeType; MultipartFile? multiPartFile; @@ -107,7 +107,7 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) async { - final filename = file!.path?.split('/')?.last ?? file.name; + final filename = file!.path?.split('/').last ?? file.name; final mimeType = filename.mimeType; MultipartFile? multiPartFile; diff --git a/packages/stream_chat/lib/src/client.dart b/packages/stream_chat/lib/src/client.dart index 5ea3030a..5117f7da 100644 --- a/packages/stream_chat/lib/src/client.dart +++ b/packages/stream_chat/lib/src/client.dart @@ -34,7 +34,7 @@ import 'package:uuid/uuid.dart'; typedef LogHandlerFunction = void Function(LogRecord record); /// Used for decoding [Map] data to a generic type `T`. -typedef DecoderFunction = T Function(Map?); +typedef DecoderFunction = T Function(Map); /// A function which can be used to request a Stream Chat API token from your /// own backend server. Function requires a single [userId]. @@ -268,9 +268,8 @@ class StreamChatClient { var stringData = options.data.toString(); if (options.data is FormData) { - final multiPart = (options.data as FormData).files[0]?.value; - stringData = - '${multiPart?.filename} - ${multiPart?.contentType}'; + final multiPart = (options.data as FormData).files[0].value; + stringData = '${multiPart.filename} - ${multiPart.contentType}'; } logger.info(''' @@ -408,7 +407,7 @@ class StreamChatClient { /// Connects the current user, this triggers a connection to the API. /// It returns a [Future] that resolves when the connection is setup. - Future connectUser(User user, String? token) async { + Future connectUser(User? user, String? token) async { if (_connectCompleter != null && !_connectCompleter!.isCompleted) { logger.warning('Already connecting'); throw Exception('Already connecting'); @@ -417,6 +416,14 @@ class StreamChatClient { _connectCompleter = Completer(); logger.info('connect user'); + + if (user == null) { + final e = Error(); + _connectCompleter! + .completeError(e, StackTrace.fromString('No user provided.')); + throw e; + } + state!.user = OwnUser.fromJson(user.toJson()); this.token = token; _anonymous = false; @@ -638,7 +645,7 @@ class StreamChatClient { bool waitForConnect = true, }) async* { final hash = base64.encode(utf8.encode( - '$filter${_asMap(sort)}$options${paginationParams?.toJson()}' + '$filter${_asMap(sort)}$options${paginationParams.toJson()}' '$messageLimit', )); @@ -731,7 +738,7 @@ class StreamChatClient { QueryChannelsResponse.fromJson, )!; - if ((res.channels ?? []).isEmpty && (paginationParams?.offset ?? 0) == 0) { + if ((res.channels ?? []).isEmpty && (paginationParams.offset) == 0) { logger.warning( ''' We could not find any channel for this query. @@ -758,7 +765,7 @@ class StreamChatClient { filter, channels.map((c) => c.channel!.cid).toList(), clearQueryCache: - paginationParams?.offset == null || paginationParams.offset == 0, + paginationParams.offset == null || paginationParams.offset == 0, ); state!.channels = updateData.key; @@ -976,8 +983,9 @@ class StreamChatClient { .then((res) => decode( res.data, ConnectGuestUserResponse.fromJson)) .whenComplete(() => _anonymous = false); + return connectUser( - (response?.user)!, + response?.user, response?.accessToken, ); } @@ -1008,7 +1016,7 @@ class StreamChatClient { Future _disconnect() async { logger.info('Client disconnecting'); - await _ws?.disconnect(); + await _ws.disconnect(); await _connectionStatusSubscription?.cancel(); } @@ -1427,7 +1435,7 @@ class ClientState { /// Used internally for optimistic update of unread count set totalUnreadCount(int? unreadCount) { - _totalUnreadCountController?.add(unreadCount ?? 0); + _totalUnreadCountController.add(unreadCount ?? 0); } void _listenChannelHidden() { @@ -1473,7 +1481,7 @@ class ClientState { void _updateUsers(List userList) { final newUsers = { - ...users ?? {}, + ...users, for (var user in userList) user!.id: user, }; _usersController.add(newUsers); @@ -1488,7 +1496,8 @@ class ClientState { Stream get userStream => _userController.stream; /// The current user - Map? get users => _usersController.value as Map?; + Map get users => + _usersController.value as Map; /// The current user as a stream Stream> get usersStream => _usersController.stream; diff --git a/packages/stream_chat/lib/src/db/chat_persistence_client.dart b/packages/stream_chat/lib/src/db/chat_persistence_client.dart index 6036c649..b3ea7c7e 100644 --- a/packages/stream_chat/lib/src/db/chat_persistence_client.dart +++ b/packages/stream_chat/lib/src/db/chat_persistence_client.dart @@ -213,7 +213,7 @@ abstract class ChatPersistenceClient { if (m.ownReactions != null) ...m.ownReactions!.map((r) => r.user), ]) - ?.expand((v) => v), + .expand((v) => v), if (cs.read != null) ...cs.read!.map((r) => r.user), if (cs.members != null) ...cs.members!.map((m) => m!.user), ]) diff --git a/packages/stream_chat/lib/src/extensions/rate_limit.dart b/packages/stream_chat/lib/src/extensions/rate_limit.dart index 8ed91481..bf54fe5c 100644 --- a/packages/stream_chat/lib/src/extensions/rate_limit.dart +++ b/packages/stream_chat/lib/src/extensions/rate_limit.dart @@ -124,7 +124,7 @@ class Debounce { Duration? maxWait, }) : _leading = leading, _trailing = trailing, - _wait = wait?.inMilliseconds ?? 0, + _wait = wait.inMilliseconds, _maxing = maxWait != null { if (_maxing) { _maxWait = math.max(maxWait!.inMilliseconds, _wait); diff --git a/packages/stream_chat/lib/src/models/attachment_file.dart b/packages/stream_chat/lib/src/models/attachment_file.dart index 8dac46f6..fa74d801 100644 --- a/packages/stream_chat/lib/src/models/attachment_file.dart +++ b/packages/stream_chat/lib/src/models/attachment_file.dart @@ -87,7 +87,7 @@ class AttachmentFile { final int? size; /// File extension for this file. - String? get extension => name?.split('.')?.last; + String? get extension => name?.split('.').last; /// Serialize to json Map toJson() => _$AttachmentFileToJson(this); diff --git a/packages/stream_chat/lib/src/models/channel_state.dart b/packages/stream_chat/lib/src/models/channel_state.dart index 64c88af7..c90e6298 100644 --- a/packages/stream_chat/lib/src/models/channel_state.dart +++ b/packages/stream_chat/lib/src/models/channel_state.dart @@ -43,8 +43,8 @@ class ChannelState { final List? read; /// Create a new instance from a json - static ChannelState fromJson(Map? json) => - _$ChannelStateFromJson(json!); + static ChannelState fromJson(Map json) => + _$ChannelStateFromJson(json); /// Serialize to json Map toJson() => _$ChannelStateToJson(this); diff --git a/packages/stream_chat/lib/src/models/serialization.dart b/packages/stream_chat/lib/src/models/serialization.dart index 48726d5e..d7cb0ad8 100644 --- a/packages/stream_chat/lib/src/models/serialization.dart +++ b/packages/stream_chat/lib/src/models/serialization.dart @@ -11,7 +11,7 @@ class Serialization { /// List of users to list of userIds static List? userIds(List? users) => - users?.map((u) => u.id)?.toList(); + users?.map((u) => u.id).toList(); /// Takes unknown json keys and puts them in the `extra_data` key static Map? moveToExtraDataFromRoot( diff --git a/packages/stream_chat/pubspec.yaml b/packages/stream_chat/pubspec.yaml index defc8db5..c854c327 100644 --- a/packages/stream_chat/pubspec.yaml +++ b/packages/stream_chat/pubspec.yaml @@ -23,7 +23,7 @@ dependencies: web_socket_channel: ^2.0.0 dev_dependencies: - build_runner: ^1.10.0 + build_runner: ^1.12.2 freezed: ^0.14.1+2 json_serializable: ^4.1.0 mocktail: ^0.1.1 diff --git a/packages/stream_chat/test/src/api/channel_test.dart b/packages/stream_chat/test/src/api/channel_test.dart index 058a8044..94990a7b 100644 --- a/packages/stream_chat/test/src/api/channel_test.dart +++ b/packages/stream_chat/test/src/api/channel_test.dart @@ -50,7 +50,7 @@ void main() { ), ); - await channelClient?.sendMessage(message); + await channelClient.sendMessage(message); verify(() => mockDio.post('/channels/messaging/testid/message', data: { @@ -80,7 +80,7 @@ void main() { statusCode: 200, requestOptions: FakeRequestOptions(), )); - await channelClient?.watch(); + await channelClient.watch(); when( () => mockDio.post( @@ -95,7 +95,7 @@ void main() { ), ); - await channelClient?.markRead(); + await channelClient.markRead(); verify(() => mockDio.post('/channels/messaging/testid/read', data: {})).called(1); @@ -124,7 +124,7 @@ void main() { ), ); - await channelClient?.getReplies('messageid', pagination); + await channelClient.getReplies('messageid', pagination); verify(() => mockDio.get('/messages/messageid/replies', queryParameters: pagination.toJson())).called(1); @@ -141,7 +141,7 @@ void main() { httpClient: mockDio, tokenProvider: (_) async => '', ); - Channel channelClient = client.channel('messaging', id: 'testid'); + final channelClient = client.channel('messaging', id: 'testid'); when(() => mockDio.post( any(), @@ -566,9 +566,7 @@ void main() { tokenProvider: (_) async => '', ); - if (client != null) { - client.state?.user = OwnUser(id: 'test-id'); - } + client.state?.user = OwnUser(id: 'test-id'); final channelClient = client.channel('messaging', id: 'testid'); const reactionType = 'test'; @@ -623,9 +621,7 @@ void main() { tokenProvider: (_) async => '', ); - if (client != null) { - client.state?.user = OwnUser(id: 'test-id'); - } + client.state?.user = OwnUser(id: 'test-id'); final channelClient = client.channel('messaging', id: 'testid'); diff --git a/packages/stream_chat/test/src/api/requests_test.dart b/packages/stream_chat/test/src/api/requests_test.dart index 1e46fee0..0e33b3d9 100644 --- a/packages/stream_chat/test/src/api/requests_test.dart +++ b/packages/stream_chat/test/src/api/requests_test.dart @@ -12,7 +12,9 @@ void main() { test('PaginationParams', () { const option = PaginationParams(); final j = option.toJson(); - expect(j, {'limit': 10, 'offset': 0}); + expect(j, containsPair('limit', 10)); + expect(j, containsPair('offset', 0)); + expect(j, contains('hash_code')); }); }); } diff --git a/packages/stream_chat/test/src/api/responses_test.dart b/packages/stream_chat/test/src/api/responses_test.dart index ad81aeff..f91248af 100644 --- a/packages/stream_chat/test/src/api/responses_test.dart +++ b/packages/stream_chat/test/src/api/responses_test.dart @@ -12,7 +12,8 @@ import 'package:stream_chat/stream_chat.dart'; void main() { group('src/api/responses', () { test('QueryChannelsResponse', () { - const jsonExample = r'''{ + const jsonExample = r''' + { "channels": [ { "channel": { @@ -3432,7 +3433,8 @@ void main() { }); test('SendReactionResponse', () { - const jsonExample = r'''{"message": { + const jsonExample = r''' + {"message": { "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3481,7 +3483,8 @@ void main() { }); test('UpdateUsersResponse', () { - const jsonExample = '''{"users": {"bbb19d9a-ee50-45bc-84e5-0584e79d0c9e":{ + const jsonExample = ''' + {"users": {"bbb19d9a-ee50-45bc-84e5-0584e79d0c9e":{ "id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e", "role": "user", "created_at": "2020-01-28T22:17:30.826259Z", @@ -3505,7 +3508,8 @@ void main() { }); test('GetMessagesByIdResponse', () { - const jsonExample = r'''{"messages":[{ + const jsonExample = r''' + {"messages":[{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3536,7 +3540,8 @@ void main() { }); test('SendActionResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3566,7 +3571,8 @@ void main() { }); test('UpdateMessageResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3596,7 +3602,8 @@ void main() { }); test('SendMessageResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3626,7 +3633,8 @@ void main() { }); test('GetMessageResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3656,7 +3664,8 @@ void main() { }); test('UpdateChannelResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3769,7 +3778,8 @@ void main() { }); test('InviteMembersResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3882,7 +3892,8 @@ void main() { }); test('RemoveMembersResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -3995,7 +4006,8 @@ void main() { }); test('AddMembersResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -4108,7 +4120,8 @@ void main() { }); test('AcceptInviteResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", @@ -4221,7 +4234,8 @@ void main() { }); test('RejectInviteResponse', () { - const jsonExample = r'''{"message":{ + const jsonExample = r''' + {"message":{ "id": "c6076f11-7768-4a04-bdf2-c43dddd6d666", "text": "What we don't know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.", "html": "\u003cp\u003eWhat we don’t know for sure is whether or not a step-daughter of the bear is assumed to be a farci hourglass.\u003c/p\u003e\n", diff --git a/packages/stream_chat/test/src/client_test.dart b/packages/stream_chat/test/src/client_test.dart index 6ae8ee3e..3c0a325c 100644 --- a/packages/stream_chat/test/src/client_test.dart +++ b/packages/stream_chat/test/src/client_test.dart @@ -21,7 +21,7 @@ class FakeRequestOptions extends Fake implements RequestOptions {} class MockHttpClientAdapter extends Mock implements HttpClientAdapter {} class Functions { - Future tokenProvider(String userId) => null; + Future tokenProvider(String userId) async => ''; } class MockFunctions extends Mock implements Functions {} @@ -155,7 +155,9 @@ void main() { 'sort': sortOptions, } ..addAll(options) - ..addAll(paginationParams.toJson())), + ..addAll(paginationParams + .toJson() + .map((key, value) => MapEntry(key, value as Object)))), }; when( diff --git a/packages/stream_chat/test/version_test.dart b/packages/stream_chat/test/version_test.dart index 55b1818a..9bbd446f 100644 --- a/packages/stream_chat/test/version_test.dart +++ b/packages/stream_chat/test/version_test.dart @@ -17,8 +17,8 @@ void main() { final String pubspecPath = '${Directory.current.path}/pubspec.yaml'; final String pubspec = File(pubspecPath).readAsStringSync(); final RegExp regex = RegExp('version:\s*(.*)'); - final RegExpMatch match = regex.firstMatch(pubspec); + final RegExpMatch? match = regex.firstMatch(pubspec); expect(match, isNotNull); - expect(PACKAGE_VERSION, match.group(1).trim()); + expect(PACKAGE_VERSION, match?.group(1)?.trim()); }); }