3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * File for the CiviCRM APIv3 job functions
31 * @package CiviCRM_APIv3
34 * @copyright CiviCRM LLC (c) 2004-2019
35 * @version $Id: Job.php 30879 2010-11-22 15:45:55Z shot $
40 * Class api_v3_JobTest
44 class api_v3_JobProcessMailingTest
extends CiviUnitTestCase
{
45 protected $_apiversion = 3;
47 public $DBResetRequired = FALSE;
48 public $_entity = 'Job';
53 protected $defaultSettings;
60 public function setUp() {
61 $this->cleanupMailingTest();
64 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
65 $this->_groupID
= $this->groupCreate();
66 $this->_email
= 'test@test.test';
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',
72 'groups' => ['include' => [$this->_groupID
]],
73 'scheduled_date' => 'now',
75 $this->defaultSettings
= [
76 // int, #mailings to send
78 // int, #contacts to receive mailing
80 // int, #concurrent cron jobs
82 // int, #times to spawn all the workers
84 // int, #extra seconds each cron job should hold lock
86 // int, max# recipients to send in a given cron run
87 'mailerBatchLimit' => 0,
88 // int, max# concurrent jobs
90 // int, max# recipients in each job
92 // int, microseconds separating messages
93 'mailThrottleTime' => 0,
95 $this->_mut
= new CiviMailUtils($this, TRUE);
96 $this->callAPISuccess('mail_settings', 'get', ['api.mail_settings.create' => ['domain' => 'chaos.org']]);
101 public function tearDown() {
102 //$this->_mut->clearMessages();
104 CRM_Utils_Hook
::singleton()->reset();
106 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
107 //$this->cleanupMailingTest();
111 public function testBasic() {
112 $this->createContactsInGroup(10, $this->_groupID
);
113 Civi
::settings()->add([
114 'mailerBatchLimit' => 2,
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));
123 * Test pause and resume on Mailing.
125 public function testPauseAndResumeMailing() {
126 $this->createContactsInGroup(10, $this->_groupID
);
127 Civi
::settings()->add([
128 'mailerBatchLimit' => 2,
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']);
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']);
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']);
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']);
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));
159 * Test mail when in non-production environment.
162 public function testMailNonProductionRun() {
163 // Test in non-production mode.
165 'environment' => 'Staging',
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
);
172 $this->createContactsInGroup(10, $this->_groupID
);
173 Civi
::settings()->add([
174 'mailerBatchLimit' => 2,
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.");
180 // Test with runInNonProductionEnvironment param.
181 $this->callAPISuccess('job', 'process_mailing', ['runInNonProductionEnvironment' => TRUE]);
182 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
184 $jobId = $this->callAPISuccessGetValue('Job', [
186 'api_action' => "group_rebuild",
188 $this->callAPISuccess('Job', 'create', [
190 'parameters' => "runInNonProductionEnvironment=TRUE",
192 $jobManager = new CRM_Core_JobManager();
193 $jobManager->executeJobById($jobId);
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
);
199 // Test in production mode.
201 'environment' => 'Production',
203 $this->callAPISuccess('Setting', 'create', $params);
204 $this->callAPISuccess('job', 'process_mailing', []);
205 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
208 public function concurrencyExamples() {
211 // Launch 3 workers, but mailerJobsMax limits us to 1 worker.
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.
221 'mailerBatchLimit' => 4,
222 'mailerJobsMax' => 1,
225 // 2 jobs which produce 0 messages
227 // 1 job which produces 4 messages
233 // Launch 3 workers, but mailerJobsMax limits us to 2 workers.
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.
244 'mailerBatchLimit' => 5,
245 'mailerJobsMax' => 2,
249 // 1 job which produce 0 messages
251 // 2 jobs which produce 5 messages
258 // Launch 3 workers and saturate them (mailerJobsMax=3)
264 'mailerBatchLimit' => 6,
265 'mailerJobsMax' => 3,
269 // 3 jobs which produce 6 messages
276 // Launch 4 workers and saturate them (mailerJobsMax=0)
282 'mailerBatchLimit' => 6,
283 'mailerJobsMax' => 0,
287 // 3 jobs which produce 6 messages
289 // 1 job which produces 2 messages
296 // Launch 1 worker, 3 times in a row. Deliver everything.
303 'mailerBatchLimit' => 7,
307 // 1 job which produces 7 messages
309 // 1 job which produces 3 messages
311 // 1 job which produces 0 messages
318 // Launch 2 worker, 3 times in a row. Deliver everything.
325 'mailerBatchLimit' => 3,
329 // 3 jobs which produce 3 messages
331 // 1 job which produces 1 messages
333 // 2 jobs which produce 0 messages
340 // For two mailings, launch 1 worker, 5 times in a row. Deliver everything.
348 'mailerBatchLimit' => 6,
352 // x6 => x4+x2 => x6 => x2 => x0
353 // 3 jobs which produce 6 messages
355 // 1 job which produces 2 messages
357 // 1 job which produces 0 messages
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.
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
384 * @dataProvider concurrencyExamples
386 public function testConcurrency($settings, $expectedTallies, $expectedTotal) {
387 $settings = array_merge($this->defaultSettings
, $settings);
389 $this->createContactsInGroup($settings['recipients'], $this->_groupID
);
390 Civi
::settings()->add(CRM_Utils_Array
::subset($settings, [
396 for ($i = 0; $i < $settings['mailings']; $i++
) {
397 $this->callAPISuccess('mailing', 'create', $this->_params
);
400 $this->_mut
->assertRecipients([]);
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', []);
410 $this->assertEquals($settings['workers'], $apiCalls->getRunningCount());
413 $allApiResults = array_merge($allApiResults, $apiCalls->getResults());
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,
422 $this->_mut
->assertRecipients($this->getRecipients(1, $expectedTotal / $settings['mailings'], 'nul.example.com', $settings['mailings']));
423 $this->assertEquals(0, $apiCalls->getRunningCount());
427 * Create contacts in group.
430 * @param int $groupID
431 * @param string $domain
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,
445 * Construct the list of email addresses for $count recipients.
449 * @param string $domain
450 * @param int $mailings
454 public function getRecipients($start, $count, $domain = 'nul.example.com', $mailings = 1) {
456 for ($m = 0; $m < $mailings; $m++
) {
457 for ($i = $start; $i < ($start +
$count); $i++
) {
458 $recipients[][0] = 'mail' . $i . '@' . $domain;
464 protected function cleanupMailingTest() {
465 $this->quickCleanup([
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',
475 'civicrm_group_contact',
481 * Categorize results based on (a) whether they succeeded
482 * and (b) the number of messages sent.
484 * @param array $apiResults
486 * One key 'error' for all failures.
487 * A separate key for each distinct quantity.
489 protected function tallyApiResults($apiResults) {
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;