-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathMailQueueHandlerTest.php
More file actions
420 lines (360 loc) · 14.5 KB
/
Copy pathMailQueueHandlerTest.php
File metadata and controls
420 lines (360 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Activity\Tests;
use OC\Mail\Message;
use OCA\Activity\AppInfo\Application;
use OCA\Activity\Data;
use OCA\Activity\GroupHelper;
use OCA\Activity\MailQueueHandler;
use OCA\Activity\UserSettings;
use OCP\Activity\IEvent;
use OCP\Activity\IManager;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeFormatter;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Mail\IEMailTemplate;
use OCP\Mail\IEmailValidator;
use OCP\Mail\IMailer;
use OCP\RichObjectStrings\IValidator;
use OCP\Server;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
/**
* Class MailQueueHandlerTest
* @package OCA\Activity\Tests
*/
#[Group('DB')]
class MailQueueHandlerTest extends TestCase {
protected MailQueueHandler $mailQueueHandler;
protected IMailer&MockObject $mailer;
protected MockObject $message;
protected IUserManager&MockObject $userManager;
protected IFactory&MockObject $lFactory;
protected IManager&MockObject $activityManager;
protected IValidator&MockObject $richObjectValidator;
protected IAppConfig&MockObject $appConfig;
protected IConfig&MockObject $config;
protected MockObject&LoggerInterface $logger;
protected IDateTimeFormatter&MockObject $dateTimeFormatter;
protected Data&MockObject $data;
protected GroupHelper&MockObject $groupHelper;
protected UserSettings&MockObject $userSettings;
protected IEmailValidator&MockObject $emailValidator;
protected function setUp(): void {
parent::setUp();
$app = self::getUniqueID('MailQueueHandlerTest', 10);
$this->userManager = $this->createMock(IUserManager::class);
$this->lFactory = $this->createMock(IFactory::class);
$this->appConfig = $this->createMock(IAppConfig::class);
$this->config = $this->createMock(IConfig::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->dateTimeFormatter = $this->createMock(IDateTimeFormatter::class);
$this->data = $this->createMock(Data::class);
$this->groupHelper = $this->createMock(GroupHelper::class);
$this->userSettings = $this->createMock(UserSettings::class);
$this->emailValidator = $this->createMock(IEmailValidator::class);
$connection = Server::get(IDBConnection::class);
$query = $connection->prepare('INSERT INTO `*PREFIX*activity_mq` '
. ' (`amq_appid`, `amq_subject`, `amq_subjectparams`, `amq_affecteduser`, `amq_timestamp`, `amq_type`, `amq_latest_send`) '
. ' VALUES(?, ?, ?, ?, ?, ?, ?)');
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user1', 150, 'phpunit', 152]);
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user1', 150, 'phpunit', 153]);
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user2', 150, 'phpunit', 150]);
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user2', 150, 'phpunit', 151]);
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user3', 150, 'phpunit', 154]);
$query->execute([$app, 'Test data', json_encode(['Param1']), 'user3', 150, 'phpunit', 155]);
$event = $this->createMock(IEvent::class);
$event->method('setApp')
->willReturnSelf();
$event->method('setType')
->willReturnSelf();
$event->method('setAffectedUser')
->willReturnSelf();
$event->method('setTimestamp')
->willReturnSelf();
$event->method('setSubject')
->willReturnSelf();
$event->method('getIcon')
->willReturn('');
$event->method('getParsedSubject')
->willReturn('');
$event->method('getRichSubject')
->willReturn('');
$event->method('getRichSubjectParameters')
->willReturn([]);
$this->activityManager = $this->createMock(IManager::class);
$this->activityManager->method('generateEvent')
->willReturn($event);
$this->activityManager->method('getProviders')
->willReturn([]);
$this->message = $this->createMock(Message::class);
$this->richObjectValidator = $this->createMock(IValidator::class);
$this->mailer = $this->createMock(IMailer::class);
$this->mailer->method('createMessage')
->willReturn($this->message);
$this->mailQueueHandler = new MailQueueHandler(
$this->dateTimeFormatter,
$connection,
$this->mailer,
$this->createMock(IURLGenerator::class),
$this->userManager,
$this->lFactory,
$this->activityManager,
$this->richObjectValidator,
$this->appConfig,
$this->config,
$this->logger,
$this->data,
$this->groupHelper,
$this->userSettings,
$this->emailValidator,
);
}
protected function tearDown(): void {
$query = Server::get(IDBConnection::class)
->prepare('DELETE FROM `*PREFIX*activity_mq` WHERE `amq_timestamp` < 500');
$query->execute();
parent::tearDown();
}
public static function getAffectedUsersData(): array {
return [
[null, ['user2', 'user1', 'user3'], []],
[5, ['user2', 'user1', 'user3'], []],
[3, ['user2', 'user1', 'user3'], []],
[2, ['user2', 'user1'], ['user3']],
[1, ['user2'], ['user1', 'user3']],
];
}
/**
* @dataProvider getAffectedUsersData
*
* @param int|null $limit
* @param array $affected
* @param array $untouched
*/
#[DataProvider('getAffectedUsersData')]
public function testGetAffectedUsers(?int $limit, array $affected, array $untouched): void {
$maxTime = 200;
$this->assertRemainingMailEntries($untouched, $maxTime, 'before doing anything');
$users = self::invokePrivate($this->mailQueueHandler, 'getAffectedUsers', [$limit, $maxTime, false, null]);
$this->assertRemainingMailEntries($untouched, $maxTime, 'after getting the affected users');
$this->assertEquals($affected, $users);
foreach ($users as $user) {
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertNotEmpty($data, 'Failed asserting that each user has a mail entry');
$this->assertSame(0, $skipped);
}
$this->assertRemainingMailEntries($untouched, $maxTime, 'after getting the affected items');
self::invokePrivate($this->mailQueueHandler, 'deleteSentItems', [$users, $maxTime]);
foreach ($users as $user) {
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertEmpty($data, 'Failed to assert that all entries for the affected users have been deleted');
$this->assertSame(0, $skipped);
}
$this->assertRemainingMailEntries($untouched, $maxTime, 'after deleting the affected items');
}
public function testGetItemsForUser(): void {
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', ['user1', 200]);
$this->assertCount(2, $data, 'Failed to assert the user has 2 entries');
$this->assertSame(0, $skipped);
$connection = Server::get(IDBConnection::class);
$query = $connection->prepare('INSERT INTO `*PREFIX*activity_mq` '
. ' (`amq_appid`, `amq_subject`, `amq_subjectparams`, `amq_affecteduser`, `amq_timestamp`, `amq_type`, `amq_latest_send`) '
. ' VALUES(?, ?, ?, ?, ?, ?, ?)');
$app = self::getUniqueID('MailQueueHandlerTest', 10);
for ($i = 0; $i < 15; $i++) {
$query->execute([$app, 'Test data', 'Param1', 'user1', 150, 'phpunit', 160 + $i]);
}
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', ['user1', 200, 5]);
$this->assertCount(5, $data, 'Failed to assert the user has 2 entries');
$this->assertSame(12, $skipped);
}
public function testPurgeItemsForUser(): void {
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', ['user1', 200]);
$this->assertCount(2, $data, 'Failed to assert the user has 2 entries');
$this->assertSame(0, $skipped);
$this->mailQueueHandler->purgeItemsForUser('user1');
[$data, $skipped] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', ['user1', 200]);
$this->assertCount(0, $data, 'Failed to assert the user has no entries left');
$this->assertSame(0, $skipped);
}
public function testSendEmailToUser(): void {
$maxTime = 200;
$user = 'user2';
$userDisplayName = 'user two';
$email = $user . '@localhost';
$template = $this->createMock(IEMailTemplate::class);
$this->mailer->expects($this->once())
->method('send')
->with($this->message);
$this->mailer->expects($this->once())
->method('createEMailTemplate')
->willReturn($template);
$this->emailValidator->expects($this->once())
->method('isValid')
->with($email)
->willReturn(true);
$template->expects($this->once())
->method('addHeader');
$template->expects($this->once())
->method('addHeading');
$template->expects($this->exactly(2))
->method('addBodyText');
$template->expects($this->once())
->method('addFooter');
$this->message->expects($this->once())
->method('setTo')
->with([$email => $userDisplayName]);
$this->message->expects($this->once())
->method('useTemplate')
->with($template);
$userObject = $this->createMock(IUser::class);
$userObject
->method('getDisplayName')
->willReturn($userDisplayName);
$this->userManager
->method('get')
->willReturnMap([
[$user, $userObject],
[$user . $user, null],
]);
$this->lFactory->expects($this->once())
->method('get')
->with(Application::APP_ID, 'en')
->willReturn($this->getMockBuilder(IL10N::class)->getMock());
$this->activityManager->expects($this->exactly(2))
->method('setCurrentUserId');
$this->dateTimeFormatter
->method('formatDateTimeRelativeDay')
->willReturn('relative');
$users = self::invokePrivate($this->mailQueueHandler, 'getAffectedUsers', [1, $maxTime, false, null]);
$this->assertEquals([$user], $users);
self::invokePrivate($this->mailQueueHandler, 'sendEmailToUser', [$user, $email, 'en', 'UTC', $maxTime]);
// Invalid user, no object no email
self::invokePrivate($this->mailQueueHandler, 'sendEmailToUser', [$user . $user, $email, 'en', 'UTC', $maxTime]);
}
public function testSendEmailsDeletesQueueOnMailerFailure(): void {
$maxTime = 200;
$this->appConfig->method('getValueBool')
->with('activity', 'enable_email', true)
->willReturn(true);
$template = $this->createMock(IEMailTemplate::class);
$this->mailer->method('createEMailTemplate')
->willReturn($template);
$this->mailer->method('send')
->willThrowException(new \Exception('SMTP timeout'));
$this->emailValidator->method('isValid')
->willReturn(true);
$userObject = $this->createMock(IUser::class);
$userObject->method('getDisplayName')
->willReturn('Test User');
$userObject->method('getEMailAddress')
->willReturn('test@localhost');
$this->userManager->method('get')
->willReturn($userObject);
$this->lFactory->method('get')
->willReturn($this->createMock(IL10N::class));
$this->config->method('getUserValueForUsers')
->willReturn([]);
$this->config->method('getSystemValue')
->willReturn('en');
$this->logger->expects($this->atLeastOnce())
->method('error');
// Send all 3 users, all will fail due to SMTP timeout
$this->mailQueueHandler->sendEmails(3, $maxTime);
// Queue entries should be deleted for all users even though sending failed
foreach (['user1', 'user2', 'user3'] as $user) {
[$data,] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertEmpty($data, "Queue entries for $user should be removed after failed send to prevent duplicate notifications");
}
}
public function testSendEmailsDeletesQueueOnSendReturnFalse(): void {
$maxTime = 200;
$this->appConfig->method('getValueBool')
->with('activity', 'enable_email', true)
->willReturn(true);
$template = $this->createMock(IEMailTemplate::class);
$this->mailer->method('createEMailTemplate')
->willReturn($template);
// sendEmailToUser returns false when email is invalid
$this->emailValidator->method('isValid')
->willReturn(false);
$userObject = $this->createMock(IUser::class);
$userObject->method('getDisplayName')
->willReturn('Test User');
$userObject->method('getEMailAddress')
->willReturn('test@localhost');
$this->userManager->method('get')
->willReturn($userObject);
$this->config->method('getUserValueForUsers')
->willReturn([]);
$this->config->method('getSystemValue')
->willReturn('en');
// Send all 3 users, all will fail due to invalid email
$this->mailQueueHandler->sendEmails(3, $maxTime);
// Queue entries should be deleted for all users even though sendEmailToUser returned false
foreach (['user1', 'user2', 'user3'] as $user) {
[$data,] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertEmpty($data, "Queue entries for $user should be removed after sendEmailToUser returns false to prevent duplicate notifications");
}
}
public function testSendEmailsSkipsWhenAdminEmailDisabled(): void {
$maxTime = 200;
$this->appConfig->method('getValueBool')
->with('activity', 'enable_email', true)
->willReturn(false);
$this->mailer->expects($this->never())
->method('send');
$result = $this->mailQueueHandler->sendEmails(3, $maxTime);
$this->assertSame(0, $result);
// Queue must be untouched so emails can be sent if admin re-enables the toggle
foreach (['user1', 'user2', 'user3'] as $user) {
[$data,] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertNotEmpty($data, "Queue entries for $user must survive when email is globally disabled");
}
}
/**
* @param array $users
* @param int $maxTime
* @param string $explain
*/
protected function assertRemainingMailEntries(array $users, int $maxTime, string $explain): void {
foreach ($users as $user) {
[$data,] = self::invokePrivate($this->mailQueueHandler, 'getItemsForUser', [$user, $maxTime]);
$this->assertNotEmpty(
$data,
'Failed asserting that the remaining user ' . $user . ' still has mails in the queue ' . $explain
);
}
}
}