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',
90 'last_name' => 'Excluder'
92 $this->callAPISuccess('GroupContact', 'create', array(
93 'group_id' => $groupIDs['a'],
94 'contact_id' => $contactIDs['a']
96 $this->callAPISuccess('GroupContact', 'create', array(
97 'group_id' => $groupIDs['b'],
98 'contact_id' => $contactIDs['b']
103 $createParams = $this->_params
;
104 $createParams['groups']['include'] = array($groupIDs['a']);
105 $createParams['groups']['exclude'] = array();
106 $createParams['mailings']['include'] = array();
107 $createParams['mailings']['exclude'] = array();
108 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
109 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
110 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
111 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
112 $getRecip1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
113 $getRecip1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecip1['values']));
114 $this->assertEquals(array($contactIDs['a']), $getRecip1_ids);
116 // ** Pass 2: Update without any changes to groups[include]
117 $nullopParams = $createParams;
118 $nullopParams['id'] = $createResult['id'];
119 $updateParams['api.mailing_job.create'] = 1;
120 unset($nullopParams['groups']['include']);
121 $this->callAPISuccess('Mailing', 'create', $nullopParams);
122 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
123 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
124 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
125 $getRecip2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
126 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecip2['values']));
127 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
129 // ** Pass 3: Update with different groups[include]
130 $updateParams = $createParams;
131 $updateParams['id'] = $createResult['id'];
132 $updateParams['groups']['include'] = array($groupIDs['b']);
133 $updateParams['api.mailing_job.create'] = 1;
134 $this->callAPISuccess('Mailing', 'create', $updateParams);
135 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
136 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
137 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
138 $getRecip3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
139 $getRecip3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecip3['values']));
140 $this->assertEquals(array($contactIDs['b']), $getRecip3_ids);
143 public function testMailerPreview() {
145 $contactID = $this->individualCreate();
146 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
147 $displayName = $displayName['values'][$contactID]['display_name'];
148 $this->assertTrue(!empty($displayName));
150 $params = $this->_params
;
151 $params['api.Mailing.preview'] = array(
153 'contact_id' => $contactID,
155 $params['options']['force_rollback'] = 1;
159 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
160 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
161 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
162 'recip' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
164 $result = $this->callAPISuccess('mailing', 'create', $params);
165 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
166 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
167 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
168 $this->assertDBQuery($maxIDs['recip'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
170 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
171 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
172 $this->assertEquals("This is $displayName", $previewResult['values']['body_text']);
173 $this->assertContains("<p>This is $displayName</p>", $previewResult['values']['body_html']);
176 public function testMailerPreviewRecipients() {
178 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
179 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
180 $contactIDs['includeme'] = $this->individualCreate(array(
181 'email' => 'include.me@example.org',
182 'first_name' => 'Includer',
183 'last_name' => 'Person'
185 $contactIDs['excludeme'] = $this->individualCreate(array(
186 'email' => 'exclude.me@example.org',
187 'last_name' => 'Excluder',
188 'last_name' => 'Excluder'
190 $this->callAPISuccess('GroupContact', 'create', array(
191 'group_id' => $groupIDs['inc'],
192 'contact_id' => $contactIDs['includeme']
194 $this->callAPISuccess('GroupContact', 'create', array(
195 'group_id' => $groupIDs['inc'],
196 'contact_id' => $contactIDs['excludeme']
198 $this->callAPISuccess('GroupContact', 'create', array(
199 'group_id' => $groupIDs['exc'],
200 'contact_id' => $contactIDs['excludeme']
203 $params = $this->_params
;
204 $params['groups']['include'] = array($groupIDs['inc']);
205 $params['groups']['exclude'] = array($groupIDs['exc']);
206 $params['mailings']['include'] = array();
207 $params['mailings']['exclude'] = array();
208 $params['options']['force_rollback'] = 1;
209 $params['api.MailingRecipients.get'] = array(
210 'mailing_id' => '$value.id',
211 'api.contact.getvalue' => array(
212 'return' => 'display_name',
214 'api.email.getvalue' => array(
221 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
222 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
223 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
225 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
226 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
227 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
228 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
230 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
231 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
232 $this->assertEquals(array((string) $contactIDs['includeme']), $previewIds);
233 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
234 $this->assertEquals(array('include.me@example.org'), $previewEmails);
235 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
236 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
239 public function testMailerSendTest_email() {
240 $contactIDs['alice'] = $this->individualCreate(array(
241 'email' => 'alice@example.org',
242 'first_name' => 'Alice',
243 'last_name' => 'Person'
246 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
248 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
249 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
250 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
252 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
253 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
255 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
256 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
259 public function testMailerSendTest_group() {
261 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
262 $contactIDs['alice'] = $this->individualCreate(array(
263 'email' => 'alice@example.org',
264 'first_name' => 'Alice',
265 'last_name' => 'Person'
267 $contactIDs['bob'] = $this->individualCreate(array(
268 'email' => 'bob@example.org',
269 'first_name' => 'Bob',
270 'last_name' => 'Person'
272 $contactIDs['carol'] = $this->individualCreate(array(
273 'email' => 'carol@example.org',
274 'first_name' => 'Carol',
275 'last_name' => 'Person'
277 $this->callAPISuccess('GroupContact', 'create', array(
278 'group_id' => $groupIDs['inc'],
279 'contact_id' => $contactIDs['alice']
281 $this->callAPISuccess('GroupContact', 'create', array(
282 'group_id' => $groupIDs['inc'],
283 'contact_id' => $contactIDs['bob']
285 $this->callAPISuccess('GroupContact', 'create', array(
286 'group_id' => $groupIDs['inc'],
287 'contact_id' => $contactIDs['carol']
291 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
292 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
293 'mailing_id' => $mail['id'],
294 'test_email' => NULL,
295 'test_group' => $groupIDs['inc'],
297 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
299 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
300 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
302 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
303 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
306 public function submitProvider() {
307 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
310 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
311 FALSE, // expectedFailure
312 1, // expectedJobCount
316 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
317 "/Failed to determine current user/", // expectedFailure
318 0, // expectedJobCount
322 array('scheduled_date' => '2014-12-13 10:00:00'),
323 FALSE, // expectedFailure
324 1, // expectedJobCount
329 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
330 0, // expectedJobCount
336 * @param bool $useLogin
337 * @param array $params
338 * @param null|string $expectedFailure
339 * @param int $expectedJobCount
340 * @dataProvider submitProvider
342 public function testMailerSubmit($useLogin, $params, $expectedFailure, $expectedJobCount) {
344 $this->createLoggedInUser();
347 $id = $this->createDraftMailing();
350 if ($expectedFailure) {
351 $submitResult = $this->callAPIFailure('mailing', 'submit', $params);
352 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
355 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $params, __FUNCTION__
, __FILE__
);
356 $this->assertTrue(is_numeric($submitResult['id']));
357 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
358 $this->assertEquals($params['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
360 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
361 1 => array($id, 'Integer'),
365 public function testMailerStats() {
366 $result = $this->groupContactCreate($this->_groupID
, 100);
367 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
369 //Create and send test mail first and change the mail job to live,
370 //because stats api only works on live mail
371 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
372 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
373 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
374 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
376 //Change the test mail into live
377 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
378 CRM_Core_DAO
::executeQuery($sql);
380 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
381 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
382 (event_queue_id int, time_stamp datetime, delivered_id int)
383 SELECT event_queue_id, time_stamp, id
384 FROM civicrm_mailing_event_delivered
385 WHERE id IN ($deliveredIds)
386 ORDER BY RAND() LIMIT 0,20;";
387 CRM_Core_DAO
::executeQuery($sql);
389 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
390 CRM_Core_DAO
::executeQuery($sql);
392 if ($type == 'unsubscribe') {
393 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
394 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
397 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
398 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
400 CRM_Core_DAO
::executeQuery($sql);
403 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
404 $expectedResult = array(
405 'Delivered' => 80, //since among 100 mails 20 has been bounced
408 'Unique Clicks' => 0,
409 'Unsubscribers' => 20,
411 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
415 * Test civicrm_mailing_delete
417 public function testMailerDeleteSuccess() {
418 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
419 $jobs = $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
420 $this->assertAPIDeleted($this->_entity
, $result['id']);
423 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
425 //------------ civicrm_mailing_event_bounce methods------------
428 * Test civicrm_mailing_event_bounce with wrong params.
429 * Note that tests like this are slightly better than no test but an
430 * api function cannot be considered supported / 'part of the api' without a
433 public function testMailerBounceWrongParams() {
435 'job_id' => 'Wrong ID',
436 'event_queue_id' => 'Wrong ID',
437 'hash' => 'Wrong Hash',
439 'time_stamp' => '20111109212100',
441 $result = $this->callAPIFailure('mailing_event', 'bounce', $params,
442 'Queue event could not be found'
446 //----------- civicrm_mailing_event_confirm methods -----------
449 * Test civicrm_mailing_event_confirm with wrong params.
450 * Note that tests like this are slightly better than no test but an
451 * api function cannot be considered supported / 'part of the api' without a
454 public function testMailerConfirmWrongParams() {
456 'contact_id' => 'Wrong ID',
457 'subscribe_id' => 'Wrong ID',
458 'hash' => 'Wrong Hash',
459 'event_subscribe_id' => '123',
460 'time_stamp' => '20111111010101',
462 $result = $this->callAPIFailure('mailing_event', 'confirm', $params,
463 'Confirmation failed'
467 //---------- civicrm_mailing_event_reply methods -----------
470 * Test civicrm_mailing_event_reply 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 testMailerReplyWrongParams() {
478 'job_id' => 'Wrong ID',
479 'event_queue_id' => 'Wrong ID',
480 'hash' => 'Wrong Hash',
481 'bodyTxt' => 'Body...',
482 'replyTo' => $this->_email
,
483 'time_stamp' => '20111111010101',
485 $result = $this->callAPIFailure('mailing_event', 'reply', $params,
486 'Queue event could not be found'
491 //----------- civicrm_mailing_event_forward methods ----------
494 * Test civicrm_mailing_event_forward with wrong params.
495 * Note that tests like this are slightly better than no test but an
496 * api function cannot be considered supported / 'part of the api' without a
499 public function testMailerForwardWrongParams() {
501 'job_id' => 'Wrong ID',
502 'event_queue_id' => 'Wrong ID',
503 'hash' => 'Wrong Hash',
504 'email' => $this->_email
,
505 'time_stamp' => '20111111010101',
507 $result = $this->callAPIFailure('mailing_event', 'forward', $params,
508 'Queue event could not be found'
515 public function createDraftMailing() {
516 $createParams = $this->_params
;
517 $createParams['api.mailing_job.create'] = 0; // note: exact match to API default
518 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
519 $this->assertTrue(is_numeric($createResult['id']));
520 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
521 1 => array($createResult['id'], 'Integer'),
523 return $createResult['id'];
526 //----------- civicrm_mailing_create ----------