Add templates/CRM/common/unittests.tpl
[civicrm-core.git] / tests / phpunit / api / v3 / MailingTest.php
CommitLineData
6a488035 1<?php
8891a36e 2/*
6a488035
TO
3 * File for the TestMailing class
4 *
5 * (PHP 5)
6 *
7 * @package CiviCRM
8 *
9 * This file is part of CiviCRM
10 *
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.
15 *
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.
20 *
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/>.
24 */
25
6a488035
TO
26
27/**
28 * Test APIv3 civicrm_mailing_* functions
29 *
6c6e6187 30 * @package CiviCRM
6a488035
TO
31 */
32class api_v3_MailingTest extends CiviUnitTestCase {
33 protected $_groupID;
34 protected $_email;
c43d01f3 35 protected $_apiversion = 3;
36 protected $_params = array();
e37b4b04 37 protected $_entity = 'Mailing';
161ae41b 38 protected $_contactID;
430ae6dd 39
d8e9212d
TO
40 /**
41 * APIv3 result from creating an example footer
42 * @var array
43 */
44 protected $footer;
45
00be9182 46 public function setUp() {
6a488035 47 parent::setUp();
7ada2376 48 $this->useTransaction();
97b7d4a0 49 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
161ae41b 50 $this->_contactID = $this->individualCreate();
fadb804f 51 $this->_groupID = $this->groupCreate();
ef170fe0 52 $this->_email = 'test@test.test';
c43d01f3 53 $this->_params = array(
51ae62c4 54 'subject' => 'Hello {contact.display_name}',
21b09c13
TO
55 'body_text' => "This is {contact.display_name}.\n{domain.address}{action.optOutUrl}",
56 'body_html' => "<p>This is {contact.display_name}.</p><p>{domain.address}{action.optOutUrl}</p>",
c43d01f3 57 'name' => 'mailing name',
161ae41b 58 'created_id' => $this->_contactID,
b0a31714
TO
59 'header_id' => '',
60 'footer_id' => '',
c43d01f3 61 );
d8e9212d
TO
62
63 $this->footer = civicrm_api3('MailingComponent', 'create', array(
64 'body_html' => '<p>From {domain.address}. To opt out, go to {action.optOutUrl}.</p>',
65 'body_text' => 'From {domain.address}. To opt out, go to {action.optOutUrl}.',
66 ));
6a488035
TO
67 }
68
00be9182 69 public function tearDown() {
97b7d4a0
TO
70 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
71 parent::tearDown();
6a488035
TO
72 }
73
74 /**
fe482240 75 * Test civicrm_mailing_create.
6a488035
TO
76 */
77 public function testMailerCreateSuccess() {
5f445749 78 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
c43d01f3 79 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
6a488035 80 $this->assertEquals(1, $jobs['count']);
ef170fe0 81 unset($this->_params['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
e37b4b04 82 $this->getAndCheck($this->_params, $result['id'], 'mailing');
6a488035
TO
83 }
84
21eb0c57
TO
85 /**
86 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
87 * Make sure these work
88 */
89 public function testMagicGroups_create_update() {
90 // BEGIN SAMPLE DATA
91 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
92 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
92915c55
TO
93 $contactIDs['a'] = $this->individualCreate(array(
94 'email' => 'include.me@example.org',
95 'first_name' => 'Includer',
5396af74 96 'last_name' => 'Person',
92915c55
TO
97 ));
98 $contactIDs['b'] = $this->individualCreate(array(
99 'email' => 'exclude.me@example.org',
5396af74 100 'last_name' => 'Excluder',
92915c55
TO
101 ));
102 $this->callAPISuccess('GroupContact', 'create', array(
103 'group_id' => $groupIDs['a'],
5396af74 104 'contact_id' => $contactIDs['a'],
92915c55
TO
105 ));
106 $this->callAPISuccess('GroupContact', 'create', array(
107 'group_id' => $groupIDs['b'],
5396af74 108 'contact_id' => $contactIDs['b'],
92915c55 109 ));
21eb0c57
TO
110 // END SAMPLE DATA
111
112 // ** Pass 1: Create
113 $createParams = $this->_params;
114 $createParams['groups']['include'] = array($groupIDs['a']);
115 $createParams['groups']['exclude'] = array();
116 $createParams['mailings']['include'] = array();
117 $createParams['mailings']['exclude'] = array();
5f445749 118 $createParams['api.mailing_job.create'] = 1;
21eb0c57
TO
119 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
120 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
121 $getGroup1_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup1['values']));
122 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
39010e60
EM
123 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
124 $getRecipient1_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient1['values']));
125 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
21eb0c57
TO
126
127 // ** Pass 2: Update without any changes to groups[include]
39010e60
EM
128 $nullOpParams = $createParams;
129 $nullOpParams['id'] = $createResult['id'];
7575b840 130 $updateParams['api.mailing_job.create'] = 1;
39010e60
EM
131 unset($nullOpParams['groups']['include']);
132 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
21eb0c57
TO
133 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
134 $getGroup2_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup2['values']));
135 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
39010e60
EM
136 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
137 $getRecip2_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient2['values']));
7575b840 138 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
21eb0c57
TO
139
140 // ** Pass 3: Update with different groups[include]
141 $updateParams = $createParams;
142 $updateParams['id'] = $createResult['id'];
143 $updateParams['groups']['include'] = array($groupIDs['b']);
7575b840 144 $updateParams['api.mailing_job.create'] = 1;
21eb0c57
TO
145 $this->callAPISuccess('Mailing', 'create', $updateParams);
146 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
147 $getGroup3_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup3['values']));
148 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
39010e60
EM
149 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
150 $getRecipient3_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient3['values']));
151 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
21eb0c57
TO
152 }
153
ef643544 154 public function testMailerPreview() {
51ae62c4 155 // BEGIN SAMPLE DATA
6c6e6187 156 $contactID = $this->individualCreate();
ef643544 157 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
158 $displayName = $displayName['values'][$contactID]['display_name'];
51ae62c4
TO
159 $this->assertTrue(!empty($displayName));
160
161 $params = $this->_params;
162 $params['api.Mailing.preview'] = array(
163 'id' => '$value.id',
164 'contact_id' => $contactID,
165 );
166 $params['options']['force_rollback'] = 1;
167 // END SAMPLE DATA
7811a84b 168
6c6e6187 169 $maxIDs = array(
51ae62c4
TO
170 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
171 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
172 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
39010e60 173 'recipient' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
51ae62c4
TO
174 );
175 $result = $this->callAPISuccess('mailing', 'create', $params);
176 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
177 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
178 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
39010e60 179 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
7811a84b 180
51ae62c4
TO
181 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
182 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
21b09c13
TO
183 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
184 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
ef643544 185 }
7811a84b 186
fddd185d
TO
187 public function testMailerPreviewRecipients() {
188 // BEGIN SAMPLE DATA
161ae41b
TO
189 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
190 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
39010e60 191 $contactIDs['include_me'] = $this->individualCreate(array(
92915c55
TO
192 'email' => 'include.me@example.org',
193 'first_name' => 'Includer',
5396af74 194 'last_name' => 'Person',
92915c55 195 ));
39010e60 196 $contactIDs['exclude_me'] = $this->individualCreate(array(
92915c55 197 'email' => 'exclude.me@example.org',
39010e60 198 'last_name' => 'Excluder',
92915c55
TO
199 ));
200 $this->callAPISuccess('GroupContact', 'create', array(
201 'group_id' => $groupIDs['inc'],
5396af74 202 'contact_id' => $contactIDs['include_me'],
92915c55
TO
203 ));
204 $this->callAPISuccess('GroupContact', 'create', array(
205 'group_id' => $groupIDs['inc'],
5396af74 206 'contact_id' => $contactIDs['exclude_me'],
92915c55
TO
207 ));
208 $this->callAPISuccess('GroupContact', 'create', array(
209 'group_id' => $groupIDs['exc'],
5396af74 210 'contact_id' => $contactIDs['exclude_me'],
92915c55 211 ));
fddd185d
TO
212
213 $params = $this->_params;
161ae41b
TO
214 $params['groups']['include'] = array($groupIDs['inc']);
215 $params['groups']['exclude'] = array($groupIDs['exc']);
fddd185d
TO
216 $params['mailings']['include'] = array();
217 $params['mailings']['exclude'] = array();
b73e0c53 218 $params['options']['force_rollback'] = 1;
5f445749 219 $params['api.mailing_job.create'] = 1;
b73e0c53
TO
220 $params['api.MailingRecipients.get'] = array(
221 'mailing_id' => '$value.id',
222 'api.contact.getvalue' => array(
223 'return' => 'display_name',
224 ),
225 'api.email.getvalue' => array(
226 'return' => 'email',
227 ),
228 );
fddd185d
TO
229 // END SAMPLE DATA
230
6c6e6187 231 $maxIDs = array(
fddd185d
TO
232 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
233 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
234 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
235 );
b73e0c53 236 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
fddd185d
TO
237 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
238 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
239 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
240
b73e0c53 241 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
fddd185d 242 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
39010e60 243 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
b73e0c53
TO
244 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
245 $this->assertEquals(array('include.me@example.org'), $previewEmails);
246 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
6c6e6187 247 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
fddd185d
TO
248 }
249
39010e60
EM
250 /**
251 *
252 */
7ada2376 253 public function testMailerSendTest_email() {
92915c55
TO
254 $contactIDs['alice'] = $this->individualCreate(array(
255 'email' => 'alice@example.org',
256 'first_name' => 'Alice',
5396af74 257 'last_name' => 'Person',
92915c55 258 ));
7811a84b 259
ef643544 260 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
7811a84b 261
736a042c 262 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
ef643544 263 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
264 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
736a042c
TO
265
266 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
267 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
268
269 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
270 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
ef643544 271 }
7811a84b 272
39010e60
EM
273 /**
274 *
275 */
7ada2376
TO
276 public function testMailerSendTest_group() {
277 // BEGIN SAMPLE DATA
161ae41b 278 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
92915c55
TO
279 $contactIDs['alice'] = $this->individualCreate(array(
280 'email' => 'alice@example.org',
281 'first_name' => 'Alice',
5396af74 282 'last_name' => 'Person',
92915c55
TO
283 ));
284 $contactIDs['bob'] = $this->individualCreate(array(
285 'email' => 'bob@example.org',
286 'first_name' => 'Bob',
5396af74 287 'last_name' => 'Person',
92915c55
TO
288 ));
289 $contactIDs['carol'] = $this->individualCreate(array(
290 'email' => 'carol@example.org',
291 'first_name' => 'Carol',
5396af74 292 'last_name' => 'Person',
92915c55
TO
293 ));
294 $this->callAPISuccess('GroupContact', 'create', array(
295 'group_id' => $groupIDs['inc'],
5396af74 296 'contact_id' => $contactIDs['alice'],
92915c55
TO
297 ));
298 $this->callAPISuccess('GroupContact', 'create', array(
299 'group_id' => $groupIDs['inc'],
5396af74 300 'contact_id' => $contactIDs['bob'],
92915c55
TO
301 ));
302 $this->callAPISuccess('GroupContact', 'create', array(
303 'group_id' => $groupIDs['inc'],
5396af74 304 'contact_id' => $contactIDs['carol'],
92915c55 305 ));
7ada2376
TO
306 // END SAMPLE DATA
307
308 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
309 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array(
310 'mailing_id' => $mail['id'],
311 'test_email' => NULL,
161ae41b 312 'test_group' => $groupIDs['inc'],
7ada2376
TO
313 ));
314 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
736a042c 315
7ada2376 316 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
161ae41b 317 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
736a042c 318
7ada2376
TO
319 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
320 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
321 }
322
ad4f6a9c
EM
323 /**
324 * @return array
325 */
6818346a
TO
326 public function submitProvider() {
327 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
328 $cases[] = array(
329 TRUE, //useLogin
d78cc635 330 array(), // createParams
6818346a
TO
331 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
332 FALSE, // expectedFailure
333 1, // expectedJobCount
334 );
335 $cases[] = array(
336 FALSE, //useLogin
d78cc635 337 array(), // createParams
6818346a
TO
338 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
339 "/Failed to determine current user/", // expectedFailure
340 0, // expectedJobCount
341 );
342 $cases[] = array(
343 TRUE, //useLogin
d78cc635 344 array(), // createParams
6818346a
TO
345 array('scheduled_date' => '2014-12-13 10:00:00'),
346 FALSE, // expectedFailure
347 1, // expectedJobCount
348 );
349 $cases[] = array(
350 TRUE, //useLogin
d78cc635 351 array(), // createParams
6818346a
TO
352 array(),
353 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
354 0, // expectedJobCount
355 );
d78cc635
TO
356 $cases[] = array(
357 TRUE, //useLogin
358 array('name' => ''), // createParams
359 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
21b09c13 360 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./", // expectedFailure
d78cc635
TO
361 0, // expectedJobCount
362 );
21b09c13
TO
363 $cases[] = array(
364 TRUE, //useLogin
365 array('body_html' => '', 'body_text' => ''), // createParams
366 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
367 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./", // expectedFailure
368 0, // expectedJobCount
369 );
370 $cases[] = array(
371 TRUE, //useLogin
372 array('body_html' => 'Oops, did I leave my tokens at home?'), // createParams
373 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
374 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./", // expectedFailure
375 0, // expectedJobCount
376 );
377 $cases[] = array(
378 TRUE, //useLogin
379 array('body_text' => 'Oops, did I leave my tokens at home?'), // createParams
380 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
381 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./", // expectedFailure
382 0, // expectedJobCount
383 );
d8e9212d
TO
384 $cases[] = array(
385 TRUE, //useLogin
386 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'), // createParams
387 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
388 FALSE, // expectedFailure
389 1, // expectedJobCount
390 );
391 $cases[] = array(
392 TRUE, //useLogin
393 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'), // createParams
394 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
395 FALSE, // expectedFailure
396 1, // expectedJobCount
397 );
6818346a
TO
398 return $cases;
399 }
400
401 /**
402 * @param bool $useLogin
d78cc635
TO
403 * @param array $createParams
404 * @param array $submitParams
6818346a
TO
405 * @param null|string $expectedFailure
406 * @param int $expectedJobCount
407 * @dataProvider submitProvider
408 */
d78cc635 409 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
6818346a
TO
410 if ($useLogin) {
411 $this->createLoggedInUser();
412 }
413
d8e9212d
TO
414 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
415 $createParams['footer_id'] = $this->footer['id'];
416 }
417
d78cc635 418 $id = $this->createDraftMailing($createParams);
6818346a 419
d78cc635 420 $submitParams['id'] = $id;
6818346a 421 if ($expectedFailure) {
d78cc635 422 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
6818346a
TO
423 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
424 }
425 else {
d78cc635 426 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__, __FILE__);
6818346a
TO
427 $this->assertTrue(is_numeric($submitResult['id']));
428 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
d78cc635 429 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
6818346a
TO
430 }
431 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
21dfd5f5 432 1 => array($id, 'Integer'),
6818346a
TO
433 ));
434 }
435
39010e60
EM
436 /**
437 *
438 */
ef643544 439 public function testMailerStats() {
440 $result = $this->groupContactCreate($this->_groupID, 100);
441 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
7811a84b 442
443 //Create and send test mail first and change the mail job to live,
444 //because stats api only works on live mail
ef643544 445 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
7811a84b 446 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
ef643544 447 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
92915c55 448 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
7811a84b 449
450 //Change the test mail into live
451 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
452 CRM_Core_DAO::executeQuery($sql);
453
ef643544 454 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
455 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
456(event_queue_id int, time_stamp datetime, delivered_id int)
457SELECT event_queue_id, time_stamp, id
458 FROM civicrm_mailing_event_delivered
459 WHERE id IN ($deliveredIds)
460 ORDER BY RAND() LIMIT 0,20;";
ef643544 461 CRM_Core_DAO::executeQuery($sql);
7811a84b 462
ef643544 463 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
464 CRM_Core_DAO::executeQuery($sql);
7811a84b 465
ef643544 466 if ($type == 'unsubscribe') {
467 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
468SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
469 }
470 else {
471 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
472SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
473 }
474 CRM_Core_DAO::executeQuery($sql);
475 }
7811a84b 476
ef643544 477 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
478 $expectedResult = array(
479 'Delivered' => 80, //since among 100 mails 20 has been bounced
480 'Bounces' => 20,
481 'Opened' => 20,
482 'Unique Clicks' => 0,
21dfd5f5 483 'Unsubscribers' => 20,
ef643544 484 );
ef643544 485 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
486 }
92915c55 487
c43d01f3 488 /**
fe482240 489 * Test civicrm_mailing_delete.
c43d01f3 490 */
491 public function testMailerDeleteSuccess() {
e37b4b04 492 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
ad4f6a9c 493 $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
e37b4b04 494 $this->assertAPIDeleted($this->_entity, $result['id']);
c43d01f3 495 }
6a488035 496
1d280e03
CW
497 /**
498 * Test Mailing.gettokens.
499 */
500 public function testMailGetTokens() {
9950a1c9 501 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
1d280e03 502 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
9950a1c9
CW
503 $result = $this->callAPIAndDocument($this->_entity, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__, __FILE__, $description);
504 $this->assertContains('Contact Type', $result['values']);
505
506 // Check that passing "sequential" correctly outputs a hierarchical array
507 $result = $this->callAPISuccess($this->_entity, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
508 $this->assertArrayHasKey('text', $result['values'][0]);
509 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
1d280e03
CW
510 }
511
00dc999a
TO
512 public function testClone() {
513 // BEGIN SAMPLE DATA
514 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
515 $contactIDs['include_me'] = $this->individualCreate(array(
516 'email' => 'include.me@example.org',
517 'first_name' => 'Includer',
518 'last_name' => 'Person',
519 ));
520 $this->callAPISuccess('GroupContact', 'create', array(
521 'group_id' => $groupIDs['inc'],
522 'contact_id' => $contactIDs['include_me'],
523 ));
524
525 $params = $this->_params;
526 $params['groups']['include'] = array($groupIDs['inc']);
527 $params['groups']['exclude'] = array();
528 $params['mailings']['include'] = array();
529 $params['mailings']['exclude'] = array();
530 // END SAMPLE DATA
531
532 $create = $this->callAPISuccess('Mailing', 'create', $params);
533 $createId = $create['id'];
534 $this->createLoggedInUser();
535 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__, __FILE__);
536 $cloneId = $clone['id'];
537
538 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
539 $this->assertTrue(is_numeric($cloneId));
540
541 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
542 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
543
544 // created_id is special - populated based on current user (ie the cloner).
545 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
546 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
547
548 // Target groups+mailings are special.
549 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
550 $this->assertEquals(1, $cloneGroups['count']);
551 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
552 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
553 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
554 }
555
6a488035
TO
556 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
557
558 //------------ civicrm_mailing_event_bounce methods------------
559
560 /**
561 * Test civicrm_mailing_event_bounce with wrong params.
e37b4b04 562 * Note that tests like this are slightly better than no test but an
563 * api function cannot be considered supported / 'part of the api' without a
564 * success test
6a488035
TO
565 */
566 public function testMailerBounceWrongParams() {
567 $params = array(
568 'job_id' => 'Wrong ID',
569 'event_queue_id' => 'Wrong ID',
570 'hash' => 'Wrong Hash',
571 'body' => 'Body...',
6a488035
TO
572 'time_stamp' => '20111109212100',
573 );
ad4f6a9c 574 $this->callAPIFailure('mailing_event', 'bounce', $params,
30d44db2 575 'Queue event could not be found'
576 );
6a488035
TO
577 }
578
579 //----------- civicrm_mailing_event_confirm methods -----------
580
581 /**
582 * Test civicrm_mailing_event_confirm with wrong params.
e37b4b04 583 * Note that tests like this are slightly better than no test but an
584 * api function cannot be considered supported / 'part of the api' without a
585 * success test
6a488035
TO
586 */
587 public function testMailerConfirmWrongParams() {
588 $params = array(
589 'contact_id' => 'Wrong ID',
590 'subscribe_id' => 'Wrong ID',
591 'hash' => 'Wrong Hash',
592 'event_subscribe_id' => '123',
593 'time_stamp' => '20111111010101',
ef170fe0 594 );
ad4f6a9c 595 $this->callAPIFailure('mailing_event', 'confirm', $params,
e37b4b04 596 'Confirmation failed'
597 );
6a488035
TO
598 }
599
600 //---------- civicrm_mailing_event_reply methods -----------
601
602 /**
603 * Test civicrm_mailing_event_reply with wrong params.
e37b4b04 604 *
605 * Note that tests like this are slightly better than no test but an
606 * api function cannot be considered supported / 'part of the api' without a
607 * success test
6a488035
TO
608 */
609 public function testMailerReplyWrongParams() {
610 $params = array(
611 'job_id' => 'Wrong ID',
612 'event_queue_id' => 'Wrong ID',
613 'hash' => 'Wrong Hash',
614 'bodyTxt' => 'Body...',
615 'replyTo' => $this->_email,
616 'time_stamp' => '20111111010101',
ef170fe0 617 );
ad4f6a9c 618 $this->callAPIFailure('mailing_event', 'reply', $params,
e37b4b04 619 'Queue event could not be found'
30d44db2 620 );
6a488035
TO
621 }
622
623
624 //----------- civicrm_mailing_event_forward methods ----------
625
626 /**
627 * Test civicrm_mailing_event_forward with wrong params.
e37b4b04 628 * Note that tests like this are slightly better than no test but an
629 * api function cannot be considered supported / 'part of the api' without a
630 * success test
6a488035
TO
631 */
632 public function testMailerForwardWrongParams() {
633 $params = array(
634 'job_id' => 'Wrong ID',
635 'event_queue_id' => 'Wrong ID',
636 'hash' => 'Wrong Hash',
637 'email' => $this->_email,
638 'time_stamp' => '20111111010101',
ef170fe0 639 );
ad4f6a9c 640 $this->callAPIFailure('mailing_event', 'forward', $params,
e37b4b04 641 'Queue event could not be found'
642 );
6a488035
TO
643 }
644
6818346a 645 /**
d78cc635
TO
646 * @param array $params
647 * Extra parameters for the draft mailing.
6818346a
TO
648 * @return array|int
649 */
d78cc635
TO
650 public function createDraftMailing($params = array()) {
651 $createParams = array_merge($this->_params, $params);
6818346a
TO
652 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__, __FILE__);
653 $this->assertTrue(is_numeric($createResult['id']));
654 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
21dfd5f5 655 1 => array($createResult['id'], 'Integer'),
6818346a
TO
656 ));
657 return $createResult['id'];
658 }
659
6c6e6187 660 //----------- civicrm_mailing_create ----------
6a488035
TO
661
662}