Merge pull request #23824 from totten/mixin-refresh
[civicrm-core.git] / tests / phpunit / CiviTest / CiviMailUtils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Mail utils for use during unit testing to allow retrieval
14 * and examination of 'sent' emails.
15 *
16 * Basic usage:
17 *
18 * $mut = new CiviMailUtils( $this, true ); //true automatically starts spooling
19 * ... do stuff ...
20 * $msg = $mut->getMostRecentEmail( 'raw' ); // or 'ezc' to get an ezc mail object
21 * ... assert stuff about $msg ...
22 * $mut->stop();
23 *
24 *
25 * @package CiviCRM
26 */
27
28 /**
29 * Class CiviMailUtils
30 */
31 class CiviMailUtils extends PHPUnit\Framework\TestCase {
32
33 /**
34 * Current outbound email option
35 * @var mixed
36 */
37 protected $_outBound_option = NULL;
38
39 /**
40 * Constructor.
41 *
42 * @param CiviUnitTestCase $unit_test The currently running test
43 * @param bool $startImmediately
44 * Start writing to db now or wait until start() is called.
45 */
46 public function __construct(&$unit_test, $startImmediately = TRUE) {
47 $this->_ut = $unit_test;
48
49 if ($startImmediately) {
50 $this->start();
51 }
52 }
53
54 /**
55 * Clean up after test.
56 *
57 * @throws \CRM_Core_Exception
58 */
59 public function __destruct() {
60 $this->stop();
61 $this->clearMessages();
62 }
63
64 /**
65 * Start writing emails to db instead of current option.
66 */
67 public function start() {
68 // save current setting for outbound option, then change it
69 $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
70 'mailing_backend'
71 );
72
73 $this->_outBound_option = $mailingBackend['outBound_option'];
74 $mailingBackend['outBound_option'] = CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB;
75
76 Civi::settings()->set('mailing_backend', $mailingBackend);
77
78 $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
79 'mailing_backend'
80 );
81 }
82
83 public function stop() {
84 $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
85 'mailing_backend'
86 );
87
88 $mailingBackend['outBound_option'] = $this->_outBound_option;
89
90 Civi::settings()->set('mailing_backend', $mailingBackend);
91 }
92
93 /**
94 * @param string $type
95 *
96 * @return ezcMail|string
97 */
98 public function getMostRecentEmail($type = 'raw') {
99 $msg = '';
100
101 $dao = CRM_Core_DAO::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id DESC LIMIT 1');
102 if ($dao->fetch()) {
103 $msg = $dao->headers . "\n\n" . $dao->body;
104 }
105
106 switch ($type) {
107 case 'raw':
108 // nothing to do
109 break;
110
111 case 'ezc':
112 $msg = $this->convertToEzc($msg);
113 break;
114 }
115 return $msg;
116 }
117
118 /**
119 * @param string $type
120 * 'raw'|'ezc'.
121 *
122 * @throws CRM_Core_Exception
123 *
124 * @return array(ezcMail)|array(string)
125 */
126 public function getAllMessages($type = 'raw') {
127 $msgs = [];
128
129 $dao = CRM_Core_DAO::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id');
130 while ($dao->fetch()) {
131 $msgs[] = $dao->headers . "\n\n" . $dao->body;
132 }
133
134 switch ($type) {
135 case 'raw':
136 // nothing to do
137 break;
138
139 case 'ezc':
140 foreach ($msgs as $i => $msg) {
141 $msgs[$i] = $this->convertToEzc($msg);
142 }
143 break;
144 }
145
146 return $msgs;
147 }
148
149 /*
150 * Utility functions (previously part of CiviUnitTestCase)
151 * Included for backward compatibility with existing tests.
152 */
153
154 /**
155 * Check contents of mail log.
156 *
157 * @param array $strings
158 * Strings that should be included.
159 * @param array $absentStrings
160 * Strings that should not be included.
161 * @param string $prefix
162 *
163 * @return \ezcMail|string
164 */
165 public function checkMailLog($strings, $absentStrings = [], $prefix = '') {
166 $mail = $this->getMostRecentEmail('raw');
167 return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
168 }
169
170 /**
171 * Check contents of mail log.
172 *
173 * @param array $strings
174 * Strings that should be included.
175 * @param array $absentStrings
176 * Strings that should not be included.
177 * @param string $prefix
178 *
179 * @return \ezcMail|string
180 */
181 public function checkAllMailLog($strings, $absentStrings = [], $prefix = '') {
182 $mails = $this->getAllMessages('raw');
183 $mail = implode(',', $mails);
184 return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
185 }
186
187 /**
188 * Check that mail log is empty.
189 * @param string $prefix
190 */
191 public function assertMailLogEmpty($prefix = '') {
192 $mail = $this->getMostRecentEmail('raw');
193 $this->_ut->assertEmpty($mail, 'mail sent when it should not have been ' . $prefix);
194 }
195
196 /**
197 * Assert that $expectedRecipients (and no else) have received emails
198 *
199 * @param array $expectedRecipients
200 * Array($msgPos => array($recipPos => $emailAddr)).
201 */
202 public function assertRecipients($expectedRecipients) {
203 $recipients = [];
204 foreach ($this->getAllMessages('ezc') as $message) {
205 $recipients[] = CRM_Utils_Array::collect('email', $message->to);
206 }
207 $cmp = function($a, $b) {
208 if ($a[0] == $b[0]) {
209 return 0;
210 }
211 return ($a[0] < $b[0]) ? 1 : -1;
212 };
213 usort($recipients, $cmp);
214 usort($expectedRecipients, $cmp);
215 $this->_ut->assertEquals(
216 $expectedRecipients,
217 $recipients,
218 "Incorrect recipients: " . print_r(array('expected' => $expectedRecipients, 'actual' => $recipients), TRUE)
219 );
220 }
221
222 /**
223 * Assert that $expectedSubjects (and no other subjects) were sent.
224 *
225 * @param array $expectedSubjects
226 * Array(string $subj).
227 */
228 public function assertSubjects($expectedSubjects) {
229 $subjects = [];
230 foreach ($this->getAllMessages('ezc') as $message) {
231 /** @var ezcMail $message */
232 $subjects[] = $message->subject;
233 }
234 sort($subjects);
235 sort($expectedSubjects);
236 $this->_ut->assertEquals(
237 $expectedSubjects,
238 $subjects,
239 "Incorrect subjects: " . print_r(array('expected' => $expectedSubjects, 'actual' => $subjects), TRUE)
240 );
241 }
242
243 /**
244 * Remove any sent messages from the log.
245 *
246 * @param int $limit
247 * How many recent messages to remove, defaults to 0 (all).
248 *
249 * @throws \CRM_Core_Exception
250 */
251 public function clearMessages($limit = 0) {
252 $sql = 'DELETE FROM civicrm_mailing_spool ORDER BY id DESC';
253 if ($limit) {
254 $sql .= ' LIMIT ' . $limit;
255 }
256 CRM_Core_DAO::executeQuery($sql);
257 }
258
259 /**
260 * @param string $msg
261 * Email header and body.
262 * @return ezcMail
263 */
264 private function convertToEzc($msg) {
265 $set = new ezcMailVariableSet($msg);
266 $parser = new ezcMailParser();
267 $mail = $parser->parseMail($set);
268 $this->_ut->assertNotEmpty($mail, 'Cannot parse mail');
269 return $mail[0];
270 }
271
272 /**
273 * @param array $strings
274 * @param $absentStrings
275 * @param $prefix
276 * @param $mail
277 * @return mixed
278 */
279 public function checkMailForStrings(array $strings, $absentStrings, $prefix, $mail) {
280 foreach ($strings as $string) {
281 $this->_ut->assertStringContainsString($string, $mail, "$string . not found in $mail $prefix");
282 }
283 foreach ($absentStrings as $string) {
284 $this->_ut->assertEmpty(strstr($mail, $string), "$string incorrectly found in $mail $prefix");
285 }
286 return $mail;
287 }
288
289 }