-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
EmailTrait.php
520 lines (442 loc) · 17 KB
/
EmailTrait.php
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<?php
declare(strict_types=1);
namespace DrevOps\BehatSteps;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\PyStringNode;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\StatementInterface;
use Drupal\user\UserInterface;
/**
* Trait EmailTrait.
*
* Email-related steps.
*
* Behat trait for email interactions.
*/
trait EmailTrait {
/**
* List of email service types.
*
* @var array<int, string>
*/
protected $emailTypes = [];
/**
* Enable email debug.
*
* @var bool
*/
protected $emailDebug = FALSE;
/**
* Enable email tracking.
*
* @BeforeScenario
*/
public function emailBeforeScenarioEnableTestEmailSystem(BeforeScenarioScope $scope): void {
// Allow to skip this by adding a tag.
if ($scope->getScenario()->hasTag('behat-steps-skip:' . __FUNCTION__)) {
return;
}
if (!$scope->getScenario()->hasTag('email')) {
return;
}
if ($scope->getScenario()->hasTag('debug')) {
$this->emailDebug = TRUE;
}
$this->emailTypes = self::emailExtractTypes($scope->getScenario()->getTags());
if (empty($this->emailTypes)) {
$this->emailTypes[] = 'default';
$module_handler = \Drupal::service('module_handler');
if ($module_handler->moduleExists('webform')) {
$this->emailTypes[] = 'webform';
}
}
self::emailEnableTestEmailSystem();
}
/**
* Disable email tracking.
*
* @AfterScenario
*/
public function emailAfterScenarioDisableTestEmailSystem(AfterScenarioScope $scope): void {
// Allow to skip this by adding a tag.
if ($scope->getScenario()->hasTag('behat-steps-skip:' . __FUNCTION__)) {
return;
}
if ($scope->getScenario()->hasTag('email')) {
self::emailDisableTestEmailSystem();
}
}
/**
* Clear test email system queue.
*
* @When I clear the test email system queue
*/
public function emailClearTestEmailSystemQueue(bool $force = FALSE): void {
if (!$force && !self::emailGetMailSystemOriginal()) {
throw new \RuntimeException('Clearing testing email system queue can be done only when email testing system is activated. Add @email tag or "When I enable the test email system" step definition to the scenario.');
}
\Drupal::state()->set('system.test_mail_collector', []);
}
/**
* Assert that an email was sent to an address.
*
* @Then an email is sent to :address
*/
public function emailAssertEmailIsSentTo(string $address): void {
foreach (self::emailGetCollectedEmails() as $record) {
$email_to = explode(',', (string) $record['to']);
if (in_array($address, $email_to)) {
return;
}
}
throw new \Exception(sprintf('Unable to find email sent to "%s" retrieved from test record collector.', $address));
}
/**
* Assert that no email messages were sent.
*
* @Then no emails were sent
*/
public function emailAssertNoEmailsWereSent(): void {
if (count(self::emailGetCollectedEmails()) > 0) {
throw new \Exception('No emails were supposed to be sent');
}
}
/**
* Assert that no email messages were sent to a specified address.
*
* @Then no emails were sent to :address
*/
public function emailAssertNoEmailsWereSentToAddress(string $address): void {
foreach ($this->emailGetCollectedEmails() as $record) {
$email_to = explode(',', (string) $record['to']);
if (in_array($address, $email_to)) {
throw new \Exception(sprintf('An email sent to "%s" retrieved from test email collector.', $address));
}
if (!empty($record['headers']['Cc'])) {
$email_cc = explode(',', (string) $record['headers']['Cc']);
if (in_array($address, $email_cc)) {
throw new \Exception(sprintf('An email cc\'ed to "%s" retrieved from test email collector.', $address));
}
}
if (!empty($record['headers']['Bcc'])) {
$email_bcc = explode(',', (string) $record['headers']['Bcc']);
if (in_array($address, $email_bcc)) {
throw new \Exception(sprintf('An email bcc\'ed to "%s" retrieved from test email collector.', $address));
}
}
}
}
/**
* Assert that an email message header contains specified content.
*
* @Then an email header :header contains:
*/
public function emailAssertEmailHeaderContains(string $header, PyStringNode $string, bool $exact = FALSE): void {
$string_value = (string) $string;
$string_value = $exact ? $string_value : trim((string) preg_replace('/\s+/', ' ', $string_value));
foreach ($this->emailGetCollectedEmails() as $record) {
$header_value = $record['headers'][$header] ?? '';
$header_value = $exact ? $header_value : trim((string) preg_replace('/\s+/', ' ', (string) $header_value));
if (str_contains((string) $header_value, $string_value)) {
return;
}
}
throw new \Exception(sprintf('Unable to find email with%s text "%s" in the header "%s" retrieved from test email collector.', ($exact ? ' exact' : ''), $string, $header));
}
/**
* Assert that an email message header contains exact specified content.
*
* @Then an email header :header contains exact:
*/
public function emailAssertEmailHeaderContainsExact(string $header, PyStringNode $string): void {
$this->emailAssertEmailHeaderContains($header, $string, TRUE);
}
/**
* Assert that an email message was sent or not sent to a user with content.
*
* @Then /^an email to "(?P<name>[^"]*)" user is "(?P<action>[^"]*)" with "(?P<field>[^"]*)" content:$/
*/
public function emailAssertEmailToUserIsActionWithContent(string $name, string $action, string $field, PyStringNode $string): void {
$user = $name === 'current' && !empty($this->getUserManager()->getCurrentUser()) ? $this->getUserManager()->getCurrentUser() : user_load_by_name($name);
if (!$user instanceof UserInterface) {
throw new \Exception(sprintf('Unable to find a user "%s"', $name));
}
if ($action === 'sent') {
$this->emailAssertEmailContains('to', new PyStringNode([$user->getEmail()], 0), TRUE);
$this->emailAssertEmailContains($field, $string);
}
elseif ($action === 'not sent') {
$this->emailAssertEmailNotContains($field, $string);
}
else {
throw new \RuntimeException(sprintf('Provided action "%s" is not from a list of allowed actions', $action));
}
}
/**
* Assert that an email message field contains a value.
*
* @Then an email :field contains
* @Then an email :field contains:
*/
public function emailAssertEmailContains(string $field, PyStringNode $string, bool $exact = FALSE): void {
$email = $this->emailFind($field, $string, $exact);
if (!$email) {
throw new \Exception(sprintf('Unable to find email with%s text "%s" in field "%s" retrieved from test email collector.', ($exact ? ' exact' : ''), $string, $field));
}
}
/**
* Assert that an email message field contains an exact value.
*
* @Then an email :field contains exact
* @Then an email :field contains exact:
*/
public function emailAssertEmailContainsExact(string $field, PyStringNode $string): void {
$this->emailAssertEmailContains($field, $string, TRUE);
}
/**
* Assert that an email message field does not contain a value.
*
* @Then an email :field does not contain
* @Then an email :field does not contain:
*/
public function emailAssertEmailNotContains(string $field, PyStringNode $string, bool $exact = FALSE): void {
if (!in_array($field, ['subject', 'body', 'to', 'from'])) {
throw new \RuntimeException(sprintf('Invalid record field %s was specified for assertion', $field));
}
$string = strval($string);
$string = $exact ? $string : trim((string) preg_replace('/\s+/', ' ', $string));
foreach (self::emailGetCollectedEmails() as $record) {
$field_string = $exact ? $record[$field] : trim((string) preg_replace('/\s+/', ' ', (string) $record[$field]));
if (str_contains((string) $field_string, $string)) {
throw new \Exception(sprintf('Found record with%s text "%s" in field "%s" retrieved from test record collector, but should not.', ($exact ? ' exact' : ''), $string, $field));
}
}
}
/**
* Assert that an email message field does not contain an exact value.
*
* @Then an email :field does not contain exact
* @Then an email :field does not contain exact:
*/
public function emailAssertEmailNotContainsExact(string $field, PyStringNode $string): void {
$this->emailAssertEmailNotContains($field, $string, TRUE);
}
/**
* Visit a link from the email.
*
* @When I follow the link number :number in the email with the subject
* @When I follow the link number :number in the email with the subject:
*/
public function emailFollowLinkNumber(string $number, PyStringNode $subject): void {
$number = intval($number);
$email = $this->emailFind('subject', $subject);
if (!$email) {
throw new \Exception(sprintf('Unable to find email with subject "%s" retrieved from test email collector.', $subject));
}
if (isset($email['params']['body']) && is_string($email['params']['body'])) {
$body = $email['params']['body'];
}
elseif (is_string($email['body'])) {
$body = $email['body'];
}
else {
throw new \Exception('No body found in email');
}
$links = self::emailExtractLinks($body);
if (empty($links)) {
throw new \Exception(sprintf('No links were found in the email with subject %s', $subject));
}
if (count($links) < $number) {
throw new \Exception(sprintf('The link with number %s was not found among %s links', $number, count($links)));
}
$link = $links[$number - 1];
print $link;
self::getSession()->visit($link);
}
/**
* Assert that a file is attached to an email message with specified subject.
*
* @Then file :name attached to the email with the subject
* @Then file :name attached to the email with the subject:
*/
public function emailAssertEmailContainsAttachmentWithName(string $name, PyStringNode $subject): void {
$email = $this->emailFind('subject', $subject);
if (!$email) {
throw new \Exception(sprintf('Unable to find email with subject "%s" retrieved from test email collector.', $subject));
}
if (!empty($email['params']['attachments'])) {
foreach ($email['params']['attachments'] as $attachment) {
if ($attachment['filename'] == $name) {
return;
}
}
}
throw new \Exception(sprintf('No attachments were found in the email with subject %s', $subject));
}
/**
* Enable test email system.
*/
protected function emailEnableTestEmailSystem(): void {
foreach ($this->emailTypes as $type) {
// Store the original system to restore after the scenario.
$original_test_system = self::emailGetMailSystemDefault($type);
// But store only if previous has not been stored yet.
if (!self::emailGetMailSystemOriginal($type)) {
self::emailSetMailSystemOriginal($type, $original_test_system);
}
// Set the test system.
self::emailSetMailSystemDefault($type, 'test_mail_collector');
}
// Flush the email buffer, allowing us to reuse this step definition
// to clear existing mail.
self::emailClearTestEmailSystemQueue(TRUE);
}
/**
* Disable test email system.
*/
protected function emailDisableTestEmailSystem(): void {
foreach ($this->emailTypes as $type) {
$original_test_system = self::emailGetMailSystemOriginal($type);
// Restore the original system to after the scenario.
self::emailSetMailSystemDefault($type, $original_test_system);
}
self::emailDeleteMailSystemOriginal();
self::emailClearTestEmailSystemQueue(TRUE);
}
/**
* Get default mail system value.
*/
protected static function emailGetMailSystemDefault(string $type = 'default'): mixed {
return \Drupal::config('system.mail')->get('interface.' . $type);
}
/**
* Set default mail system value.
*/
protected static function emailSetMailSystemDefault(string $type, mixed $value): void {
\Drupal::configFactory()->getEditable('system.mail')->set('interface.' . $type, $value)->save();
// Maisystem module completely takes over default interface, so we need to
// update it as well if the module is installed.
// @note: For some unknown reasons, we do not need to reset this back to
// the original values after the test. The values in the configuration
// will not be overridden.
if (\Drupal::service('module_handler')->moduleExists('mailsystem')) {
\Drupal::configFactory()->getEditable('mailsystem.settings')
->set('defaults.sender', $value)
->set('defaults.formatter', $value)
->save();
}
}
/**
* Get original mail system value.
*/
protected static function emailGetMailSystemOriginal(string $type = 'default'): mixed {
return \Drupal::config('system.mail_original')->get('interface.' . $type);
}
/**
* Set original mail system value.
*/
protected static function emailSetMailSystemOriginal(string $type, mixed $value): void {
\Drupal::configFactory()->getEditable('system.mail_original')->set('interface.' . $type, $value)->save();
}
/**
* Remove original mail system value.
*/
protected static function emailDeleteMailSystemOriginal(): void {
\Drupal::configFactory()->getEditable('system.mail_original')->delete();
}
/**
* Get emails collected during the test.
*
* @return array<string,array<string,mixed>>
* Array of collected emails.
*/
protected function emailGetCollectedEmails(): array {
// Directly read data from the database to avoid cache invalidation that
// may corrupt the system under test.
$query = Database::getConnection()->query("SELECT name, value FROM {key_value} WHERE name = 'system.test_mail_collector'");
if ($query instanceof StatementInterface) {
$emails = array_map(unserialize(...), $query->fetchAllKeyed());
}
$emails = empty($emails['system.test_mail_collector']) ? [] : $emails['system.test_mail_collector'];
if ($this->emailDebug) {
$fields = ['to', 'from', 'subject', 'body'];
foreach ($emails as $idx => $email) {
printf("----------------------------------------\n");
printf("Email number: %s\n", $idx);
printf("----------------------------------------\n");
foreach ($fields as $field) {
printf("Field: %s\n", $field);
printf("Value: %s\n", $email[$field] ?? '<EMPTY>');
print PHP_EOL;
}
}
}
return $emails;
}
/**
* Find an email message field containing a value.
*
* @param string $field
* Field to search in.
* @param \Behat\Gherkin\Node\PyStringNode $string
* String to search for.
* @param bool $exact
* Whether to search for an exact match.
*
* @return array<string,string|array<string,mixed>>|null
* Email record or NULL if not found.
*/
protected function emailFind(string $field, PyStringNode $string, bool $exact = FALSE): ?array {
if (!in_array($field, ['subject', 'body', 'to', 'from'])) {
throw new \RuntimeException(sprintf('Invalid email field %s was specified for assertion', $field));
}
$string = strval($string);
$string = $exact ? $string : trim((string) preg_replace('/\s+/', ' ', $string));
foreach (self::emailGetCollectedEmails() as $record) {
$field_string = $record[$field] ?? '';
$field_string = $exact ? $field_string : trim((string) preg_replace('/\s+/', ' ', (string) $field_string));
if (str_contains((string) $field_string, $string)) {
return $record;
}
}
return NULL;
}
/**
* Extract all links from provided string.
*
* @param string $string
* String to extract links from.
*
* @return array<int, string>
* Array of extracted links.
*/
protected static function emailExtractLinks(string $string): array {
// Correct links before extraction.
$pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))';
$string = preg_replace_callback(sprintf('#%s#i', $pattern), function (array $matches): string {
return preg_match('!^https?://!i', $matches[0]) ? $matches[0] : 'http://' . $matches[0];
}, $string);
preg_match_all(sprintf('#%s#i', $pattern), (string) $string, $matches);
return empty($matches[0]) ? [] : $matches[0];
}
/**
* Extract email types from tags.
*
* @param array<int, string> $tags
* Array of tags.
*
* @return array<int, string>
* Array of email types.
*/
protected static function emailExtractTypes(array $tags): array {
$types = [];
foreach ($tags as $tag) {
if (str_starts_with((string) $tag, 'email')) {
$parts = explode(':', (string) $tag);
$types[] = count($parts) > 1 ? implode(':', array_slice($parts, 1)) : 'default';
}
}
return $types;
}
}