Merge pull request #14897 from mattwire/membership_payment2
[civicrm-core.git] / tests / phpunit / api / v3 / JobProcessMailingTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * File for the CiviCRM APIv3 job functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Job
33 *
34 * @copyright CiviCRM LLC (c) 2004-2019
35 * @version $Id: Job.php 30879 2010-11-22 15:45:55Z shot $
36 *
37 */
38
39 /**
40 * Class api_v3_JobTest
41 * @group headless
42 * @group civimail
43 */
44 class api_v3_JobProcessMailingTest extends CiviUnitTestCase {
45 protected $_apiversion = 3;
46
47 public $DBResetRequired = FALSE;
48 public $_entity = 'Job';
49 public $_params = [];
50 private $_groupID;
51 private $_email;
52
53 protected $defaultSettings;
54
55 /**
56 * @var CiviMailUtils
57 */
58 private $_mut;
59
60 public function setUp() {
61 $this->cleanupMailingTest();
62 parent::setUp();
63 // DGW
64 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0;
65 $this->_groupID = $this->groupCreate();
66 $this->_email = 'test@test.test';
67 $this->_params = [
68 'subject' => 'Accidents in cars cause children',
69 'body_text' => 'BEWARE children need regular infusions of toys. Santa knows your {domain.address}. There is no {action.optOutUrl}.',
70 'name' => 'mailing name',
71 'created_id' => 1,
72 'groups' => ['include' => [$this->_groupID]],
73 'scheduled_date' => 'now',
74 ];
75 $this->defaultSettings = [
76 // int, #mailings to send
77 'mailings' => 1,
78 // int, #contacts to receive mailing
79 'recipients' => 20,
80 // int, #concurrent cron jobs
81 'workers' => 1,
82 // int, #times to spawn all the workers
83 'iterations' => 1,
84 // int, #extra seconds each cron job should hold lock
85 'lockHold' => 0,
86 // int, max# recipients to send in a given cron run
87 'mailerBatchLimit' => 0,
88 // int, max# concurrent jobs
89 'mailerJobsMax' => 0,
90 // int, max# recipients in each job
91 'mailerJobSize' => 0,
92 // int, microseconds separating messages
93 'mailThrottleTime' => 0,
94 ];
95 $this->_mut = new CiviMailUtils($this, TRUE);
96 $this->callAPISuccess('mail_settings', 'get', ['api.mail_settings.create' => ['domain' => 'chaos.org']]);
97 }
98
99 /**
100 */
101 public function tearDown() {
102 //$this->_mut->clearMessages();
103 $this->_mut->stop();
104 CRM_Utils_Hook::singleton()->reset();
105 // DGW
106 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0;
107 //$this->cleanupMailingTest();
108 parent::tearDown();
109 }
110
111 public function testBasic() {
112 $this->createContactsInGroup(10, $this->_groupID);
113 Civi::settings()->add([
114 'mailerBatchLimit' => 2,
115 ]);
116 $this->callAPISuccess('mailing', 'create', $this->_params);
117 $this->_mut->assertRecipients([]);
118 $this->callAPISuccess('job', 'process_mailing', []);
119 $this->_mut->assertRecipients($this->getRecipients(1, 2));
120 }
121
122 /**
123 * Test pause and resume on Mailing.
124 */
125 public function testPauseAndResumeMailing() {
126 $this->createContactsInGroup(10, $this->_groupID);
127 Civi::settings()->add([
128 'mailerBatchLimit' => 2,
129 ]);
130 $this->_mut->clearMessages();
131 //Create a test mailing and check if the status is set to Scheduled.
132 $result = $this->callAPISuccess('mailing', 'create', $this->_params);
133 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $result['id']]);
134 $this->assertEquals('Scheduled', $jobs['values'][$jobs['id']]['status']);
135
136 //Pause the mailing.
137 CRM_Mailing_BAO_MailingJob::pause($result['id']);
138 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $result['id']]);
139 $this->assertEquals('Paused', $jobs['values'][$jobs['id']]['status']);
140
141 //Verify if Paused mailing isn't considered in process_mailing job.
142 $this->callAPISuccess('job', 'process_mailing', []);
143 //Check if mail log is empty.
144 $this->_mut->assertMailLogEmpty();
145 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $result['id']]);
146 $this->assertEquals('Paused', $jobs['values'][$jobs['id']]['status']);
147
148 //Resume should set the status back to Scheduled.
149 CRM_Mailing_BAO_MailingJob::resume($result['id']);
150 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $result['id']]);
151 $this->assertEquals('Scheduled', $jobs['values'][$jobs['id']]['status']);
152
153 //Execute the job and it should send the mailing to the recipients now.
154 $this->callAPISuccess('job', 'process_mailing', []);
155 $this->_mut->assertRecipients($this->getRecipients(1, 2));
156 }
157
158 /**
159 * Test mail when in non-production environment.
160 *
161 */
162 public function testMailNonProductionRun() {
163 // Test in non-production mode.
164 $params = [
165 'environment' => 'Staging',
166 ];
167 $this->callAPISuccess('Setting', 'create', $params);
168 //Assert if outbound mail is disabled.
169 $mailingBackend = Civi::settings()->get('mailing_backend');
170 $this->assertEquals($mailingBackend['outBound_option'], CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED);
171
172 $this->createContactsInGroup(10, $this->_groupID);
173 Civi::settings()->add([
174 'mailerBatchLimit' => 2,
175 ]);
176 $this->callAPISuccess('mailing', 'create', $this->_params);
177 $this->_mut->assertRecipients([]);
178 $this->callAPIFailure('job', 'process_mailing', "Failure in api call for job process_mailing: Job has not been executed as it is a non-production environment.");
179
180 // Test with runInNonProductionEnvironment param.
181 $this->callAPISuccess('job', 'process_mailing', ['runInNonProductionEnvironment' => TRUE]);
182 $this->_mut->assertRecipients($this->getRecipients(1, 2));
183
184 $jobId = $this->callAPISuccessGetValue('Job', [
185 'return' => "id",
186 'api_action' => "group_rebuild",
187 ]);
188 $this->callAPISuccess('Job', 'create', [
189 'id' => $jobId,
190 'parameters' => "runInNonProductionEnvironment=TRUE",
191 ]);
192 $jobManager = new CRM_Core_JobManager();
193 $jobManager->executeJobById($jobId);
194
195 //Assert if outbound mail is still disabled.
196 $mailingBackend = Civi::settings()->get('mailing_backend');
197 $this->assertEquals($mailingBackend['outBound_option'], CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED);
198
199 // Test in production mode.
200 $params = [
201 'environment' => 'Production',
202 ];
203 $this->callAPISuccess('Setting', 'create', $params);
204 $this->callAPISuccess('job', 'process_mailing', []);
205 $this->_mut->assertRecipients($this->getRecipients(1, 2));
206 }
207
208 public function concurrencyExamples() {
209 $es = [];
210
211 // Launch 3 workers, but mailerJobsMax limits us to 1 worker.
212 $es[0] = [
213 [
214 'recipients' => 20,
215 'workers' => 3,
216 // FIXME: lockHold is unrealistic/unrepresentative. In reality, this situation fails because
217 // the data.* locks trample the worker.* locks. However, setting lockHold allows us to
218 // approximate the behavior of what would happen *if* the lock-implementation didn't suffer
219 // trampling effects.
220 'lockHold' => 10,
221 'mailerBatchLimit' => 4,
222 'mailerJobsMax' => 1,
223 ],
224 [
225 // 2 jobs which produce 0 messages
226 0 => 2,
227 // 1 job which produces 4 messages
228 4 => 1,
229 ],
230 4,
231 ];
232
233 // Launch 3 workers, but mailerJobsMax limits us to 2 workers.
234 $es[1] = [
235 // Settings.
236 [
237 'recipients' => 20,
238 'workers' => 3,
239 // FIXME: lockHold is unrealistic/unrepresentative. In reality, this situation fails because
240 // the data.* locks trample the worker.* locks. However, setting lockHold allows us to
241 // approximate the behavior of what would happen *if* the lock-implementation didn't suffer
242 // trampling effects.
243 'lockHold' => 10,
244 'mailerBatchLimit' => 5,
245 'mailerJobsMax' => 2,
246 ],
247 // Tallies.
248 [
249 // 1 job which produce 0 messages
250 0 => 1,
251 // 2 jobs which produce 5 messages
252 5 => 2,
253 ],
254 // Total sent.
255 10,
256 ];
257
258 // Launch 3 workers and saturate them (mailerJobsMax=3)
259 $es[2] = [
260 // Settings.
261 [
262 'recipients' => 20,
263 'workers' => 3,
264 'mailerBatchLimit' => 6,
265 'mailerJobsMax' => 3,
266 ],
267 // Tallies.
268 [
269 // 3 jobs which produce 6 messages
270 6 => 3,
271 ],
272 // Total sent.
273 18,
274 ];
275
276 // Launch 4 workers and saturate them (mailerJobsMax=0)
277 $es[3] = [
278 // Settings.
279 [
280 'recipients' => 20,
281 'workers' => 4,
282 'mailerBatchLimit' => 6,
283 'mailerJobsMax' => 0,
284 ],
285 // Tallies.
286 [
287 // 3 jobs which produce 6 messages
288 6 => 3,
289 // 1 job which produces 2 messages
290 2 => 1,
291 ],
292 // Total sent.
293 20,
294 ];
295
296 // Launch 1 worker, 3 times in a row. Deliver everything.
297 $es[4] = [
298 // Settings.
299 [
300 'recipients' => 10,
301 'workers' => 1,
302 'iterations' => 3,
303 'mailerBatchLimit' => 7,
304 ],
305 // Tallies.
306 [
307 // 1 job which produces 7 messages
308 7 => 1,
309 // 1 job which produces 3 messages
310 3 => 1,
311 // 1 job which produces 0 messages
312 0 => 1,
313 ],
314 // Total sent.
315 10,
316 ];
317
318 // Launch 2 worker, 3 times in a row. Deliver everything.
319 $es[5] = [
320 // Settings.
321 [
322 'recipients' => 10,
323 'workers' => 2,
324 'iterations' => 3,
325 'mailerBatchLimit' => 3,
326 ],
327 // Tallies.
328 [
329 // 3 jobs which produce 3 messages
330 3 => 3,
331 // 1 job which produces 1 messages
332 1 => 1,
333 // 2 jobs which produce 0 messages
334 0 => 2,
335 ],
336 // Total sent.
337 10,
338 ];
339
340 // For two mailings, launch 1 worker, 5 times in a row. Deliver everything.
341 $es[6] = [
342 // Settings.
343 [
344 'mailings' => 2,
345 'recipients' => 10,
346 'workers' => 1,
347 'iterations' => 5,
348 'mailerBatchLimit' => 6,
349 ],
350 // Tallies.
351 [
352 // x6 => x4+x2 => x6 => x2 => x0
353 // 3 jobs which produce 6 messages
354 6 => 3,
355 // 1 job which produces 2 messages
356 2 => 1,
357 // 1 job which produces 0 messages
358 0 => 1,
359 ],
360 // Total sent.
361 20,
362 ];
363
364 return $es;
365 }
366
367 /**
368 * Setup various mail configuration options (eg $mailerBatchLimit,
369 * $mailerJobMax) and spawn multiple worker threads ($workers).
370 * Allow the threads to complete. (Optionally, repeat the above
371 * process.) Finally, check to see if the right number of
372 * jobs delivered the right number of messages.
373 *
374 * @param array $settings
375 * An array of settings (eg mailerBatchLimit, workers). See comments
376 * for $this->defaultSettings.
377 * @param array $expectedTallies
378 * A listing of the number cron-runs keyed by their size.
379 * For example, array(10=>2) means that there 2 cron-runs
380 * which delivered 10 messages each.
381 * @param int $expectedTotal
382 * The total number of contacts for whom messages should have
383 * been sent.
384 * @dataProvider concurrencyExamples
385 */
386 public function testConcurrency($settings, $expectedTallies, $expectedTotal) {
387 $settings = array_merge($this->defaultSettings, $settings);
388
389 $this->createContactsInGroup($settings['recipients'], $this->_groupID);
390 Civi::settings()->add(CRM_Utils_Array::subset($settings, [
391 'mailerBatchLimit',
392 'mailerJobsMax',
393 'mailThrottleTime',
394 ]));
395
396 for ($i = 0; $i < $settings['mailings']; $i++) {
397 $this->callAPISuccess('mailing', 'create', $this->_params);
398 }
399
400 $this->_mut->assertRecipients([]);
401
402 $allApiResults = [];
403 for ($iterationId = 0; $iterationId < $settings['iterations']; $iterationId++) {
404 $apiCalls = $this->createExternalAPI();
405 $apiCalls->addEnv(['CIVICRM_CRON_HOLD' => $settings['lockHold']]);
406 for ($workerId = 0; $workerId < $settings['workers']; $workerId++) {
407 $apiCalls->addCall('job', 'process_mailing', []);
408 }
409 $apiCalls->start();
410 $this->assertEquals($settings['workers'], $apiCalls->getRunningCount());
411
412 $apiCalls->wait();
413 $allApiResults = array_merge($allApiResults, $apiCalls->getResults());
414 }
415
416 $actualTallies = $this->tallyApiResults($allApiResults);
417 $this->assertEquals($expectedTallies, $actualTallies, 'API tallies should match.' . print_r([
418 'expectedTallies' => $expectedTallies,
419 'actualTallies' => $actualTallies,
420 'apiResults' => $allApiResults,
421 ], TRUE));
422 $this->_mut->assertRecipients($this->getRecipients(1, $expectedTotal / $settings['mailings'], 'nul.example.com', $settings['mailings']));
423 $this->assertEquals(0, $apiCalls->getRunningCount());
424 }
425
426 /**
427 * Create contacts in group.
428 *
429 * @param int $count
430 * @param int $groupID
431 * @param string $domain
432 */
433 public function createContactsInGroup($count, $groupID, $domain = 'nul.example.com') {
434 for ($i = 1; $i <= $count; $i++) {
435 $contactID = $this->individualCreate(['first_name' => $count, 'email' => 'mail' . $i . '@' . $domain]);
436 $this->callAPISuccess('group_contact', 'create', [
437 'contact_id' => $contactID,
438 'group_id' => $groupID,
439 'status' => 'Added',
440 ]);
441 }
442 }
443
444 /**
445 * Construct the list of email addresses for $count recipients.
446 *
447 * @param int $start
448 * @param int $count
449 * @param string $domain
450 * @param int $mailings
451 *
452 * @return array
453 */
454 public function getRecipients($start, $count, $domain = 'nul.example.com', $mailings = 1) {
455 $recipients = [];
456 for ($m = 0; $m < $mailings; $m++) {
457 for ($i = $start; $i < ($start + $count); $i++) {
458 $recipients[][0] = 'mail' . $i . '@' . $domain;
459 }
460 }
461 return $recipients;
462 }
463
464 protected function cleanupMailingTest() {
465 $this->quickCleanup([
466 'civicrm_mailing',
467 'civicrm_mailing_job',
468 'civicrm_mailing_spool',
469 'civicrm_mailing_group',
470 'civicrm_mailing_recipients',
471 'civicrm_mailing_event_queue',
472 'civicrm_mailing_event_bounce',
473 'civicrm_mailing_event_delivered',
474 'civicrm_group',
475 'civicrm_group_contact',
476 'civicrm_contact',
477 ]);
478 }
479
480 /**
481 * Categorize results based on (a) whether they succeeded
482 * and (b) the number of messages sent.
483 *
484 * @param array $apiResults
485 * @return array
486 * One key 'error' for all failures.
487 * A separate key for each distinct quantity.
488 */
489 protected function tallyApiResults($apiResults) {
490 $ret = [];
491 foreach ($apiResults as $apiResult) {
492 $key = !empty($apiResult['is_error']) ? 'error' : $apiResult['values']['processed'];
493 $ret[$key] = !empty($ret[$key]) ? 1 + $ret[$key] : 1;
494 }
495 return $ret;
496 }
497
498 }