3 * File for the TestMailing class
9 * This file is part of CiviCRM
11 * CiviCRM is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Affero General Public License
13 * as published by the Free Software Foundation; either version 3 of
14 * the License, or (at your option) any later version.
16 * CiviCRM is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
21 * You should have received a copy of the GNU Affero General Public
22 * License along with this program. If not, see
23 * <http://www.gnu.org/licenses/>.
26 require_once 'CiviTest/CiviUnitTestCase.php';
30 * Test APIv3 civicrm_mailing_* functions
34 class api_v3_MailingTest
extends CiviUnitTestCase
{
37 protected $_apiversion = 3;
38 protected $_params = array();
39 protected $_entity = 'Mailing';
40 protected $_contactID;
42 public function setUp() {
44 $this->useTransaction();
45 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
46 $this->_contactID
= $this->individualCreate();
47 $this->_groupID
= $this->groupCreate();
48 $this->_email
= 'test@test.test';
49 $this->_params
= array(
50 'subject' => 'Hello {contact.display_name}',
51 'body_text' => "This is {contact.display_name}",
52 'body_html' => "<p>This is {contact.display_name}</p>",
53 'name' => 'mailing name',
54 'created_id' => $this->_contactID
,
58 public function tearDown() {
59 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
64 * Test civicrm_mailing_create
66 public function testMailerCreateSuccess() {
67 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params
, __FUNCTION__
, __FILE__
);
68 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
69 $this->assertEquals(1, $jobs['count']);
70 unset($this->_params
['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
71 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
75 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
76 * Make sure these work
78 public function testMagicGroups_create_update() {
80 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
81 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
82 $contactIDs['a'] = $this->individualCreate(array(
83 'email' => 'include.me@example.org',
84 'first_name' => 'Includer',
85 'last_name' => 'Person'
87 $contactIDs['b'] = $this->individualCreate(array(
88 'email' => 'exclude.me@example.org',
89 'last_name' => 'Excluder'
91 $this->callAPISuccess('GroupContact', 'create', array(
92 'group_id' => $groupIDs['a'],
93 'contact_id' => $contactIDs['a']
95 $this->callAPISuccess('GroupContact', 'create', array(
96 'group_id' => $groupIDs['b'],
97 'contact_id' => $contactIDs['b']
102 $createParams = $this->_params
;
103 $createParams['groups']['include'] = array($groupIDs['a']);
104 $createParams['groups']['exclude'] = array();
105 $createParams['mailings']['include'] = array();
106 $createParams['mailings']['exclude'] = array();
107 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
108 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
109 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
110 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
111 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
112 $getRecipient1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient1['values']));
113 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
115 // ** Pass 2: Update without any changes to groups[include]
116 $nullOpParams = $createParams;
117 $nullOpParams['id'] = $createResult['id'];
118 $updateParams['api.mailing_job.create'] = 1;
119 unset($nullOpParams['groups']['include']);
120 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
121 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
122 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
123 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
124 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
125 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient2['values']));
126 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
128 // ** Pass 3: Update with different groups[include]
129 $updateParams = $createParams;
130 $updateParams['id'] = $createResult['id'];
131 $updateParams['groups']['include'] = array($groupIDs['b']);
132 $updateParams['api.mailing_job.create'] = 1;
133 $this->callAPISuccess('Mailing', 'create', $updateParams);
134 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
135 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
136 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
137 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
138 $getRecipient3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient3['values']));
139 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
142 public function testMailerPreview() {
144 $contactID = $this->individualCreate();
145 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
146 $displayName = $displayName['values'][$contactID]['display_name'];
147 $this->assertTrue(!empty($displayName));
149 $params = $this->_params
;
150 $params['api.Mailing.preview'] = array(
152 'contact_id' => $contactID,
154 $params['options']['force_rollback'] = 1;
158 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
159 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
160 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
161 'recipient' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
163 $result = $this->callAPISuccess('mailing', 'create', $params);
164 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
165 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
166 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
167 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
169 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
170 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
171 $this->assertEquals("This is $displayName", $previewResult['values']['body_text']);
172 $this->assertContains("<p>This is $displayName</p>", $previewResult['values']['body_html']);
175 public function testMailerPreviewRecipients() {
177 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
178 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
179 $contactIDs['include_me'] = $this->individualCreate(array(
180 'email' => 'include.me@example.org',
181 'first_name' => 'Includer',
182 'last_name' => 'Person'
184 $contactIDs['exclude_me'] = $this->individualCreate(array(
185 'email' => 'exclude.me@example.org',
186 'last_name' => 'Excluder',
188 $this->callAPISuccess('GroupContact', 'create', array(
189 'group_id' => $groupIDs['inc'],
190 'contact_id' => $contactIDs['include_me']
192 $this->callAPISuccess('GroupContact', 'create', array(
193 'group_id' => $groupIDs['inc'],
194 'contact_id' => $contactIDs['exclude_me']
196 $this->callAPISuccess('GroupContact', 'create', array(
197 'group_id' => $groupIDs['exc'],
198 'contact_id' => $contactIDs['exclude_me']
201 $params = $this->_params
;
202 $params['groups']['include'] = array($groupIDs['inc']);
203 $params['groups']['exclude'] = array($groupIDs['exc']);
204 $params['mailings']['include'] = array();
205 $params['mailings']['exclude'] = array();
206 $params['options']['force_rollback'] = 1;
207 $params['api.MailingRecipients.get'] = array(
208 'mailing_id' => '$value.id',
209 'api.contact.getvalue' => array(
210 'return' => 'display_name',
212 'api.email.getvalue' => array(
219 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
220 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
221 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
223 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
224 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
225 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
226 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
228 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
229 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
230 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
231 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
232 $this->assertEquals(array('include.me@example.org'), $previewEmails);
233 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
234 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
240 public function testMailerSendTest_email() {
241 $contactIDs['alice'] = $this->individualCreate(array(
242 'email' => 'alice@example.org',
243 'first_name' => 'Alice',
244 'last_name' => 'Person'
247 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
249 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
250 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
251 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
253 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
254 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
256 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
257 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
263 public function testMailerSendTest_group() {
265 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
266 $contactIDs['alice'] = $this->individualCreate(array(
267 'email' => 'alice@example.org',
268 'first_name' => 'Alice',
269 'last_name' => 'Person'
271 $contactIDs['bob'] = $this->individualCreate(array(
272 'email' => 'bob@example.org',
273 'first_name' => 'Bob',
274 'last_name' => 'Person'
276 $contactIDs['carol'] = $this->individualCreate(array(
277 'email' => 'carol@example.org',
278 'first_name' => 'Carol',
279 'last_name' => 'Person'
281 $this->callAPISuccess('GroupContact', 'create', array(
282 'group_id' => $groupIDs['inc'],
283 'contact_id' => $contactIDs['alice']
285 $this->callAPISuccess('GroupContact', 'create', array(
286 'group_id' => $groupIDs['inc'],
287 'contact_id' => $contactIDs['bob']
289 $this->callAPISuccess('GroupContact', 'create', array(
290 'group_id' => $groupIDs['inc'],
291 'contact_id' => $contactIDs['carol']
295 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
296 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
297 'mailing_id' => $mail['id'],
298 'test_email' => NULL,
299 'test_group' => $groupIDs['inc'],
301 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
303 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
304 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
306 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
307 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
313 public function submitProvider() {
314 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
317 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
318 FALSE, // expectedFailure
319 1, // expectedJobCount
323 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
324 "/Failed to determine current user/", // expectedFailure
325 0, // expectedJobCount
329 array('scheduled_date' => '2014-12-13 10:00:00'),
330 FALSE, // expectedFailure
331 1, // expectedJobCount
336 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
337 0, // expectedJobCount
343 * @param bool $useLogin
344 * @param array $params
345 * @param null|string $expectedFailure
346 * @param int $expectedJobCount
347 * @dataProvider submitProvider
349 public function testMailerSubmit($useLogin, $params, $expectedFailure, $expectedJobCount) {
351 $this->createLoggedInUser();
354 $id = $this->createDraftMailing();
357 if ($expectedFailure) {
358 $submitResult = $this->callAPIFailure('mailing', 'submit', $params);
359 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
362 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $params, __FUNCTION__
, __FILE__
);
363 $this->assertTrue(is_numeric($submitResult['id']));
364 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
365 $this->assertEquals($params['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
367 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
368 1 => array($id, 'Integer'),
375 public function testMailerStats() {
376 $result = $this->groupContactCreate($this->_groupID
, 100);
377 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
379 //Create and send test mail first and change the mail job to live,
380 //because stats api only works on live mail
381 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
382 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
383 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
384 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
386 //Change the test mail into live
387 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
388 CRM_Core_DAO
::executeQuery($sql);
390 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
391 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
392 (event_queue_id int, time_stamp datetime, delivered_id int)
393 SELECT event_queue_id, time_stamp, id
394 FROM civicrm_mailing_event_delivered
395 WHERE id IN ($deliveredIds)
396 ORDER BY RAND() LIMIT 0,20;";
397 CRM_Core_DAO
::executeQuery($sql);
399 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
400 CRM_Core_DAO
::executeQuery($sql);
402 if ($type == 'unsubscribe') {
403 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
404 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
407 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
408 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
410 CRM_Core_DAO
::executeQuery($sql);
413 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
414 $expectedResult = array(
415 'Delivered' => 80, //since among 100 mails 20 has been bounced
418 'Unique Clicks' => 0,
419 'Unsubscribers' => 20,
421 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
425 * Test civicrm_mailing_delete
427 public function testMailerDeleteSuccess() {
428 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
429 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
430 $this->assertAPIDeleted($this->_entity
, $result['id']);
433 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
435 //------------ civicrm_mailing_event_bounce methods------------
438 * Test civicrm_mailing_event_bounce with wrong params.
439 * Note that tests like this are slightly better than no test but an
440 * api function cannot be considered supported / 'part of the api' without a
443 public function testMailerBounceWrongParams() {
445 'job_id' => 'Wrong ID',
446 'event_queue_id' => 'Wrong ID',
447 'hash' => 'Wrong Hash',
449 'time_stamp' => '20111109212100',
451 $this->callAPIFailure('mailing_event', 'bounce', $params,
452 'Queue event could not be found'
456 //----------- civicrm_mailing_event_confirm methods -----------
459 * Test civicrm_mailing_event_confirm with wrong params.
460 * Note that tests like this are slightly better than no test but an
461 * api function cannot be considered supported / 'part of the api' without a
464 public function testMailerConfirmWrongParams() {
466 'contact_id' => 'Wrong ID',
467 'subscribe_id' => 'Wrong ID',
468 'hash' => 'Wrong Hash',
469 'event_subscribe_id' => '123',
470 'time_stamp' => '20111111010101',
472 $this->callAPIFailure('mailing_event', 'confirm', $params,
473 'Confirmation failed'
477 //---------- civicrm_mailing_event_reply methods -----------
480 * Test civicrm_mailing_event_reply with wrong params.
482 * Note that tests like this are slightly better than no test but an
483 * api function cannot be considered supported / 'part of the api' without a
486 public function testMailerReplyWrongParams() {
488 'job_id' => 'Wrong ID',
489 'event_queue_id' => 'Wrong ID',
490 'hash' => 'Wrong Hash',
491 'bodyTxt' => 'Body...',
492 'replyTo' => $this->_email
,
493 'time_stamp' => '20111111010101',
495 $this->callAPIFailure('mailing_event', 'reply', $params,
496 'Queue event could not be found'
501 //----------- civicrm_mailing_event_forward methods ----------
504 * Test civicrm_mailing_event_forward with wrong params.
505 * Note that tests like this are slightly better than no test but an
506 * api function cannot be considered supported / 'part of the api' without a
509 public function testMailerForwardWrongParams() {
511 'job_id' => 'Wrong ID',
512 'event_queue_id' => 'Wrong ID',
513 'hash' => 'Wrong Hash',
514 'email' => $this->_email
,
515 'time_stamp' => '20111111010101',
517 $this->callAPIFailure('mailing_event', 'forward', $params,
518 'Queue event could not be found'
525 public function createDraftMailing() {
526 $createParams = $this->_params
;
527 $createParams['api.mailing_job.create'] = 0; // note: exact match to API default
528 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
529 $this->assertTrue(is_numeric($createResult['id']));
530 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
531 1 => array($createResult['id'], 'Integer'),
533 return $createResult['id'];
536 //----------- civicrm_mailing_create ----------