CRM-15578 - Mailing API - Replace "preview_recipients" action with chained calls
[civicrm-core.git] / tests / phpunit / api / v3 / MailingTest.php
1 <?php
2 /*
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
26 require_once 'CiviTest/CiviUnitTestCase.php';
27
28
29 /**
30 * Test APIv3 civicrm_mailing_* functions
31 *
32 * @package CiviCRM
33 */
34 class api_v3_MailingTest extends CiviUnitTestCase {
35 protected $_groupID;
36 protected $_email;
37 protected $_apiversion = 3;
38 protected $_params = array();
39 protected $_entity = 'Mailing';
40 protected $_groupIDs; // array(string $pseudonym => int $id)
41 protected $_contactIDs; // array(string $pseudonym => int $id)
42
43 /**
44 * @return array
45 */
46 function get_info() {
47 return array(
48 'name' => 'Mailer',
49 'description' => 'Test all Mailer methods.',
50 'group' => 'CiviCRM API Tests',
51 );
52 }
53
54 function setUp() {
55 parent::setUp();
56 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
57 $this->_contactIDs = array();
58 $this->_contactIDs[] = $this->individualCreate();
59 $this->_groupID = $this->groupCreate();
60 $this->_groupIDs = array();
61 $this->_email = 'test@test.test';
62 $this->_params = array(
63 'subject' => 'maild',
64 'body_text' => "This is {contact.display_name}",
65 'name' => 'mailing name',
66 'created_id' => $this->_contactIDs[0],
67 );
68 }
69
70 function tearDown() {
71 foreach ($this->_contactIDs as $contactID) {
72 $this->contactDelete($contactID);
73 }
74 $this->groupDelete($this->_groupID);
75 foreach ($this->_groupIDs as $groupID) {
76 $this->groupDelete($groupID);
77 }
78 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
79 parent::tearDown();
80 }
81
82 /**
83 * Test civicrm_mailing_create
84 */
85 public function testMailerCreateSuccess() {
86 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params, __FUNCTION__, __FILE__);
87 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
88 $this->assertEquals(1, $jobs['count']);
89 unset($this->_params['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
90 $this->getAndCheck($this->_params, $result['id'], 'mailing');
91 }
92
93 public function testMailerPreview() {
94 $contactID = $this->individualCreate();
95 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
96 $displayName = $displayName['values'][$contactID]['display_name'];
97
98 $result = $this->callAPISuccess('mailing', 'create', $this->_params);
99
100 $params = array('id' => $result['id'], 'contact_id' => $contactID);
101 $result = $this->callAPISuccess('mailing', 'preview', $params);
102 $text = $result['values']['text'];
103 $this->assertEquals("This is $displayName", $text); // verify the text returned is correct, with replaced token
104 $this->deleteMailing($result['id']);
105 }
106
107 public function testMailerPreviewRecipients() {
108 // BEGIN SAMPLE DATA
109 $this->groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
110 $this->groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
111 $this->contactIDs['includeme'] = $this->individualCreate(array('email' => 'include.me@example.org', 'first_name' => 'Includer', 'last_name' => 'Person'));
112 $this->contactIDs['excludeme'] = $this->individualCreate(array('email' => 'exclude.me@example.org', 'last_name' => 'Excluder', 'last_name' => 'Excluder'));
113 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $this->groupIDs['inc'], 'contact_id' => $this->contactIDs['includeme']));
114 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $this->groupIDs['inc'], 'contact_id' => $this->contactIDs['excludeme']));
115 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $this->groupIDs['exc'], 'contact_id' => $this->contactIDs['excludeme']));
116
117 $params = $this->_params;
118 $params['groups']['include'] = array($this->groupIDs['inc']);
119 $params['groups']['exclude'] = array($this->groupIDs['exc']);
120 $params['mailings']['include'] = array();
121 $params['mailings']['exclude'] = array();
122 $params['options']['force_rollback'] = 1;
123 $params['api.MailingRecipients.get'] = array(
124 'mailing_id' => '$value.id',
125 'api.contact.getvalue' => array(
126 'return' => 'display_name',
127 ),
128 'api.email.getvalue' => array(
129 'return' => 'email',
130 ),
131 );
132 // END SAMPLE DATA
133
134 $maxIDs = array(
135 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
136 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
137 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
138 );
139 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
140 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
141 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
142 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
143
144 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
145 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
146 $this->assertEquals(array((string)$this->contactIDs['includeme']), $previewIds);
147 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
148 $this->assertEquals(array('include.me@example.org'), $previewEmails);
149 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
150 $this->assertTrue((bool)preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
151 }
152
153 public function testMailerSendTestMail() {
154 $contactID = $this->individualCreate();
155 $result = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
156 $email = $result['values'][$contactID]['email'];
157
158 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
159
160 $params = array('mailing_id' => $mail['id'], 'test_email' => $email, 'test_group' => NULL);
161 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
162 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
163 $this->assertEquals($contactID, $deliveredInfo['values'][$deliveredInfo['id']]['contact_id'], "in line " . __LINE__); //verify the contact_id of the recipient
164 $this->deleteMailing($mail['id']);
165 }
166
167 public function testMailerStats() {
168 $result = $this->groupContactCreate($this->_groupID, 100);
169 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
170
171 //Create and send test mail first and change the mail job to live,
172 //because stats api only works on live mail
173 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
174 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
175 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
176 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
177
178 //Change the test mail into live
179 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
180 CRM_Core_DAO::executeQuery($sql);
181
182 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
183 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
184 (event_queue_id int, time_stamp datetime, delivered_id int)
185 SELECT event_queue_id, time_stamp, id
186 FROM civicrm_mailing_event_delivered
187 WHERE id IN ($deliveredIds)
188 ORDER BY RAND() LIMIT 0,20;";
189 CRM_Core_DAO::executeQuery($sql);
190
191 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
192 CRM_Core_DAO::executeQuery($sql);
193
194 if ($type == 'unsubscribe') {
195 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
196 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
197 }
198 else {
199 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
200 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
201 }
202 CRM_Core_DAO::executeQuery($sql);
203 }
204
205 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
206 $expectedResult = array(
207 'Delivered' => 80, //since among 100 mails 20 has been bounced
208 'Bounces' => 20,
209 'Opened' => 20,
210 'Unique Clicks' => 0,
211 'Unsubscribers' => 20
212 );
213 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
214 $this->deleteMailing($mail['id']);
215 }
216 /**
217 * Test civicrm_mailing_delete
218 */
219 public function testMailerDeleteSuccess() {
220 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
221 $jobs = $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
222 $this->assertAPIDeleted($this->_entity, $result['id']);
223 }
224
225 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
226
227 //------------ civicrm_mailing_event_bounce methods------------
228
229 /**
230 * Test civicrm_mailing_event_bounce with wrong params.
231 * Note that tests like this are slightly better than no test but an
232 * api function cannot be considered supported / 'part of the api' without a
233 * success test
234 */
235 public function testMailerBounceWrongParams() {
236 $params = array(
237 'job_id' => 'Wrong ID',
238 'event_queue_id' => 'Wrong ID',
239 'hash' => 'Wrong Hash',
240 'body' => 'Body...',
241 'time_stamp' => '20111109212100',
242 );
243 $result = $this->callAPIFailure('mailing_event', 'bounce', $params,
244 'Queue event could not be found'
245 );
246 }
247
248 //----------- civicrm_mailing_event_confirm methods -----------
249
250 /**
251 * Test civicrm_mailing_event_confirm with wrong params.
252 * Note that tests like this are slightly better than no test but an
253 * api function cannot be considered supported / 'part of the api' without a
254 * success test
255 */
256 public function testMailerConfirmWrongParams() {
257 $params = array(
258 'contact_id' => 'Wrong ID',
259 'subscribe_id' => 'Wrong ID',
260 'hash' => 'Wrong Hash',
261 'event_subscribe_id' => '123',
262 'time_stamp' => '20111111010101',
263 );
264 $result = $this->callAPIFailure('mailing_event', 'confirm', $params,
265 'Confirmation failed'
266 );
267 }
268
269 //---------- civicrm_mailing_event_reply methods -----------
270
271 /**
272 * Test civicrm_mailing_event_reply with wrong params.
273 *
274 * Note that tests like this are slightly better than no test but an
275 * api function cannot be considered supported / 'part of the api' without a
276 * success test
277 */
278 public function testMailerReplyWrongParams() {
279 $params = array(
280 'job_id' => 'Wrong ID',
281 'event_queue_id' => 'Wrong ID',
282 'hash' => 'Wrong Hash',
283 'bodyTxt' => 'Body...',
284 'replyTo' => $this->_email,
285 'time_stamp' => '20111111010101',
286 );
287 $result = $this->callAPIFailure('mailing_event', 'reply', $params,
288 'Queue event could not be found'
289 );
290 }
291
292
293 //----------- civicrm_mailing_event_forward methods ----------
294
295 /**
296 * Test civicrm_mailing_event_forward with wrong params.
297 * Note that tests like this are slightly better than no test but an
298 * api function cannot be considered supported / 'part of the api' without a
299 * success test
300 */
301 public function testMailerForwardWrongParams() {
302 $params = array(
303 'job_id' => 'Wrong ID',
304 'event_queue_id' => 'Wrong ID',
305 'hash' => 'Wrong Hash',
306 'email' => $this->_email,
307 'time_stamp' => '20111111010101',
308 );
309 $result = $this->callAPIFailure('mailing_event', 'forward', $params,
310 'Queue event could not be found'
311 );
312 }
313
314 //----------- civicrm_mailing_create ----------
315
316 }