3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * Mail utils for use during unit testing to allow retrieval
14 * and examination of 'sent' emails.
18 * $mut = new CiviMailUtils( $this, true ); //true automatically starts spooling
20 * $msg = $mut->getMostRecentEmail( 'raw' ); // or 'ezc' to get an ezc mail object
21 * ... assert stuff about $msg ...
31 class CiviMailUtils
extends PHPUnit\Framework\TestCase
{
34 * Current outbound email option
37 protected $_outBound_option = NULL;
43 protected $_webtest = FALSE;
48 * @param CiviSeleniumTestCase|CiviUnitTestCase $unit_test The currently running test
49 * @param bool $startImmediately
50 * Start writing to db now or wait until start() is called.
52 public function __construct(&$unit_test, $startImmediately = TRUE) {
53 $this->_ut
= $unit_test;
55 // Check if running under webtests or not
56 if (is_subclass_of($unit_test, 'CiviSeleniumTestCase')) {
57 $this->_webtest
= TRUE;
60 if ($startImmediately) {
66 * Clean up after test.
68 * @throws \CRM_Core_Exception
70 public function __destruct() {
72 $this->clearMessages();
76 * Start writing emails to db instead of current option.
78 public function start() {
79 if ($this->_webtest
) {
80 // Change outbound mail setting
81 $this->_ut
->openCiviPage('admin/setting/smtp', "reset=1", "_qf_Smtp_next");
83 // First remember the current setting
84 $this->_outBound_option
= $this->getSelectedOutboundOption();
86 $this->_ut
->click('xpath=//input[@name="outBound_option" and @value="' . CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
. '"]');
87 $this->_ut
->clickLink("_qf_Smtp_next");
89 // Is there supposed to be a status message displayed when outbound email settings are changed?
95 // save current setting for outbound option, then change it
96 $mailingBackend = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
100 $this->_outBound_option
= $mailingBackend['outBound_option'];
101 $mailingBackend['outBound_option'] = CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
;
103 Civi
::settings()->set('mailing_backend', $mailingBackend);
105 $mailingBackend = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
111 public function stop() {
112 if ($this->_webtest
) {
113 if ($this->_outBound_option
!= CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
) {
114 // Change outbound mail setting
115 $this->_ut
->openCiviPage('admin/setting/smtp', "reset=1", "_qf_Smtp_next");
116 $this->_ut
->click('xpath=//input[@name="outBound_option" and @value="' . $this->_outBound_option
. '"]');
117 // There will be a warning when switching from test to live mode
118 if ($this->_outBound_option
!= CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
) {
119 $this->_ut
->getAlert();
121 $this->_ut
->clickLink("_qf_Smtp_next");
126 $mailingBackend = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
130 $mailingBackend['outBound_option'] = $this->_outBound_option
;
132 Civi
::settings()->set('mailing_backend', $mailingBackend);
137 * @param string $type
139 * @return ezcMail|string
141 public function getMostRecentEmail($type = 'raw') {
144 if ($this->_webtest
) {
145 // I don't understand but for some reason we have to load the page twice for a recent mailing to appear.
146 $this->_ut
->openCiviPage('mailing/browse/archived', 'reset=1');
147 $this->_ut
->openCiviPage('mailing/browse/archived', 'reset=1', 'css=td.crm-mailing-name');
149 // We can't fetch mailing headers from webtest so we'll only try if the format is raw
150 if ($this->_webtest
&& $type == 'raw') {
151 // This should select the first "Report" link in the table, which is sorted by Completion Date descending, so in theory is the most recent email. Not sure of a more robust way at the moment.
152 $this->_ut
->clickLink('xpath=//tr[contains(@id, "crm-mailing_")]//a[text()="Report"]');
154 // Also not sure how robust this is, but there isn't a good
155 // identifier for this link either.
156 $this->_ut
->waitForElementPresent('xpath=//a[contains(text(), "View complete message")]');
157 $this->_ut
->clickAjaxLink('xpath=//a[contains(text(), "View complete message")]');
158 $msg = $this->_ut
->getText('css=.ui-dialog-content.crm-ajax-container');
161 $dao = CRM_Core_DAO
::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id DESC LIMIT 1');
163 $msg = $dao->headers
. "\n\n" . $dao->body
;
173 $msg = $this->convertToEzc($msg);
180 * @param string $type
183 * @throws CRM_Core_Exception
185 * @return array(ezcMail)|array(string)
187 public function getAllMessages($type = 'raw') {
190 if ($this->_webtest
) {
191 throw new CRM_Core_Exception('Not implemented: getAllMessages for WebTest');
193 $dao = CRM_Core_DAO
::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id');
194 while ($dao->fetch()) {
195 $msgs[] = $dao->headers
. "\n\n" . $dao->body
;
204 foreach ($msgs as $i => $msg) {
205 $msgs[$i] = $this->convertToEzc($msg);
216 public function getSelectedOutboundOption() {
217 $selectedOption = CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
;
218 // Is there a better way to do this? How do you get the currently selected value of a radio button in selenium?
219 for ($i = 0; $i <= 5; $i++
) {
220 if ($i != CRM_Mailing_Config
::OUTBOUND_OPTION_MOCK
) {
221 if ($this->_ut
->getValue('xpath=//input[@name="outBound_option" and @value="' . $i . '"]') == "on") {
222 $selectedOption = $i;
227 return $selectedOption;
231 * Utility functions (previously part of CiviUnitTestCase)
232 * Included for backward compatibility with existing tests.
236 * Check contents of mail log.
238 * @param array $strings
239 * Strings that should be included.
240 * @param array $absentStrings
241 * Strings that should not be included.
242 * @param string $prefix
244 * @return \ezcMail|string
246 public function checkMailLog($strings, $absentStrings = [], $prefix = '') {
247 $mail = $this->getMostRecentEmail('raw');
248 return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
252 * Check contents of mail log.
254 * @param array $strings
255 * Strings that should be included.
256 * @param array $absentStrings
257 * Strings that should not be included.
258 * @param string $prefix
260 * @return \ezcMail|string
262 public function checkAllMailLog($strings, $absentStrings = [], $prefix = '') {
263 $mails = $this->getAllMessages('raw');
264 $mail = implode(',', $mails);
265 return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
269 * Check that mail log is empty.
270 * @param string $prefix
272 public function assertMailLogEmpty($prefix = '') {
273 $mail = $this->getMostRecentEmail('raw');
274 $this->_ut
->assertEmpty($mail, 'mail sent when it should not have been ' . $prefix);
278 * Assert that $expectedRecipients (and no else) have received emails
280 * @param array $expectedRecipients
281 * Array($msgPos => array($recipPos => $emailAddr)).
283 public function assertRecipients($expectedRecipients) {
285 foreach ($this->getAllMessages('ezc') as $message) {
286 $recipients[] = CRM_Utils_Array
::collect('email', $message->to
);
288 $cmp = function($a, $b) {
289 if ($a[0] == $b[0]) {
292 return ($a[0] < $b[0]) ?
1 : -1;
294 usort($recipients, $cmp);
295 usort($expectedRecipients, $cmp);
296 $this->_ut
->assertEquals(
299 "Incorrect recipients: " . print_r(array('expected' => $expectedRecipients, 'actual' => $recipients), TRUE)
304 * Assert that $expectedSubjects (and no other subjects) were sent.
306 * @param array $expectedSubjects
307 * Array(string $subj).
309 public function assertSubjects($expectedSubjects) {
311 foreach ($this->getAllMessages('ezc') as $message) {
312 /** @var ezcMail $message */
313 $subjects[] = $message->subject
;
316 sort($expectedSubjects);
317 $this->_ut
->assertEquals(
320 "Incorrect subjects: " . print_r(array('expected' => $expectedSubjects, 'actual' => $subjects), TRUE)
325 * Remove any sent messages from the log.
328 * How many recent messages to remove, defaults to 0 (all).
330 * @throws \CRM_Core_Exception
332 public function clearMessages($limit = 0) {
333 if ($this->_webtest
) {
334 throw new \
CRM_Core_Exception("Not implemented: clearMessages for WebTest");
337 $sql = 'DELETE FROM civicrm_mailing_spool ORDER BY id DESC';
339 $sql .= ' LIMIT ' . $limit;
341 CRM_Core_DAO
::executeQuery($sql);
347 * Email header and body.
350 private function convertToEzc($msg) {
351 $set = new ezcMailVariableSet($msg);
352 $parser = new ezcMailParser();
353 $mail = $parser->parseMail($set);
354 $this->_ut
->assertNotEmpty($mail, 'Cannot parse mail');
359 * @param array $strings
360 * @param $absentStrings
365 public function checkMailForStrings(array $strings, $absentStrings = [], $prefix = '', $mail) {
366 foreach ($strings as $string) {
367 $this->_ut
->assertContains($string, $mail, "$string . not found in $mail $prefix");
369 foreach ($absentStrings as $string) {
370 $this->_ut
->assertEmpty(strstr($mail, $string), "$string incorrectly found in $mail $prefix");