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(), // createParams
318 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
319 FALSE, // expectedFailure
320 1, // expectedJobCount
324 array(), // createParams
325 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
326 "/Failed to determine current user/", // expectedFailure
327 0, // expectedJobCount
331 array(), // createParams
332 array('scheduled_date' => '2014-12-13 10:00:00'),
333 FALSE, // expectedFailure
334 1, // expectedJobCount
338 array(), // createParams
340 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
341 0, // expectedJobCount
345 array('name' => ''), // createParams
346 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
347 "/Mailing cannot be sent. There are missing fields \\(name\\)./", // expectedFailure
348 0, // expectedJobCount
354 * @param bool $useLogin
355 * @param array $createParams
356 * @param array $submitParams
357 * @param null|string $expectedFailure
358 * @param int $expectedJobCount
359 * @dataProvider submitProvider
361 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
363 $this->createLoggedInUser();
366 $id = $this->createDraftMailing($createParams);
368 $submitParams['id'] = $id;
369 if ($expectedFailure) {
370 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
371 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
374 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
375 $this->assertTrue(is_numeric($submitResult['id']));
376 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
377 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
379 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
380 1 => array($id, 'Integer'),
387 public function testMailerStats() {
388 $result = $this->groupContactCreate($this->_groupID
, 100);
389 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
391 //Create and send test mail first and change the mail job to live,
392 //because stats api only works on live mail
393 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
394 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
395 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
396 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
398 //Change the test mail into live
399 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
400 CRM_Core_DAO
::executeQuery($sql);
402 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
403 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
404 (event_queue_id int, time_stamp datetime, delivered_id int)
405 SELECT event_queue_id, time_stamp, id
406 FROM civicrm_mailing_event_delivered
407 WHERE id IN ($deliveredIds)
408 ORDER BY RAND() LIMIT 0,20;";
409 CRM_Core_DAO
::executeQuery($sql);
411 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
412 CRM_Core_DAO
::executeQuery($sql);
414 if ($type == 'unsubscribe') {
415 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
416 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
419 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
420 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
422 CRM_Core_DAO
::executeQuery($sql);
425 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
426 $expectedResult = array(
427 'Delivered' => 80, //since among 100 mails 20 has been bounced
430 'Unique Clicks' => 0,
431 'Unsubscribers' => 20,
433 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
437 * Test civicrm_mailing_delete
439 public function testMailerDeleteSuccess() {
440 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
441 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
442 $this->assertAPIDeleted($this->_entity
, $result['id']);
445 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
447 //------------ civicrm_mailing_event_bounce methods------------
450 * Test civicrm_mailing_event_bounce with wrong params.
451 * Note that tests like this are slightly better than no test but an
452 * api function cannot be considered supported / 'part of the api' without a
455 public function testMailerBounceWrongParams() {
457 'job_id' => 'Wrong ID',
458 'event_queue_id' => 'Wrong ID',
459 'hash' => 'Wrong Hash',
461 'time_stamp' => '20111109212100',
463 $this->callAPIFailure('mailing_event', 'bounce', $params,
464 'Queue event could not be found'
468 //----------- civicrm_mailing_event_confirm methods -----------
471 * Test civicrm_mailing_event_confirm with wrong params.
472 * Note that tests like this are slightly better than no test but an
473 * api function cannot be considered supported / 'part of the api' without a
476 public function testMailerConfirmWrongParams() {
478 'contact_id' => 'Wrong ID',
479 'subscribe_id' => 'Wrong ID',
480 'hash' => 'Wrong Hash',
481 'event_subscribe_id' => '123',
482 'time_stamp' => '20111111010101',
484 $this->callAPIFailure('mailing_event', 'confirm', $params,
485 'Confirmation failed'
489 //---------- civicrm_mailing_event_reply methods -----------
492 * Test civicrm_mailing_event_reply with wrong params.
494 * Note that tests like this are slightly better than no test but an
495 * api function cannot be considered supported / 'part of the api' without a
498 public function testMailerReplyWrongParams() {
500 'job_id' => 'Wrong ID',
501 'event_queue_id' => 'Wrong ID',
502 'hash' => 'Wrong Hash',
503 'bodyTxt' => 'Body...',
504 'replyTo' => $this->_email
,
505 'time_stamp' => '20111111010101',
507 $this->callAPIFailure('mailing_event', 'reply', $params,
508 'Queue event could not be found'
513 //----------- civicrm_mailing_event_forward methods ----------
516 * Test civicrm_mailing_event_forward with wrong params.
517 * Note that tests like this are slightly better than no test but an
518 * api function cannot be considered supported / 'part of the api' without a
521 public function testMailerForwardWrongParams() {
523 'job_id' => 'Wrong ID',
524 'event_queue_id' => 'Wrong ID',
525 'hash' => 'Wrong Hash',
526 'email' => $this->_email
,
527 'time_stamp' => '20111111010101',
529 $this->callAPIFailure('mailing_event', 'forward', $params,
530 'Queue event could not be found'
535 * @param array $params
536 * Extra parameters for the draft mailing.
539 public function createDraftMailing($params = array()) {
540 $createParams = array_merge($this->_params
, $params);
541 $createParams['api.mailing_job.create'] = 0; // note: exact match to API default
542 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
543 $this->assertTrue(is_numeric($createResult['id']));
544 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
545 1 => array($createResult['id'], 'Integer'),
547 return $createResult['id'];
550 //----------- civicrm_mailing_create ----------