3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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';
49 public $_params = array();
53 protected $defaultSettings;
60 public function setUp() {
61 $this->cleanupMailingTest();
63 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
64 $this->_groupID
= $this->groupCreate();
65 $this->_email
= 'test@test.test';
66 $this->_params
= array(
67 'subject' => 'Accidents in cars cause children',
68 'body_text' => 'BEWARE children need regular infusions of toys. Santa knows your {domain.address}. There is no {action.optOutUrl}.',
69 'name' => 'mailing name',
71 'groups' => array('include' => array($this->_groupID
)),
72 'scheduled_date' => 'now',
74 $this->defaultSettings
= array(
75 'mailings' => 1, // int, #mailings to send
76 'recipients' => 20, // int, #contacts to receive mailing
77 'workers' => 1, // int, #concurrent cron jobs
78 'iterations' => 1, // int, #times to spawn all the workers
79 'lockHold' => 0, // int, #extra seconds each cron job should hold lock
80 'mailerBatchLimit' => 0, // int, max# recipients to send in a given cron run
81 'mailerJobsMax' => 0, // int, max# concurrent jobs
82 'mailerJobSize' => 0, // int, max# recipients in each job
83 'mailThrottleTime' => 0, // int, microseconds separating messages
85 $this->_mut
= new CiviMailUtils($this, TRUE);
86 $this->callAPISuccess('mail_settings', 'get', array('api.mail_settings.create' => array('domain' => 'chaos.org')));
91 public function tearDown() {
92 //$this->_mut->clearMessages();
94 CRM_Utils_Hook
::singleton()->reset();
95 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
96 //$this->cleanupMailingTest();
100 public function testBasic() {
101 $this->createContactsInGroup(10, $this->_groupID
);
102 Civi
::settings()->add(array(
103 'mailerBatchLimit' => 2,
105 $this->callAPISuccess('mailing', 'create', $this->_params
);
106 $this->_mut
->assertRecipients(array());
107 $this->callAPISuccess('job', 'process_mailing', array());
108 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
112 * Test pause and resume on Mailing.
114 public function testPauseAndResumeMailing() {
115 $this->createContactsInGroup(10, $this->_groupID
);
116 Civi
::settings()->add(array(
117 'mailerBatchLimit' => 2,
119 $this->_mut
->clearMessages();
120 //Create a test mailing and check if the status is set to Scheduled.
121 $result = $this->callAPISuccess('mailing', 'create', $this->_params
);
122 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
123 $this->assertEquals('Scheduled', $jobs['values'][$jobs['id']]['status']);
126 CRM_Mailing_BAO_MailingJob
::pause($result['id']);
127 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
128 $this->assertEquals('Paused', $jobs['values'][$jobs['id']]['status']);
130 //Verify if Paused mailing isn't considered in process_mailing job.
131 $this->callAPISuccess('job', 'process_mailing', array());
132 //Check if mail log is empty.
133 $this->_mut
->assertMailLogEmpty();
134 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
135 $this->assertEquals('Paused', $jobs['values'][$jobs['id']]['status']);
137 //Resume should set the status back to Scheduled.
138 CRM_Mailing_BAO_MailingJob
::resume($result['id']);
139 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
140 $this->assertEquals('Scheduled', $jobs['values'][$jobs['id']]['status']);
142 //Execute the job and it should send the mailing to the recipients now.
143 $this->callAPISuccess('job', 'process_mailing', array());
144 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
148 * Test mail when in non-production environment.
151 public function testMailNonProductionRun() {
152 // Test in non-production mode.
154 'environment' => 'Staging',
156 $this->callAPISuccess('Setting', 'create', $params);
157 //Assert if outbound mail is disabled.
158 $mailingBackend = Civi
::settings()->get('mailing_backend');
159 $this->assertEquals($mailingBackend['outBound_option'], CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
);
161 $this->createContactsInGroup(10, $this->_groupID
);
162 Civi
::settings()->add(array(
163 'mailerBatchLimit' => 2,
165 $this->callAPISuccess('mailing', 'create', $this->_params
);
166 $this->_mut
->assertRecipients(array());
167 $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.");
169 // Test with runInNonProductionEnvironment param.
170 $this->callAPISuccess('job', 'process_mailing', array('runInNonProductionEnvironment' => TRUE));
171 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
173 $jobId = $this->callAPISuccessGetValue('Job', array(
175 'api_action' => "group_rebuild",
177 $this->callAPISuccess('Job', 'create', array(
179 'parameters' => "runInNonProductionEnvironment=TRUE",
181 $jobManager = new CRM_Core_JobManager();
182 $jobManager->executeJobById($jobId);
184 //Assert if outbound mail is still disabled.
185 $mailingBackend = Civi
::settings()->get('mailing_backend');
186 $this->assertEquals($mailingBackend['outBound_option'], CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
);
188 // Test in production mode.
190 'environment' => 'Production',
192 $this->callAPISuccess('Setting', 'create', $params);
193 $this->callAPISuccess('job', 'process_mailing', array());
194 $this->_mut
->assertRecipients($this->getRecipients(1, 2));
197 public function concurrencyExamples() {
200 // Launch 3 workers, but mailerJobsMax limits us to 1 worker.
205 // FIXME: lockHold is unrealistic/unrepresentative. In reality, this situation fails because
206 // the data.* locks trample the worker.* locks. However, setting lockHold allows us to
207 // approximate the behavior of what would happen *if* the lock-implementation didn't suffer
208 // trampling effects.
210 'mailerBatchLimit' => 4,
211 'mailerJobsMax' => 1,
214 0 => 2, // 2 jobs which produce 0 messages
215 4 => 1, // 1 job which produces 4 messages
220 // Launch 3 workers, but mailerJobsMax limits us to 2 workers.
225 // FIXME: lockHold is unrealistic/unrepresentative. In reality, this situation fails because
226 // the data.* locks trample the worker.* locks. However, setting lockHold allows us to
227 // approximate the behavior of what would happen *if* the lock-implementation didn't suffer
228 // trampling effects.
230 'mailerBatchLimit' => 5,
231 'mailerJobsMax' => 2,
234 0 => 1, // 1 job which produce 0 messages
235 5 => 2, // 2 jobs which produce 5 messages
240 // Launch 3 workers and saturate them (mailerJobsMax=3)
245 'mailerBatchLimit' => 6,
246 'mailerJobsMax' => 3,
249 6 => 3, // 3 jobs which produce 6 messages
254 // Launch 4 workers and saturate them (mailerJobsMax=0)
259 'mailerBatchLimit' => 6,
260 'mailerJobsMax' => 0,
263 6 => 3, // 3 jobs which produce 6 messages
264 2 => 1, // 1 job which produces 2 messages
269 // Launch 1 worker, 3 times in a row. Deliver everything.
275 'mailerBatchLimit' => 7,
278 7 => 1, // 1 job which produces 7 messages
279 3 => 1, // 1 job which produces 3 messages
280 0 => 1, // 1 job which produces 0 messages
285 // Launch 2 worker, 3 times in a row. Deliver everything.
291 'mailerBatchLimit' => 3,
294 3 => 3, // 3 jobs which produce 3 messages
295 1 => 1, // 1 job which produces 1 messages
296 0 => 2, // 2 jobs which produce 0 messages
301 // For two mailings, launch 1 worker, 5 times in a row. Deliver everything.
308 'mailerBatchLimit' => 6,
311 // x6 => x4+x2 => x6 => x2 => x0
312 6 => 3, // 3 jobs which produce 6 messages
313 2 => 1, // 1 job which produces 2 messages
314 0 => 1, // 1 job which produces 0 messages
323 * Setup various mail configuration options (eg $mailerBatchLimit,
324 * $mailerJobMax) and spawn multiple worker threads ($workers).
325 * Allow the threads to complete. (Optionally, repeat the above
326 * process.) Finally, check to see if the right number of
327 * jobs delivered the right number of messages.
329 * @param array $settings
330 * An array of settings (eg mailerBatchLimit, workers). See comments
331 * for $this->defaultSettings.
332 * @param array $expectedTallies
333 * A listing of the number cron-runs keyed by their size.
334 * For example, array(10=>2) means that there 2 cron-runs
335 * which delivered 10 messages each.
336 * @param int $expectedTotal
337 * The total number of contacts for whom messages should have
339 * @dataProvider concurrencyExamples
341 public function testConcurrency($settings, $expectedTallies, $expectedTotal) {
342 $settings = array_merge($this->defaultSettings
, $settings);
344 $this->createContactsInGroup($settings['recipients'], $this->_groupID
);
345 Civi
::settings()->add(CRM_Utils_Array
::subset($settings, array(
351 for ($i = 0; $i < $settings['mailings']; $i++
) {
352 $this->callAPISuccess('mailing', 'create', $this->_params
);
355 $this->_mut
->assertRecipients(array());
357 $allApiResults = array();
358 for ($iterationId = 0; $iterationId < $settings['iterations']; $iterationId++
) {
359 $apiCalls = $this->createExternalAPI();
360 $apiCalls->addEnv(array('CIVICRM_CRON_HOLD' => $settings['lockHold']));
361 for ($workerId = 0; $workerId < $settings['workers']; $workerId++
) {
362 $apiCalls->addCall('job', 'process_mailing', array());
365 $this->assertEquals($settings['workers'], $apiCalls->getRunningCount());
368 $allApiResults = array_merge($allApiResults, $apiCalls->getResults());
371 $actualTallies = $this->tallyApiResults($allApiResults);
372 $this->assertEquals($expectedTallies, $actualTallies, 'API tallies should match.' . print_r(array(
373 'expectedTallies' => $expectedTallies,
374 'actualTallies' => $actualTallies,
375 'apiResults' => $allApiResults,
377 $this->_mut
->assertRecipients($this->getRecipients(1, $expectedTotal / $settings['mailings'], 'nul.example.com', $settings['mailings']));
378 $this->assertEquals(0, $apiCalls->getRunningCount());
382 * Create contacts in group.
385 * @param int $groupID
386 * @param string $domain
388 public function createContactsInGroup($count, $groupID, $domain = 'nul.example.com') {
389 for ($i = 1; $i <= $count; $i++
) {
390 $contactID = $this->individualCreate(array('first_name' => $count, 'email' => 'mail' . $i . '@' . $domain));
391 $this->callAPISuccess('group_contact', 'create', array(
392 'contact_id' => $contactID,
393 'group_id' => $groupID,
400 * Construct the list of email addresses for $count recipients.
404 * @param string $domain
405 * @param int $mailings
409 public function getRecipients($start, $count, $domain = 'nul.example.com', $mailings = 1) {
410 $recipients = array();
411 for ($m = 0; $m < $mailings; $m++
) {
412 for ($i = $start; $i < ($start +
$count); $i++
) {
413 $recipients[][0] = 'mail' . $i . '@' . $domain;
419 protected function cleanupMailingTest() {
420 $this->quickCleanup(array(
422 'civicrm_mailing_job',
423 'civicrm_mailing_spool',
424 'civicrm_mailing_group',
425 'civicrm_mailing_recipients',
426 'civicrm_mailing_event_queue',
427 'civicrm_mailing_event_bounce',
428 'civicrm_mailing_event_delivered',
430 'civicrm_group_contact',
436 * Categorize results based on (a) whether they succeeded
437 * and (b) the number of messages sent.
439 * @param array $apiResults
441 * One key 'error' for all failures.
442 * A separate key for each distinct quantity.
444 protected function tallyApiResults($apiResults) {
446 foreach ($apiResults as $apiResult) {
447 $key = !empty($apiResult['is_error']) ?
'error' : $apiResult['values']['processed'];
448 $ret[$key] = !empty($ret[$key]) ?
1 +
$ret[$key] : 1;