Files

1647 lines
55 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:collection/collection.dart';
import 'package:core/data/network/dio_client.dart';
import 'package:core/data/network/download/download_client.dart';
import 'package:core/data/network/download/download_manager.dart';
import 'package:core/domain/exceptions/download_file_exception.dart';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:jmap_dart_client/http/http_client.dart';
import 'package:jmap_dart_client/jmap/core/id.dart';
import 'package:jmap_dart_client/jmap/core/properties/properties.dart';
import 'package:jmap_dart_client/jmap/mail/email/email.dart';
import 'package:jmap_dart_client/jmap/mail/email/email_address.dart';
import 'package:jmap_dart_client/jmap/mail/mailbox/mailbox.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:model/account/account_request.dart';
import 'package:model/email/attachment.dart';
import 'package:model/email/email_action_type.dart';
import 'package:model/email/mark_star_action.dart';
import 'package:model/email/read_actions.dart';
import 'package:model/extensions/account_id_extensions.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:tmail_ui_user/features/composer/domain/exceptions/forbidden_to_send_exception.dart';
import 'package:tmail_ui_user/features/composer/domain/exceptions/invalid_recipients_exception.dart';
import 'package:tmail_ui_user/features/composer/domain/exceptions/set_method_exception.dart';
import 'package:tmail_ui_user/features/composer/domain/model/email_request.dart';
import 'package:tmail_ui_user/features/email/data/network/email_api.dart';
import 'package:tmail_ui_user/features/email/domain/exceptions/email_exceptions.dart';
import 'package:tmail_ui_user/features/email/domain/model/move_action.dart';
import 'package:tmail_ui_user/features/email/domain/model/move_to_mailbox_request.dart';
import 'package:uuid/uuid.dart';
import '../../../../fixtures/account_fixtures.dart';
import '../../../../fixtures/session_fixtures.dart';
import 'email_api_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<HttpClient>(),
MockSpec<DownloadManager>(),
MockSpec<DownloadClient>(),
MockSpec<DioClient>(),
MockSpec<Uuid>(),
])
void main() {
group('EmailAPI::test', () {
late HttpClient httpClient;
late DownloadManager downloadManager;
late DioClient dioClient;
late Uuid uuid;
late EmailAPI emailApi;
setUp(() {
httpClient = MockHttpClient();
downloadManager = MockDownloadManager();
dioClient = MockDioClient();
uuid = MockUuid();
emailApi = EmailAPI(
httpClient,
downloadManager,
dioClient,
uuid,
);
});
group('markAsRead::test', () {
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$seen": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsRead(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
ReadActions.markAsRead,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is greater than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 200;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$seen": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsRead(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
ReadActions.markAsRead,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is less than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 20;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$seen": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsRead(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
ReadActions.markAsRead,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN totalEmails is less than defaultMaxObjectsInSet\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 30;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$seen": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsRead(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
ReadActions.markAsRead,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
});
group('markAsStar::test', () {
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$flagged": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsStar(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
MarkStarAction.markStar,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is greater than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 200;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$flagged": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsStar(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
MarkStarAction.markStar,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is less than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 20;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$flagged": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsStar(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
MarkStarAction.markStar,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN totalEmails is less than defaultMaxObjectsInSet\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 30;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
],
[
"Email/get",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"state": "b965db40-c11c-11ef-9cfb-ef2eae0e64b1",
"list": List.generate(maxBatches, (index) => {
"id": "email_$index",
"keywords": {
"\$flagged": true
}
}),
"notFound": []
},
"c1"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.markAsStar(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
MarkStarAction.markStar,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
});
group('deleteMultipleEmailsPermanently::test', () {
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"destroyed": List.generate(maxBatches, (index) => "email_$index")
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.deleteMultipleEmailsPermanently(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is greater than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 200;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"destroyed": List.generate(maxBatches, (index) => "email_$index")
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.deleteMultipleEmailsPermanently(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is less than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 20;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"destroyed": List.generate(maxBatches, (index) => "email_$index")
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.deleteMultipleEmailsPermanently(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN totalEmails is less than defaultMaxObjectsInSet\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 30;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"destroyed": List.generate(maxBatches, (index) => "email_$index")
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.deleteMultipleEmailsPermanently(
aliceSession,
AccountFixtures.aliceAccountId,
emailIds,
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
});
group('moveToMailbox::test', () {
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.moveToMailbox(
aliceSession,
AccountFixtures.aliceAccountId,
MoveToMailboxRequest(
{
MailboxId(Id('mailboxA')): emailIds,
},
MailboxId(Id('mailboxB')),
MoveAction.moving,
EmailActionType.moveToMailbox,
),
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is greater than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 200;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.moveToMailbox(
aliceSession,
AccountFixtures.aliceAccountId,
MoveToMailboxRequest(
{
MailboxId(Id('mailboxA')): emailIds,
},
MailboxId(Id('mailboxB')),
MoveAction.moving,
EmailActionType.moveToMailbox,
),
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN maxObjectsInSet is less than defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 20;
const totalEmails = 100;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.moveToMailbox(
aliceSession,
AccountFixtures.aliceAccountId,
MoveToMailboxRequest(
{
MailboxId(Id('mailboxA')): emailIds,
},
MailboxId(Id('mailboxB')),
MoveAction.moving,
EmailActionType.moveToMailbox,
),
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
test(
'SHOULD calls execute the correct number of times\n'
'WHEN totalEmails is less than defaultMaxObjectsInSet\n'
'WHEN maxObjectsInSet equal defaultMaxObjectsInSet\n'
'AND defaultMaxObjectsInSet is 50',
() async {
// Arrange
const defaultMaxObjectsInSet = 50;
const maxObjectsInSet = 50;
const totalEmails = 30;
final maxBatches = [maxObjectsInSet, defaultMaxObjectsInSet, totalEmails].min;
final countIterations = (totalEmails / maxBatches).ceil();
final aliceSession = SessionFixtures.getAliceSessionWithMaxObjectsInSet(maxObjectsInSet);
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "2c9f1b12-b35a-43e6-9af2-0106fb53a943",
"methodResponses": [
[
"Email/set",
{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"newState": "4cb1e760-c11b-11ef-9cfb-ef2eae0e64b1",
"updated": {
for (var item in List.generate(maxBatches, (index) => {"email_$index": null}))
item.keys.first: item.values.first
}
},
"c0"
]
]
});
final emailIds = List.generate(
totalEmails,
(index) => EmailId(Id('email_$index')),
);
// Act
final result = await emailApi.moveToMailbox(
aliceSession,
AccountFixtures.aliceAccountId,
MoveToMailboxRequest(
{
MailboxId(Id('mailboxA')): emailIds,
},
MailboxId(Id('mailboxB')),
MoveAction.moving,
EmailActionType.moveToMailbox,
),
);
// Assert
verify(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).called(countIterations);
expect(result.emailIdsSuccess.length, totalEmails);
expect(result.mapErrors.isEmpty, isTrue);
});
});
group('getEmailMetadata:', () {
final emailId = EmailId(Id('email-id-123'));
final properties = Properties({'id'});
void stubHttpResponse(List<Map<String, dynamic>> emailList) {
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
'sessionState': 'some-state',
'methodResponses': [
[
'Email/get',
{
'accountId': AccountFixtures.aliceAccountId.asString,
'state': 'email-state',
'list': emailList,
'notFound': [],
},
'c0',
]
]
});
}
test(
'SHOULD return first email in the list '
'WHEN server response contains the requested email',
() async {
stubHttpResponse([
{'id': 'email-id-123'},
]);
final result = await emailApi.getEmailMetadata(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailId,
properties,
);
expect(result.id, emailId);
});
test(
'SHOULD throw NotFoundEmailException '
'WHEN server response returns an empty list',
() async {
stubHttpResponse([]);
await expectLater(
emailApi.getEmailMetadata(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailId,
properties,
),
throwsA(isA<NotFoundEmailException>()),
);
});
});
group('sendEmail::test', () {
final emailRequest = EmailRequest(
email: Email(
mailboxIds: {MailboxId(Id('outbox')): true},
from: {EmailAddress(null, 'alice@linagora.com')},
to: {EmailAddress(null, 'rejected@linagora.com')},
),
emailActionType: EmailActionType.compose,
);
test(
'SHOULD throw InvalidRecipientsException with the rejected addresses '
'WHEN EmailSubmission/set reports an invalidRecipients SetError\n'
'AND the addresses are read from the EmailSubmission/set response, not Email/set',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "state-1",
"methodResponses": [
[
"Email/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-1",
"created": <String, dynamic>{
"draft-1": <String, dynamic>{"id": "email-1"},
},
},
"c0"
],
[
// The submission failure belongs to the EmailSubmission/set response.
"EmailSubmission/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-1",
"notCreated": <String, dynamic>{
"draft-1": <String, dynamic>{
"type": "invalidRecipients",
"description": "Invalid recipients",
"invalidRecipients": ["rejected@linagora.com"],
},
},
},
"c1"
]
]
});
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
throwsA(isA<InvalidRecipientsException>()
.having(
(exception) => exception.invalidRecipients,
'invalidRecipients',
{'rejected@linagora.com'},
)
.having(
(exception) => exception.createdEmailId,
'createdEmailId',
EmailId(Id('email-1')),
)),
);
});
Map<String, dynamic> refusedSubmissionResponse(
Map<String, dynamic> setError,
) => {
"sessionState": "state-1",
"methodResponses": [
[
"Email/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-1",
"created": <String, dynamic>{
"draft-1": <String, dynamic>{"id": "email-1"},
},
},
"c0"
],
[
"EmailSubmission/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-1",
"notCreated": <String, dynamic>{"draft-1": setError},
},
"c1"
]
]
};
test(
'SHOULD throw ForbiddenToSendException carrying the created email\n'
'WHEN EmailSubmission/set reports a forbiddenToSend SetError',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => refusedSubmissionResponse({
"type": "forbiddenToSend",
"description": "Domain activation is pending: mail DNS configuration is not validated",
}));
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
throwsA(isA<ForbiddenToSendException>()
.having(
(exception) => exception.createdEmailId,
'createdEmailId',
EmailId(Id('email-1')),
)
.having(
(exception) => exception.mapErrors.values.single.type,
'error type',
ForbiddenToSendException.errorType,
)),
);
});
test(
'SHOULD throw a plain SetMethodException, not ForbiddenToSendException\n'
'WHEN EmailSubmission/set reports another SetError',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => refusedSubmissionResponse({
"type": "forbiddenFrom",
"description": "Not allowed to send from this address",
}));
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
throwsA(allOf(
isA<SetMethodException>(),
isNot(isA<ForbiddenToSendException>()),
isNot(isA<InvalidRecipientsException>()),
)),
);
});
test(
'SHOULD throw SetMethodException, not InvalidRecipientsException\n'
'WHEN Email/set does not create the email',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => {
"sessionState": "state-1",
"methodResponses": [
[
"Email/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-1",
"notCreated": <String, dynamic>{
"draft-1": <String, dynamic>{"type": "overQuota"},
},
},
"c0"
],
]
});
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
throwsA(allOf(
isA<SetMethodException>(),
isNot(isA<InvalidRecipientsException>()),
)),
);
});
// On an accepted submission James answers EmailSubmission/set, then runs
// onSuccessUpdateEmail as an implicit Email/set sharing its call id.
Map<String, dynamic> acceptedSubmissionResponse(
Map<String, dynamic> implicitEmailSetResult,
) => {
"sessionState": "state-1",
"methodResponses": [
[
"Email/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-1",
"newState": "state-2",
"created": <String, dynamic>{
"draft-1": <String, dynamic>{"id": "email-1"},
},
},
"c0"
],
[
"EmailSubmission/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"newState": "state-1",
"created": <String, dynamic>{
"draft-1": <String, dynamic>{
"id": "submission-1",
"sendAt": "2026-09-25T08:53:22Z",
},
},
},
"c1"
],
[
"Email/set",
<String, dynamic>{
"accountId": AccountFixtures.aliceAccountId.asString,
"oldState": "state-2",
"newState": "state-3",
...implicitEmailSetResult,
},
"c1"
],
]
};
test(
'SHOULD complete\n'
'WHEN EmailSubmission/set creates the submission\n'
'AND the implicit Email/set moves the email to Sent',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => acceptedSubmissionResponse({
"updated": <String, dynamic>{"email-1": null},
}));
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
completes,
);
});
test(
'SHOULD complete, as the email is already sent\n'
'WHEN EmailSubmission/set creates the submission\n'
'AND the implicit Email/set fails to move the email to Sent',
() async {
when(uuid.v1()).thenReturn('draft-1');
when(httpClient.post(
'',
data: anyNamed('data'),
cancelToken: anyNamed('cancelToken'),
)).thenAnswer((_) async => acceptedSubmissionResponse({
"notUpdated": <String, dynamic>{
"email-1": <String, dynamic>{
"type": "notFound",
"description": "Mailbox not found",
},
},
}));
await expectLater(
emailApi.sendEmail(
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
emailRequest,
),
completes,
);
});
});
group('exportAttachment::test', () {
late Directory temporaryRoot;
late MockDownloadClient downloadClient;
late EmailAPI exportEmailApi;
setUp(() {
temporaryRoot = Directory.systemTemp.createTempSync('email_api_test_');
final previousPathProvider = PathProviderPlatform.instance;
PathProviderPlatform.instance = _FakePathProviderPlatform(temporaryRoot.path);
addTearDown(() {
PathProviderPlatform.instance = previousPathProvider;
temporaryRoot.deleteSync(recursive: true);
});
downloadClient = MockDownloadClient();
exportEmailApi = EmailAPI(httpClient, DownloadManager(downloadClient), dioClient, uuid);
});
Future<String> exportOnce(Attachment attachment) async => (await exportEmailApi.exportAttachment(
attachment,
AccountFixtures.aliceAccountId,
'https://example.com/download/{accountId}/{blobId}',
AccountRequest(),
CancelToken(),
)).filePath;
// DownloadManager removes its staging directory only after the result is sent.
Future<List<String>> entriesAfterStagingCleanup(Directory directory) async {
final deadline = DateTime.now().add(const Duration(seconds: 5));
List<String> entries() => directory.listSync().map((entity) => entity.path).toList();
while (entries().any((path) => path.contains('/.download_')) && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
return entries();
}
test(
'SHOULD keep the content of each export\n'
'WHEN two attachments that generate the same file name are exported at the same time',
() async {
final sharedPrefix = 'x' * 251;
final firstAttachment = Attachment(blobId: Id('blob-a'), name: '$sharedPrefix-A.pdf');
final secondAttachment = Attachment(blobId: Id('blob-b'), name: '$sharedPrefix-B.pdf');
expect(firstAttachment.generateFileSystemName(), secondAttachment.generateFileSystemName());
const firstContent = [1, 1, 1];
const secondContent = [2, 2];
when(downloadClient.downloadFile(any, any, any)).thenAnswer((invocation) async {
final downloadUrl = invocation.positionalArguments[0] as String;
return ResponseBody.fromBytes(downloadUrl.contains('blob-a') ? firstContent : secondContent, 200);
});
final exports = await Future.wait([firstAttachment, secondAttachment].map(exportOnce));
expect(File(exports[0]).readAsBytesSync(), firstContent);
expect(File(exports[1]).readAsBytesSync(), secondContent);
expect(File(exports[0]).parent.path, '${temporaryRoot.path}/attachment/blob-a');
expect(File(exports[1]).parent.path, '${temporaryRoot.path}/attachment/blob-b');
});
test(
'SHOULD reuse the same file\n'
'WHEN the same attachment is exported twice',
() async {
final attachment = Attachment(blobId: Id('blob-a'), name: 'report.pdf');
when(downloadClient.downloadFile(any, any, any))
.thenAnswer((_) async => ResponseBody.fromBytes([1, 2, 3], 200));
final firstPath = await exportOnce(attachment);
final secondPath = await exportOnce(attachment);
expect(secondPath, firstPath);
expect(File(secondPath).readAsBytesSync(), [1, 2, 3]);
expect(await entriesAfterStagingCleanup(File(secondPath).parent), [secondPath]);
});
test(
'SHOULD keep the completed file\n'
'WHEN a later export of the same attachment fails mid-download',
() async {
final attachment = Attachment(blobId: Id('blob-a'), name: 'report.pdf');
when(downloadClient.downloadFile(any, any, any))
.thenAnswer((_) async => ResponseBody.fromBytes([1, 2, 3], 200));
final completedPath = await exportOnce(attachment);
when(downloadClient.downloadFile(any, any, any)).thenAnswer((_) async => ResponseBody(
Stream<Uint8List>.multi((controller) {
controller.add(Uint8List.fromList([9]));
controller.addError(Exception('connection reset'));
controller.close();
}),
200,
));
await expectLater(exportOnce(attachment), throwsA(isA<CommonDownloadFileException>()));
expect(File(completedPath).readAsBytesSync(), [1, 2, 3]);
expect(await entriesAfterStagingCleanup(File(completedPath).parent), [completedPath]);
});
test(
'SHOULD export the attachment\n'
'WHEN its blobId is the longest Id accepted',
() async {
final attachment = Attachment(blobId: Id('b' * 254), name: 'report.pdf');
when(downloadClient.downloadFile(any, any, any))
.thenAnswer((_) async => ResponseBody.fromBytes([1, 2, 3], 200));
final exportedPath = await exportOnce(attachment);
expect(File(exportedPath).readAsBytesSync(), [1, 2, 3]);
});
});
});
}
class _FakePathProviderPlatform extends Fake
with MockPlatformInterfaceMixin
implements PathProviderPlatform {
_FakePathProviderPlatform(this.temporaryPath);
final String temporaryPath;
@override
Future<String?> getTemporaryPath() async => temporaryPath;
}