CRM-16373 - CRM_Core_Config - Use `Runtime` and `MagicMerge`
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
1 <?php
2 /**
3 * File for the CiviUnitTestCase class
4 *
5 * (PHP 5)
6 *
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
10 * @package CiviCRM
11 *
12 * This file is part of CiviCRM
13 *
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
18 *
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
23 *
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
27 */
28
29 use Civi\Payment\System;
30
31 /**
32 * Include configuration
33 */
34 define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
35 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
36
37 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
38 require_once CIVICRM_SETTINGS_LOCAL_PATH;
39 }
40 require_once CIVICRM_SETTINGS_PATH;
41 /**
42 * Include class definitions
43 */
44 require_once 'tests/phpunit/Utils.php';
45 require_once 'api/api.php';
46 require_once 'CRM/Financial/BAO/FinancialType.php';
47 define('API_LATEST_VERSION', 3);
48
49 /**
50 * Base class for CiviCRM unit tests
51 *
52 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
53 * may opt for one or neither:
54 *
55 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
56 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
57 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
58 * 2. useTransaction() executes the test inside a transaction. It's easier to use
59 * (because you don't need to identify specific tables), but it doesn't work for tests
60 * which manipulate schema or truncate data -- and could behave inconsistently
61 * for tests which specifically examine DB transactions.
62 *
63 * Common functions for unit tests
64 * @package CiviCRM
65 */
66 class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
67
68 /**
69 * Api version - easier to override than just a define
70 */
71 protected $_apiversion = API_LATEST_VERSION;
72 /**
73 * Database has been initialized.
74 *
75 * @var boolean
76 */
77 private static $dbInit = FALSE;
78
79 /**
80 * Database connection.
81 *
82 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
83 */
84 protected $_dbconn;
85
86 /**
87 * The database name.
88 *
89 * @var string
90 */
91 static protected $_dbName;
92
93 /**
94 * Track tables we have modified during a test.
95 */
96 protected $_tablesToTruncate = array();
97
98 /**
99 * @var array of temporary directory names
100 */
101 protected $tempDirs;
102
103 /**
104 * @var Utils instance
105 */
106 public static $utils;
107
108 /**
109 * @var boolean populateOnce allows to skip db resets in setUp
110 *
111 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
112 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
113 * "CHECK RUNS" ONLY!
114 *
115 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
116 *
117 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
118 */
119 public static $populateOnce = FALSE;
120
121 /**
122 * @var boolean DBResetRequired allows skipping DB reset
123 * in specific test case. If you still need
124 * to reset single test (method) of such case, call
125 * $this->cleanDB() in the first line of this
126 * test (method).
127 */
128 public $DBResetRequired = TRUE;
129
130 /**
131 * @var CRM_Core_Transaction|NULL
132 */
133 private $tx = NULL;
134
135 /**
136 * @var CRM_Utils_Hook_UnitTests hookClass
137 * example of setting a method for a hook
138 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
139 */
140 public $hookClass = NULL;
141
142 /**
143 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
144 */
145 protected $_params = array();
146
147 /**
148 * @var CRM_Extension_System
149 */
150 protected $origExtensionSystem;
151
152 /**
153 * Constructor.
154 *
155 * Because we are overriding the parent class constructor, we
156 * need to show the same arguments as exist in the constructor of
157 * PHPUnit_Framework_TestCase, since
158 * PHPUnit_Framework_TestSuite::createTest() creates a
159 * ReflectionClass of the Test class and checks the constructor
160 * of that class to decide how to set up the test.
161 *
162 * @param string $name
163 * @param array $data
164 * @param string $dataName
165 */
166 public function __construct($name = NULL, array$data = array(), $dataName = '') {
167 parent::__construct($name, $data, $dataName);
168
169 // we need full error reporting
170 error_reporting(E_ALL & ~E_NOTICE);
171
172 if (!empty($GLOBALS['mysql_db'])) {
173 self::$_dbName = $GLOBALS['mysql_db'];
174 }
175 else {
176 self::$_dbName = 'civicrm_tests_dev';
177 }
178
179 // create test database
180 self::$utils = new Utils($GLOBALS['mysql_host'],
181 $GLOBALS['mysql_port'],
182 $GLOBALS['mysql_user'],
183 $GLOBALS['mysql_pass']
184 );
185
186 // also load the class loader
187 require_once 'CRM/Core/ClassLoader.php';
188 CRM_Core_ClassLoader::singleton()->register();
189 if (function_exists('_civix_phpunit_setUp')) {
190 // FIXME: loosen coupling
191 _civix_phpunit_setUp();
192 }
193 }
194
195 /**
196 * Override to run the test and assert its state.
197 * @return mixed
198 * @throws \Exception
199 * @throws \PHPUnit_Framework_IncompleteTest
200 * @throws \PHPUnit_Framework_SkippedTest
201 */
202 protected function runTest() {
203 try {
204 return parent::runTest();
205 }
206 catch (PEAR_Exception $e) {
207 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
208 throw new Exception(\CRM_Core_Error::formatTextException($e), $e->getCode());
209 }
210 }
211
212 /**
213 * @return bool
214 */
215 public function requireDBReset() {
216 return $this->DBResetRequired;
217 }
218
219 /**
220 * @return string
221 */
222 public static function getDBName() {
223 $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
224 return $dbName;
225 }
226
227 /**
228 * Create database connection for this instance.
229 *
230 * Initialize the test database if it hasn't been initialized
231 *
232 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
233 */
234 protected function getConnection() {
235 $dbName = self::$_dbName;
236 if (!self::$dbInit) {
237 $dbName = self::getDBName();
238
239 // install test database
240 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
241
242 static::_populateDB(FALSE, $this);
243
244 self::$dbInit = TRUE;
245 }
246 return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
247 }
248
249 /**
250 * Required implementation of abstract method.
251 */
252 protected function getDataSet() {
253 }
254
255 /**
256 * @param bool $perClass
257 * @param null $object
258 * @return bool
259 * TRUE if the populate logic runs; FALSE if it is skipped
260 */
261 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
262
263 if ($perClass || $object == NULL) {
264 $dbreset = TRUE;
265 }
266 else {
267 $dbreset = $object->requireDBReset();
268 }
269
270 if (self::$populateOnce || !$dbreset) {
271 return FALSE;
272 }
273 self::$populateOnce = NULL;
274
275 $dbName = self::getDBName();
276 $pdo = self::$utils->pdo;
277 // only consider real tables and not views
278 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
279 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
280
281 $truncates = array();
282 $drops = array();
283 foreach ($tables as $table) {
284 // skip log tables
285 if (substr($table['table_name'], 0, 4) == 'log_') {
286 continue;
287 }
288
289 // don't change list of installed extensions
290 if ($table['table_name'] == 'civicrm_extension') {
291 continue;
292 }
293
294 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
295 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
296 }
297 else {
298 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
299 }
300 }
301
302 $queries = array(
303 "USE {$dbName};",
304 "SET foreign_key_checks = 0",
305 // SQL mode needs to be strict, that's our standard
306 "SET SQL_MODE='STRICT_ALL_TABLES';",
307 "SET global innodb_flush_log_at_trx_commit = 2;",
308 );
309 $queries = array_merge($queries, $truncates);
310 $queries = array_merge($queries, $drops);
311 foreach ($queries as $query) {
312 if (self::$utils->do_query($query) === FALSE) {
313 // failed to create test database
314 echo "failed to create test db.";
315 exit;
316 }
317 }
318
319 // initialize test database
320 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
321 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
322 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
323
324 $query2 = file_get_contents($sql_file2);
325 $query3 = file_get_contents($sql_file3);
326 $query4 = file_get_contents($sql_file4);
327 if (self::$utils->do_query($query2) === FALSE) {
328 echo "Cannot load civicrm_data.mysql. Aborting.";
329 exit;
330 }
331 if (self::$utils->do_query($query3) === FALSE) {
332 echo "Cannot load test_data.mysql. Aborting.";
333 exit;
334 }
335 if (self::$utils->do_query($query4) === FALSE) {
336 echo "Cannot load test_data.mysql. Aborting.";
337 exit;
338 }
339
340 // done with all the loading, get transactions back
341 if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
342 echo "Cannot set global? Huh?";
343 exit;
344 }
345
346 if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
347 echo "Cannot get foreign keys back? Huh?";
348 exit;
349 }
350
351 unset($query, $query2, $query3);
352
353 // Rebuild triggers
354 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
355
356 CRM_Core_BAO_ConfigSetting::setEnabledComponents(array(
357 'CiviEvent',
358 'CiviContribute',
359 'CiviMember',
360 'CiviMail',
361 'CiviReport',
362 'CiviPledge',
363 ));
364
365 return TRUE;
366 }
367
368 public static function setUpBeforeClass() {
369 static::_populateDB(TRUE);
370
371 // also set this global hack
372 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
373 }
374
375 /**
376 * Common setup functions for all unit tests.
377 */
378 protected function setUp() {
379 $session = CRM_Core_Session::singleton();
380 $session->set('userID', NULL);
381
382 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
383 // Use a temporary file for STDIN
384 $GLOBALS['stdin'] = tmpfile();
385 if ($GLOBALS['stdin'] === FALSE) {
386 echo "Couldn't open temporary file\n";
387 exit(1);
388 }
389
390 // Get and save a connection to the database
391 $this->_dbconn = $this->getConnection();
392
393 // reload database before each test
394 // $this->_populateDB();
395
396 // "initialize" CiviCRM to avoid problems when running single tests
397 // FIXME: look at it closer in second stage
398
399 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
400 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
401
402 // disable any left-over test extensions
403 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
404
405 // reset all the caches
406 CRM_Utils_System::flushCache();
407
408 // initialize the object once db is loaded
409 \Civi::reset();
410 $config = CRM_Core_Config::singleton(TRUE, TRUE); // ugh, performance
411
412 // when running unit tests, use mockup user framework
413 $config->setUserFramework('UnitTests');
414 $this->hookClass = CRM_Utils_Hook::singleton(TRUE);
415
416 // Make sure the DB connection is setup properly
417 $config->userSystem->setMySQLTimeZone();
418 $env = new CRM_Utils_Check_Env();
419 CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
420
421 // clear permissions stub to not check permissions
422 $config->userPermissionClass->permissions = NULL;
423
424 //flush component settings
425 CRM_Core_Component::getEnabledComponents(TRUE);
426
427 error_reporting(E_ALL);
428
429 $this->_sethtmlGlobals();
430 }
431
432 /**
433 * Read everything from the datasets directory and insert into the db.
434 */
435 public function loadAllFixtures() {
436 $fixturesDir = __DIR__ . '/../../fixtures';
437
438 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
439
440 $xmlFiles = glob($fixturesDir . '/*.xml');
441 foreach ($xmlFiles as $xmlFixture) {
442 $op = new PHPUnit_Extensions_Database_Operation_Insert();
443 $dataset = $this->createXMLDataSet($xmlFixture);
444 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
445 $op->execute($this->_dbconn, $dataset);
446 }
447
448 $yamlFiles = glob($fixturesDir . '/*.yaml');
449 foreach ($yamlFiles as $yamlFixture) {
450 $op = new PHPUnit_Extensions_Database_Operation_Insert();
451 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
452 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
453 $op->execute($this->_dbconn, $dataset);
454 }
455
456 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
457 }
458
459 /**
460 * Emulate a logged in user since certain functions use that.
461 * value to store a record in the DB (like activity)
462 * CRM-8180
463 *
464 * @return int
465 * Contact ID of the created user.
466 */
467 public function createLoggedInUser() {
468 $params = array(
469 'first_name' => 'Logged In',
470 'last_name' => 'User ' . rand(),
471 'contact_type' => 'Individual',
472 );
473 $contactID = $this->individualCreate($params);
474 $this->callAPISuccess('UFMatch', 'create', array(
475 'contact_id' => $contactID,
476 'uf_name' => 'superman',
477 'uf_id' => 6,
478 ));
479
480 $session = CRM_Core_Session::singleton();
481 $session->set('userID', $contactID);
482 return $contactID;
483 }
484
485 public function cleanDB() {
486 self::$populateOnce = NULL;
487 $this->DBResetRequired = TRUE;
488
489 $this->_dbconn = $this->getConnection();
490 static::_populateDB();
491 $this->tempDirs = array();
492 }
493
494 /**
495 * Create default domain contacts for the two domains added during test class.
496 * database population.
497 */
498 public function createDomainContacts() {
499 $default_domain_contact = $this->organizationCreate();
500 $second_domain_contact = $this->organizationCreate();
501 }
502
503 /**
504 * Common teardown functions for all unit tests.
505 */
506 protected function tearDown() {
507 error_reporting(E_ALL & ~E_NOTICE);
508 CRM_Utils_Hook::singleton()->reset();
509 $this->hookClass->reset();
510 $session = CRM_Core_Session::singleton();
511 $session->set('userID', NULL);
512
513 if ($this->tx) {
514 $this->tx->rollback()->commit();
515 $this->tx = NULL;
516
517 CRM_Core_Transaction::forceRollbackIfEnabled();
518 \Civi\Core\Transaction\Manager::singleton(TRUE);
519 }
520 else {
521 CRM_Core_Transaction::forceRollbackIfEnabled();
522 \Civi\Core\Transaction\Manager::singleton(TRUE);
523
524 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
525 $this->quickCleanup($tablesToTruncate);
526 $this->createDomainContacts();
527 }
528
529 $this->cleanTempDirs();
530 $this->unsetExtensionSystem();
531 $this->clearOutputBuffer();
532 }
533
534 /**
535 * FIXME: Maybe a better way to do it
536 */
537 public function foreignKeyChecksOff() {
538 self::$utils = new Utils($GLOBALS['mysql_host'],
539 $GLOBALS['mysql_port'],
540 $GLOBALS['mysql_user'],
541 $GLOBALS['mysql_pass']
542 );
543 $dbName = self::getDBName();
544 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
545 if (self::$utils->do_query($query) === FALSE) {
546 // fail happens
547 echo 'Cannot set foreign_key_checks = 0';
548 exit(1);
549 }
550 return TRUE;
551 }
552
553 public function foreignKeyChecksOn() {
554 // FIXME: might not be needed if previous fixme implemented
555 }
556
557 /**
558 * Generic function to compare expected values after an api call to retrieved.
559 * DB values.
560 *
561 * @daoName string DAO Name of object we're evaluating.
562 * @id int Id of object
563 * @match array Associative array of field name => expected value. Empty if asserting
564 * that a DELETE occurred
565 * @delete boolean True if we're checking that a DELETE action occurred.
566 * @param $daoName
567 * @param $id
568 * @param $match
569 * @param bool $delete
570 * @throws \PHPUnit_Framework_AssertionFailedError
571 */
572 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
573 if (empty($id)) {
574 // adding this here since developers forget to check for an id
575 // and hence we get the first value in the db
576 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
577 }
578
579 $object = new $daoName();
580 $object->id = $id;
581 $verifiedCount = 0;
582
583 // If we're asserting successful record deletion, make sure object is NOT found.
584 if ($delete) {
585 if ($object->find(TRUE)) {
586 $this->fail("Object not deleted by delete operation: $daoName, $id");
587 }
588 return;
589 }
590
591 // Otherwise check matches of DAO field values against expected values in $match.
592 if ($object->find(TRUE)) {
593 $fields = &$object->fields();
594 foreach ($fields as $name => $value) {
595 $dbName = $value['name'];
596 if (isset($match[$name])) {
597 $verifiedCount++;
598 $this->assertEquals($object->$dbName, $match[$name]);
599 }
600 elseif (isset($match[$dbName])) {
601 $verifiedCount++;
602 $this->assertEquals($object->$dbName, $match[$dbName]);
603 }
604 }
605 }
606 else {
607 $this->fail("Could not retrieve object: $daoName, $id");
608 }
609 $object->free();
610 $matchSize = count($match);
611 if ($verifiedCount != $matchSize) {
612 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
613 }
614 }
615
616 /**
617 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
618 * @param string $daoName
619 * @param $searchValue
620 * @param $returnColumn
621 * @param $searchColumn
622 * @param $message
623 *
624 * @return null|string
625 * @throws PHPUnit_Framework_AssertionFailedError
626 */
627 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
628 if (empty($searchValue)) {
629 $this->fail("empty value passed to assertDBNotNull");
630 }
631 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
632 $this->assertNotNull($value, $message);
633
634 return $value;
635 }
636
637 /**
638 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
639 * @param string $daoName
640 * @param $searchValue
641 * @param $returnColumn
642 * @param $searchColumn
643 * @param $message
644 */
645 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
646 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
647 $this->assertNull($value, $message);
648 }
649
650 /**
651 * Request a record from the DB by id. Success if row not found.
652 * @param string $daoName
653 * @param int $id
654 * @param null $message
655 */
656 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
657 $message = $message ? $message : "$daoName (#$id) should not exist";
658 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
659 $this->assertNull($value, $message);
660 }
661
662 /**
663 * Request a record from the DB by id. Success if row not found.
664 * @param string $daoName
665 * @param int $id
666 * @param null $message
667 */
668 public function assertDBRowExist($daoName, $id, $message = NULL) {
669 $message = $message ? $message : "$daoName (#$id) should exist";
670 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
671 $this->assertEquals($id, $value, $message);
672 }
673
674 /**
675 * Compare a single column value in a retrieved DB record to an expected value.
676 * @param string $daoName
677 * @param $searchValue
678 * @param $returnColumn
679 * @param $searchColumn
680 * @param $expectedValue
681 * @param $message
682 */
683 public function assertDBCompareValue(
684 $daoName, $searchValue, $returnColumn, $searchColumn,
685 $expectedValue, $message
686 ) {
687 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
688 $this->assertEquals($value, $expectedValue, $message);
689 }
690
691 /**
692 * Compare all values in a single retrieved DB record to an array of expected values.
693 * @param string $daoName
694 * @param array $searchParams
695 * @param $expectedValues
696 */
697 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
698 //get the values from db
699 $dbValues = array();
700 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
701
702 // compare db values with expected values
703 self::assertAttributesEquals($expectedValues, $dbValues);
704 }
705
706 /**
707 * Assert that a SQL query returns a given value.
708 *
709 * The first argument is an expected value. The remaining arguments are passed
710 * to CRM_Core_DAO::singleValueQuery
711 *
712 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
713 * array(1 => array("Whiz", "String")));
714 * @param $expected
715 * @param $query
716 * @param array $params
717 * @param string $message
718 */
719 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
720 if ($message) {
721 $message .= ': ';
722 }
723 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
724 $this->assertEquals($expected, $actual,
725 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
726 $message, $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
727 )
728 );
729 }
730
731 /**
732 * Assert that two array-trees are exactly equal, notwithstanding
733 * the sorting of keys
734 *
735 * @param array $expected
736 * @param array $actual
737 */
738 public function assertTreeEquals($expected, $actual) {
739 $e = array();
740 $a = array();
741 CRM_Utils_Array::flatten($expected, $e, '', ':::');
742 CRM_Utils_Array::flatten($actual, $a, '', ':::');
743 ksort($e);
744 ksort($a);
745
746 $this->assertEquals($e, $a);
747 }
748
749 /**
750 * Assert that two numbers are approximately equal.
751 *
752 * @param int|float $expected
753 * @param int|float $actual
754 * @param int|float $tolerance
755 * @param string $message
756 */
757 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
758 if ($message === NULL) {
759 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
760 }
761 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
762 }
763
764 /**
765 * Assert attributes are equal.
766 *
767 * @param $expectedValues
768 * @param $actualValues
769 * @param string $message
770 *
771 * @throws PHPUnit_Framework_AssertionFailedError
772 */
773 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
774 foreach ($expectedValues as $paramName => $paramValue) {
775 if (isset($actualValues[$paramName])) {
776 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
777 }
778 else {
779 $this->fail("Attribute '$paramName' not present in actual array.");
780 }
781 }
782 }
783
784 /**
785 * @param $key
786 * @param $list
787 */
788 public function assertArrayKeyExists($key, &$list) {
789 $result = isset($list[$key]) ? TRUE : FALSE;
790 $this->assertTrue($result, ts("%1 element exists?",
791 array(1 => $key)
792 ));
793 }
794
795 /**
796 * @param $key
797 * @param $list
798 */
799 public function assertArrayValueNotNull($key, &$list) {
800 $this->assertArrayKeyExists($key, $list);
801
802 $value = isset($list[$key]) ? $list[$key] : NULL;
803 $this->assertTrue($value,
804 ts("%1 element not null?",
805 array(1 => $key)
806 )
807 );
808 }
809
810 /**
811 * Check that api returned 'is_error' => 0.
812 *
813 * @param array $apiResult
814 * Api result.
815 * @param string $prefix
816 * Extra test to add to message.
817 */
818 public function assertAPISuccess($apiResult, $prefix = '') {
819 if (!empty($prefix)) {
820 $prefix .= ': ';
821 }
822 $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
823
824 if (!empty($apiResult['debug_information'])) {
825 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
826 }
827 if (!empty($apiResult['trace'])) {
828 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
829 }
830 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
831 }
832
833 /**
834 * Check that api returned 'is_error' => 1.
835 *
836 * @param array $apiResult
837 * Api result.
838 * @param string $prefix
839 * Extra test to add to message.
840 * @param null $expectedError
841 */
842 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
843 if (!empty($prefix)) {
844 $prefix .= ': ';
845 }
846 if ($expectedError && !empty($apiResult['is_error'])) {
847 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
848 }
849 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
850 $this->assertNotEmpty($apiResult['error_message']);
851 }
852
853 /**
854 * @param $expected
855 * @param $actual
856 * @param string $message
857 */
858 public function assertType($expected, $actual, $message = '') {
859 return $this->assertInternalType($expected, $actual, $message);
860 }
861
862 /**
863 * Check that a deleted item has been deleted.
864 *
865 * @param $entity
866 * @param $id
867 */
868 public function assertAPIDeleted($entity, $id) {
869 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
870 }
871
872
873 /**
874 * Check that api returned 'is_error' => 1
875 * else provide full message
876 * @param array $result
877 * @param $expected
878 * @param array $valuesToExclude
879 * @param string $prefix
880 * Extra test to add to message.
881 */
882 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
883 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
884 foreach ($valuesToExclude as $value) {
885 if (isset($result[$value])) {
886 unset($result[$value]);
887 }
888 if (isset($expected[$value])) {
889 unset($expected[$value]);
890 }
891 }
892 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
893 }
894
895 /**
896 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
897 *
898 * @param $entity
899 * @param $action
900 * @param array $params
901 * @return array|int
902 */
903 public function civicrm_api($entity, $action, $params) {
904 return civicrm_api($entity, $action, $params);
905 }
906
907 /**
908 * Create a batch of external API calls which can
909 * be executed concurrently.
910 *
911 * @code
912 * $calls = $this->createExternalAPI()
913 * ->addCall('Contact', 'get', ...)
914 * ->addCall('Contact', 'get', ...)
915 * ...
916 * ->run()
917 * ->getResults();
918 * @endcode
919 *
920 * @return \Civi\API\ExternalBatch
921 * @throws PHPUnit_Framework_SkippedTestError
922 */
923 public function createExternalAPI() {
924 global $civicrm_root;
925 $defaultParams = array(
926 'version' => $this->_apiversion,
927 'debug' => 1,
928 );
929
930 $calls = new \Civi\API\ExternalBatch($defaultParams);
931 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
932
933 if (!$calls->isSupported()) {
934 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
935 }
936
937 return $calls;
938 }
939
940 /**
941 * wrap api functions.
942 * so we can ensure they succeed & throw exceptions without litterering the test with checks
943 *
944 * @param string $entity
945 * @param string $action
946 * @param array $params
947 * @param mixed $checkAgainst
948 * Optional value to check result against, implemented for getvalue,.
949 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
950 * for getsingle the array is compared against an array passed in - the id is not compared (for
951 * better or worse )
952 *
953 * @return array|int
954 */
955 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
956 $params = array_merge(array(
957 'version' => $this->_apiversion,
958 'debug' => 1,
959 ),
960 $params
961 );
962 switch (strtolower($action)) {
963 case 'getvalue':
964 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
965
966 case 'getsingle':
967 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
968
969 case 'getcount':
970 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
971 }
972 $result = $this->civicrm_api($entity, $action, $params);
973 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
974 return $result;
975 }
976
977 /**
978 * This function exists to wrap api getValue function & check the result
979 * so we can ensure they succeed & throw exceptions without litterering the test with checks
980 * There is a type check in this
981 *
982 * @param string $entity
983 * @param array $params
984 * @param string $type
985 * Per http://php.net/manual/en/function.gettype.php possible types.
986 * - boolean
987 * - integer
988 * - double
989 * - string
990 * - array
991 * - object
992 *
993 * @return array|int
994 */
995 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
996 $params += array(
997 'version' => $this->_apiversion,
998 'debug' => 1,
999 );
1000 $result = $this->civicrm_api($entity, 'getvalue', $params);
1001 if ($type) {
1002 if ($type == 'integer') {
1003 // api seems to return integers as strings
1004 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
1005 }
1006 else {
1007 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1008 }
1009 }
1010 return $result;
1011 }
1012
1013 /**
1014 * This function exists to wrap api getsingle function & check the result
1015 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1016 *
1017 * @param string $entity
1018 * @param array $params
1019 * @param array $checkAgainst
1020 * Array to compare result against.
1021 * - boolean
1022 * - integer
1023 * - double
1024 * - string
1025 * - array
1026 * - object
1027 *
1028 * @throws Exception
1029 * @return array|int
1030 */
1031 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1032 $params += array(
1033 'version' => $this->_apiversion,
1034 'debug' => 1,
1035 );
1036 $result = $this->civicrm_api($entity, 'getsingle', $params);
1037 if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
1038 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1039 }
1040 if ($checkAgainst) {
1041 // @todo - have gone with the fn that unsets id? should we check id?
1042 $this->checkArrayEquals($result, $checkAgainst);
1043 }
1044 return $result;
1045 }
1046
1047 /**
1048 * This function exists to wrap api getValue function & check the result
1049 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1050 * There is a type check in this
1051 * @param string $entity
1052 * @param array $params
1053 * @param null $count
1054 * @throws Exception
1055 * @return array|int
1056 */
1057 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1058 $params += array(
1059 'version' => $this->_apiversion,
1060 'debug' => 1,
1061 );
1062 $result = $this->civicrm_api($entity, 'getcount', $params);
1063 if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
1064 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1065 }
1066 if (is_int($count)) {
1067 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1068 }
1069 return $result;
1070 }
1071
1072 /**
1073 * This function exists to wrap api functions.
1074 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1075 *
1076 * @param string $entity
1077 * @param string $action
1078 * @param array $params
1079 * @param string $function
1080 * Pass this in to create a generated example.
1081 * @param string $file
1082 * Pass this in to create a generated example.
1083 * @param string $description
1084 * @param string|null $exampleName
1085 *
1086 * @return array|int
1087 */
1088 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1089 $params['version'] = $this->_apiversion;
1090 $result = $this->callAPISuccess($entity, $action, $params);
1091 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1092 return $result;
1093 }
1094
1095 /**
1096 * This function exists to wrap api functions.
1097 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1098 * @param string $entity
1099 * @param string $action
1100 * @param array $params
1101 * @param string $expectedErrorMessage
1102 * Error.
1103 * @param null $extraOutput
1104 * @return array|int
1105 */
1106 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1107 if (is_array($params)) {
1108 $params += array(
1109 'version' => $this->_apiversion,
1110 );
1111 }
1112 $result = $this->civicrm_api($entity, $action, $params);
1113 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1114 return $result;
1115 }
1116
1117 /**
1118 * Create required data based on $this->entity & $this->params
1119 * This is just a way to set up the test data for delete & get functions
1120 * so the distinction between set
1121 * up & tested functions is clearer
1122 *
1123 * @return array
1124 * api Result
1125 */
1126 public function createTestEntity() {
1127 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
1128 }
1129
1130 /**
1131 * Generic function to create Organisation, to be used in test cases
1132 *
1133 * @param array $params
1134 * parameters for civicrm_contact_add api function call
1135 * @param int $seq
1136 * sequence number if creating multiple organizations
1137 *
1138 * @return int
1139 * id of Organisation created
1140 */
1141 public function organizationCreate($params = array(), $seq = 0) {
1142 if (!$params) {
1143 $params = array();
1144 }
1145 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1146 return $this->_contactCreate($params);
1147 }
1148
1149 /**
1150 * Generic function to create Individual, to be used in test cases
1151 *
1152 * @param array $params
1153 * parameters for civicrm_contact_add api function call
1154 * @param int $seq
1155 * sequence number if creating multiple individuals
1156 *
1157 * @return int
1158 * id of Individual created
1159 */
1160 public function individualCreate($params = array(), $seq = 0) {
1161 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1162 return $this->_contactCreate($params);
1163 }
1164
1165 /**
1166 * Generic function to create Household, to be used in test cases
1167 *
1168 * @param array $params
1169 * parameters for civicrm_contact_add api function call
1170 * @param int $seq
1171 * sequence number if creating multiple households
1172 *
1173 * @return int
1174 * id of Household created
1175 */
1176 public function householdCreate($params = array(), $seq = 0) {
1177 $params = array_merge($this->sampleContact('Household', $seq), $params);
1178 return $this->_contactCreate($params);
1179 }
1180
1181 /**
1182 * Helper function for getting sample contact properties.
1183 *
1184 * @param string $contact_type
1185 * enum contact type: Individual, Organization
1186 * @param int $seq
1187 * sequence number for the values of this type
1188 *
1189 * @return array
1190 * properties of sample contact (ie. $params for API call)
1191 */
1192 public function sampleContact($contact_type, $seq = 0) {
1193 $samples = array(
1194 'Individual' => array(
1195 // The number of values in each list need to be coprime numbers to not have duplicates
1196 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1197 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1198 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1199 ),
1200 'Organization' => array(
1201 'organization_name' => array(
1202 'Unit Test Organization',
1203 'Acme',
1204 'Roberts and Sons',
1205 'Cryo Space Labs',
1206 'Sharper Pens',
1207 ),
1208 ),
1209 'Household' => array(
1210 'household_name' => array('Unit Test household'),
1211 ),
1212 );
1213 $params = array('contact_type' => $contact_type);
1214 foreach ($samples[$contact_type] as $key => $values) {
1215 $params[$key] = $values[$seq % count($values)];
1216 }
1217 if ($contact_type == 'Individual') {
1218 $params['email'] = strtolower(
1219 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1220 );
1221 $params['prefix_id'] = 3;
1222 $params['suffix_id'] = 3;
1223 }
1224 return $params;
1225 }
1226
1227 /**
1228 * Private helper function for calling civicrm_contact_add.
1229 *
1230 * @param array $params
1231 * For civicrm_contact_add api function call.
1232 *
1233 * @throws Exception
1234 *
1235 * @return int
1236 * id of Household created
1237 */
1238 private function _contactCreate($params) {
1239 $result = $this->callAPISuccess('contact', 'create', $params);
1240 if (!empty($result['is_error']) || empty($result['id'])) {
1241 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array::value('trace', $result));
1242 }
1243 return $result['id'];
1244 }
1245
1246 /**
1247 * Delete contact, ensuring it is not the domain contact
1248 *
1249 * @param int $contactID
1250 * Contact ID to delete
1251 */
1252 public function contactDelete($contactID) {
1253 $domain = new CRM_Core_BAO_Domain();
1254 $domain->contact_id = $contactID;
1255 if (!$domain->find(TRUE)) {
1256 $this->callAPISuccess('contact', 'delete', array(
1257 'id' => $contactID,
1258 'skip_undelete' => 1,
1259 ));
1260 }
1261 }
1262
1263 /**
1264 * @param int $contactTypeId
1265 *
1266 * @throws Exception
1267 */
1268 public function contactTypeDelete($contactTypeId) {
1269 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1270 if (!$result) {
1271 throw new Exception('Could not delete contact type');
1272 }
1273 }
1274
1275 /**
1276 * @param array $params
1277 *
1278 * @return mixed
1279 */
1280 public function membershipTypeCreate($params = array()) {
1281 CRM_Member_PseudoConstant::flush('membershipType');
1282 CRM_Core_Config::clearDBCache();
1283 $memberOfOrganization = $this->organizationCreate();
1284 $params = array_merge(array(
1285 'name' => 'General',
1286 'duration_unit' => 'year',
1287 'duration_interval' => 1,
1288 'period_type' => 'rolling',
1289 'member_of_contact_id' => $memberOfOrganization,
1290 'domain_id' => 1,
1291 'financial_type_id' => 1,
1292 'is_active' => 1,
1293 'sequential' => 1,
1294 'visibility' => 'Public',
1295 ), $params);
1296
1297 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1298
1299 CRM_Member_PseudoConstant::flush('membershipType');
1300 CRM_Utils_Cache::singleton()->flush();
1301
1302 return $result['id'];
1303 }
1304
1305 /**
1306 * @param array $params
1307 *
1308 * @return mixed
1309 */
1310 public function contactMembershipCreate($params) {
1311 $pre = array(
1312 'join_date' => '2007-01-21',
1313 'start_date' => '2007-01-21',
1314 'end_date' => '2007-12-21',
1315 'source' => 'Payment',
1316 );
1317
1318 foreach ($pre as $key => $val) {
1319 if (!isset($params[$key])) {
1320 $params[$key] = $val;
1321 }
1322 }
1323
1324 $result = $this->callAPISuccess('Membership', 'create', $params);
1325 return $result['id'];
1326 }
1327
1328 /**
1329 * Delete Membership Type.
1330 *
1331 * @param array $params
1332 */
1333 public function membershipTypeDelete($params) {
1334 $this->callAPISuccess('MembershipType', 'Delete', $params);
1335 }
1336
1337 /**
1338 * @param int $membershipID
1339 */
1340 public function membershipDelete($membershipID) {
1341 $deleteParams = array('id' => $membershipID);
1342 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1343 }
1344
1345 /**
1346 * @param string $name
1347 *
1348 * @return mixed
1349 */
1350 public function membershipStatusCreate($name = 'test member status') {
1351 $params['name'] = $name;
1352 $params['start_event'] = 'start_date';
1353 $params['end_event'] = 'end_date';
1354 $params['is_current_member'] = 1;
1355 $params['is_active'] = 1;
1356
1357 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1358 CRM_Member_PseudoConstant::flush('membershipStatus');
1359 return $result['id'];
1360 }
1361
1362 /**
1363 * @param int $membershipStatusID
1364 */
1365 public function membershipStatusDelete($membershipStatusID) {
1366 if (!$membershipStatusID) {
1367 return;
1368 }
1369 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1370 }
1371
1372 /**
1373 * @param array $params
1374 *
1375 * @return mixed
1376 */
1377 public function relationshipTypeCreate($params = array()) {
1378 $params = array_merge(array(
1379 'name_a_b' => 'Relation 1 for relationship type create',
1380 'name_b_a' => 'Relation 2 for relationship type create',
1381 'contact_type_a' => 'Individual',
1382 'contact_type_b' => 'Organization',
1383 'is_reserved' => 1,
1384 'is_active' => 1,
1385 ),
1386 $params
1387 );
1388
1389 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1390 CRM_Core_PseudoConstant::flush('relationshipType');
1391
1392 return $result['id'];
1393 }
1394
1395 /**
1396 * Delete Relatinship Type.
1397 *
1398 * @param int $relationshipTypeID
1399 */
1400 public function relationshipTypeDelete($relationshipTypeID) {
1401 $params['id'] = $relationshipTypeID;
1402 $this->callAPISuccess('relationship_type', 'delete', $params);
1403 }
1404
1405 /**
1406 * @param array $params
1407 *
1408 * @return mixed
1409 */
1410 public function paymentProcessorTypeCreate($params = NULL) {
1411 if (is_null($params)) {
1412 $params = array(
1413 'name' => 'API_Test_PP',
1414 'title' => 'API Test Payment Processor',
1415 'class_name' => 'CRM_Core_Payment_APITest',
1416 'billing_mode' => 'form',
1417 'is_recur' => 0,
1418 'is_reserved' => 1,
1419 'is_active' => 1,
1420 );
1421 }
1422 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1423
1424 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1425
1426 return $result['id'];
1427 }
1428
1429 /**
1430 * Create test Authorize.net instance.
1431 *
1432 * @param array $params
1433 *
1434 * @return mixed
1435 */
1436 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1437 $params = array_merge(array(
1438 'name' => 'Authorize',
1439 'domain_id' => CRM_Core_Config::domainID(),
1440 'payment_processor_type_id' => 'AuthNet',
1441 'title' => 'AuthNet',
1442 'is_active' => 1,
1443 'is_default' => 0,
1444 'is_test' => 1,
1445 'is_recur' => 1,
1446 'user_name' => '4y5BfuW7jm',
1447 'password' => '4cAmW927n8uLf5J8',
1448 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1449 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1450 'class_name' => 'Payment_AuthorizeNet',
1451 'billing_mode' => 1,
1452 ), $params);
1453
1454 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1455 return $result['id'];
1456 }
1457
1458 /**
1459 * Create Participant.
1460 *
1461 * @param array $params
1462 * Array of contact id and event id values.
1463 *
1464 * @return int
1465 * $id of participant created
1466 */
1467 public function participantCreate($params) {
1468 if (empty($params['contact_id'])) {
1469 $params['contact_id'] = $this->individualCreate();
1470 }
1471 if (empty($params['event_id'])) {
1472 $event = $this->eventCreate();
1473 $params['event_id'] = $event['id'];
1474 }
1475 $defaults = array(
1476 'status_id' => 2,
1477 'role_id' => 1,
1478 'register_date' => 20070219,
1479 'source' => 'Wimbeldon',
1480 'event_level' => 'Payment',
1481 'debug' => 1,
1482 );
1483
1484 $params = array_merge($defaults, $params);
1485 $result = $this->callAPISuccess('Participant', 'create', $params);
1486 return $result['id'];
1487 }
1488
1489 /**
1490 * Create Payment Processor.
1491 *
1492 * @return CRM_Financial_DAO_PaymentProcessor
1493 * instance of Payment Processor
1494 */
1495 public function processorCreate() {
1496 $processorParams = array(
1497 'domain_id' => 1,
1498 'name' => 'Dummy',
1499 'payment_processor_type_id' => 10,
1500 'financial_account_id' => 12,
1501 'is_test' => TRUE,
1502 'is_active' => 1,
1503 'user_name' => '',
1504 'url_site' => 'http://dummy.com',
1505 'url_recur' => 'http://dummy.com',
1506 'billing_mode' => 1,
1507 );
1508 return CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1509 }
1510
1511 /**
1512 * Create Payment Processor.
1513 *
1514 * @param array $processorParams
1515 *
1516 * @return \CRM_Core_Payment_Dummy
1517 * Instance of Dummy Payment Processor
1518 */
1519 public function dummyProcessorCreate($processorParams = array()) {
1520 $paymentProcessor = $this->processorCreate($processorParams);
1521 return Civi\Payment\System::singleton()->getById($paymentProcessor->id);
1522 }
1523
1524 /**
1525 * Create contribution page.
1526 *
1527 * @param array $params
1528 * @return array
1529 * Array of contribution page
1530 */
1531 public function contributionPageCreate($params) {
1532 $this->_pageParams = array(
1533 'title' => 'Test Contribution Page',
1534 'financial_type_id' => 1,
1535 'currency' => 'USD',
1536 'financial_account_id' => 1,
1537 'payment_processor' => $params['processor_id'],
1538 'is_active' => 1,
1539 'is_allow_other_amount' => 1,
1540 'min_amount' => 10,
1541 'max_amount' => 1000,
1542 );
1543 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1544 return $contributionPage;
1545 }
1546
1547 /**
1548 * Create Tag.
1549 *
1550 * @param array $params
1551 * @return array
1552 * result of created tag
1553 */
1554 public function tagCreate($params = array()) {
1555 $defaults = array(
1556 'name' => 'New Tag3',
1557 'description' => 'This is description for Our New Tag ',
1558 'domain_id' => '1',
1559 );
1560 $params = array_merge($defaults, $params);
1561 $result = $this->callAPISuccess('Tag', 'create', $params);
1562 return $result['values'][$result['id']];
1563 }
1564
1565 /**
1566 * Delete Tag.
1567 *
1568 * @param int $tagId
1569 * Id of the tag to be deleted.
1570 *
1571 * @return int
1572 */
1573 public function tagDelete($tagId) {
1574 require_once 'api/api.php';
1575 $params = array(
1576 'tag_id' => $tagId,
1577 );
1578 $result = $this->callAPISuccess('Tag', 'delete', $params);
1579 return $result['id'];
1580 }
1581
1582 /**
1583 * Add entity(s) to the tag
1584 *
1585 * @param array $params
1586 *
1587 * @return bool
1588 */
1589 public function entityTagAdd($params) {
1590 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1591 return TRUE;
1592 }
1593
1594 /**
1595 * Create contribution.
1596 *
1597 * @param int $cID
1598 * Contact_id.
1599 *
1600 * @return int
1601 * id of created contribution
1602 */
1603 public function pledgeCreate($cID) {
1604 $params = array(
1605 'contact_id' => $cID,
1606 'pledge_create_date' => date('Ymd'),
1607 'start_date' => date('Ymd'),
1608 'scheduled_date' => date('Ymd'),
1609 'amount' => 100.00,
1610 'pledge_status_id' => '2',
1611 'financial_type_id' => '1',
1612 'pledge_original_installment_amount' => 20,
1613 'frequency_interval' => 5,
1614 'frequency_unit' => 'year',
1615 'frequency_day' => 15,
1616 'installments' => 5,
1617 );
1618
1619 $result = $this->callAPISuccess('Pledge', 'create', $params);
1620 return $result['id'];
1621 }
1622
1623 /**
1624 * Delete contribution.
1625 *
1626 * @param int $pledgeId
1627 */
1628 public function pledgeDelete($pledgeId) {
1629 $params = array(
1630 'pledge_id' => $pledgeId,
1631 );
1632 $this->callAPISuccess('Pledge', 'delete', $params);
1633 }
1634
1635 /**
1636 * Create contribution.
1637 *
1638 * @param array $params
1639 * Array of parameters.
1640 * @param int $cTypeID
1641 * Id of financial type.
1642 * @param int $invoiceID
1643 * @param int $trxnID
1644 * @param int $paymentInstrumentID
1645 *
1646 * @return int
1647 * id of created contribution
1648 */
1649 public function contributionCreate($params, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345,
1650 $paymentInstrumentID = 1) {
1651
1652 $params = array_merge(array(
1653 'domain_id' => 1,
1654 'receive_date' => date('Ymd'),
1655 'total_amount' => 100.00,
1656 'fee_amount' => 5.00,
1657 'net_ammount' => 95.00,
1658 'financial_type_id' => $cTypeID,
1659 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1660 'non_deductible_amount' => 10.00,
1661 'trxn_id' => $trxnID,
1662 'invoice_id' => $invoiceID,
1663 'source' => 'SSF',
1664 'contribution_status_id' => 1,
1665 ), $params);
1666
1667 $result = $this->callAPISuccess('contribution', 'create', $params);
1668 return $result['id'];
1669 }
1670
1671 /**
1672 * Create online contribution.
1673 *
1674 * @param array $params
1675 * @param int $financialType
1676 * Id of financial type.
1677 * @param int $invoiceID
1678 * @param int $trxnID
1679 *
1680 * @return int
1681 * id of created contribution
1682 */
1683 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1684 $contribParams = array(
1685 'contact_id' => $params['contact_id'],
1686 'receive_date' => date('Ymd'),
1687 'total_amount' => 100.00,
1688 'financial_type_id' => $financialType,
1689 'contribution_page_id' => $params['contribution_page_id'],
1690 'trxn_id' => 12345,
1691 'invoice_id' => 67890,
1692 'source' => 'SSF',
1693 );
1694 $contribParams = array_merge($contribParams, $params);
1695 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1696
1697 return $result['id'];
1698 }
1699
1700 /**
1701 * Delete contribution.
1702 *
1703 * @param int $contributionId
1704 *
1705 * @return array|int
1706 */
1707 public function contributionDelete($contributionId) {
1708 $params = array(
1709 'contribution_id' => $contributionId,
1710 );
1711 $result = $this->callAPISuccess('contribution', 'delete', $params);
1712 return $result;
1713 }
1714
1715 /**
1716 * Create an Event.
1717 *
1718 * @param array $params
1719 * Name-value pair for an event.
1720 *
1721 * @return array
1722 */
1723 public function eventCreate($params = array()) {
1724 // if no contact was passed, make up a dummy event creator
1725 if (!isset($params['contact_id'])) {
1726 $params['contact_id'] = $this->_contactCreate(array(
1727 'contact_type' => 'Individual',
1728 'first_name' => 'Event',
1729 'last_name' => 'Creator',
1730 ));
1731 }
1732
1733 // set defaults for missing params
1734 $params = array_merge(array(
1735 'title' => 'Annual CiviCRM meet',
1736 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1737 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1738 'event_type_id' => 1,
1739 'is_public' => 1,
1740 'start_date' => 20081021,
1741 'end_date' => 20081023,
1742 'is_online_registration' => 1,
1743 'registration_start_date' => 20080601,
1744 'registration_end_date' => 20081015,
1745 'max_participants' => 100,
1746 'event_full_text' => 'Sorry! We are already full',
1747 'is_monetory' => 0,
1748 'is_active' => 1,
1749 'is_show_location' => 0,
1750 ), $params);
1751
1752 return $this->callAPISuccess('Event', 'create', $params);
1753 }
1754
1755 /**
1756 * Delete event.
1757 *
1758 * @param int $id
1759 * ID of the event.
1760 *
1761 * @return array|int
1762 */
1763 public function eventDelete($id) {
1764 $params = array(
1765 'event_id' => $id,
1766 );
1767 return $this->callAPISuccess('event', 'delete', $params);
1768 }
1769
1770 /**
1771 * Delete participant.
1772 *
1773 * @param int $participantID
1774 *
1775 * @return array|int
1776 */
1777 public function participantDelete($participantID) {
1778 $params = array(
1779 'id' => $participantID,
1780 );
1781 return $this->callAPISuccess('Participant', 'delete', $params);
1782 }
1783
1784 /**
1785 * Create participant payment.
1786 *
1787 * @param int $participantID
1788 * @param int $contributionID
1789 * @return int
1790 * $id of created payment
1791 */
1792 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1793 //Create Participant Payment record With Values
1794 $params = array(
1795 'participant_id' => $participantID,
1796 'contribution_id' => $contributionID,
1797 );
1798
1799 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1800 return $result['id'];
1801 }
1802
1803 /**
1804 * Delete participant payment.
1805 *
1806 * @param int $paymentID
1807 */
1808 public function participantPaymentDelete($paymentID) {
1809 $params = array(
1810 'id' => $paymentID,
1811 );
1812 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1813 }
1814
1815 /**
1816 * Add a Location.
1817 *
1818 * @param int $contactID
1819 * @return int
1820 * location id of created location
1821 */
1822 public function locationAdd($contactID) {
1823 $address = array(
1824 1 => array(
1825 'location_type' => 'New Location Type',
1826 'is_primary' => 1,
1827 'name' => 'Saint Helier St',
1828 'county' => 'Marin',
1829 'country' => 'UNITED STATES',
1830 'state_province' => 'Michigan',
1831 'supplemental_address_1' => 'Hallmark Ct',
1832 'supplemental_address_2' => 'Jersey Village',
1833 ),
1834 );
1835
1836 $params = array(
1837 'contact_id' => $contactID,
1838 'address' => $address,
1839 'location_format' => '2.0',
1840 'location_type' => 'New Location Type',
1841 );
1842
1843 $result = $this->callAPISuccess('Location', 'create', $params);
1844 return $result;
1845 }
1846
1847 /**
1848 * Delete Locations of contact.
1849 *
1850 * @param array $params
1851 * Parameters.
1852 */
1853 public function locationDelete($params) {
1854 $this->callAPISuccess('Location', 'delete', $params);
1855 }
1856
1857 /**
1858 * Add a Location Type.
1859 *
1860 * @param array $params
1861 * @return CRM_Core_DAO_LocationType
1862 * location id of created location
1863 */
1864 public function locationTypeCreate($params = NULL) {
1865 if ($params === NULL) {
1866 $params = array(
1867 'name' => 'New Location Type',
1868 'vcard_name' => 'New Location Type',
1869 'description' => 'Location Type for Delete',
1870 'is_active' => 1,
1871 );
1872 }
1873
1874 $locationType = new CRM_Core_DAO_LocationType();
1875 $locationType->copyValues($params);
1876 $locationType->save();
1877 // clear getfields cache
1878 CRM_Core_PseudoConstant::flush();
1879 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1880 return $locationType;
1881 }
1882
1883 /**
1884 * Delete a Location Type.
1885 *
1886 * @param int $locationTypeId
1887 */
1888 public function locationTypeDelete($locationTypeId) {
1889 $locationType = new CRM_Core_DAO_LocationType();
1890 $locationType->id = $locationTypeId;
1891 $locationType->delete();
1892 }
1893
1894 /**
1895 * Add a Group.
1896 *
1897 * @param array $params
1898 * @return int
1899 * groupId of created group
1900 */
1901 public function groupCreate($params = array()) {
1902 $params = array_merge(array(
1903 'name' => 'Test Group 1',
1904 'domain_id' => 1,
1905 'title' => 'New Test Group Created',
1906 'description' => 'New Test Group Created',
1907 'is_active' => 1,
1908 'visibility' => 'Public Pages',
1909 'group_type' => array(
1910 '1' => 1,
1911 '2' => 1,
1912 ),
1913 ), $params);
1914
1915 $result = $this->callAPISuccess('Group', 'create', $params);
1916 return $result['id'];
1917 }
1918
1919
1920 /**
1921 * Function to add a Group.
1922 *
1923 * @params array to add group
1924 *
1925 * @param int $groupID
1926 * @param int $totalCount
1927 * @return int
1928 * groupId of created group
1929 */
1930 public function groupContactCreate($groupID, $totalCount = 10) {
1931 $params = array('group_id' => $groupID);
1932 for ($i = 1; $i <= $totalCount; $i++) {
1933 $contactID = $this->individualCreate();
1934 if ($i == 1) {
1935 $params += array('contact_id' => $contactID);
1936 }
1937 else {
1938 $params += array("contact_id.$i" => $contactID);
1939 }
1940 }
1941 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1942
1943 return $result;
1944 }
1945
1946 /**
1947 * Delete a Group.
1948 *
1949 * @param int $gid
1950 */
1951 public function groupDelete($gid) {
1952
1953 $params = array(
1954 'id' => $gid,
1955 );
1956
1957 $this->callAPISuccess('Group', 'delete', $params);
1958 }
1959
1960 /**
1961 * Create a UFField.
1962 * @param array $params
1963 */
1964 public function uFFieldCreate($params = array()) {
1965 $params = array_merge(array(
1966 'uf_group_id' => 1,
1967 'field_name' => 'first_name',
1968 'is_active' => 1,
1969 'is_required' => 1,
1970 'visibility' => 'Public Pages and Listings',
1971 'is_searchable' => '1',
1972 'label' => 'first_name',
1973 'field_type' => 'Individual',
1974 'weight' => 1,
1975 ), $params);
1976 $this->callAPISuccess('uf_field', 'create', $params);
1977 }
1978
1979 /**
1980 * Add a UF Join Entry.
1981 *
1982 * @param array $params
1983 * @return int
1984 * $id of created UF Join
1985 */
1986 public function ufjoinCreate($params = NULL) {
1987 if ($params === NULL) {
1988 $params = array(
1989 'is_active' => 1,
1990 'module' => 'CiviEvent',
1991 'entity_table' => 'civicrm_event',
1992 'entity_id' => 3,
1993 'weight' => 1,
1994 'uf_group_id' => 1,
1995 );
1996 }
1997 $result = $this->callAPISuccess('uf_join', 'create', $params);
1998 return $result;
1999 }
2000
2001 /**
2002 * Delete a UF Join Entry.
2003 *
2004 * @param array $params
2005 * with missing uf_group_id
2006 */
2007 public function ufjoinDelete($params = NULL) {
2008 if ($params === NULL) {
2009 $params = array(
2010 'is_active' => 1,
2011 'module' => 'CiviEvent',
2012 'entity_table' => 'civicrm_event',
2013 'entity_id' => 3,
2014 'weight' => 1,
2015 'uf_group_id' => '',
2016 );
2017 }
2018
2019 crm_add_uf_join($params);
2020 }
2021
2022 /**
2023 * @param array $params
2024 * Optional parameters.
2025 *
2026 * @return int
2027 * Campaign ID.
2028 */
2029 public function campaignCreate($params = array()) {
2030 $this->enableCiviCampaign();
2031 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2032 'name' => 'big_campaign',
2033 'title' => 'Campaign',
2034 ), $params));
2035 return $campaign['id'];
2036 }
2037
2038 /**
2039 * Create Group for a contact.
2040 *
2041 * @param int $contactId
2042 */
2043 public function contactGroupCreate($contactId) {
2044 $params = array(
2045 'contact_id.1' => $contactId,
2046 'group_id' => 1,
2047 );
2048
2049 $this->callAPISuccess('GroupContact', 'Create', $params);
2050 }
2051
2052 /**
2053 * Delete Group for a contact.
2054 *
2055 * @param int $contactId
2056 */
2057 public function contactGroupDelete($contactId) {
2058 $params = array(
2059 'contact_id.1' => $contactId,
2060 'group_id' => 1,
2061 );
2062 $this->civicrm_api('GroupContact', 'Delete', $params);
2063 }
2064
2065 /**
2066 * Create Activity.
2067 *
2068 * @param array $params
2069 * @return array|int
2070 */
2071 public function activityCreate($params = NULL) {
2072
2073 if ($params === NULL) {
2074 $individualSourceID = $this->individualCreate();
2075
2076 $contactParams = array(
2077 'first_name' => 'Julia',
2078 'Last_name' => 'Anderson',
2079 'prefix' => 'Ms.',
2080 'email' => 'julia_anderson@civicrm.org',
2081 'contact_type' => 'Individual',
2082 );
2083
2084 $individualTargetID = $this->individualCreate($contactParams);
2085
2086 $params = array(
2087 'source_contact_id' => $individualSourceID,
2088 'target_contact_id' => array($individualTargetID),
2089 'assignee_contact_id' => array($individualTargetID),
2090 'subject' => 'Discussion on warm beer',
2091 'activity_date_time' => date('Ymd'),
2092 'duration_hours' => 30,
2093 'duration_minutes' => 20,
2094 'location' => 'Baker Street',
2095 'details' => 'Lets schedule a meeting',
2096 'status_id' => 1,
2097 'activity_name' => 'Meeting',
2098 );
2099 }
2100
2101 $result = $this->callAPISuccess('Activity', 'create', $params);
2102
2103 $result['target_contact_id'] = $individualTargetID;
2104 $result['assignee_contact_id'] = $individualTargetID;
2105 return $result;
2106 }
2107
2108 /**
2109 * Create an activity type.
2110 *
2111 * @param array $params
2112 * Parameters.
2113 * @return array
2114 */
2115 public function activityTypeCreate($params) {
2116 return $this->callAPISuccess('ActivityType', 'create', $params);
2117 }
2118
2119 /**
2120 * Delete activity type.
2121 *
2122 * @param int $activityTypeId
2123 * Id of the activity type.
2124 * @return array
2125 */
2126 public function activityTypeDelete($activityTypeId) {
2127 $params['activity_type_id'] = $activityTypeId;
2128 return $this->callAPISuccess('ActivityType', 'delete', $params);
2129 }
2130
2131 /**
2132 * Create custom group.
2133 *
2134 * @param array $params
2135 * @return array|int
2136 */
2137 public function customGroupCreate($params = array()) {
2138 $defaults = array(
2139 'title' => 'new custom group',
2140 'extends' => 'Contact',
2141 'domain_id' => 1,
2142 'style' => 'Inline',
2143 'is_active' => 1,
2144 );
2145
2146 $params = array_merge($defaults, $params);
2147
2148 if (strlen($params['title']) > 13) {
2149 $params['title'] = substr($params['title'], 0, 13);
2150 }
2151
2152 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2153 $this->callAPISuccess('custom_group', 'get', array(
2154 'title' => $params['title'],
2155 array('api.custom_group.delete' => 1),
2156 ));
2157
2158 return $this->callAPISuccess('custom_group', 'create', $params);
2159 }
2160
2161 /**
2162 * Existing function doesn't allow params to be over-ridden so need a new one
2163 * this one allows you to only pass in the params you want to change
2164 * @param array $params
2165 * @return array|int
2166 */
2167 public function CustomGroupCreateByParams($params = array()) {
2168 $defaults = array(
2169 'title' => "API Custom Group",
2170 'extends' => 'Contact',
2171 'domain_id' => 1,
2172 'style' => 'Inline',
2173 'is_active' => 1,
2174 );
2175 $params = array_merge($defaults, $params);
2176 return $this->callAPISuccess('custom_group', 'create', $params);
2177 }
2178
2179 /**
2180 * Create custom group with multi fields.
2181 * @param array $params
2182 * @return array|int
2183 */
2184 public function CustomGroupMultipleCreateByParams($params = array()) {
2185 $defaults = array(
2186 'style' => 'Tab',
2187 'is_multiple' => 1,
2188 );
2189 $params = array_merge($defaults, $params);
2190 return $this->CustomGroupCreateByParams($params);
2191 }
2192
2193 /**
2194 * Create custom group with multi fields.
2195 * @param array $params
2196 * @return array
2197 */
2198 public function CustomGroupMultipleCreateWithFields($params = array()) {
2199 // also need to pass on $params['custom_field'] if not set but not in place yet
2200 $ids = array();
2201 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2202 $ids['custom_group_id'] = $customGroup['id'];
2203
2204 $customField = $this->customFieldCreate(array(
2205 'custom_group_id' => $ids['custom_group_id'],
2206 'label' => 'field_1' . $ids['custom_group_id'],
2207 ));
2208
2209 $ids['custom_field_id'][] = $customField['id'];
2210
2211 $customField = $this->customFieldCreate(array(
2212 'custom_group_id' => $ids['custom_group_id'],
2213 'default_value' => '',
2214 'label' => 'field_2' . $ids['custom_group_id'],
2215 ));
2216 $ids['custom_field_id'][] = $customField['id'];
2217
2218 $customField = $this->customFieldCreate(array(
2219 'custom_group_id' => $ids['custom_group_id'],
2220 'default_value' => '',
2221 'label' => 'field_3' . $ids['custom_group_id'],
2222 ));
2223 $ids['custom_field_id'][] = $customField['id'];
2224
2225 return $ids;
2226 }
2227
2228 /**
2229 * Create a custom group with a single text custom field. See
2230 * participant:testCreateWithCustom for how to use this
2231 *
2232 * @param string $function
2233 * __FUNCTION__.
2234 * @param string $filename
2235 * $file __FILE__.
2236 *
2237 * @return array
2238 * ids of created objects
2239 */
2240 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2241 $params = array('title' => $function);
2242 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2243 $params['extends'] = $entity ? $entity : 'Contact';
2244 $customGroup = $this->CustomGroupCreate($params);
2245 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2246 CRM_Core_PseudoConstant::flush();
2247
2248 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2249 }
2250
2251 /**
2252 * Delete custom group.
2253 *
2254 * @param int $customGroupID
2255 *
2256 * @return array|int
2257 */
2258 public function customGroupDelete($customGroupID) {
2259 $params['id'] = $customGroupID;
2260 return $this->callAPISuccess('custom_group', 'delete', $params);
2261 }
2262
2263 /**
2264 * Create custom field.
2265 *
2266 * @param array $params
2267 * (custom_group_id) is required.
2268 * @return array
2269 */
2270 public function customFieldCreate($params) {
2271 $params = array_merge(array(
2272 'label' => 'Custom Field',
2273 'data_type' => 'String',
2274 'html_type' => 'Text',
2275 'is_searchable' => 1,
2276 'is_active' => 1,
2277 'default_value' => 'defaultValue',
2278 ), $params);
2279
2280 $result = $this->callAPISuccess('custom_field', 'create', $params);
2281 // these 2 functions are called with force to flush static caches
2282 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2283 CRM_Core_Component::getEnabledComponents(1);
2284 return $result;
2285 }
2286
2287 /**
2288 * Delete custom field.
2289 *
2290 * @param int $customFieldID
2291 *
2292 * @return array|int
2293 */
2294 public function customFieldDelete($customFieldID) {
2295
2296 $params['id'] = $customFieldID;
2297 return $this->callAPISuccess('custom_field', 'delete', $params);
2298 }
2299
2300 /**
2301 * Create note.
2302 *
2303 * @param int $cId
2304 * @return array
2305 */
2306 public function noteCreate($cId) {
2307 $params = array(
2308 'entity_table' => 'civicrm_contact',
2309 'entity_id' => $cId,
2310 'note' => 'hello I am testing Note',
2311 'contact_id' => $cId,
2312 'modified_date' => date('Ymd'),
2313 'subject' => 'Test Note',
2314 );
2315
2316 return $this->callAPISuccess('Note', 'create', $params);
2317 }
2318
2319 /**
2320 * Enable CiviCampaign Component.
2321 */
2322 public function enableCiviCampaign() {
2323 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2324 // force reload of config object
2325 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2326 //flush cache by calling with reset
2327 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2328 }
2329
2330 /**
2331 * Create test generated example in api/v3/examples.
2332 *
2333 * To turn this off (e.g. on the server) set
2334 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2335 * in your settings file
2336 *
2337 * @param string $entity
2338 * @param string $action
2339 * @param array $params
2340 * Array as passed to civicrm_api function.
2341 * @param array $result
2342 * Array as received from the civicrm_api function.
2343 * @param string $testFunction
2344 * Calling function - generally __FUNCTION__.
2345 * @param string $testFile
2346 * Called from file - generally __FILE__.
2347 * @param string $description
2348 * Descriptive text for the example file.
2349 * @param string $exampleName
2350 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2351 */
2352 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2353 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
2354 return;
2355 }
2356 $entity = _civicrm_api_get_camel_name($entity);
2357 $action = strtolower($action);
2358
2359 if (empty($exampleName)) {
2360 // Attempt to convert lowercase action name to CamelCase.
2361 // This is clunky/imperfect due to the convention of all lowercase actions.
2362 $exampleName = CRM_Utils_String::convertStringToCamel($action);
2363 $knownPrefixes = array(
2364 'Get',
2365 'Set',
2366 'Create',
2367 'Update',
2368 'Send',
2369 );
2370 foreach ($knownPrefixes as $prefix) {
2371 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2372 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2373 }
2374 }
2375 }
2376
2377 $this->tidyExampleResult($result);
2378 if (isset($params['version'])) {
2379 unset($params['version']);
2380 }
2381 // Format multiline description as array
2382 $desc = array();
2383 if (is_string($description) && strlen($description)) {
2384 foreach (explode("\n", $description) as $line) {
2385 $desc[] = trim($line);
2386 }
2387 }
2388 $smarty = CRM_Core_Smarty::singleton();
2389 $smarty->assign('testFunction', $testFunction);
2390 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2391 $smarty->assign('params', $params);
2392 $smarty->assign('entity', $entity);
2393 $smarty->assign('testFile', basename($testFile));
2394 $smarty->assign('description', $desc);
2395 $smarty->assign('result', $result);
2396 $smarty->assign('action', $action);
2397
2398 if (file_exists('../tests/templates/documentFunction.tpl')) {
2399 if (!is_dir("../api/v3/examples/$entity")) {
2400 mkdir("../api/v3/examples/$entity");
2401 }
2402 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2403 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2404 fclose($f);
2405 }
2406 }
2407
2408 /**
2409 * Tidy up examples array so that fields that change often ..don't
2410 * and debug related fields are unset
2411 *
2412 * @param array $result
2413 */
2414 public function tidyExampleResult(&$result) {
2415 if (!is_array($result)) {
2416 return;
2417 }
2418 $fieldsToChange = array(
2419 'hash' => '67eac7789eaee00',
2420 'modified_date' => '2012-11-14 16:02:35',
2421 'created_date' => '2013-07-28 08:49:19',
2422 'create_date' => '20120130621222105',
2423 'application_received_date' => '20130728084957',
2424 'in_date' => '2013-07-28 08:50:19',
2425 'scheduled_date' => '20130728085413',
2426 'approval_date' => '20130728085413',
2427 'pledge_start_date_high' => '20130726090416',
2428 'start_date' => '2013-07-29 00:00:00',
2429 'event_start_date' => '2013-07-29 00:00:00',
2430 'end_date' => '2013-08-04 00:00:00',
2431 'event_end_date' => '2013-08-04 00:00:00',
2432 'decision_date' => '20130805000000',
2433 );
2434
2435 $keysToUnset = array('xdebug', 'undefined_fields');
2436 foreach ($keysToUnset as $unwantedKey) {
2437 if (isset($result[$unwantedKey])) {
2438 unset($result[$unwantedKey]);
2439 }
2440 }
2441 if (isset($result['values'])) {
2442 if (!is_array($result['values'])) {
2443 return;
2444 }
2445 $resultArray = &$result['values'];
2446 }
2447 elseif (is_array($result)) {
2448 $resultArray = &$result;
2449 }
2450 else {
2451 return;
2452 }
2453
2454 foreach ($resultArray as $index => &$values) {
2455 if (!is_array($values)) {
2456 continue;
2457 }
2458 foreach ($values as $key => &$value) {
2459 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2460 if (isset($value['is_error'])) {
2461 // we have a std nested result format
2462 $this->tidyExampleResult($value);
2463 }
2464 else {
2465 foreach ($value as &$nestedResult) {
2466 // this is an alternative syntax for nested results a keyed array of results
2467 $this->tidyExampleResult($nestedResult);
2468 }
2469 }
2470 }
2471 if (in_array($key, $keysToUnset)) {
2472 unset($values[$key]);
2473 break;
2474 }
2475 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2476 $value = $fieldsToChange[$key];
2477 }
2478 if (is_string($value)) {
2479 $value = addslashes($value);
2480 }
2481 }
2482 }
2483 }
2484
2485 /**
2486 * Delete note.
2487 *
2488 * @param array $params
2489 *
2490 * @return array|int
2491 */
2492 public function noteDelete($params) {
2493 return $this->callAPISuccess('Note', 'delete', $params);
2494 }
2495
2496 /**
2497 * Create custom field with Option Values.
2498 *
2499 * @param array $customGroup
2500 * @param string $name
2501 * Name of custom field.
2502 *
2503 * @return array|int
2504 */
2505 public function customFieldOptionValueCreate($customGroup, $name) {
2506 $fieldParams = array(
2507 'custom_group_id' => $customGroup['id'],
2508 'name' => 'test_custom_group',
2509 'label' => 'Country',
2510 'html_type' => 'Select',
2511 'data_type' => 'String',
2512 'weight' => 4,
2513 'is_required' => 1,
2514 'is_searchable' => 0,
2515 'is_active' => 1,
2516 );
2517
2518 $optionGroup = array(
2519 'domain_id' => 1,
2520 'name' => 'option_group1',
2521 'label' => 'option_group_label1',
2522 );
2523
2524 $optionValue = array(
2525 'option_label' => array('Label1', 'Label2'),
2526 'option_value' => array('value1', 'value2'),
2527 'option_name' => array($name . '_1', $name . '_2'),
2528 'option_weight' => array(1, 2),
2529 'option_status' => 1,
2530 );
2531
2532 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2533
2534 return $this->callAPISuccess('custom_field', 'create', $params);
2535 }
2536
2537 /**
2538 * @param $entities
2539 *
2540 * @return bool
2541 */
2542 public function confirmEntitiesDeleted($entities) {
2543 foreach ($entities as $entity) {
2544
2545 $result = $this->callAPISuccess($entity, 'Get', array());
2546 if ($result['error'] == 1 || $result['count'] > 0) {
2547 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2548 return TRUE;
2549 }
2550 }
2551 return FALSE;
2552 }
2553
2554 /**
2555 * @param $tablesToTruncate
2556 * @param bool $dropCustomValueTables
2557 * @throws \Exception
2558 */
2559 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2560 if ($this->tx) {
2561 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2562 }
2563 if ($dropCustomValueTables) {
2564 $tablesToTruncate[] = 'civicrm_custom_group';
2565 $tablesToTruncate[] = 'civicrm_custom_field';
2566 }
2567
2568 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2569
2570 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2571 foreach ($tablesToTruncate as $table) {
2572 $sql = "TRUNCATE TABLE $table";
2573 CRM_Core_DAO::executeQuery($sql);
2574 }
2575 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2576
2577 if ($dropCustomValueTables) {
2578 $dbName = self::getDBName();
2579 $query = "
2580 SELECT TABLE_NAME as tableName
2581 FROM INFORMATION_SCHEMA.TABLES
2582 WHERE TABLE_SCHEMA = '{$dbName}'
2583 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2584 ";
2585
2586 $tableDAO = CRM_Core_DAO::executeQuery($query);
2587 while ($tableDAO->fetch()) {
2588 $sql = "DROP TABLE {$tableDAO->tableName}";
2589 CRM_Core_DAO::executeQuery($sql);
2590 }
2591 }
2592 }
2593
2594 /**
2595 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2596 */
2597 public function quickCleanUpFinancialEntities() {
2598 $tablesToTruncate = array(
2599 'civicrm_activity',
2600 'civicrm_activity_contact',
2601 'civicrm_contribution',
2602 'civicrm_contribution_soft',
2603 'civicrm_contribution_product',
2604 'civicrm_financial_trxn',
2605 'civicrm_financial_item',
2606 'civicrm_contribution_recur',
2607 'civicrm_line_item',
2608 'civicrm_contribution_page',
2609 'civicrm_payment_processor',
2610 'civicrm_entity_financial_trxn',
2611 'civicrm_membership',
2612 'civicrm_membership_type',
2613 'civicrm_membership_payment',
2614 'civicrm_membership_log',
2615 'civicrm_membership_block',
2616 'civicrm_event',
2617 'civicrm_participant',
2618 'civicrm_participant_payment',
2619 'civicrm_pledge',
2620 'civicrm_price_set_entity',
2621 'civicrm_price_field_value',
2622 'civicrm_price_field',
2623 );
2624 $this->quickCleanup($tablesToTruncate);
2625 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2626 $this->restoreDefaultPriceSetConfig();
2627 $var = TRUE;
2628 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
2629 Civi\Payment\System::singleton()->flushProcessors();
2630 }
2631
2632 public function restoreDefaultPriceSetConfig() {
2633 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2634 CRM_Core_DAO::executeQuery("INSERT INTO `civicrm_price_field` (`id`, `price_set_id`, `name`, `label`, `html_type`, `is_enter_qty`, `help_pre`, `help_post`, `weight`, `is_display_amounts`, `options_per_line`, `is_active`, `is_required`, `active_on`, `expire_on`, `javascript`, `visibility_id`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', 'Text', 0, NULL, NULL, 1, 1, 1, 1, 1, NULL, NULL, NULL, 1)");
2635 CRM_Core_DAO::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2636 }
2637 /*
2638 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2639 * Default behaviour is to also delete the entity
2640 * @param array $params
2641 * Params array to check against.
2642 * @param int $id
2643 * Id of the entity concerned.
2644 * @param string $entity
2645 * Name of entity concerned (e.g. membership).
2646 * @param bool $delete
2647 * Should the entity be deleted as part of this check.
2648 * @param string $errorText
2649 * Text to print on error.
2650 */
2651 /**
2652 * @param array $params
2653 * @param int $id
2654 * @param $entity
2655 * @param int $delete
2656 * @param string $errorText
2657 *
2658 * @throws Exception
2659 */
2660 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2661
2662 $result = $this->callAPISuccessGetSingle($entity, array(
2663 'id' => $id,
2664 ));
2665
2666 if ($delete) {
2667 $this->callAPISuccess($entity, 'Delete', array(
2668 'id' => $id,
2669 ));
2670 }
2671 $dateFields = $keys = $dateTimeFields = array();
2672 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2673 foreach ($fields['values'] as $field => $settings) {
2674 if (array_key_exists($field, $result)) {
2675 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2676 }
2677 else {
2678 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2679 }
2680 $type = CRM_Utils_Array::value('type', $settings);
2681 if ($type == CRM_Utils_Type::T_DATE) {
2682 $dateFields[] = $settings['name'];
2683 // we should identify both real names & unique names as dates
2684 if ($field != $settings['name']) {
2685 $dateFields[] = $field;
2686 }
2687 }
2688 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2689 $dateTimeFields[] = $settings['name'];
2690 // we should identify both real names & unique names as dates
2691 if ($field != $settings['name']) {
2692 $dateTimeFields[] = $field;
2693 }
2694 }
2695 }
2696
2697 if (strtolower($entity) == 'contribution') {
2698 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2699 // this is not returned in id format
2700 unset($params['payment_instrument_id']);
2701 $params['contribution_source'] = $params['source'];
2702 unset($params['source']);
2703 }
2704
2705 foreach ($params as $key => $value) {
2706 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2707 continue;
2708 }
2709 if (in_array($key, $dateFields)) {
2710 $value = date('Y-m-d', strtotime($value));
2711 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2712 }
2713 if (in_array($key, $dateTimeFields)) {
2714 $value = date('Y-m-d H:i:s', strtotime($value));
2715 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2716 }
2717 $this->assertEquals($value, $result[$keys[$key]], $key . " GetandCheck function determines that for key {$key} value: $value doesn't match " . print_r($result[$keys[$key]], TRUE) . $errorText);
2718 }
2719 }
2720
2721 /**
2722 * Get formatted values in the actual and expected result.
2723 * @param array $actual
2724 * Actual calculated values.
2725 * @param array $expected
2726 * Expected values.
2727 */
2728 public function checkArrayEquals(&$actual, &$expected) {
2729 self::unsetId($actual);
2730 self::unsetId($expected);
2731 $this->assertEquals($actual, $expected);
2732 }
2733
2734 /**
2735 * Unset the key 'id' from the array
2736 * @param array $unformattedArray
2737 * The array from which the 'id' has to be unset.
2738 */
2739 public static function unsetId(&$unformattedArray) {
2740 $formattedArray = array();
2741 if (array_key_exists('id', $unformattedArray)) {
2742 unset($unformattedArray['id']);
2743 }
2744 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2745 foreach ($unformattedArray['values'] as $key => $value) {
2746 if (is_array($value)) {
2747 foreach ($value as $k => $v) {
2748 if ($k == 'id') {
2749 unset($value[$k]);
2750 }
2751 }
2752 }
2753 elseif ($key == 'id') {
2754 $unformattedArray[$key];
2755 }
2756 $formattedArray = array($value);
2757 }
2758 $unformattedArray['values'] = $formattedArray;
2759 }
2760 }
2761
2762 /**
2763 * Helper to enable/disable custom directory support
2764 *
2765 * @param array $customDirs
2766 * With members:.
2767 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2768 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2769 */
2770 public function customDirectories($customDirs) {
2771 require_once 'CRM/Core/Config.php';
2772 $config = CRM_Core_Config::singleton();
2773
2774 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2775 unset($config->customPHPPathDir);
2776 }
2777 elseif ($customDirs['php_path'] === TRUE) {
2778 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2779 }
2780 else {
2781 $config->customPHPPathDir = $php_path;
2782 }
2783
2784 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2785 unset($config->customTemplateDir);
2786 }
2787 elseif ($customDirs['template_path'] === TRUE) {
2788 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2789 }
2790 else {
2791 $config->customTemplateDir = $template_path;
2792 }
2793 }
2794
2795 /**
2796 * Generate a temporary folder.
2797 *
2798 * @param string $prefix
2799 * @return string
2800 */
2801 public function createTempDir($prefix = 'test-') {
2802 $tempDir = CRM_Utils_File::tempdir($prefix);
2803 $this->tempDirs[] = $tempDir;
2804 return $tempDir;
2805 }
2806
2807 public function cleanTempDirs() {
2808 if (!is_array($this->tempDirs)) {
2809 // fix test errors where this is not set
2810 return;
2811 }
2812 foreach ($this->tempDirs as $tempDir) {
2813 if (is_dir($tempDir)) {
2814 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2815 }
2816 }
2817 }
2818
2819 /**
2820 * Temporarily replace the singleton extension with a different one.
2821 * @param \CRM_Extension_System $system
2822 */
2823 public function setExtensionSystem(CRM_Extension_System $system) {
2824 if ($this->origExtensionSystem == NULL) {
2825 $this->origExtensionSystem = CRM_Extension_System::singleton();
2826 }
2827 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2828 }
2829
2830 public function unsetExtensionSystem() {
2831 if ($this->origExtensionSystem !== NULL) {
2832 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2833 $this->origExtensionSystem = NULL;
2834 }
2835 }
2836
2837 /**
2838 * Temporarily alter the settings-metadata to add a mock setting.
2839 *
2840 * WARNING: The setting metadata will disappear on the next cache-clear.
2841 *
2842 * @param $extras
2843 * @return void
2844 */
2845 public function setMockSettingsMetaData($extras) {
2846 CRM_Core_BAO_Setting::$_cache = array();
2847 $this->callAPISuccess('system', 'flush', array());
2848 CRM_Core_BAO_Setting::$_cache = array();
2849
2850 CRM_Utils_Hook::singleton()
2851 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2852 $metadata = array_merge($metadata, $extras);
2853 });
2854
2855 $fields = $this->callAPISuccess('setting', 'getfields', array());
2856 foreach ($extras as $key => $spec) {
2857 $this->assertNotEmpty($spec['title']);
2858 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2859 }
2860 }
2861
2862 /**
2863 * @param string $name
2864 */
2865 public function financialAccountDelete($name) {
2866 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2867 $financialAccount->name = $name;
2868 if ($financialAccount->find(TRUE)) {
2869 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2870 $entityFinancialType->financial_account_id = $financialAccount->id;
2871 $entityFinancialType->delete();
2872 $financialAccount->delete();
2873 }
2874 }
2875
2876 /**
2877 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2878 * (NB unclear if this is still required)
2879 */
2880 public function _sethtmlGlobals() {
2881 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2882 'required' => array(
2883 'html_quickform_rule_required',
2884 'HTML/QuickForm/Rule/Required.php',
2885 ),
2886 'maxlength' => array(
2887 'html_quickform_rule_range',
2888 'HTML/QuickForm/Rule/Range.php',
2889 ),
2890 'minlength' => array(
2891 'html_quickform_rule_range',
2892 'HTML/QuickForm/Rule/Range.php',
2893 ),
2894 'rangelength' => array(
2895 'html_quickform_rule_range',
2896 'HTML/QuickForm/Rule/Range.php',
2897 ),
2898 'email' => array(
2899 'html_quickform_rule_email',
2900 'HTML/QuickForm/Rule/Email.php',
2901 ),
2902 'regex' => array(
2903 'html_quickform_rule_regex',
2904 'HTML/QuickForm/Rule/Regex.php',
2905 ),
2906 'lettersonly' => array(
2907 'html_quickform_rule_regex',
2908 'HTML/QuickForm/Rule/Regex.php',
2909 ),
2910 'alphanumeric' => array(
2911 'html_quickform_rule_regex',
2912 'HTML/QuickForm/Rule/Regex.php',
2913 ),
2914 'numeric' => array(
2915 'html_quickform_rule_regex',
2916 'HTML/QuickForm/Rule/Regex.php',
2917 ),
2918 'nopunctuation' => array(
2919 'html_quickform_rule_regex',
2920 'HTML/QuickForm/Rule/Regex.php',
2921 ),
2922 'nonzero' => array(
2923 'html_quickform_rule_regex',
2924 'HTML/QuickForm/Rule/Regex.php',
2925 ),
2926 'callback' => array(
2927 'html_quickform_rule_callback',
2928 'HTML/QuickForm/Rule/Callback.php',
2929 ),
2930 'compare' => array(
2931 'html_quickform_rule_compare',
2932 'HTML/QuickForm/Rule/Compare.php',
2933 ),
2934 );
2935 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2936 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2937 'group' => array(
2938 'HTML/QuickForm/group.php',
2939 'HTML_QuickForm_group',
2940 ),
2941 'hidden' => array(
2942 'HTML/QuickForm/hidden.php',
2943 'HTML_QuickForm_hidden',
2944 ),
2945 'reset' => array(
2946 'HTML/QuickForm/reset.php',
2947 'HTML_QuickForm_reset',
2948 ),
2949 'checkbox' => array(
2950 'HTML/QuickForm/checkbox.php',
2951 'HTML_QuickForm_checkbox',
2952 ),
2953 'file' => array(
2954 'HTML/QuickForm/file.php',
2955 'HTML_QuickForm_file',
2956 ),
2957 'image' => array(
2958 'HTML/QuickForm/image.php',
2959 'HTML_QuickForm_image',
2960 ),
2961 'password' => array(
2962 'HTML/QuickForm/password.php',
2963 'HTML_QuickForm_password',
2964 ),
2965 'radio' => array(
2966 'HTML/QuickForm/radio.php',
2967 'HTML_QuickForm_radio',
2968 ),
2969 'button' => array(
2970 'HTML/QuickForm/button.php',
2971 'HTML_QuickForm_button',
2972 ),
2973 'submit' => array(
2974 'HTML/QuickForm/submit.php',
2975 'HTML_QuickForm_submit',
2976 ),
2977 'select' => array(
2978 'HTML/QuickForm/select.php',
2979 'HTML_QuickForm_select',
2980 ),
2981 'hiddenselect' => array(
2982 'HTML/QuickForm/hiddenselect.php',
2983 'HTML_QuickForm_hiddenselect',
2984 ),
2985 'text' => array(
2986 'HTML/QuickForm/text.php',
2987 'HTML_QuickForm_text',
2988 ),
2989 'textarea' => array(
2990 'HTML/QuickForm/textarea.php',
2991 'HTML_QuickForm_textarea',
2992 ),
2993 'fckeditor' => array(
2994 'HTML/QuickForm/fckeditor.php',
2995 'HTML_QuickForm_FCKEditor',
2996 ),
2997 'tinymce' => array(
2998 'HTML/QuickForm/tinymce.php',
2999 'HTML_QuickForm_TinyMCE',
3000 ),
3001 'dojoeditor' => array(
3002 'HTML/QuickForm/dojoeditor.php',
3003 'HTML_QuickForm_dojoeditor',
3004 ),
3005 'link' => array(
3006 'HTML/QuickForm/link.php',
3007 'HTML_QuickForm_link',
3008 ),
3009 'advcheckbox' => array(
3010 'HTML/QuickForm/advcheckbox.php',
3011 'HTML_QuickForm_advcheckbox',
3012 ),
3013 'date' => array(
3014 'HTML/QuickForm/date.php',
3015 'HTML_QuickForm_date',
3016 ),
3017 'static' => array(
3018 'HTML/QuickForm/static.php',
3019 'HTML_QuickForm_static',
3020 ),
3021 'header' => array(
3022 'HTML/QuickForm/header.php',
3023 'HTML_QuickForm_header',
3024 ),
3025 'html' => array(
3026 'HTML/QuickForm/html.php',
3027 'HTML_QuickForm_html',
3028 ),
3029 'hierselect' => array(
3030 'HTML/QuickForm/hierselect.php',
3031 'HTML_QuickForm_hierselect',
3032 ),
3033 'autocomplete' => array(
3034 'HTML/QuickForm/autocomplete.php',
3035 'HTML_QuickForm_autocomplete',
3036 ),
3037 'xbutton' => array(
3038 'HTML/QuickForm/xbutton.php',
3039 'HTML_QuickForm_xbutton',
3040 ),
3041 'advmultiselect' => array(
3042 'HTML/QuickForm/advmultiselect.php',
3043 'HTML_QuickForm_advmultiselect',
3044 ),
3045 );
3046 }
3047
3048 /**
3049 * Set up an acl allowing contact to see 2 specified groups
3050 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3051 *
3052 * You need to have pre-created these groups & created the user e.g
3053 * $this->createLoggedInUser();
3054 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3055 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3056 */
3057 public function setupACL($isProfile = FALSE) {
3058 global $_REQUEST;
3059 $_REQUEST = $this->_params;
3060
3061 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
3062 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3063 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3064 'option_group_id' => $optionGroupID,
3065 'label' => 'pick me',
3066 'value' => 55,
3067 ));
3068
3069 CRM_Core_DAO::executeQuery("
3070 TRUNCATE civicrm_acl_cache
3071 ");
3072
3073 CRM_Core_DAO::executeQuery("
3074 TRUNCATE civicrm_acl_contact_cache
3075 ");
3076
3077 CRM_Core_DAO::executeQuery("
3078 INSERT INTO civicrm_acl_entity_role (
3079 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3080 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3081 ");
3082
3083 if ($isProfile) {
3084 CRM_Core_DAO::executeQuery("
3085 INSERT INTO civicrm_acl (
3086 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3087 )
3088 VALUES (
3089 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3090 );
3091 ");
3092 }
3093 else {
3094 CRM_Core_DAO::executeQuery("
3095 INSERT INTO civicrm_acl (
3096 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3097 )
3098 VALUES (
3099 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3100 );
3101 ");
3102
3103 CRM_Core_DAO::executeQuery("
3104 INSERT INTO civicrm_acl (
3105 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3106 )
3107 VALUES (
3108 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3109 );
3110 ");
3111 }
3112
3113 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
3114 $this->callAPISuccess('group_contact', 'create', array(
3115 'group_id' => $this->_permissionedGroup,
3116 'contact_id' => $this->_loggedInUser,
3117 ));
3118
3119 if (!$isProfile) {
3120 //flush cache
3121 CRM_ACL_BAO_Cache::resetCache();
3122 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
3123 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3124 }
3125 }
3126
3127 /**
3128 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3129 */
3130 public function offsetDefaultPriceSet() {
3131 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3132 $firstID = $contributionPriceSet['id'];
3133 $this->callAPISuccess('price_set', 'create', array(
3134 'id' => $contributionPriceSet['id'],
3135 'is_active' => 0,
3136 'name' => 'old',
3137 ));
3138 unset($contributionPriceSet['id']);
3139 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3140 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3141 'price_set_id' => $firstID,
3142 'options' => array('limit' => 1),
3143 ));
3144 unset($priceField['id']);
3145 $priceField['price_set_id'] = $newPriceSet['id'];
3146 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3147 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3148 'price_set_id' => $firstID,
3149 'sequential' => 1,
3150 'options' => array('limit' => 1),
3151 ));
3152
3153 unset($priceFieldValue['id']);
3154 //create some padding to use up ids
3155 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3156 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3157 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3158 }
3159
3160 /**
3161 * Create an instance of the paypal processor.
3162 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3163 * this parent class & we don't have a structure for that yet
3164 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3165 * & the best protection against that is the functions this class affords
3166 * @param array $params
3167 * @return int $result['id'] payment processor id
3168 */
3169 public function paymentProcessorCreate($params = array()) {
3170 $params = array_merge(array(
3171 'name' => 'demo',
3172 'domain_id' => CRM_Core_Config::domainID(),
3173 'payment_processor_type_id' => 'PayPal',
3174 'is_active' => 1,
3175 'is_default' => 0,
3176 'is_test' => 1,
3177 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3178 'password' => '1183377788',
3179 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3180 'url_site' => 'https://www.sandbox.paypal.com/',
3181 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3182 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3183 'class_name' => 'Payment_PayPalImpl',
3184 'billing_mode' => 3,
3185 'financial_type_id' => 1,
3186 ),
3187 $params);
3188 if (!is_numeric($params['payment_processor_type_id'])) {
3189 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3190 //here
3191 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3192 'name' => $params['payment_processor_type_id'],
3193 'return' => 'id',
3194 ), 'integer');
3195 }
3196 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3197 return $result['id'];
3198 }
3199
3200 /**
3201 * Set up initial recurring payment allowing subsequent IPN payments.
3202 */
3203 public function setupRecurringPaymentProcessorTransaction() {
3204 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3205 'contact_id' => $this->_contactID,
3206 'amount' => 1000,
3207 'sequential' => 1,
3208 'installments' => 5,
3209 'frequency_unit' => 'Month',
3210 'frequency_interval' => 1,
3211 'invoice_id' => $this->_invoiceID,
3212 'contribution_status_id' => 2,
3213 'processor_id' => $this->_paymentProcessorID,
3214 'api.contribution.create' => array(
3215 'total_amount' => '200',
3216 'invoice_id' => $this->_invoiceID,
3217 'financial_type_id' => 1,
3218 'contribution_status_id' => 'Pending',
3219 'contact_id' => $this->_contactID,
3220 'contribution_page_id' => $this->_contributionPageID,
3221 'payment_processor_id' => $this->_paymentProcessorID,
3222 'is_test' => 0,
3223 ),
3224 ));
3225 $this->_contributionRecurID = $contributionRecur['id'];
3226 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
3227 }
3228
3229 /**
3230 * We don't have a good way to set up a recurring contribution with a membership so let's just do one then alter it
3231 */
3232 public function setupMembershipRecurringPaymentProcessorTransaction() {
3233 $this->ids['membership_type'] = $this->membershipTypeCreate();
3234 //create a contribution so our membership & contribution don't both have id = 1
3235 $this->contributionCreate(array(
3236 'contact_id' => $this->_contactID,
3237 'is_test' => 1),
3238 1, 'abcd', '345j');
3239 $this->setupRecurringPaymentProcessorTransaction();
3240
3241 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
3242 'contact_id' => $this->_contactID,
3243 'membership_type_id' => $this->ids['membership_type'],
3244 'contribution_recur_id' => $this->_contributionRecurID,
3245 'format.only_id' => TRUE,
3246 ));
3247 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3248 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
3249
3250 $this->callAPISuccess('line_item', 'create', array(
3251 'entity_table' => 'civicrm_membership',
3252 'entity_id' => $this->ids['membership'],
3253 'contribution_id' => $this->_contributionID,
3254 'label' => 'General',
3255 'qty' => 1,
3256 'unit_price' => 200,
3257 'line_total' => 200,
3258 'financial_type_id' => 1,
3259 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3260 'return' => 'id',
3261 'label' => 'Membership Amount',
3262 )),
3263 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3264 'return' => 'id',
3265 'label' => 'General',
3266 )),
3267 ));
3268 $this->callAPISuccess('membership_payment', 'create', array(
3269 'contribution_id' => $this->_contributionID,
3270 'membership_id' => $this->ids['membership'],
3271 ));
3272 }
3273
3274 /**
3275 * @param $message
3276 *
3277 * @throws Exception
3278 */
3279 public function CiviUnitTestCase_fatalErrorHandler($message) {
3280 throw new Exception("{$message['message']}: {$message['code']}");
3281 }
3282
3283 /**
3284 * Helper function to create new mailing.
3285 * @return mixed
3286 */
3287 public function createMailing() {
3288 $params = array(
3289 'subject' => 'maild' . rand(),
3290 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3291 'name' => 'mailing name' . rand(),
3292 'created_id' => 1,
3293 );
3294
3295 $result = $this->callAPISuccess('Mailing', 'create', $params);
3296 return $result['id'];
3297 }
3298
3299 /**
3300 * Helper function to delete mailing.
3301 * @param $id
3302 */
3303 public function deleteMailing($id) {
3304 $params = array(
3305 'id' => $id,
3306 );
3307
3308 $this->callAPISuccess('Mailing', 'delete', $params);
3309 }
3310
3311 /**
3312 * Wrap the entire test case in a transaction.
3313 *
3314 * Only subsequent DB statements will be wrapped in TX -- this cannot
3315 * retroactively wrap old DB statements. Therefore, it makes sense to
3316 * call this at the beginning of setUp().
3317 *
3318 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3319 * this option does not work with, e.g., custom-data.
3320 *
3321 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3322 * if TRUNCATE or ALTER is called while using a transaction.
3323 *
3324 * @param bool $nest
3325 * Whether to use nesting or reference-counting.
3326 */
3327 public function useTransaction($nest = TRUE) {
3328 if (!$this->tx) {
3329 $this->tx = new CRM_Core_Transaction($nest);
3330 $this->tx->rollback();
3331 }
3332 }
3333
3334 public function clearOutputBuffer() {
3335 while (ob_get_level() > 0) {
3336 ob_end_clean();
3337 }
3338 }
3339
3340 /**
3341 * @param $exists
3342 * @param array $apiResult
3343 */
3344 protected function assertAttachmentExistence($exists, $apiResult) {
3345 $fileId = $apiResult['id'];
3346 $this->assertTrue(is_numeric($fileId));
3347 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3348 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3349 1 => array($fileId, 'Int'),
3350 ));
3351 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3352 1 => array($fileId, 'Int'),
3353 ));
3354 }
3355
3356 }