rename package folders

This commit is contained in:
Salvatore Giordano
2021-02-01 15:45:58 +01:00
parent 6682ad5e8b
commit 964a428f2e
445 changed files with 1 additions and 343 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,18 @@
import 'package:test/test.dart';
import 'package:stream_chat/stream_chat.dart';
void main() {
group('src/api/requests', () {
test('SortOption', () {
final option = SortOption('name');
final j = option.toJson();
expect(j, {'field': 'name', 'direction': -1});
});
test('PaginationParams', () {
final option = PaginationParams();
final j = option.toJson();
expect(j, {'limit': 10});
});
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,9 @@
import 'package:test/test.dart';
import 'package:stream_chat/src/api/web_socket_channel_stub.dart';
void main() {
test('src/api/web_socket_stub_test', () {
expect(
() => connectWebSocket('fakeurl'), throwsA(isA<UnimplementedError>()));
});
}
@@ -0,0 +1,353 @@
import 'dart:async';
import 'package:test/test.dart';
import 'package:logging/logging.dart';
import 'package:mockito/mockito.dart';
import 'package:stream_chat/src/api/connection_status.dart';
import 'package:stream_chat/src/api/websocket.dart';
import 'package:stream_chat/src/models/event.dart';
import 'package:stream_chat/src/models/user.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class Functions {
WebSocketChannel connectFunc(
String url, {
Iterable<String> protocols,
Map<String, dynamic> headers,
Duration pingInterval,
}) =>
null;
void handleFunc(Event event) => null;
}
class MockFunctions extends Mock implements Functions {}
class MockWSChannel extends Mock implements WebSocketChannel {}
class MockWSSink extends Mock implements WebSocketSink {}
void main() {
group('src/api/websocket', () {
test('should connect with correct parameters', () async {
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: (e) {
print(e);
},
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.sink).thenAnswer((_) => MockWSSink());
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
final timer = Timer.periodic(
Duration(milliseconds: 100),
(_) => streamController.sink.add('{}'),
);
await ws.connect();
verify(connectFunc(computedUrl)).called(1);
expect(ws.connectionStatus, ConnectionStatus.connected);
await streamController.close();
timer.cancel();
});
});
test('should connect with correct parameters and handle events', () async {
final handleFunc = MockFunctions().handleFunc;
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: handleFunc,
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.sink).thenAnswer((_) => MockWSSink());
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
final connect = ws.connect().then((_) {
streamController.sink.add('{}');
return Future.delayed(Duration(milliseconds: 200));
}).then((value) {
verify(connectFunc(computedUrl)).called(1);
verify(handleFunc(any)).called(greaterThan(0));
return streamController.close();
});
streamController.sink.add('{}');
return connect;
});
test('should close correctly the controller', () async {
final handleFunc = MockFunctions().handleFunc;
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: handleFunc,
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.sink).thenAnswer((_) => MockWSSink());
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
final connect = ws.connect().then((_) {
streamController.sink.add('{}');
return Future.delayed(Duration(milliseconds: 200));
}).then((value) {
verify(connectFunc(computedUrl)).called(1);
verify(handleFunc(any)).called(greaterThan(0));
return streamController.close();
});
streamController.sink.add('{}');
return connect;
});
test('should run correctly health check', () async {
final handleFunc = MockFunctions().handleFunc;
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: handleFunc,
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final mockWSSink = MockWSSink();
final StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
when(mockWSChannel.sink).thenReturn(mockWSSink);
final timer = Timer.periodic(
Duration(milliseconds: 1000),
(_) => streamController.sink.add('{}'),
);
final connect = ws.connect().then((_) {
streamController.sink.add('{}');
return Future.delayed(Duration(milliseconds: 200));
}).then((value) async {
verify(mockWSSink.add("{'type': 'health.check'}")).called(greaterThan(0));
timer.cancel();
await streamController.close();
return mockWSSink.close();
});
streamController.sink.add('{}');
return connect;
});
test('should run correctly reconnection check', () async {
final handleFunc = MockFunctions().handleFunc;
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
Logger.root.level = Level.ALL;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: handleFunc,
connectFunc: connectFunc,
reconnectionMonitorTimeout: 1,
reconnectionMonitorInterval: 1,
);
final mockWSChannel = MockWSChannel();
final mockWSSink = MockWSSink();
StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
when(mockWSChannel.sink).thenReturn(mockWSSink);
final connect = ws.connect().then((_) {
streamController.sink.add('{}');
streamController.close();
streamController = StreamController<String>.broadcast();
streamController.sink.add('{}');
return Future.delayed(Duration(milliseconds: 200));
}).then((value) async {
verify(mockWSSink.add("{'type': 'health.check'}")).called(greaterThan(0));
verify(connectFunc(computedUrl)).called(2);
await streamController.close();
return mockWSSink.close();
});
streamController.sink.add('{}');
return connect;
});
test('should close correctly the controller', () async {
final handleFunc = MockFunctions().handleFunc;
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: handleFunc,
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final mockWSSink = MockWSSink();
final StreamController<String> streamController =
StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
when(mockWSChannel.sink).thenReturn(mockWSSink);
final connect = ws.connect().then((_) {
streamController.sink.add('{}');
return Future.delayed(Duration(milliseconds: 200));
}).then((value) async {
await ws.disconnect();
verify(mockWSSink.close()).called(greaterThan(0));
await streamController.close();
await mockWSSink.close();
});
streamController.sink.add('{}');
return connect;
});
test('should throw an error', () async {
final ConnectWebSocket connectFunc = MockFunctions().connectFunc;
final ws = WebSocket(
baseUrl: 'baseurl',
user: User(id: 'testid'),
logger: Logger('ws'),
connectParams: {'test': 'true'},
connectPayload: {'payload': 'test'},
handler: (e) {
print(e);
},
connectFunc: connectFunc,
);
final mockWSChannel = MockWSChannel();
final streamController = StreamController<String>.broadcast();
final computedUrl =
'wss://baseurl/connect?test=true&json=%7B%22payload%22%3A%22test%22%2C%22user_details%22%3A%7B%22id%22%3A%22testid%22%7D%7D';
when(connectFunc(computedUrl)).thenAnswer((_) => mockWSChannel);
when(mockWSChannel.sink).thenAnswer((_) => MockWSSink());
when(mockWSChannel.stream).thenAnswer((_) {
return streamController.stream;
});
Future.delayed(
Duration(milliseconds: 1000),
() => streamController.sink.addError('test error'),
);
try {
expect(await ws.connect(), throwsA(isA<String>()));
} catch (e) {
verify(connectFunc(computedUrl)).called(greaterThanOrEqualTo(1));
}
});
}
@@ -0,0 +1,939 @@
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:logging/logging.dart';
import 'package:mockito/mockito.dart';
import 'package:stream_chat/src/api/requests.dart';
import 'package:stream_chat/src/client.dart';
import 'package:stream_chat/src/exceptions.dart';
import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/user.dart';
import 'package:test/test.dart';
class MockDio extends Mock implements DioForNative {}
class MockHttpClientAdapter extends Mock implements HttpClientAdapter {}
class Functions {
Future<String> tokenProvider(String userId) => null;
}
class MockFunctions extends Mock implements Functions {}
void main() {
group('src/client', () {
group('constructor', () {
final List<String> log = [];
overridePrint(testFn()) => () {
log.clear();
final spec = ZoneSpecification(print: (_, __, ___, String msg) {
// Add to log instead of printing to stdout
log.add(msg);
});
return Zone.current.fork(specification: spec).run(testFn);
};
tearDown(() {
log.clear();
});
test('should create the object correctly', () {
final client = StreamChatClient('api-key');
expect(client.baseURL, 'chat-us-east-1.stream-io-api.com');
expect(client.apiKey, 'api-key');
expect(client.logLevel, Level.WARNING);
expect(client.httpClient.options.connectTimeout, 6000);
expect(client.httpClient.options.receiveTimeout, 6000);
});
test('should create the object correctly', overridePrint(() {
final LogHandlerFunction logHandler = (LogRecord record) {
print(record.message);
};
final client = StreamChatClient(
'api-key',
connectTimeout: Duration(seconds: 10),
receiveTimeout: Duration(seconds: 12),
logLevel: Level.INFO,
baseURL: 'test.com',
logHandlerFunction: logHandler,
);
expect(client.baseURL, 'test.com');
expect(client.apiKey, 'api-key');
expect(Logger.root.level, Level.INFO);
expect(client.httpClient.options.connectTimeout, 10000);
expect(client.httpClient.options.receiveTimeout, 12000);
client.logger.warning('test');
client.logger.config('test config');
expect([log[log.length - 2], log[log.length - 1]],
['instantiating new client', 'test']);
}));
test('Channel', () {
final client = StreamChatClient('test');
final Map<String, dynamic> data = {'test': 1};
final channelClient = client.channel('type', id: 'id', extraData: data);
expect(channelClient.type, 'type');
expect(channelClient.id, 'id');
});
});
group('queryChannels', () {
test('should pass right default parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final queryParams = {
'payload': json.encode({
"filter_conditions": null,
"sort": null,
"state": true,
"watch": true,
"presence": false,
"limit": 10,
}),
};
when(mockDio.get<String>('/channels', queryParameters: queryParams))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.queryChannels(waitForConnect: false);
verify(mockDio.get<String>('/channels', queryParameters: queryParams))
.called(1);
});
test('should pass right parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final queryFilter = <String, dynamic>{
"id": {
"\$in": ["test"],
},
};
final sortOptions = <SortOption>[];
final options = {"state": false, "watch": false, "presence": true};
final paginationParams = PaginationParams(
limit: 10,
offset: 2,
);
final queryParams = {
'payload': json.encode({
"filter_conditions": queryFilter,
"sort": sortOptions,
}
..addAll(options)
..addAll(paginationParams.toJson())),
};
when(mockDio.get<String>('/channels', queryParameters: queryParams))
.thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.queryChannels(
filter: queryFilter,
sort: sortOptions,
options: options,
paginationParams: paginationParams,
waitForConnect: false,
);
verify(mockDio.get<String>('/channels', queryParameters: queryParams))
.called(1);
});
});
group('search', () {
test('should pass right default parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final queryParams = {
'payload': json.encode({
"filter_conditions": null,
'query': null,
'sort': null,
}),
};
when(mockDio.get<String>('/search', queryParameters: queryParams))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.search(null, null, null, null);
verify(mockDio.get<String>('/search', queryParameters: queryParams))
.called(1);
});
test('should pass right parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final filters = {
"id": {
"\$in": ["test"],
},
};
final sortOptions = [SortOption('name')];
final query = 'query';
final queryParams = {
'payload': json.encode({
"filter_conditions": filters,
'query': query,
'sort': sortOptions,
"limit": 10,
}),
};
when(mockDio.get<String>('/search', queryParameters: queryParams))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.search(
filters,
sortOptions,
query,
PaginationParams(),
);
verify(mockDio.get<String>('/search', queryParameters: queryParams))
.called(1);
});
});
group('devices', () {
test('addDevice', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/devices', data: {
'id': 'test-id',
'push_provider': 'firebase',
})).thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.addDevice('test-id', PushProvider.firebase);
verify(
mockDio.post<String>(
'/devices',
data: {'id': 'test-id', 'push_provider': 'firebase'},
),
).called(1);
});
test('getDevices', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.get<String>('/devices'))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.getDevices();
verify(mockDio.get<String>('/devices')).called(1);
});
test('removeDevice', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio
.delete<String>('/devices', queryParameters: {'id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.removeDevice('test-id');
verify(mockDio.delete<String>('/devices',
queryParameters: {'id': 'test-id'})).called(1);
});
});
test('devToken', () {
final client = StreamChatClient('api-key');
final token = client.devToken('test');
expect(
token,
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidGVzdCJ9.devtoken',
);
});
group('queryUsers', () {
test('should pass right default parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final queryParams = {
'payload': json.encode({
"filter_conditions": {},
"sort": null,
"presence": false,
}),
};
when(mockDio.get<String>('/users', queryParameters: queryParams))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.queryUsers();
verify(mockDio.get<String>('/users', queryParameters: queryParams))
.called(1);
});
test('should pass right parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> queryFilter = {
"id": {
"\$in": ["test"],
},
};
final List<SortOption> sortOptions = [];
final options = {"presence": true};
final Map<String, dynamic> queryParams = {
'payload': json.encode({
"filter_conditions": queryFilter,
"sort": sortOptions,
}..addAll(options)),
};
when(mockDio.get<String>('/users', queryParameters: queryParams))
.thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.queryUsers(
filter: queryFilter,
sort: sortOptions,
options: options,
);
verify(mockDio.get<String>('/users', queryParameters: queryParams))
.called(1);
});
});
group('user', () {
test('setUser should throw exception', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/flag',
data: {'target_user_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.flagUser('test-id');
verify(mockDio.post<String>('/moderation/flag',
data: {'target_user_id': 'test-id'})).called(1);
});
test('flagUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
expect(() => client.setUserWithProvider(User(id: 'test-id')),
throwsA(isA<Exception>()));
});
test('unflagUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/unflag',
data: {'target_user_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.unflagUser('test-id');
verify(mockDio.post<String>('/moderation/unflag',
data: {'target_user_id': 'test-id'})).called(1);
});
test('updateUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final user = User(id: 'test-id');
final data = {
'users': {user.id: user.toJson()},
};
when(mockDio.post<String>('/users', data: data))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.updateUser(user);
verify(mockDio.post<String>('/users', data: data)).called(1);
});
test('updateUsers', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final user = User(id: 'test-id');
final user2 = User(id: 'test-id2');
final data = {
'users': {
user.id: user.toJson(),
user2.id: user2.toJson(),
},
};
when(mockDio.post<String>('/users', data: data))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.updateUsers([user, user2]);
verify(mockDio.post<String>('/users', data: data)).called(1);
});
test('banUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/ban',
data: {'test': true, 'target_user_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.banUser('test-id', {'test': true});
verify(mockDio.post<String>('/moderation/ban',
data: {'test': true, 'target_user_id': 'test-id'})).called(1);
});
test('unbanUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.delete<String>('/moderation/ban',
queryParameters: {'test': true, 'target_user_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.unbanUser('test-id', {'test': true});
verify(mockDio.delete<String>('/moderation/ban',
queryParameters: {'test': true, 'target_user_id': 'test-id'}))
.called(1);
});
test('muteUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/mute',
data: {'target_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.muteUser('test-id');
verify(mockDio.post<String>('/moderation/mute',
data: {'target_id': 'test-id'})).called(1);
});
test('unmuteUser', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/unmute',
data: {'target_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.unmuteUser('test-id');
verify(mockDio.post<String>('/moderation/unmute',
data: {'target_id': 'test-id'})).called(1);
});
});
group('message', () {
test('flagMessage', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/flag',
data: {'target_message_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.flagMessage('test-id');
verify(mockDio.post<String>('/moderation/flag',
data: {'target_message_id': 'test-id'})).called(1);
});
test('unflagMessage', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/moderation/unflag',
data: {'target_message_id': 'test-id'}))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.unflagMessage('test-id');
verify(mockDio.post<String>('/moderation/unflag',
data: {'target_message_id': 'test-id'})).called(1);
});
test('updateMessage', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final message = Message(
id: 'test',
updatedAt: DateTime.now(),
);
when(mockDio.post<String>(
'/messages/${message.id}',
data: {'message': message},
)).thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.updateMessage(message);
verify(mockDio.post<String>('/messages/${message.id}',
data: {'message': anything})).called(1);
});
test('deleteMessage', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final messageId = 'test';
when(mockDio.delete<String>('/messages/$messageId'))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.deleteMessage(Message(id: messageId));
verify(mockDio.delete<String>('/messages/$messageId')).called(1);
});
test('getMessage', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final messageId = 'test';
when(mockDio.get<String>('/messages/$messageId'))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.getMessage(messageId);
verify(mockDio.get<String>('/messages/$messageId')).called(1);
});
test('markAllRead', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
when(mockDio.post<String>('/channels/read'))
.thenAnswer((_) async => Response(data: '{}', statusCode: 200));
await client.markAllRead();
verify(mockDio.post<String>('/channels/read')).called(1);
});
});
group('api methods', () {
group('get', () {
test('should put the correct parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> queryParams = {
'test': 1,
};
when(mockDio.get<String>('/test', queryParameters: queryParams))
.thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.get('/test', queryParameters: queryParams);
verify(mockDio.get<String>('/test', queryParameters: queryParams))
.called(1);
});
test('should catch the error', () async {
final dioHttp = Dio();
final mockHttpClientAdapter = MockHttpClientAdapter();
dioHttp.httpClientAdapter = mockHttpClientAdapter;
final client = StreamChatClient(
'api-key',
httpClient: dioHttp,
);
when(mockHttpClientAdapter.fetch(any, any, any)).thenAnswer(
(_) async => ResponseBody.fromString('test error', 400));
expect(client.get('/test'), throwsA(ApiError('test error', 400)));
});
});
group('post', () {
test('should put the correct parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> data = {
'test': 1,
};
when(mockDio.post<String>('/test', data: data)).thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.post('/test', data: data);
verify(mockDio.post<String>('/test', data: data)).called(1);
});
test('should catch the error', () async {
final dioHttp = Dio();
final mockHttpClientAdapter = MockHttpClientAdapter();
dioHttp.httpClientAdapter = mockHttpClientAdapter;
final client = StreamChatClient(
'api-key',
httpClient: dioHttp,
);
when(mockHttpClientAdapter.fetch(any, any, any)).thenAnswer(
(_) async => ResponseBody.fromString('test error', 400));
expect(client.post('/test'), throwsA(ApiError('test error', 400)));
});
});
group('put', () {
test('should put the correct parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> data = {
'test': 1,
};
when(mockDio.put<String>('/test', data: data)).thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.put('/test', data: data);
verify(mockDio.put<String>('/test', data: data)).called(1);
});
test('should catch the error', () async {
final dioHttp = Dio();
final mockHttpClientAdapter = MockHttpClientAdapter();
dioHttp.httpClientAdapter = mockHttpClientAdapter;
final client = StreamChatClient(
'api-key',
httpClient: dioHttp,
);
when(mockHttpClientAdapter.fetch(any, any, any)).thenAnswer(
(_) async => ResponseBody.fromString('test error', 400));
expect(client.put('/test'), throwsA(ApiError('test error', 400)));
});
});
group('patch', () {
test('should put the correct parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> data = {
'test': 1,
};
when(mockDio.patch<String>('/test', data: data))
.thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.patch('/test', data: data);
verify(mockDio.patch<String>('/test', data: data)).called(1);
});
test('should catch the error', () async {
final dioHttp = Dio();
final mockHttpClientAdapter = MockHttpClientAdapter();
dioHttp.httpClientAdapter = mockHttpClientAdapter;
final client = StreamChatClient(
'api-key',
httpClient: dioHttp,
);
when(mockHttpClientAdapter.fetch(any, any, any)).thenAnswer(
(_) async => ResponseBody.fromString('test error', 400));
expect(client.patch('/test'), throwsA(ApiError('test error', 400)));
});
});
group('delete', () {
test('should put the correct parameters', () async {
final mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions());
when(mockDio.interceptors).thenReturn(Interceptors());
final client = StreamChatClient(
'api-key',
httpClient: mockDio,
);
final Map<String, dynamic> queryParams = {
'test': 1,
};
when(mockDio.delete<String>('/test', queryParameters: queryParams))
.thenAnswer((_) async {
return Response(data: '{}', statusCode: 200);
});
await client.delete('/test', queryParameters: queryParams);
verify(mockDio.delete<String>('/test', queryParameters: queryParams))
.called(1);
});
test('should catch the error', () async {
final dioHttp = Dio();
final mockHttpClientAdapter = MockHttpClientAdapter();
dioHttp.httpClientAdapter = mockHttpClientAdapter;
final client = StreamChatClient(
'api-key',
httpClient: dioHttp,
);
when(mockHttpClientAdapter.fetch(any, any, any)).thenAnswer(
(_) async => ResponseBody.fromString('test error', 400));
expect(client.delete('/test'), throwsA(ApiError('test error', 400)));
});
});
});
});
}
@@ -0,0 +1,46 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/action.dart';
void main() {
group('src/models/action', () {
const jsonExample = r'''{
"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,69 @@
import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/action.dart';
import 'dart:convert';
import 'package:test/test.dart';
void main() {
group('src/models/attachment', () {
const jsonExample = r'''{
"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'
},
);
});
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,56 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/channel_model.dart';
void main() {
group('src/models/channel', () {
const jsonExample = '''
{
"id": "test",
"type": "livestream",
"cid": "test:livestream",
"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("test:livestream"));
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', '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"},
frozen: false,
);
expect(
channel.toJson(),
{'id': 'id', 'type': 'type', 'name': 'cool', 'frozen': false},
);
});
});
}
@@ -0,0 +1,40 @@
import 'package:stream_chat/src/models/command.dart';
import 'dart:convert';
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,31 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/device.dart';
void main() {
group('src/models/device', () {
const jsonExample = r'''{
"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,89 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/event.dart';
import 'package:stream_chat/src/models/own_user.dart';
import 'package:stream_chat/stream_chat.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>());
});
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,
'is_local': true,
'member': null,
'channel_id': null,
'channel_type': null,
'parent_id': null,
},
);
});
});
}
@@ -0,0 +1,35 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/member.dart';
import 'package:stream_chat/src/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,153 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/src/models/user.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
},
"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>>());
});
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",
silent: false,
attachments: [
Attachment.fromJson({
"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: {'hey': 'test'},
status: MessageSendingStatus.sent,
);
expect(
message.toJson(),
json.decode(r'''
{
"id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f",
"text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"silent": 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"
}
],
"mentioned_users": null,
"parent_id": "parentId",
"quoted_message": null,
"quoted_message_id": null,
"show_in_channel": true,
"hey": "test"
}
'''),
);
});
});
}
@@ -0,0 +1,72 @@
import 'package:test/test.dart';
import 'package:stream_chat/src/models/reaction.dart';
import 'dart:convert';
import 'package:stream_chat/src/models/user.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.init("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.init("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/models/read.dart';
import 'package:stream_chat/src/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.init('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/models/serialization.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 = Serialization.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 = Serialization.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 = Serialization.moveToExtraDataFromRoot(null, [
'prop1',
'prop2',
]);
expect(result, null);
});
});
}
@@ -0,0 +1,28 @@
import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/user.dart';
void main() {
group('src/models/user', () {
const jsonExample = '''
{
"id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e"
}
''';
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",
});
});
});
}