add core/api tests

Signed-off-by: Sahil Kumar <[email protected]>
This commit is contained in:
Sahil Kumar
2021-06-08 16:09:17 +05:30
parent bdfbc27917
commit 89f989003d
35 changed files with 1788 additions and 56 deletions
@@ -0,0 +1,136 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/attachment_file_uploader.dart';
import 'package:stream_chat/src/core/models/attachment_file.dart';
import 'package:test/test.dart';
import '../../fakes.dart';
import '../../matchers.dart';
import '../../mocks.dart';
import '../../utils.dart';
void main() {
late final client = MockHttpClient();
late StreamAttachmentFileUploader fileUploader;
setUp(() {
fileUploader = StreamAttachmentFileUploader(client);
registerFallbackValue<MultipartFile>(FakeMultiPartFile());
});
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
test('sendImage', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const path = '/channels/$channelType/$channelId/image';
final file = assetFile('test_image.jpeg');
final attachmentFile = AttachmentFile(
size: 333,
path: file.path,
bytes: file.readAsBytesSync(),
);
final multipartFile = await attachmentFile.toMultipartFile();
when(() => client.postFile(
path,
any(that: isSameMultipartFileAs(multipartFile)),
)).thenAnswer((_) async => successResponse(path, data: {
'file': 'test-file-url',
}));
final res = await fileUploader.sendImage(
attachmentFile,
channelId,
channelType,
);
expect(res, isNotNull);
expect(res.file, isNotNull);
expect(res.file, isNotEmpty);
verify(() => client.postFile(
path,
any(that: isSameMultipartFileAs(multipartFile)),
)).called(1);
verifyNoMoreInteractions(client);
});
test('sendFile', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const path = '/channels/$channelType/$channelId/file';
final file = assetFile('example.pdf');
final attachmentFile = AttachmentFile(
size: 333,
path: file.path,
bytes: file.readAsBytesSync(),
);
final multipartFile = await attachmentFile.toMultipartFile();
when(() => client.postFile(
path,
any(that: isSameMultipartFileAs(multipartFile)),
)).thenAnswer((_) async => successResponse(path, data: {
'file': 'test-file-url',
}));
final res = await fileUploader.sendFile(
attachmentFile,
channelId,
channelType,
);
expect(res, isNotNull);
expect(res.file, isNotNull);
expect(res.file, isNotEmpty);
verify(() => client.postFile(
path,
any(that: isSameMultipartFileAs(multipartFile)),
)).called(1);
verifyNoMoreInteractions(client);
});
test('deleteImage', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const path = '/channels/$channelType/$channelId/image';
const url = 'test-image-url';
when(() => client.delete(path, queryParameters: {'url': url})).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await fileUploader.deleteImage(url, channelId, channelType);
expect(res, isNotNull);
verify(() => client.delete(path, queryParameters: {'url': url})).called(1);
verifyNoMoreInteractions(client);
});
test('deleteFile', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const path = '/channels/$channelType/$channelId/file';
const url = 'test-file-url';
when(() => client.delete(path, queryParameters: {'url': url})).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await fileUploader.deleteFile(url, channelId, channelType);
expect(res, isNotNull);
verify(() => client.delete(path, queryParameters: {'url': url})).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,492 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/channel_api.dart';
import 'package:stream_chat/src/core/models/channel_model.dart';
import 'package:stream_chat/src/core/models/channel_state.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
String _getChannelUrl(String channelId, String channelType) =>
'/channels/$channelType/$channelId';
ChannelState _generateChannelState(
String channelId,
String channelType,
) {
final channel = ChannelModel(id: channelId, type: channelType);
final messages = List.generate(
3,
(index) => Message(
id: 'test-message-id-$index',
text: 'test-message-text-$index',
),
);
final members = List.generate(
3,
(index) => Member(userId: 'test-user-id-$index'),
);
final reads = List.generate(
3,
(index) => Read(
lastRead: DateTime.now(),
user: User(id: 'test-user-id-$index'),
),
);
final watchers = List.generate(
3,
(index) => User(id: 'test-user-id-$index'),
);
final state = ChannelState(
channel: channel,
messages: messages,
pinnedMessages: messages,
members: members,
read: reads,
watchers: watchers,
watcherCount: watchers.length,
);
return state;
}
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late ChannelApi channelApi;
setUp(() {
channelApi = ChannelApi(client);
});
test('queryChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const channelData = <String, Object>{'name': 'test-channel'};
const messagePagination = PaginationParams();
const membersPagination = PaginationParams();
const watchersPagination = PaginationParams();
const channelPath = '/channels/$channelType/$channelId';
const path = '$channelPath/query';
final channelState = _generateChannelState(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(
path,
data: channelState.toJson(),
));
final res = await channelApi.queryChannel(
channelType,
channelId: channelId,
channelData: channelData,
messagesPagination: messagePagination,
membersPagination: membersPagination,
watchersPagination: watchersPagination,
);
expect(res, isNotNull);
expect(res.messages.length, channelState.messages.length);
expect(res.pinnedMessages.length, channelState.pinnedMessages.length);
expect(res.members.length, channelState.members.length);
expect(res.read.length, channelState.read.length);
expect(res.watchers.length, channelState.watchers.length);
expect(res.watcherCount, channelState.watcherCount);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('queryChannels', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final filter = Filter.in_('cid', const ['test-cid']);
const sort = [SortOption<ChannelModel>('test-field')];
const memberLimit = 33;
const messageLimit = 33;
const path = '/channels';
final channelState = _generateChannelState(channelId, channelType);
when(() => client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(
path,
data: {
'channels': [channelState.toJson()]
},
));
final res = await channelApi.queryChannels(
filter: filter,
sort: sort,
memberLimit: memberLimit,
messageLimit: messageLimit,
);
expect(res, isNotNull);
expect(res.channels, isNotEmpty);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('markAllRead', () async {
const path = 'channels/read';
when(() => client.post(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.markAllRead();
expect(res, isNotNull);
verify(() => client.post(path)).called(1);
verifyNoMoreInteractions(client);
});
test('updateChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const data = {'name': 'test-channel-name'};
final message = Message(id: 'test-message-id', text: 'channel-updated');
final path = _getChannelUrl(channelId, channelType);
final channelModel = ChannelModel(
id: channelId,
type: channelType,
extraData: data,
);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.updateChannel(
channelId,
channelType,
data,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('updateChannelPartial', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const data = {'name': 'test-channel-name'};
final path = _getChannelUrl(channelId, channelType);
final channelModel = ChannelModel(
id: channelId,
type: channelType,
extraData: data,
);
when(() => client.patch(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
}));
final res = await channelApi.updateChannelPartial(
channelId,
channelType,
data,
);
expect(res, isNotNull);
verify(() => client.patch(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('acceptChannelInvite', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final message = Message(id: 'test-message-id', text: 'channel-accepted');
final channelModel = ChannelModel(id: channelId, type: channelType);
final path = _getChannelUrl(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.acceptChannelInvite(
channelId,
channelType,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('rejectChannelInvite', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final message = Message(id: 'test-message-id', text: 'channel-rejected');
final channelModel = ChannelModel(id: channelId, type: channelType);
final path = _getChannelUrl(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.rejectChannelInvite(
channelId,
channelType,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('inviteChannelMembers', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const memberIds = ['test-member-id-1', 'test-member-id-2'];
final channelModel = ChannelModel(id: channelId, type: channelType);
final message = Message(id: 'test-message-id', text: 'members-invited');
final path = _getChannelUrl(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.inviteChannelMembers(
channelId,
channelType,
memberIds,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('addMembers', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const memberIds = ['test-member-id-1', 'test-member-id-2'];
final channelModel = ChannelModel(id: channelId, type: channelType);
final message = Message(id: 'test-message-id', text: 'members-added');
final path = _getChannelUrl(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.addMembers(
channelId,
channelType,
memberIds,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('removeMembers', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const memberIds = ['test-member-id-1', 'test-member-id-2'];
final channelModel = ChannelModel(id: channelId, type: channelType);
final message = Message(id: 'test-message-id', text: 'members-removed');
final path = _getChannelUrl(channelId, channelType);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'channel': channelModel.toJson(),
'message': message.toJson(),
}));
final res = await channelApi.removeMembers(
channelId,
channelType,
memberIds,
message: message,
);
expect(res, isNotNull);
expect(res.channel.cid, channelModel.cid);
expect(res.message?.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('sendEvent', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final event = Event(type: 'event.test');
final path = '${_getChannelUrl(channelId, channelType)}/event';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.sendEvent(channelId, channelType, event);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('deleteChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final path = _getChannelUrl(channelId, channelType);
when(() => client.delete(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.deleteChannel(channelId, channelType);
expect(res, isNotNull);
verify(() => client.delete(path)).called(1);
verifyNoMoreInteractions(client);
});
test('truncateChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final path = '${_getChannelUrl(channelId, channelType)}/truncate';
when(() => client.post(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.truncateChannel(channelId, channelType);
expect(res, isNotNull);
verify(() => client.post(path)).called(1);
verifyNoMoreInteractions(client);
});
test('hideChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final path = '${_getChannelUrl(channelId, channelType)}/hide';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.hideChannel(channelId, channelType);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('showChannel', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final path = '${_getChannelUrl(channelId, channelType)}/show';
when(() => client.post(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.showChannel(channelId, channelType);
expect(res, isNotNull);
verify(() => client.post(path)).called(1);
verifyNoMoreInteractions(client);
});
test('markRead', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const messageId = 'test-message-id';
final path = '${_getChannelUrl(channelId, channelType)}/read';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.markRead(
channelId,
channelType,
messageId: messageId,
);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('stopWatching', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final path = '${_getChannelUrl(channelId, channelType)}/stop-watching';
when(() => client.post(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await channelApi.stopWatching(channelId, channelType);
expect(res, isNotNull);
verify(() => client.post(path)).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,84 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/device_api.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late DeviceApi deviceApi;
setUp(() {
deviceApi = DeviceApi(client);
});
test('addDevice', () async {
const deviceId = 'test-device-id';
const pushProvider = PushProvider.firebase;
const path = '/devices';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await deviceApi.addDevice(deviceId, pushProvider);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('getDevices', () async {
const path = '/devices';
final devices = List.generate(
3,
(index) => Device(
id: 'test-device-id-$index',
pushProvider: PushProvider.firebase.name,
),
);
when(() => client.get(path)).thenAnswer(
(_) async => successResponse(path, data: {
'devices': [...devices.map((it) => it.toJson())]
}),
);
final res = await deviceApi.getDevices();
expect(res, isNotNull);
expect(res.devices.length, devices.length);
verify(() => client.get(path)).called(1);
verifyNoMoreInteractions(client);
});
test('removeDevice', () async {
const deviceId = 'test-device-id';
const path = '/devices';
when(
() => client.delete(path, queryParameters: any(named: 'queryParameters')),
).thenAnswer((_) async => successResponse(path, data: <String, dynamic>{}));
final res = await deviceApi.removeDevice(deviceId);
expect(res, isNotNull);
verify(
() => client.delete(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,211 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/general_api.dart';
import 'package:stream_chat/src/core/api/requests.dart';
import 'package:stream_chat/src/core/models/channel_model.dart';
import 'package:stream_chat/src/core/models/event.dart';
import 'package:stream_chat/src/core/models/filter.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late GeneralApi generalApi;
setUp(() {
generalApi = GeneralApi(client);
});
test('sync', () async {
const cids = ['test-cid-1', 'test-cid-2', 'test-cid-3'];
final lastSyncAt = DateTime.now();
const path = '/sync';
final events =
List.generate(3, (index) => Event(type: 'test-event-type-$index'));
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'events': [...events.map((it) => it.toJson())]
}));
final res = await generalApi.sync(cids, lastSyncAt);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
group('searchMessages', () {
test(
'should throw if `query` and `messageFilters` is not provided',
() async {
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
try {
await generalApi.searchMessages(filter);
} catch (e) {
expect(e, isA<ArgumentError>());
}
},
);
test(
'should throw if `query` and `messageFilters` both are provided',
() async {
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const query = 'test-query';
final messageFilter = Filter.query('key', 'text');
try {
await generalApi.searchMessages(
filter,
query: query,
messageFilters: messageFilter,
);
} catch (e) {
expect(e, isA<ArgumentError>());
}
},
);
test('should run successfully with `query`', () async {
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const query = 'test-query';
const sort = [SortOption<ChannelModel>('test-field')];
const pagination = PaginationParams();
const path = '/search';
when(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).thenAnswer((_) async => successResponse(path, data: {'results': []}));
final res = await generalApi.searchMessages(
filter,
query: query,
sort: sort,
pagination: pagination,
);
expect(res, isNotNull);
expect(res.results, isEmpty);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('should run successfully with `messageFilter`', () async {
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const sort = [SortOption<ChannelModel>('test-field')];
final messageFilter = Filter.query('key', 'text');
const pagination = PaginationParams();
const path = '/search';
when(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).thenAnswer((_) async => successResponse(path, data: {'results': []}));
final res = await generalApi.searchMessages(
filter,
messageFilters: messageFilter,
sort: sort,
pagination: pagination,
);
expect(res, isNotNull);
expect(res.results, isEmpty);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
});
group('queryMembers', () {
test('with `channelId`', () async {
const channelType = 'test-channel-type';
const channelId = 'test-channel-id';
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const pagination = PaginationParams();
const sort = [SortOption('test-field')];
const path = '/members';
final members = List.generate(
3,
(index) => Member(userId: 'test-user-id=$index'),
);
when(() =>
client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'members': [...members.map((it) => it.toJson())]
}));
final res = await generalApi.queryMembers(
channelType,
channelId: channelId,
filter: filter,
pagination: pagination,
sort: sort,
);
expect(res, isNotNull);
expect(res.members.length, members.length);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('with `members`', () async {
const channelType = 'test-channel-type';
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const pagination = PaginationParams();
const sort = [SortOption('test-field')];
const path = '/members';
final members = List.generate(
3,
(index) => Member(userId: 'test-user-id=$index'),
);
when(() =>
client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'members': [...members.map((it) => it.toJson())]
}));
final res = await generalApi.queryMembers(
channelType,
filter: filter,
pagination: pagination,
sort: sort,
members: members,
);
expect(res, isNotNull);
expect(res.members.length, members.length);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
});
}
@@ -0,0 +1,44 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/guest_api.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late GuestApi guestApi;
setUp(() {
guestApi = GuestApi(client);
});
test('getGuestUser', () async {
const accessToken = 'test-guest-token';
final user = User(id: 'test-user-id');
const path = '/guest';
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'access_token': accessToken,
'user': user.toJson(),
}));
final res = await guestApi.getGuestUser(user);
expect(res, isNotNull);
expect(res.accessToken, accessToken);
expect(res.user.id, user.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,291 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/message_api.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late MessageApi messageApi;
setUp(() {
messageApi = MessageApi(client);
});
test('sendMessage', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
final message = Message(id: 'test-message-id', text: 'test-message-text');
const path = '/channels/$channelType/$channelId/message';
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'message': message.toJson(),
}));
final res = await messageApi.sendMessage(channelId, channelType, message);
expect(res, isNotNull);
expect(res.message.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('getMessagesById', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const messageIds = ['test-message-id-1', 'test-message-id-2'];
const path = '/channels/$channelType/$channelId/messages';
final messages = List.generate(
3,
(index) => Message(id: 'test-message-id-$index'),
);
when(() => client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'messages': [...messages.map((it) => it.toJson())],
}));
final res = await messageApi.getMessagesById(
channelId,
channelType,
messageIds,
);
expect(res, isNotNull);
expect(res.messages.length, messages.length);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('getMessage', () async {
const messageId = 'test-message-id';
const path = '/messages/$messageId';
final message = Message(id: messageId);
when(() => client.get(path)).thenAnswer((_) async =>
successResponse(path, data: {'message': message.toJson()}));
final res = await messageApi.getMessage(messageId);
expect(res, isNotNull);
expect(res.message.id, messageId);
verify(() => client.get(path)).called(1);
verifyNoMoreInteractions(client);
});
test('updateMessage', () async {
final message = Message(id: 'test-message-id');
final path = '/messages/${message.id}';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: {'message': message.toJson()}),
);
final res = await messageApi.updateMessage(message);
expect(res, isNotNull);
expect(res.message.id, message.id);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('deleteMessage', () async {
const messageId = 'test-message-id';
const path = '/messages/$messageId';
when(() => client.delete(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}),
);
final res = await messageApi.deleteMessage(messageId);
expect(res, isNotNull);
verify(() => client.delete(path)).called(1);
verifyNoMoreInteractions(client);
});
test('sendAction', () async {
const channelId = 'test-channel-id';
const channelType = 'test-channel-type';
const messageId = 'test-message-id';
const formData = {'test-key': 'test-data'};
const path = '/messages/$messageId/action';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await messageApi.sendAction(
channelId,
channelType,
messageId,
formData,
);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('sendReaction', () async {
const messageId = 'test-message-id';
const reactionType = 'test-reaction-type';
const extraData = {'test-key': 'test-data'};
const path = '/messages/$messageId/reaction';
final message = Message(id: messageId);
final reaction = Reaction(type: reactionType, messageId: messageId);
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'message': message.toJson(),
'reaction': reaction.toJson(),
}));
final res = await messageApi.sendReaction(
messageId,
reactionType,
extraData: extraData,
);
expect(res, isNotNull);
expect(res.message.id, messageId);
expect(res.reaction.messageId, messageId);
expect(res.reaction.type, reactionType);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('deleteReaction', () async {
const messageId = 'test-message-id';
const reactionType = 'test-reaction-type';
const path = '/messages/$messageId/reaction/$reactionType';
when(() => client.delete(path)).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await messageApi.deleteReaction(messageId, reactionType);
expect(res, isNotNull);
verify(() => client.delete(path)).called(1);
verifyNoMoreInteractions(client);
});
test('getReactions', () async {
const messageId = 'test-message-id';
const options = PaginationParams();
const path = '/messages/$messageId/reactions';
final reactions = List.generate(
3,
(index) => Reaction(
type: 'test-reaction-type-$index',
messageId: messageId,
),
);
when(() => client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'reactions': [...reactions.map((it) => it.toJson())]
}));
final res = await messageApi.getReactions(messageId, options);
expect(res, isNotNull);
expect(res.reactions.length, reactions.length);
expect(res.reactions.every((it) => it.messageId == messageId), isTrue);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('translateMessage', () async {
const messageId = 'test-message-id';
const messageText = 'hello';
const language = 'hi'; // Hindi
final message = Message(id: messageId, text: messageText);
final path = '/messages/${message.id}/translate';
const translatedMessageText = 'नमस्ते';
final translatedMessage = TranslatedMessage(const {
language: translatedMessageText,
});
when(() => client.post(path, data: any(named: 'data')))
.thenAnswer((_) async => successResponse(path, data: {
'message': translatedMessage.toJson(),
}));
final res = await messageApi.translateMessage(messageId, language);
expect(res, isNotNull);
expect(res.message.i18n?.containsKey(language), isTrue);
expect(res.message.i18n?[language], translatedMessageText);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('getReplies', () async {
const parentId = 'test-parent-id';
const options = PaginationParams();
const path = '/messages/$parentId/replies';
final messages = List.generate(
3,
(index) => Message(
id: 'test-message-id-$index',
parentId: parentId,
),
);
when(() => client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'messages': [...messages.map((it) => it.toJson())]
}));
final res = await messageApi.getReplies(parentId, options);
expect(res, isNotNull);
expect(res.messages.length, messages.length);
expect(res.messages.every((it) => it.parentId == parentId), isTrue);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,190 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/moderation_api.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late ModerationApi moderationApi;
setUp(() {
moderationApi = ModerationApi(client);
});
test('muteUser', () async {
const userId = 'test-user-id';
const path = '/moderation/mute';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.muteUser(userId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('unmuteUser', () async {
const userId = 'test-user-id';
const path = '/moderation/unmute';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.unmuteUser(userId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('muteChannel', () async {
const channelCid = 'test-channel-cid';
const expiration = Duration(days: 3);
const path = '/moderation/mute/channel';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.muteChannel(
channelCid,
expiration: expiration,
);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('unmuteChannel', () async {
const channelCid = 'test-channel-cid';
const path = '/moderation/unmute/channel';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.unmuteChannel(channelCid);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('flagMessage', () async {
const messageId = 'test-message-id';
const path = '/moderation/flag';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.flagMessage(messageId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('unflagMessage', () async {
const messageId = 'test-message-id';
const path = '/moderation/unflag';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.unflagMessage(messageId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('flagUser', () async {
const userId = 'test-message-id';
const path = '/moderation/flag';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.flagUser(userId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('unflagUser', () async {
const userId = 'test-message-id';
const path = '/moderation/unflag';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.unflagUser(userId);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('banUser', () async {
const targetUserId = 'test-target-user-id';
const options = {'key': 'value'};
const path = '/moderation/ban';
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.banUser(targetUserId, options: options);
expect(res, isNotNull);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
test('unbanUser', () async {
const targetUserId = 'test-target-user-id';
const options = {'key': 'value'};
const path = '/moderation/ban';
when(
() => client.delete(path, queryParameters: any(named: 'queryParameters')),
).thenAnswer((_) async => successResponse(path, data: <String, dynamic>{}));
final res = await moderationApi.unbanUser(targetUserId, options: options);
expect(res, isNotNull);
verify(
() => client.delete(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,49 @@
import 'package:stream_chat/src/core/api/stream_chat_api.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
const apiKey = 'test-api-key';
late final client = MockHttpClient();
late StreamChatApi streamChatApi;
setUp(() {
streamChatApi = StreamChatApi(
apiKey,
client: client,
);
});
test('`.user`', () {
expect(streamChatApi.user, isNotNull);
});
test('`.guest`', () {
expect(streamChatApi.guest, isNotNull);
});
test('`.message`', () {
expect(streamChatApi.message, isNotNull);
});
test('`.channel`', () {
expect(streamChatApi.channel, isNotNull);
});
test('`.device`', () {
expect(streamChatApi.device, isNotNull);
});
test('`.moderation`', () {
expect(streamChatApi.moderation, isNotNull);
});
test('`.general`', () {
expect(streamChatApi.general, isNotNull);
});
test('`.fileUploader`', () {
expect(streamChatApi.fileUploader, isNotNull);
});
}
@@ -0,0 +1,77 @@
import 'package:dio/dio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/core/api/requests.dart';
import 'package:stream_chat/src/core/api/user_api.dart';
import 'package:stream_chat/src/core/models/filter.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
import '../../mocks.dart';
void main() {
Response successResponse(String path, {Object? data}) => Response(
data: data,
requestOptions: RequestOptions(path: path),
statusCode: 200,
);
late final client = MockHttpClient();
late UserApi userApi;
setUp(() {
userApi = UserApi(client);
});
test('queryUsers', () async {
const presence = true;
final filter = Filter.in_('cid', const ['test-cid-1', 'test-cid-2']);
const sort = [SortOption('test-field')];
const pagination = PaginationParams();
const path = '/users';
final users = List.generate(3, (index) => User(id: 'test-user-id-$index'));
when(() => client.get(path, queryParameters: any(named: 'queryParameters')))
.thenAnswer((_) async => successResponse(path, data: {
'users': [...users.map((it) => it.toJson())]
}));
final res = await userApi.queryUsers(
presence: presence,
filter: filter,
sort: sort,
pagination: pagination,
);
expect(res, isNotNull);
expect(res.users.length, users.length);
verify(
() => client.get(path, queryParameters: any(named: 'queryParameters')),
).called(1);
verifyNoMoreInteractions(client);
});
test('updateUsers', () async {
final users = List.generate(3, (index) => User(id: 'test-user-id-$index'));
const path = '/users';
final updatedUsers = {for (final user in users) user.id: user};
when(() => client.post(path, data: any(named: 'data'))).thenAnswer(
(_) async => successResponse(path, data: {
'users': updatedUsers
.map((key, value) => MapEntry(key, value.toJson()))
}));
final res = await userApi.updateUsers(users);
expect(res, isNotNull);
expect(res.users.length, updatedUsers.length);
verify(() => client.post(path, data: any(named: 'data'))).called(1);
verifyNoMoreInteractions(client);
});
}
@@ -0,0 +1,47 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/core/models/action.dart';
void main() {
group('src/models/action', () {
const jsonExample = '''
{
"name": "name",
"style": "style",
"text": "text",
"type": "type",
"value": "value"
}''';
test('should parse json correctly', () {
final action = Action.fromJson(json.decode(jsonExample));
expect(action.name, 'name');
expect(action.style, 'style');
expect(action.text, 'text');
expect(action.type, 'type');
expect(action.value, 'value');
});
test('should serialize to json correctly', () {
final action = Action(
name: 'name',
style: 'style',
text: 'text',
type: 'type',
value: 'value',
);
expect(
action.toJson(),
{
'name': 'name',
'style': 'style',
'text': 'text',
'type': 'type',
'value': 'value',
},
);
});
});
}
@@ -0,0 +1,76 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/action.dart';
import 'package:stream_chat/src/core/models/attachment.dart';
import 'package:test/test.dart';
void main() {
group('src/models/attachment', () {
const jsonExample = '''
{
"type": "giphy",
"title": "awesome",
"title_link": "https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti",
"thumb_url": "https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif",
"actions": [
{
"name": "image_action",
"text": "Send",
"style": "primary",
"type": "button",
"value": "send"
},
{
"name": "image_action",
"text": "Shuffle",
"style": "default",
"type": "button",
"value": "shuffle"
},
{
"name": "image_action",
"text": "Cancel",
"style": "default",
"type": "button",
"value": "cancel"
}
]
}''';
test('should parse json correctly', () {
final attachment = Attachment.fromJson(json.decode(jsonExample));
expect(attachment.type, 'giphy');
expect(attachment.title, 'awesome');
expect(
attachment.titleLink,
'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti',
);
expect(
attachment.thumbUrl,
'https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif',
);
expect(attachment.actions, hasLength(3));
expect(attachment.actions[0], isA<Action>());
});
test('should serialize to json correctly', () {
final channel = Attachment(
type: 'image',
title: 'soo',
titleLink:
'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti',
);
expect(
channel.toJson(),
{
'type': 'image',
'title': 'soo',
'title_link':
'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti',
'actions': [],
},
);
});
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/channel_model.dart';
import 'package:test/test.dart';
void main() {
group('src/models/channel', () {
const jsonExample = '''
{
"id": "test",
"type": "livestream",
"cid": "livestream:test",
"cats": true,
"fruit": ["bananas", "apples"]
}
''';
test('should parse json correctly', () {
final channel = ChannelModel.fromJson(json.decode(jsonExample));
expect(channel.id, equals('test'));
expect(channel.type, equals('livestream'));
expect(channel.cid, equals('livestream:test'));
expect(channel.extraData['cats'], equals(true));
expect(channel.extraData['fruit'], equals(['bananas', 'apples']));
});
test('should serialize to json correctly', () {
final channel = ChannelModel(
type: 'type',
id: 'id',
cid: 'a:a',
extraData: {'name': 'cool'},
);
expect(
channel.toJson(),
{'id': 'id', 'type': 'type', 'frozen': false, 'name': 'cool'},
);
});
test('should serialize to json correctly when frozen is provided', () {
final channel = ChannelModel(
type: 'type',
id: 'id',
cid: 'a:a',
extraData: {'name': 'cool'},
);
expect(
channel.toJson(),
{'id': 'id', 'type': 'type', 'name': 'cool', 'frozen': false},
);
});
});
}
@@ -0,0 +1,40 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/command.dart';
import 'package:test/test.dart';
void main() {
group('src/models/command', () {
const jsonExample = '''
{
"name": "giphy",
"description": "Post a random gif to the channel",
"args": "[text]"
}
''';
test('should parse json correctly', () {
final command = Command.fromJson(json.decode(jsonExample));
expect(command.name, 'giphy');
expect(command.description, 'Post a random gif to the channel');
expect(command.args, '[text]');
});
test('should serialize to json correctly', () {
final command = Command(
name: 'giphy',
description: 'Post a random gif to the channel',
args: '[text]',
);
expect(
command.toJson(),
{
'name': 'giphy',
'description': 'Post a random gif to the channel',
'args': '[text]',
},
);
});
});
}
@@ -0,0 +1,32 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/core/models/device.dart';
void main() {
group('src/models/device', () {
const jsonExample = '''
{
"id": "device-id",
"push_provider": "push-provider"
}''';
test('should parse json correctly', () {
final device = Device.fromJson(json.decode(jsonExample));
expect(device.id, 'device-id');
expect(device.pushProvider, 'push-provider');
});
test('should serialize to json correctly', () {
final device = Device(id: 'device-id', pushProvider: 'push-provider');
expect(
device.toJson(),
{
'id': 'device-id',
'push_provider': 'push-provider',
},
);
});
});
}
@@ -0,0 +1,90 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/event.dart';
import 'package:stream_chat/src/core/models/own_user.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
void main() {
group('src/models/event', () {
const jsonExample = '''
{
"type": "type",
"cid": "cid",
"connection_id": "connectionId",
"created_at": "2019-04-03T18:43:33.213374Z",
"me": {
"id": "dry-meadow-0",
"role": "user",
"created_at": "2019-03-27T17:40:17.155892Z",
"updated_at": "2020-01-29T03:22:47.641589Z",
"last_active": "2020-01-29T03:22:47.63613Z",
"banned": false,
"online": false,
"image": "https://getstream.io/random_svg/?name=Dry+meadow",
"name": "Dry meadow"
},
"parent_id": null,
"user": {
"id": "dry-meadow-0",
"role": "user",
"created_at": "2019-03-27T17:40:17.155892Z",
"updated_at": "2020-01-29T03:22:47.641589Z",
"last_active": "2020-01-29T03:22:47.63613Z",
"banned": false,
"online": false,
"image": "https://getstream.io/random_svg/?name=Dry+meadow",
"name": "Dry meadow"
}
}
''';
test('should parse json correctly', () {
final event = Event.fromJson(json.decode(jsonExample));
expect(event.type, 'type');
expect(event.cid, 'cid');
expect(event.connectionId, 'connectionId');
expect(event.createdAt, isA<DateTime>());
expect(event.me, isA<OwnUser>());
expect(event.user, isA<User>());
expect(event.isLocal, false);
});
test('should serialize to json correctly', () {
final event = Event(
user: User(id: 'id'),
type: 'type',
cid: 'cid',
connectionId: 'connectionId',
createdAt: DateTime.parse('2020-01-29T03:22:47.63613Z'),
me: OwnUser(id: 'id2'),
totalUnreadCount: 1,
unreadChannels: 1,
online: true,
);
expect(
event.toJson(),
{
'type': 'type',
'cid': 'cid',
'connection_id': 'connectionId',
'created_at': '2020-01-29T03:22:47.636130Z',
'me': {'id': 'id2'},
'user': {'id': 'id'},
'reaction': null,
'message': null,
'channel': null,
'total_unread_count': 1,
'unread_channels': 1,
'online': true,
'member': null,
'channel_id': null,
'channel_type': null,
'parent_id': null,
'is_local': true,
},
);
});
});
}
@@ -0,0 +1,244 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/core/models/filter.dart';
void main() {
group('operators', () {
test('equal', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.equal(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.equal.rawValue);
});
test('notEqual', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.notEqual(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.notEqual.rawValue);
});
test('greater', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.greater(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.greater.rawValue);
});
test('greaterOrEqual', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.greaterOrEqual(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.greaterOrEqual.rawValue);
});
test('less', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.less(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.less.rawValue);
});
test('lessOrEqual', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.lessOrEqual(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.lessOrEqual.rawValue);
});
test('in', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.in_(key, values);
expect(filter.key, key);
expect(filter.value, values);
expect(filter.operator, FilterOperator.in_.rawValue);
});
test('in', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.in_(key, values);
expect(filter.key, key);
expect(filter.value, values);
expect(filter.operator, FilterOperator.in_.rawValue);
});
test('notIn', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.notIn(key, values);
expect(filter.key, key);
expect(filter.value, values);
expect(filter.operator, FilterOperator.notIn.rawValue);
});
test('query', () {
const key = 'testKey';
const value = 'testQuery';
final filter = Filter.query(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.query.rawValue);
});
test('autoComplete', () {
const key = 'testKey';
const value = 'testQuery';
final filter = Filter.autoComplete(key, value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, FilterOperator.autoComplete.rawValue);
});
test('exists', () {
const key = 'testKey';
final filter = Filter.exists(key);
expect(filter.key, key);
expect(filter.value, isTrue);
expect(filter.operator, FilterOperator.exists.rawValue);
});
test('notExists', () {
const key = 'testKey';
final filter = Filter.exists(key, exists: false);
expect(filter.key, key);
expect(filter.value, isFalse);
expect(filter.operator, FilterOperator.exists.rawValue);
});
test('custom', () {
const key = 'testKey';
const value = 'testValue';
const operator = '\$customOperator';
const filter = Filter.custom(operator: operator, key: key, value: value);
expect(filter.key, key);
expect(filter.value, value);
expect(filter.operator, operator);
});
test('raw', () {
const value = {
'test': ['a', 'b'],
};
const filter = Filter.raw(value: value);
expect(filter.value, value);
});
group('groupedOperator', () {
final filter1 = Filter.equal('testKey', 'testValue');
final filter2 = Filter.in_('testKey', const ['testValue']);
final filters = [filter1, filter2];
test('and', () {
final filter = Filter.and(filters);
expect(filter.key, isNull);
expect(filter.value, filters);
expect(filter.operator, FilterOperator.and.rawValue);
});
test('or', () {
final filter = Filter.or(filters);
expect(filter.key, isNull);
expect(filter.value, filters);
expect(filter.operator, FilterOperator.or.rawValue);
});
test('nor', () {
final filter = Filter.nor(filters);
expect(filter.key, isNull);
expect(filter.value, filters);
expect(filter.operator, FilterOperator.nor.rawValue);
});
});
});
group('encoding', () {
group('nonGroupedFilter', () {
test('simpleValue', () {
const key = 'testKey';
const value = 'testValue';
final filter = Filter.equal(key, value);
final encoded = json.encode(filter);
expect(
encoded,
'{"$key":{"${FilterOperator.equal.rawValue}":${json.encode(value)}}}',
);
});
test('listValue', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.in_(key, values);
final encoded = json.encode(filter);
expect(
encoded,
'{"$key":{"${FilterOperator.in_.rawValue}":${json.encode(values)}}}',
);
});
test('custom with no operator', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.custom(key: key, value: values);
final encoded = json.encode(filter);
expect(
encoded,
'{"$key":${json.encode(values)}}',
);
});
test('raw', () {
const value = {
'test': ['a', 'b'],
};
const filter = Filter.raw(value: value);
final encoded = json.encode(filter);
expect(
encoded,
json.encode(value),
);
});
});
test('groupedFilter', () {
final filter1 = Filter.equal('testKey', 'testValue');
final filter2 = Filter.in_('testKey', const ['testValue']);
final filters = [filter1, filter2];
final filter = Filter.and(filters);
final encoded = json.encode(filter);
expect(
encoded,
'{"${FilterOperator.and.rawValue}":${json.encode(filters)}}',
);
});
group('equality', () {
test('simpleFilter', () {
final filter1 = Filter.equal('testKey', 'testValue');
final filter2 = Filter.equal('testKey', 'testValue');
expect(filter1, filter2);
});
test('groupedFilter', () {
final filter1 = Filter.and([Filter.equal('testKey', 'testValue')]);
final filter2 = Filter.and([Filter.equal('testKey', 'testValue')]);
expect(filter1, filter2);
});
});
});
}
@@ -0,0 +1,35 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/core/models/member.dart';
import 'package:stream_chat/src/core/models/user.dart';
void main() {
group('src/models/member', () {
const jsonExample = '''
{
"user": {
"id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e",
"role": "user",
"created_at": "2020-01-28T22:17:30.826259Z",
"updated_at": "2020-01-28T22:17:31.101222Z",
"banned": false,
"online": false,
"name": "Robin Papa",
"image": "https://pbs.twimg.com/profile_images/669512187778498560/L7wQctBt.jpg"
},
"role": "member",
"created_at": "2020-01-28T22:17:30.95443Z",
"updated_at": "2020-01-28T22:17:30.95443Z"
}
''';
test('should parse json correctly', () {
final member = Member.fromJson(json.decode(jsonExample));
expect(member.user, isA<User>());
expect(member.role, 'member');
expect(member.createdAt, DateTime.parse('2020-01-28T22:17:30.95443Z'));
expect(member.updatedAt, DateTime.parse('2020-01-28T22:17:30.95443Z'));
});
});
}
@@ -0,0 +1,166 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/attachment.dart';
import 'package:stream_chat/src/core/models/message.dart';
import 'package:stream_chat/src/core/models/reaction.dart';
import 'package:stream_chat/src/core/models/user.dart';
import 'package:test/test.dart';
void main() {
group('src/models/message', () {
const jsonExample = r'''
{
"id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f",
"text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"type": "regular",
"silent": false,
"status": "SENT",
"user": {
"id": "c1c9b454-2bcc-402d-8bb0-2f3706ce1680",
"role": "user",
"created_at": "2020-01-28T22:17:30.83015Z",
"updated_at": "2020-01-28T22:17:31.19435Z",
"banned": false,
"online": false,
"image": "https://randomuser.me/api/portraits/women/2.jpg",
"name": "Mia Denys"
},
"attachments": [
{
"type": "video",
"author_name": "GIPHY",
"title": "The Lion King Disney GIF - Find \u0026 Share on GIPHY",
"title_link": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"text": "Discover \u0026 share this Lion King Live Action GIF with everyone you know. GIPHY is how you search, share, discover, and create GIFs.",
"image_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"thumb_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"asset_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.mp4",
"og_scrape_url": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA"
}
],
"latest_reactions": [
{
"message_id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f",
"user_id": "c1c9b454-2bcc-402d-8bb0-2f3706ce1680",
"user": {
"id": "c1c9b454-2bcc-402d-8bb0-2f3706ce1680",
"role": "user",
"created_at": "2020-01-28T22:17:30.83015Z",
"updated_at": "2020-01-28T22:17:31.19435Z",
"banned": false,
"online": false,
"image": "https://randomuser.me/api/portraits/women/2.jpg",
"name": "Mia Denys"
},
"type": "love",
"score": 1,
"created_at": "2020-01-28T22:17:31.128376Z",
"updated_at": "2020-01-28T22:17:31.128376Z"
}
],
"own_reactions": [],
"reaction_counts": {
"love": 1
},
"reaction_scores": {
"love": 1
},
"pinned": false,
"pinned_at": null,
"pin_expires": null,
"pinned_by": null,
"reply_count": 0,
"created_at": "2020-01-28T22:17:31.107978Z",
"updated_at": "2020-01-28T22:17:31.130506Z",
"mentioned_users": []
}''';
test('should parse json correctly', () {
final message = Message.fromJson(json.decode(jsonExample));
expect(message.id, '4637f7e4-a06b-42db-ba5a-8d8270dd926f');
expect(message.text,
'https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA');
expect(message.type, 'regular');
expect(message.user, isA<User>());
expect(message.silent, isA<bool>());
expect(message.attachments, isA<List<Attachment>>());
expect(message.latestReactions, isA<List<Reaction>>());
expect(message.ownReactions, isA<List<Reaction>>());
expect(message.reactionCounts, {'love': 1});
expect(message.reactionScores, {'love': 1});
expect(message.createdAt, DateTime.parse('2020-01-28T22:17:31.107978Z'));
expect(message.updatedAt, DateTime.parse('2020-01-28T22:17:31.130506Z'));
expect(message.mentionedUsers, isA<List<User>>());
expect(message.pinned, false);
expect(message.pinnedAt, null);
expect(message.pinExpires, null);
expect(message.pinnedBy, null);
});
test('should serialize to json correctly', () {
final message = Message(
id: '4637f7e4-a06b-42db-ba5a-8d8270dd926f',
text:
'https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA',
attachments: [
Attachment.fromJson(const {
'type': 'video',
'author_name': 'GIPHY',
'title': 'The Lion King Disney GIF - Find \u0026 Share on GIPHY',
'title_link':
'https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif',
'text':
'''Discover \u0026 share this Lion King Live Action GIF with everyone you know. GIPHY is how you search, share, discover, and create GIFs.''',
'image_url':
'https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif',
'thumb_url':
'https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif',
'asset_url':
'https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.mp4',
'og_scrape_url':
'https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA'
})
],
showInChannel: true,
parentId: 'parentId',
extraData: const {'hey': 'test'},
);
expect(
message.toJson(),
json.decode('''
{
"id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f",
"text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"silent": false,
"skip_push": false,
"attachments": [
{
"type": "video",
"title_link": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"title": "The Lion King Disney GIF - Find & Share on GIPHY",
"thumb_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"text": "Discover & share this Lion King Live Action GIF with everyone you know. GIPHY is how you search, share, discover, and create GIFs.",
"og_scrape_url": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"image_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"author_name": "GIPHY",
"asset_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.mp4",
"actions": []
}
],
"mentioned_users": [],
"parent_id": "parentId",
"quoted_message": null,
"quoted_message_id": null,
"pinned": false,
"pinned_at": null,
"pin_expires": null,
"pinned_by": null,
"show_in_channel": true,
"hey": "test"
}
'''),
);
});
});
}
@@ -0,0 +1,72 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/reaction.dart';
import 'package:stream_chat/src/core/models/user.dart';
import 'package:test/test.dart';
void main() {
group('src/models/reaction', () {
const jsonExample = '''
{
"message_id": "76cd8c82-b557-4e48-9d12-87995d3a0e04",
"user_id": "2de0297c-f3f2-489d-b930-ef77342edccf",
"user": {
"id": "2de0297c-f3f2-489d-b930-ef77342edccf",
"role": "user",
"created_at": "2020-01-28T22:17:30.810011Z",
"updated_at": "2020-01-28T22:17:31.077195Z",
"banned": false,
"online": false,
"image": "https://randomuser.me/api/portraits/women/45.jpg",
"name": "Daisy Morgan"
},
"type": "wow",
"score": 1,
"created_at": "2020-01-28T22:17:31.108742Z",
"updated_at": "2020-01-28T22:17:31.108742Z"
}
''';
test('should parse json correctly', () {
final reaction = Reaction.fromJson(json.decode(jsonExample));
expect(reaction.messageId, '76cd8c82-b557-4e48-9d12-87995d3a0e04');
expect(reaction.createdAt, DateTime.parse('2020-01-28T22:17:31.108742Z'));
expect(reaction.type, 'wow');
expect(
reaction.user?.toJson(),
User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: {
'image': 'https://randomuser.me/api/portraits/women/45.jpg',
'name': 'Daisy Morgan'
}).toJson(),
);
expect(reaction.score, 1);
expect(reaction.userId, '2de0297c-f3f2-489d-b930-ef77342edccf');
expect(reaction.extraData, {'updated_at': '2020-01-28T22:17:31.108742Z'});
});
test('should serialize to json correctly', () {
final reaction = Reaction(
messageId: '76cd8c82-b557-4e48-9d12-87995d3a0e04',
createdAt: DateTime.parse('2020-01-28T22:17:31.108742Z'),
type: 'wow',
user: User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: {
'image': 'https://randomuser.me/api/portraits/women/45.jpg',
'name': 'Daisy Morgan'
}),
userId: '2de0297c-f3f2-489d-b930-ef77342edccf',
extraData: {'bananas': 'yes'},
score: 1,
);
expect(
reaction.toJson(),
{
'message_id': '76cd8c82-b557-4e48-9d12-87995d3a0e04',
'type': 'wow',
'score': 1,
'bananas': 'yes',
},
);
});
});
}
@@ -0,0 +1,40 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/core/models/read.dart';
import 'package:stream_chat/src/core/models/user.dart';
void main() {
group('src/models/read', () {
const jsonExample = '''
{
"user": {
"id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e"
},
"last_read": "2020-01-28T22:17:30.966485504Z",
"unread_messages": 10
}
''';
test('should parse json correctly', () {
final read = Read.fromJson(json.decode(jsonExample));
expect(read.lastRead, DateTime.parse('2020-01-28T22:17:30.966485504Z'));
expect(read.user.id, 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e');
expect(read.unreadMessages, 10);
});
test('should serialize to json correctly', () {
final read = Read(
lastRead: DateTime.parse('2020-01-28T22:17:30.966485504Z'),
user: User(id: 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e'),
unreadMessages: 10,
);
expect(read.toJson(), {
'user': {'id': 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e'},
'last_read': '2020-01-28T22:17:30.966485Z',
'unread_messages': 10,
});
});
});
}
@@ -0,0 +1,60 @@
import 'package:test/test.dart';
import 'package:stream_chat/src/core/util/serializer.dart';
void main() {
group('src/models/serialization', () {
test('should move unknown keys from root to dedicate property', () {
final json = {
'prop1': 'test',
'prop2': 123,
'prop3': true,
};
final result = Serializer.moveToExtraDataFromRoot(json, [
'prop1',
'prop2',
]);
expect(result, {
'prop1': 'test',
'prop2': 123,
'extra_data': {
'prop3': true,
},
});
expect(json, {
'prop1': 'test',
'prop2': 123,
'prop3': true,
});
});
test('should have empty extraData', () {
final result = Serializer.moveToExtraDataFromRoot({
'prop1': 'test',
'prop2': 123,
'prop3': true,
}, [
'prop1',
'prop2',
'prop3'
]);
expect(result, {
'prop1': 'test',
'prop2': 123,
'prop3': true,
'extra_data': {},
});
});
test('should return null', () {
final result = Serializer.moveToExtraDataFromRoot({}, [
'prop1',
'prop2',
]);
expect(result, {'extra_data': {}});
});
});
}
@@ -0,0 +1,31 @@
import 'dart:convert';
import 'package:stream_chat/src/core/models/user.dart';
import 'package:test/test.dart';
void main() {
group('src/models/user', () {
const jsonExample = '''
{
"id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e",
"role": "test-role"
}
''';
test('should parse json correctly', () {
final user = User.fromJson(json.decode(jsonExample));
expect(user.id, 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e');
});
test('should serialize to json correctly', () {
final user = User(
id: 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e',
role: 'abc',
);
expect(user.toJson(), {
'id': 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e',
});
});
});
}