3 * File for the CiviUnitTestCase class
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
12 * This file is part of CiviCRM
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.
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.
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/>.
30 * Include configuration
32 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
33 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
38 require_once CIVICRM_SETTINGS_PATH
;
40 * Include class definitions
42 require_once 'PHPUnit/Extensions/Database/TestCase.php';
43 require_once 'PHPUnit/Framework/TestResult.php';
44 require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45 require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46 require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47 require_once 'tests/phpunit/Utils.php';
48 require_once 'api/api.php';
49 require_once 'CRM/Financial/BAO/FinancialType.php';
50 define('API_LATEST_VERSION', 3);
53 * Base class for CiviCRM unit tests
55 * Common functions for unit tests
58 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
61 * api version - easier to override than just a defin
63 protected $_apiversion = API_LATEST_VERSION
;
65 * Database has been initialized
69 private static $dbInit = FALSE;
74 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
83 static protected $_dbName;
86 * @var array of temporary directory names
96 * @var boolean populateOnce allows to skip db resets in setUp
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
106 public static $populateOnce = FALSE;
109 * Allow classes to state E-notice compliance
111 public $_eNoticeCompliant = TRUE;
114 * @var boolean DBResetRequired allows skipping DB reset
115 * in specific test case. If you still need
116 * to reset single test (method) of such case, call
117 * $this->cleanDB() in the first line of this
120 public $DBResetRequired = TRUE;
125 * Because we are overriding the parent class constructor, we
126 * need to show the same arguments as exist in the constructor of
127 * PHPUnit_Framework_TestCase, since
128 * PHPUnit_Framework_TestSuite::createTest() creates a
129 * ReflectionClass of the Test class and checks the constructor
130 * of that class to decide how to set up the test.
132 * @param string $name
134 * @param string $dataName
136 function __construct($name = NULL, array$data = array(), $dataName = '') {
137 parent
::__construct($name, $data, $dataName);
139 // we need full error reporting
140 error_reporting(E_ALL
& ~E_NOTICE
);
142 if (!empty($GLOBALS['mysql_db'])) {
143 self
::$_dbName = $GLOBALS['mysql_db'];
146 self
::$_dbName = 'civicrm_tests_dev';
149 // create test database
150 self
::$utils = new Utils($GLOBALS['mysql_host'],
151 $GLOBALS['mysql_user'],
152 $GLOBALS['mysql_pass']
155 // also load the class loader
156 require_once 'CRM/Core/ClassLoader.php';
157 CRM_Core_ClassLoader
::singleton()->register();
158 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
159 _civix_phpunit_setUp();
163 function requireDBReset() {
164 return $this->DBResetRequired
;
167 static function getDBName() {
168 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
173 * Create database connection for this instance
175 * Initialize the test database if it hasn't been initialized
177 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
179 protected function getConnection() {
180 $dbName = self
::$_dbName;
181 if (!self
::$dbInit) {
182 $dbName = self
::getDBName();
184 // install test database
185 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
187 static::_populateDB(FALSE, $this);
189 self
::$dbInit = TRUE;
191 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
195 * Required implementation of abstract method
197 protected function getDataSet() {
201 * @param bool $perClass
202 * @param null $object
203 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
205 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
207 if ($perClass ||
$object == NULL) {
211 $dbreset = $object->requireDBReset();
214 if (self
::$populateOnce ||
!$dbreset) {
217 self
::$populateOnce = NULL;
219 $dbName = self
::getDBName();
220 $pdo = self
::$utils->pdo
;
221 // only consider real tables and not views
222 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
223 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
225 $truncates = array();
227 foreach ($tables as $table) {
229 if (substr($table['table_name'], 0, 4) == 'log_') {
233 // don't change list of installed extensions
234 if ($table['table_name'] == 'civicrm_extension') {
238 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
239 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
242 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
248 "SET foreign_key_checks = 0",
249 // SQL mode needs to be strict, that's our standard
250 "SET SQL_MODE='STRICT_ALL_TABLES';",
251 "SET global innodb_flush_log_at_trx_commit = 2;",
253 $queries = array_merge($queries, $truncates);
254 $queries = array_merge($queries, $drops);
255 foreach ($queries as $query) {
256 if (self
::$utils->do_query($query) === FALSE) {
257 // failed to create test database
258 echo "failed to create test db.";
263 // initialize test database
264 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
265 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
266 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
268 $query2 = file_get_contents($sql_file2);
269 $query3 = file_get_contents($sql_file3);
270 $query4 = file_get_contents($sql_file4);
271 if (self
::$utils->do_query($query2) === FALSE) {
272 echo "Cannot load civicrm_data.mysql. Aborting.";
275 if (self
::$utils->do_query($query3) === FALSE) {
276 echo "Cannot load test_data.mysql. Aborting.";
279 if (self
::$utils->do_query($query4) === FALSE) {
280 echo "Cannot load test_data.mysql. Aborting.";
284 // done with all the loading, get transactions back
285 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
286 echo "Cannot set global? Huh?";
290 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
291 echo "Cannot get foreign keys back? Huh?";
295 unset($query, $query2, $query3);
298 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
303 public static function setUpBeforeClass() {
304 static::_populateDB(TRUE);
306 // also set this global hack
307 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
311 * Common setup functions for all unit tests
313 protected function setUp() {
314 CRM_Utils_Hook
::singleton(TRUE);
315 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
316 // Use a temporary file for STDIN
317 $GLOBALS['stdin'] = tmpfile();
318 if ($GLOBALS['stdin'] === FALSE) {
319 echo "Couldn't open temporary file\n";
323 // Get and save a connection to the database
324 $this->_dbconn
= $this->getConnection();
326 // reload database before each test
327 // $this->_populateDB();
329 // "initialize" CiviCRM to avoid problems when running single tests
330 // FIXME: look at it closer in second stage
332 // initialize the object once db is loaded
333 $config = CRM_Core_Config
::singleton();
335 // when running unit tests, use mockup user framework
336 $config->setUserFramework('UnitTests');
338 // also fix the fatal error handler to throw exceptions,
340 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
342 // enable backtrace to get meaningful errors
343 $config->backtrace
= 1;
345 // disable any left-over test extensions
346 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
348 // reset all the caches
349 CRM_Utils_System
::flushCache();
351 // clear permissions stub to not check permissions
352 $config = CRM_Core_Config
::singleton();
353 $config->userPermissionClass
->permissions
= NULL;
355 //flush component settings
356 CRM_Core_Component
::getEnabledComponents(TRUE);
358 if ($this->_eNoticeCompliant
) {
359 error_reporting(E_ALL
);
362 error_reporting(E_ALL
& ~E_NOTICE
);
367 * emulate a logged in user since certain functions use that
368 * value to store a record in the DB (like activity)
371 public function createLoggedInUser() {
373 'first_name' => 'Logged In',
374 'last_name' => 'User ' . rand(),
375 'contact_type' => 'Individual',
377 $contactID = $this->individualCreate($params);
379 $session = CRM_Core_Session
::singleton();
380 $session->set('userID', $contactID);
383 public function cleanDB() {
384 self
::$populateOnce = NULL;
385 $this->DBResetRequired
= TRUE;
387 $this->_dbconn
= $this->getConnection();
388 static::_populateDB();
389 $this->tempDirs
= array();
393 * Common teardown functions for all unit tests
395 protected function tearDown() {
396 error_reporting(E_ALL
& ~E_NOTICE
);
397 $tablesToTruncate = array('civicrm_contact');
398 $this->quickCleanup($tablesToTruncate);
399 $this->cleanTempDirs();
400 $this->unsetExtensionSystem();
404 * FIXME: Maybe a better way to do it
406 function foreignKeyChecksOff() {
407 self
::$utils = new Utils($GLOBALS['mysql_host'],
408 $GLOBALS['mysql_user'],
409 $GLOBALS['mysql_pass']
411 $dbName = self
::getDBName();
412 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
413 if (self
::$utils->do_query($query) === FALSE) {
415 echo 'Cannot set foreign_key_checks = 0';
421 function foreignKeyChecksOn() {
422 // FIXME: might not be needed if previous fixme implemented
426 * Generic function to compare expected values after an api call to retrieved
429 * @daoName string DAO Name of object we're evaluating.
430 * @id int Id of object
431 * @match array Associative array of field name => expected value. Empty if asserting
432 * that a DELETE occurred
433 * @delete boolean True if we're checking that a DELETE action occurred.
435 function assertDBState($daoName, $id, $match, $delete = FALSE) {
437 // adding this here since developers forget to check for an id
438 // and hence we get the first value in the db
439 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
442 $object = new $daoName();
446 // If we're asserting successful record deletion, make sure object is NOT found.
448 if ($object->find(TRUE)) {
449 $this->fail("Object not deleted by delete operation: $daoName, $id");
454 // Otherwise check matches of DAO field values against expected values in $match.
455 if ($object->find(TRUE)) {
456 $fields = & $object->fields();
457 foreach ($fields as $name => $value) {
458 $dbName = $value['name'];
459 if (isset($match[$name])) {
461 $this->assertEquals($object->$dbName, $match[$name]);
463 elseif (isset($match[$dbName])) {
465 $this->assertEquals($object->$dbName, $match[$dbName]);
470 $this->fail("Could not retrieve object: $daoName, $id");
473 $matchSize = count($match);
474 if ($verifiedCount != $matchSize) {
475 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
479 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
480 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
481 if (empty($searchValue)) {
482 $this->fail("empty value passed to assertDBNotNull");
484 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
485 $this->assertNotNull($value, $message);
490 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
491 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
492 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
493 $this->assertNull($value, $message);
496 // Request a record from the DB by id. Success if row not found.
497 function assertDBRowNotExist($daoName, $id, $message = NULL) {
498 $message = $message ?
$message : "$daoName (#$id) should not exist";
499 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
500 $this->assertNull($value, $message);
503 // Request a record from the DB by id. Success if row not found.
504 function assertDBRowExist($daoName, $id, $message = NULL) {
505 $message = $message ?
$message : "$daoName (#$id) should exist";
506 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
507 $this->assertEquals($id, $value, $message);
510 // Compare a single column value in a retrieved DB record to an expected value
511 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
512 $expectedValue, $message
514 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
515 $this->assertEquals($value, $expectedValue, $message);
518 // Compare all values in a single retrieved DB record to an array of expected values
519 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
520 //get the values from db
522 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
524 // compare db values with expected values
525 self
::assertAttributesEquals($expectedValues, $dbValues);
529 * Assert that a SQL query returns a given value
531 * The first argument is an expected value. The remaining arguments are passed
532 * to CRM_Core_DAO::singleValueQuery
534 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
535 * array(1 => array("Whiz", "String")));
537 function assertDBQuery($expected, $query, $params = array()) {
538 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
539 $this->assertEquals($expected, $actual,
540 sprintf('expected=[%s] actual=[%s] query=[%s]',
541 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
547 * Assert that two array-trees are exactly equal, notwithstanding
548 * the sorting of keys
550 * @param array $expected
551 * @param array $actual
553 function assertTreeEquals($expected, $actual) {
556 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
557 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
561 $this->assertEquals($e, $a);
565 * Assert that two numbers are approximately equal
567 * @param int|float $expected
568 * @param int|float $actual
569 * @param int|float $tolerance
570 * @param string $message
572 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
573 if ($message === NULL) {
574 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
576 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
579 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
580 foreach ($expectedValues as $paramName => $paramValue) {
581 if (isset($actualValues[$paramName])) {
582 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is $paramValue value 2 is {$actualValues[$paramName]}");
585 $this->fail("Attribute '$paramName' not present in actual array.");
590 function assertArrayKeyExists($key, &$list) {
591 $result = isset($list[$key]) ?
TRUE : FALSE;
592 $this->assertTrue($result, ts("%1 element exists?",
597 function assertArrayValueNotNull($key, &$list) {
598 $this->assertArrayKeyExists($key, $list);
600 $value = isset($list[$key]) ?
$list[$key] : NULL;
601 $this->assertTrue($value,
602 ts("%1 element not null?",
609 * check that api returned 'is_error' => 0
610 * else provide full message
611 * @param array $apiResult api result
612 * @param string $prefix extra test to add to message
614 function assertAPISuccess($apiResult, $prefix = '') {
615 if (!empty($prefix)) {
618 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
620 if(!empty($apiResult['debug_information'])) {
621 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
623 if(!empty($apiResult['trace'])){
624 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
626 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
630 * check that api returned 'is_error' => 1
631 * else provide full message
632 * @param array $apiResult api result
633 * @param string $prefix extra test to add to message
635 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
636 if (!empty($prefix)) {
639 if($expectedError && !empty($apiResult['is_error'])){
640 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
642 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
643 $this->assertNotEmpty($apiResult['error_message']);
646 function assertType($expected, $actual, $message = '') {
647 return $this->assertInternalType($expected, $actual, $message);
651 * check that a deleted item has been deleted
653 function assertAPIDeleted($entity, $id) {
654 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
659 * check that api returned 'is_error' => 1
660 * else provide full message
661 * @param array $apiResult api result
662 * @param string $prefix extra test to add to message
664 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
665 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
666 foreach ($valuesToExclude as $value) {
667 if(isset($result[$value])) {
668 unset($result[$value]);
670 if(isset($expected[$value])) {
671 unset($expected[$value]);
674 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
678 * This function exists to wrap api functions
679 * so we can ensure they succeed & throw exceptions without litterering the test with checks
680 * @param string $entity
681 * @param string $action
682 * @param array $params
683 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
684 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
685 * for getsingle the array is compared against an array passed in - the id is not compared (for
688 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
689 $params = array_merge(array(
690 'version' => $this->_apiversion
,
695 switch (strtolower($action)) {
697 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
699 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
701 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
703 $result = civicrm_api($entity, $action, $params);
704 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
709 * This function exists to wrap api getValue function & check the result
710 * so we can ensure they succeed & throw exceptions without litterering the test with checks
711 * There is a type check in this
712 * @param string $entity
713 * @param array $params
714 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
722 function callAPISuccessGetValue($entity, $params, $type = NULL) {
724 'version' => $this->_apiversion
,
727 $result = civicrm_api($entity, 'getvalue', $params);
729 if($type == 'integer'){
730 // api seems to return integers as strings
731 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
734 $this->assertType($type, $result, "returned result should have been of type $type but was " );
741 * This function exists to wrap api getsingle function & check the result
742 * so we can ensure they succeed & throw exceptions without litterering the test with checks
743 * @param string $entity
744 * @param array $params
745 * @param array $checkAgainst - array to compare result against
753 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
755 'version' => $this->_apiversion
,
758 $result = civicrm_api($entity, 'getsingle', $params);
759 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
760 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
763 // @todo - have gone with the fn that unsets id? should we check id?
764 $this->checkArrayEquals($result, $checkAgainst);
769 * This function exists to wrap api getValue function & check the result
770 * so we can ensure they succeed & throw exceptions without litterering the test with checks
771 * There is a type check in this
772 * @param string $entity
773 * @param array $params
774 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
782 function callAPISuccessGetCount($entity, $params, $count = NULL) {
784 'version' => $this->_apiversion
,
787 $result = civicrm_api($entity, 'getcount', $params);
788 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
789 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
792 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
797 * This function exists to wrap api functions
798 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
800 * @param string $entity
801 * @param string $action
802 * @param array $params
803 * @param string $function - pass this in to create a generated example
804 * @param string $file - pass this in to create a generated example
806 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
807 $params['version'] = $this->_apiversion
;
808 $result = $this->callAPISuccess($entity, $action, $params);
809 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
814 * This function exists to wrap api functions
815 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
816 * @param string $entity
817 * @param string $action
818 * @param array $params
819 * @param string $expectedErrorMessage error
821 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
822 if (is_array($params)) {
824 'version' => $this->_apiversion
,
827 $result = civicrm_api($entity, $action, $params);
828 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
833 * Create required data based on $this->entity & $this->params
834 * This is just a way to set up the test data for delete & get functions
835 * so the distinction between set
836 * up & tested functions is clearer
838 * @return array api Result
840 public function createTestEntity(){
841 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
845 * Generic function to create Organisation, to be used in test cases
847 * @param array parameters for civicrm_contact_add api function call
849 * @return int id of Organisation created
851 function organizationCreate($params = array()) {
856 'organization_name' => 'Unit Test Organization',
857 'contact_type' => 'Organization',
859 return $this->_contactCreate(array_merge($orgParams, $params));
863 * Generic function to create Individual, to be used in test cases
865 * @param array parameters for civicrm_contact_add api function call
867 * @return int id of Individual created
869 function individualCreate($params = NULL) {
870 if ($params === NULL) {
872 'first_name' => 'Anthony',
873 'middle_name' => 'J.',
874 'last_name' => 'Anderson',
877 'email' => 'anthony_anderson@civicrm.org',
878 'contact_type' => 'Individual',
881 return $this->_contactCreate($params);
885 * Generic function to create Household, to be used in test cases
887 * @param array parameters for civicrm_contact_add api function call
889 * @return int id of Household created
891 function householdCreate($params = NULL) {
892 if ($params === NULL) {
894 'household_name' => 'Unit Test household',
895 'contact_type' => 'Household',
898 return $this->_contactCreate($params);
902 * Private helper function for calling civicrm_contact_add
904 * @param array parameters for civicrm_contact_add api function call
906 * @return int id of Household created
908 private function _contactCreate($params) {
909 $result = $this->callAPISuccess('contact', 'create', $params);
910 if (CRM_Utils_Array
::value('is_error', $result) ||
911 !CRM_Utils_Array
::value('id', $result)
913 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
915 return $result['id'];
918 function contactDelete($contactID) {
921 'skip_undelete' => 1,
924 $domain = new CRM_Core_BAO_Domain
;
925 $domain->contact_id
= $contactID;
926 if ($domain->find(TRUE)) {
927 // we are finding tests trying to delete the domain contact in cleanup
928 //since this is mainly for cleanup lets put a safeguard here
931 $result = $this->callAPISuccess('contact', 'delete', $params);
935 function contactTypeDelete($contactTypeId) {
936 require_once 'CRM/Contact/BAO/ContactType.php';
937 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
939 throw new Exception('Could not delete contact type');
943 function membershipTypeCreate($params = array()) {
944 CRM_Member_PseudoConstant
::flush('membershipType');
945 CRM_Core_Config
::clearDBCache();
946 $params = array_merge(array(
948 'duration_unit' => 'year',
949 'duration_interval' => 1,
950 'period_type' => 'rolling',
951 'member_of_contact_id' => 1,
953 'financial_type_id' => 1,
959 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
961 CRM_Member_PseudoConstant
::flush('membershipType');
962 CRM_Utils_Cache
::singleton()->flush();
964 return $result['id'];
967 function contactMembershipCreate($params) {
969 'join_date' => '2007-01-21',
970 'start_date' => '2007-01-21',
971 'end_date' => '2007-12-21',
972 'source' => 'Payment',
975 foreach ($pre as $key => $val) {
976 if (!isset($params[$key])) {
977 $params[$key] = $val;
981 $result = $this->callAPISuccess('Membership', 'create', $params);
982 return $result['id'];
986 * Function to delete Membership Type
988 * @param int $membershipTypeID
990 function membershipTypeDelete($params) {
991 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
995 function membershipDelete($membershipID) {
996 $deleteParams = array('id' => $membershipID);
997 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1001 function membershipStatusCreate($name = 'test member status') {
1002 $params['name'] = $name;
1003 $params['start_event'] = 'start_date';
1004 $params['end_event'] = 'end_date';
1005 $params['is_current_member'] = 1;
1006 $params['is_active'] = 1;
1008 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1009 CRM_Member_PseudoConstant
::flush('membershipStatus');
1010 return $result['id'];
1013 function membershipStatusDelete($membershipStatusID) {
1014 if (!$membershipStatusID) {
1017 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1021 function relationshipTypeCreate($params = array()) {
1022 $params = array_merge(array(
1023 'name_a_b' => 'Relation 1 for relationship type create',
1024 'name_b_a' => 'Relation 2 for relationship type create',
1025 'contact_type_a' => 'Individual',
1026 'contact_type_b' => 'Organization',
1033 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1034 CRM_Core_PseudoConstant
::flush('relationshipType');
1036 return $result['id'];
1040 * Function to delete Relatinship Type
1042 * @param int $relationshipTypeID
1044 function relationshipTypeDelete($relationshipTypeID) {
1045 $params['id'] = $relationshipTypeID;
1046 $this->callAPISuccess('relationship_type', 'delete', $params);
1049 function paymentProcessorTypeCreate($params = NULL) {
1050 if (is_null($params)) {
1052 'name' => 'API_Test_PP',
1053 'title' => 'API Test Payment Processor',
1054 'class_name' => 'CRM_Core_Payment_APITest',
1055 'billing_mode' => 'form',
1061 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1063 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1065 return $result['id'];
1069 * Function to create Participant
1071 * @param array $params array of contact id and event id values
1073 * @return int $id of participant created
1075 function participantCreate($params) {
1076 if(empty($params['contact_id'])){
1077 $params['contact_id'] = $this->individualCreate();
1079 if(empty($params['event_id'])){
1080 $event = $this->eventCreate();
1081 $params['event_id'] = $event['id'];
1086 'register_date' => 20070219,
1087 'source' => 'Wimbeldon',
1088 'event_level' => 'Payment',
1092 $params = array_merge($defaults, $params);
1093 $result = $this->callAPISuccess('Participant', 'create', $params);
1094 return $result['id'];
1098 * Function to create Payment Processor
1100 * @return object of Payment Processsor
1102 function processorCreate() {
1103 $processorParams = array(
1106 'payment_processor_type_id' => 10,
1107 'financial_account_id' => 12,
1110 'url_site' => 'http://dummy.com',
1111 'url_recur' => 'http://dummy.com',
1112 'billing_mode' => 1,
1114 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1115 return $paymentProcessor;
1119 * Function to create contribution page
1121 * @return object of contribution page
1123 function contributionPageCreate($params) {
1124 $this->_pageParams
= array(
1125 'title' => 'Test Contribution Page',
1126 'financial_type_id' => 1,
1127 'currency' => 'USD',
1128 'financial_account_id' => 1,
1129 'payment_processor' => $params['processor_id'],
1131 'is_allow_other_amount' => 1,
1133 'max_amount' => 1000,
1135 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1136 return $contributionPage;
1140 * Function to create Tag
1142 * @return array result of created tag
1144 function tagCreate($params = array()) {
1146 'name' => 'New Tag3',
1147 'description' => 'This is description for Our New Tag ',
1150 $params = array_merge($defaults, $params);
1151 $result = $this->callAPISuccess('Tag', 'create', $params);
1152 return $result['values'][$result['id']];
1156 * Function to delete Tag
1158 * @param int $tagId id of the tag to be deleted
1160 function tagDelete($tagId) {
1161 require_once 'api/api.php';
1165 $result = $this->callAPISuccess('Tag', 'delete', $params);
1166 return $result['id'];
1170 * Add entity(s) to the tag
1172 * @param array $params
1174 function entityTagAdd($params) {
1175 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1180 * Function to create contribution
1182 * @param int $cID contact_id
1183 * @param int $cTypeID id of financial type
1185 * @return int id of created contribution
1187 function pledgeCreate($cID) {
1189 'contact_id' => $cID,
1190 'pledge_create_date' => date('Ymd'),
1191 'start_date' => date('Ymd'),
1192 'scheduled_date' => date('Ymd'),
1194 'pledge_status_id' => '2',
1195 'financial_type_id' => '1',
1196 'pledge_original_installment_amount' => 20,
1197 'frequency_interval' => 5,
1198 'frequency_unit' => 'year',
1199 'frequency_day' => 15,
1200 'installments' => 5,
1203 $result = $this->callAPISuccess('Pledge', 'create', $params);
1204 return $result['id'];
1208 * Function to delete contribution
1210 * @param int $contributionId
1212 function pledgeDelete($pledgeId) {
1214 'pledge_id' => $pledgeId,
1216 $this->callAPISuccess('Pledge', 'delete', $params);
1220 * Function to create contribution
1222 * @param int $cID contact_id
1223 * @param int $cTypeID id of financial type
1225 * @return int id of created contribution
1227 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1230 'contact_id' => $cID,
1231 'receive_date' => date('Ymd'),
1232 'total_amount' => 100.00,
1233 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1234 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1235 'non_deductible_amount' => 10.00,
1236 'trxn_id' => $trxnID,
1237 'invoice_id' => $invoiceID,
1239 'contribution_status_id' => 1,
1240 // 'note' => 'Donating for Nobel Cause', *Fixme
1244 $params['fee_amount'] = 5.00;
1245 $params['net_amount'] = 95.00;
1248 $result = $this->callAPISuccess('contribution', 'create', $params);
1249 return $result['id'];
1253 * Function to create online contribution
1255 * @param int $financialType id of financial type
1257 * @return int id of created contribution
1259 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1260 $contribParams = array(
1261 'contact_id' => $params['contact_id'],
1262 'receive_date' => date('Ymd'),
1263 'total_amount' => 100.00,
1264 'financial_type_id' => $financialType,
1265 'contribution_page_id' => $params['contribution_page_id'],
1267 'invoice_id' => 67890,
1270 $contribParams = array_merge($contribParams, $params);
1271 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1273 return $result['id'];
1277 * Function to delete contribution
1279 * @param int $contributionId
1281 function contributionDelete($contributionId) {
1283 'contribution_id' => $contributionId,
1285 $result = $this->callAPISuccess('contribution', 'delete', $params);
1290 * Function to create an Event
1292 * @param array $params name-value pair for an event
1294 * @return array $event
1296 function eventCreate($params = array()) {
1297 // if no contact was passed, make up a dummy event creator
1298 if (!isset($params['contact_id'])) {
1299 $params['contact_id'] = $this->_contactCreate(array(
1300 'contact_type' => 'Individual',
1301 'first_name' => 'Event',
1302 'last_name' => 'Creator',
1306 // set defaults for missing params
1307 $params = array_merge(array(
1308 'title' => 'Annual CiviCRM meet',
1309 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1310 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1311 'event_type_id' => 1,
1313 'start_date' => 20081021,
1314 'end_date' => 20081023,
1315 'is_online_registration' => 1,
1316 'registration_start_date' => 20080601,
1317 'registration_end_date' => 20081015,
1318 'max_participants' => 100,
1319 'event_full_text' => 'Sorry! We are already full',
1322 'is_show_location' => 0,
1325 return $this->callAPISuccess('Event', 'create', $params);
1329 * Function to delete event
1331 * @param int $id ID of the event
1333 function eventDelete($id) {
1337 return $this->callAPISuccess('event', 'delete', $params);
1341 * Function to delete participant
1343 * @param int $participantID
1345 function participantDelete($participantID) {
1347 'id' => $participantID,
1349 return $this->callAPISuccess('Participant', 'delete', $params);
1353 * Function to create participant payment
1355 * @return int $id of created payment
1357 function participantPaymentCreate($participantID, $contributionID = NULL) {
1358 //Create Participant Payment record With Values
1360 'participant_id' => $participantID,
1361 'contribution_id' => $contributionID,
1364 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1365 return $result['id'];
1369 * Function to delete participant payment
1371 * @param int $paymentID
1373 function participantPaymentDelete($paymentID) {
1377 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1381 * Function to add a Location
1383 * @return int location id of created location
1385 function locationAdd($contactID) {
1388 'location_type' => 'New Location Type',
1390 'name' => 'Saint Helier St',
1391 'county' => 'Marin',
1392 'country' => 'United States',
1393 'state_province' => 'Michigan',
1394 'supplemental_address_1' => 'Hallmark Ct',
1395 'supplemental_address_2' => 'Jersey Village',
1400 'contact_id' => $contactID,
1401 'address' => $address,
1402 'location_format' => '2.0',
1403 'location_type' => 'New Location Type',
1406 $result = $this->callAPISuccess('Location', 'create', $params);
1411 * Function to delete Locations of contact
1413 * @params array $pamars parameters
1415 function locationDelete($params) {
1416 $result = $this->callAPISuccess('Location', 'delete', $params);
1420 * Function to add a Location Type
1422 * @return int location id of created location
1424 function locationTypeCreate($params = NULL) {
1425 if ($params === NULL) {
1427 'name' => 'New Location Type',
1428 'vcard_name' => 'New Location Type',
1429 'description' => 'Location Type for Delete',
1434 $locationType = new CRM_Core_DAO_LocationType();
1435 $locationType->copyValues($params);
1436 $locationType->save();
1437 // clear getfields cache
1438 CRM_Core_PseudoConstant
::flush();
1439 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1440 return $locationType;
1444 * Function to delete a Location Type
1446 * @param int location type id
1448 function locationTypeDelete($locationTypeId) {
1449 $locationType = new CRM_Core_DAO_LocationType();
1450 $locationType->id
= $locationTypeId;
1451 $locationType->delete();
1455 * Function to add a Group
1457 * @params array to add group
1459 * @return int groupId of created group
1462 function groupCreate($params = NULL) {
1463 if ($params === NULL) {
1465 'name' => 'Test Group 1',
1467 'title' => 'New Test Group Created',
1468 'description' => 'New Test Group Created',
1470 'visibility' => 'Public Pages',
1471 'group_type' => array(
1478 $result = $this->callAPISuccess('Group', 'create', $params);
1479 return $result['id'];
1483 * Function to delete a Group
1487 function groupDelete($gid) {
1493 $this->callAPISuccess('Group', 'delete', $params);
1497 * Function to add a UF Join Entry
1499 * @return int $id of created UF Join
1501 function ufjoinCreate($params = NULL) {
1502 if ($params === NULL) {
1505 'module' => 'CiviEvent',
1506 'entity_table' => 'civicrm_event',
1512 $result = $this->callAPISuccess('uf_join', 'create', $params);
1517 * Function to delete a UF Join Entry
1519 * @param array with missing uf_group_id
1521 function ufjoinDelete($params = NULL) {
1522 if ($params === NULL) {
1525 'module' => 'CiviEvent',
1526 'entity_table' => 'civicrm_event',
1529 'uf_group_id' => '',
1533 crm_add_uf_join($params);
1537 * Function to create Group for a contact
1539 * @param int $contactId
1541 function contactGroupCreate($contactId) {
1543 'contact_id.1' => $contactId,
1547 $this->callAPISuccess('GroupContact', 'Create', $params);
1551 * Function to delete Group for a contact
1553 * @param array $params
1555 function contactGroupDelete($contactId) {
1557 'contact_id.1' => $contactId,
1560 civicrm_api('GroupContact', 'Delete', $params);
1564 * Function to create Activity
1566 * @param int $contactId
1568 function activityCreate($params = NULL) {
1570 if ($params === NULL) {
1571 $individualSourceID = $this->individualCreate(NULL);
1573 $contactParams = array(
1574 'first_name' => 'Julia',
1575 'Last_name' => 'Anderson',
1577 'email' => 'julia_anderson@civicrm.org',
1578 'contact_type' => 'Individual',
1581 $individualTargetID = $this->individualCreate($contactParams);
1584 'source_contact_id' => $individualSourceID,
1585 'target_contact_id' => array($individualTargetID),
1586 'assignee_contact_id' => array($individualTargetID),
1587 'subject' => 'Discussion on warm beer',
1588 'activity_date_time' => date('Ymd'),
1589 'duration_hours' => 30,
1590 'duration_minutes' => 20,
1591 'location' => 'Baker Street',
1592 'details' => 'Lets schedule a meeting',
1594 'activity_name' => 'Meeting',
1598 $result = $this->callAPISuccess('Activity', 'create', $params);
1600 $result['target_contact_id'] = $individualTargetID;
1601 $result['assignee_contact_id'] = $individualTargetID;
1606 * Function to create an activity type
1608 * @params array $params parameters
1610 function activityTypeCreate($params) {
1611 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1616 * Function to delete activity type
1618 * @params Integer $activityTypeId id of the activity type
1620 function activityTypeDelete($activityTypeId) {
1621 $params['activity_type_id'] = $activityTypeId;
1622 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1627 * Function to create custom group
1629 * @param string $className
1630 * @param string $title name of custom group
1632 function customGroupCreate($params = array()) {
1634 'title' => 'new custom group',
1635 'extends' => 'Contact',
1637 'style' => 'Inline',
1641 $params = array_merge($defaults, $params);
1643 if (strlen($params['title']) > 13) {
1644 $params['title'] = substr($params['title'], 0, 13);
1647 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1648 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1650 return $this->callAPISuccess('custom_group', 'create', $params);
1654 * existing function doesn't allow params to be over-ridden so need a new one
1655 * this one allows you to only pass in the params you want to change
1657 function CustomGroupCreateByParams($params = array()) {
1659 'title' => "API Custom Group",
1660 'extends' => 'Contact',
1662 'style' => 'Inline',
1665 $params = array_merge($defaults, $params);
1666 return $this->callAPISuccess('custom_group', 'create', $params);
1670 * Create custom group with multi fields
1672 function CustomGroupMultipleCreateByParams($params = array()) {
1677 $params = array_merge($defaults, $params);
1678 return $this->CustomGroupCreateByParams($params);
1682 * Create custom group with multi fields
1684 function CustomGroupMultipleCreateWithFields($params = array()) {
1685 // also need to pass on $params['custom_field'] if not set but not in place yet
1687 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1688 $ids['custom_group_id'] = $customGroup['id'];
1690 $customField = $this->customFieldCreate($ids['custom_group_id']);
1692 $ids['custom_field_id'][] = $customField['id'];
1694 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_2');
1695 $ids['custom_field_id'][] = $customField['id'];
1697 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_3');
1698 $ids['custom_field_id'][] = $customField['id'];
1704 * Create a custom group with a single text custom field. See
1705 * participant:testCreateWithCustom for how to use this
1707 * @param string $function __FUNCTION__
1708 * @param string $file __FILE__
1710 * @return array $ids ids of created objects
1713 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1714 $params = array('title' => $function);
1715 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1716 $params['extends'] = $entity ?
$entity : 'Contact';
1717 $customGroup = $this->CustomGroupCreate($params);
1718 $customField = $this->customFieldCreate($customGroup['id'], $function);
1719 CRM_Core_PseudoConstant
::flush();
1721 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1725 * Function to delete custom group
1727 * @param int $customGroupID
1729 function customGroupDelete($customGroupID) {
1731 $params['id'] = $customGroupID;
1732 return $this->callAPISuccess('custom_group', 'delete', $params);
1736 * Function to create custom field
1738 * @param int $customGroupID
1739 * @param string $name name of custom field
1740 * @param int $apiversion API version to use
1742 function customFieldCreate($customGroupID, $name = "Cust Field") {
1747 'custom_group_id' => $customGroupID,
1748 'data_type' => 'String',
1749 'html_type' => 'Text',
1750 'is_searchable' => 1,
1752 'version' => $this->_apiversion
,
1755 $result = civicrm_api('custom_field', 'create', $params);
1757 if ($result['is_error'] == 0 && isset($result['id'])) {
1758 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1759 // force reset of enabled components to help grab custom fields
1760 CRM_Core_Component
::getEnabledComponents(1);
1764 if (civicrm_error($result)
1765 ||
!(CRM_Utils_Array
::value('customFieldId', $result['result']))
1767 throw new Exception('Could not create Custom Field ' . $result['error_message']);
1772 * Function to delete custom field
1774 * @param int $customFieldID
1776 function customFieldDelete($customFieldID) {
1778 $params['id'] = $customFieldID;
1779 return $this->callAPISuccess('custom_field', 'delete', $params);
1783 * Function to create note
1785 * @params array $params name-value pair for an event
1787 * @return array $note
1789 function noteCreate($cId) {
1791 'entity_table' => 'civicrm_contact',
1792 'entity_id' => $cId,
1793 'note' => 'hello I am testing Note',
1794 'contact_id' => $cId,
1795 'modified_date' => date('Ymd'),
1796 'subject' => 'Test Note',
1799 return $this->callAPISuccess('Note', 'create', $params);
1803 * Create test generated example in api/v3/examples.
1804 * To turn this off (e.g. on the server) set
1805 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1806 * in your settings file
1807 * @param array $params array as passed to civicrm_api function
1808 * @param array $result array as received from the civicrm_api function
1809 * @param string $function calling function - generally __FUNCTION__
1810 * @param string $filename called from file - generally __FILE__
1811 * @param string $description descriptive text for the example file
1812 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1813 * @param string $action - optional action - otherwise taken from function name
1815 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1816 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1819 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1820 //todo - this is a bit cludgey
1821 if (empty($action)) {
1822 if (strstr($function, 'Create')) {
1823 $action = empty($action) ?
'create' : $action;
1824 $entityAction = 'Create';
1826 elseif (strstr($function, 'GetSingle')) {
1827 $action = empty($action) ?
'getsingle' : $action;
1828 $entityAction = 'GetSingle';
1830 elseif (strstr($function, 'GetValue')) {
1831 $action = empty($action) ?
'getvalue' : $action;
1832 $entityAction = 'GetValue';
1834 elseif (strstr($function, 'GetCount')) {
1835 $action = empty($action) ?
'getcount' : $action;
1836 $entityAction = 'GetCount';
1838 elseif (strstr($function, 'Get')) {
1839 $action = empty($action) ?
'get' : $action;
1840 $entityAction = 'Get';
1842 elseif (strstr($function, 'Delete')) {
1843 $action = empty($action) ?
'delete' : $action;
1844 $entityAction = 'Delete';
1846 elseif (strstr($function, 'Update')) {
1847 $action = empty($action) ?
'update' : $action;
1848 $entityAction = 'Update';
1850 elseif (strstr($function, 'Subscribe')) {
1851 $action = empty($action) ?
'subscribe' : $action;
1852 $entityAction = 'Subscribe';
1854 elseif (strstr($function, 'Set')) {
1855 $action = empty($action) ?
'set' : $action;
1856 $entityAction = 'Set';
1858 elseif (strstr($function, 'Apply')) {
1859 $action = empty($action) ?
'apply' : $action;
1860 $entityAction = 'Apply';
1862 elseif (strstr($function, 'Replace')) {
1863 $action = empty($action) ?
'replace' : $action;
1864 $entityAction = 'Replace';
1868 $entityAction = ucwords($action);
1871 $this->tidyExampleResult($result);
1872 if(isset($params['version'])) {
1873 unset($params['version']);
1875 // a cleverer person than me would do it in a single regex
1876 if (strstr($entity, 'UF')) {
1877 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1880 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1882 $smarty = CRM_Core_Smarty
::singleton();
1883 $smarty->assign('testfunction', $function);
1884 $function = $fnPrefix . "_" . strtolower($action);
1885 $smarty->assign('function', $function);
1886 $smarty->assign('fnPrefix', $fnPrefix);
1887 $smarty->assign('params', $params);
1888 $smarty->assign('entity', $entity);
1889 $smarty->assign('filename', basename($filename));
1890 $smarty->assign('description', $description);
1891 $smarty->assign('result', $result);
1893 $smarty->assign('action', $action);
1894 if (empty($subfile)) {
1895 if (file_exists('../tests/templates/documentFunction.tpl')) {
1896 $f = fopen("../api/v3/examples/$entity$entityAction.php", "w");
1897 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1902 if (file_exists('../tests/templates/documentFunction.tpl')) {
1903 if (!is_dir("../api/v3/examples/$entity")) {
1904 mkdir("../api/v3/examples/$entity");
1906 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1907 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1914 * Tidy up examples array so that fields that change often ..don't
1915 * and debug related fields are unset
1916 * @param array $params
1918 function tidyExampleResult(&$result){
1919 if(!is_array($result)) {
1922 $fieldsToChange = array(
1923 'hash' => '67eac7789eaee00',
1924 'modified_date' => '2012-11-14 16:02:35',
1925 'created_date' => '2013-07-28 08:49:19',
1926 'create_date' => '20120130621222105',
1927 'application_received_date' => '20130728084957',
1928 'in_date' => '2013-07-28 08:50:19',
1929 'scheduled_date' => '20130728085413',
1930 'approval_date' => '20130728085413',
1931 'pledge_start_date_high' => '20130726090416',
1932 'start_date' => '2013-07-29 00:00:00',
1933 'event_start_date' => '2013-07-29 00:00:00',
1934 'end_date' => '2013-08-04 00:00:00',
1935 'event_end_date' => '2013-08-04 00:00:00',
1936 'decision_date' => '20130805000000',
1939 $keysToUnset = array('xdebug', 'undefined_fields',);
1940 foreach ($keysToUnset as $unwantedKey) {
1941 if(isset($result[$unwantedKey])) {
1942 unset($result[$unwantedKey]);
1945 if (isset($result['values'])) {
1946 if(!is_array($result['values'])) {
1949 $resultArray = &$result['values'];
1951 elseif(is_array($result)) {
1952 $resultArray = &$result;
1958 foreach ($resultArray as $index => &$values) {
1959 if(!is_array($values)) {
1962 foreach($values as $key => &$value) {
1963 if(substr($key, 0, 3) == 'api' && is_array($value)) {
1964 if(isset($value['is_error'])) {
1965 // we have a std nested result format
1966 $this->tidyExampleResult($value);
1969 foreach ($value as &$nestedResult) {
1970 // this is an alternative syntax for nested results a keyed array of results
1971 $this->tidyExampleResult($nestedResult);
1975 if(in_array($key, $keysToUnset)) {
1976 unset($values[$key]);
1978 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
1979 $value = $fieldsToChange[$key];
1986 * Function to delete note
1988 * @params int $noteID
1991 function noteDelete($params) {
1992 return $this->callAPISuccess('Note', 'delete', $params);
1996 * Function to create custom field with Option Values
1998 * @param array $customGroup
1999 * @param string $name name of custom field
2001 function customFieldOptionValueCreate($customGroup, $name) {
2002 $fieldParams = array(
2003 'custom_group_id' => $customGroup['id'],
2004 'name' => 'test_custom_group',
2005 'label' => 'Country',
2006 'html_type' => 'Select',
2007 'data_type' => 'String',
2010 'is_searchable' => 0,
2014 $optionGroup = array(
2016 'name' => 'option_group1',
2017 'label' => 'option_group_label1',
2020 $optionValue = array(
2021 'option_label' => array('Label1', 'Label2'),
2022 'option_value' => array('value1', 'value2'),
2023 'option_name' => array($name . '_1', $name . '_2'),
2024 'option_weight' => array(1, 2),
2025 'option_status' => 1,
2028 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2030 return $this->callAPISuccess('custom_field', 'create', $params);
2033 function confirmEntitiesDeleted($entities) {
2034 foreach ($entities as $entity) {
2036 $result = $this->callAPISuccess($entity, 'Get', array());
2037 if ($result['error'] == 1 ||
$result['count'] > 0) {
2038 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2044 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2045 if ($dropCustomValueTables) {
2046 $tablesToTruncate[] = 'civicrm_custom_group';
2047 $tablesToTruncate[] = 'civicrm_custom_field';
2050 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2051 foreach ($tablesToTruncate as $table) {
2052 $sql = "TRUNCATE TABLE $table";
2053 CRM_Core_DAO
::executeQuery($sql);
2055 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2057 if ($dropCustomValueTables) {
2058 $dbName = self
::getDBName();
2060 SELECT TABLE_NAME as tableName
2061 FROM INFORMATION_SCHEMA.TABLES
2062 WHERE TABLE_SCHEMA = '{$dbName}'
2063 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2066 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2067 while ($tableDAO->fetch()) {
2068 $sql = "DROP TABLE {$tableDAO->tableName}";
2069 CRM_Core_DAO
::executeQuery($sql);
2075 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2076 * Default behaviour is to also delete the entity
2077 * @param array $params params array to check agains
2078 * @param int $id id of the entity concerned
2079 * @param string $entity name of entity concerned (e.g. membership)
2080 * @param bool $delete should the entity be deleted as part of this check
2081 * @param string $errorText text to print on error
2084 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2086 $result = $this->callAPISuccessGetSingle($entity, array(
2091 $this->callAPISuccess($entity, 'Delete', array(
2095 $dateFields = $keys = $dateTimeFields = array();
2096 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2097 foreach ($fields['values'] as $field => $settings) {
2098 if (array_key_exists($field, $result)) {
2099 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2102 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2104 $type = CRM_Utils_Array
::value('type', $settings);
2105 if ($type == CRM_Utils_Type
::T_DATE
) {
2106 $dateFields[] = $settings['name'];
2107 // we should identify both real names & unique names as dates
2108 if($field != $settings['name']) {
2109 $dateFields[] = $field;
2112 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2113 $dateTimeFields[] = $settings['name'];
2114 // we should identify both real names & unique names as dates
2115 if($field != $settings['name']) {
2116 $dateTimeFields[] = $field;
2121 if (strtolower($entity) == 'contribution') {
2122 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2123 // this is not returned in id format
2124 unset($params['payment_instrument_id']);
2125 $params['contribution_source'] = $params['source'];
2126 unset($params['source']);
2129 foreach ($params as $key => $value) {
2130 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2133 if (in_array($key, $dateFields)) {
2134 $value = date('Y-m-d', strtotime($value));
2135 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2137 if (in_array($key, $dateTimeFields)) {
2138 $value = date('Y-m-d H:i:s', strtotime($value));
2139 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2141 $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);
2146 * Function to get formatted values in the actual and expected result
2147 * @param array $actual actual calculated values
2148 * @param array $expected expected values
2151 function checkArrayEquals(&$actual, &$expected) {
2152 self
::unsetId($actual);
2153 self
::unsetId($expected);
2154 $this->assertEquals($actual, $expected);
2158 * Function to unset the key 'id' from the array
2159 * @param array $unformattedArray The array from which the 'id' has to be unset
2162 static function unsetId(&$unformattedArray) {
2163 $formattedArray = array();
2164 if (array_key_exists('id', $unformattedArray)) {
2165 unset($unformattedArray['id']);
2167 if (CRM_Utils_Array
::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2168 foreach ($unformattedArray['values'] as $key => $value) {
2169 if (is_Array($value)) {
2170 foreach ($value as $k => $v) {
2176 elseif ($key == 'id') {
2177 $unformattedArray[$key];
2179 $formattedArray = array($value);
2181 $unformattedArray['values'] = $formattedArray;
2186 * Helper to enable/disable custom directory support
2188 * @param array $customDirs with members:
2189 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2190 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2192 function customDirectories($customDirs) {
2193 require_once 'CRM/Core/Config.php';
2194 $config = CRM_Core_Config
::singleton();
2196 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2197 unset($config->customPHPPathDir
);
2199 elseif ($customDirs['php_path'] === TRUE) {
2200 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2203 $config->customPHPPathDir
= $php_path;
2206 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2207 unset($config->customTemplateDir
);
2209 elseif ($customDirs['template_path'] === TRUE) {
2210 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2213 $config->customTemplateDir
= $template_path;
2218 * Generate a temporary folder
2222 function createTempDir($prefix = 'test-') {
2223 $tempDir = CRM_Utils_File
::tempdir($prefix);
2224 $this->tempDirs
[] = $tempDir;
2228 function cleanTempDirs() {
2229 if (!is_array($this->tempDirs
)) {
2230 // fix test errors where this is not set
2233 foreach ($this->tempDirs
as $tempDir) {
2234 if (is_dir($tempDir)) {
2235 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2241 * Temporarily replace the singleton extension with a different one
2243 function setExtensionSystem(CRM_Extension_System
$system) {
2244 if ($this->origExtensionSystem
== NULL) {
2245 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2247 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2250 function unsetExtensionSystem() {
2251 if ($this->origExtensionSystem
!== NULL) {
2252 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2253 $this->origExtensionSystem
= NULL;
2257 function financialAccountDelete($name) {
2258 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2259 $financialAccount->name
= $name;
2260 if($financialAccount->find(TRUE)) {
2261 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2262 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2263 $entityFinancialType->delete();
2264 $financialAccount->delete();
2269 * Use $ids as an instruction to do test cleanup
2271 function deleteFromIDSArray() {
2272 foreach ($this->ids
as $entity => $ids) {
2273 foreach ($ids as $id) {
2274 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2280 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2281 * (NB unclear if this is still required)
2283 function _sethtmlGlobals() {
2284 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2285 'required' => array(
2286 'html_quickform_rule_required',
2287 'HTML/QuickForm/Rule/Required.php'
2289 'maxlength' => array(
2290 'html_quickform_rule_range',
2291 'HTML/QuickForm/Rule/Range.php'
2293 'minlength' => array(
2294 'html_quickform_rule_range',
2295 'HTML/QuickForm/Rule/Range.php'
2297 'rangelength' => array(
2298 'html_quickform_rule_range',
2299 'HTML/QuickForm/Rule/Range.php'
2302 'html_quickform_rule_email',
2303 'HTML/QuickForm/Rule/Email.php'
2306 'html_quickform_rule_regex',
2307 'HTML/QuickForm/Rule/Regex.php'
2309 'lettersonly' => array(
2310 'html_quickform_rule_regex',
2311 'HTML/QuickForm/Rule/Regex.php'
2313 'alphanumeric' => array(
2314 'html_quickform_rule_regex',
2315 'HTML/QuickForm/Rule/Regex.php'
2318 'html_quickform_rule_regex',
2319 'HTML/QuickForm/Rule/Regex.php'
2321 'nopunctuation' => array(
2322 'html_quickform_rule_regex',
2323 'HTML/QuickForm/Rule/Regex.php'
2326 'html_quickform_rule_regex',
2327 'HTML/QuickForm/Rule/Regex.php'
2329 'callback' => array(
2330 'html_quickform_rule_callback',
2331 'HTML/QuickForm/Rule/Callback.php'
2334 'html_quickform_rule_compare',
2335 'HTML/QuickForm/Rule/Compare.php'
2338 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2339 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2341 'HTML/QuickForm/group.php',
2342 'HTML_QuickForm_group'
2345 'HTML/QuickForm/hidden.php',
2346 'HTML_QuickForm_hidden'
2349 'HTML/QuickForm/reset.php',
2350 'HTML_QuickForm_reset'
2352 'checkbox' => array(
2353 'HTML/QuickForm/checkbox.php',
2354 'HTML_QuickForm_checkbox'
2357 'HTML/QuickForm/file.php',
2358 'HTML_QuickForm_file'
2361 'HTML/QuickForm/image.php',
2362 'HTML_QuickForm_image'
2364 'password' => array(
2365 'HTML/QuickForm/password.php',
2366 'HTML_QuickForm_password'
2369 'HTML/QuickForm/radio.php',
2370 'HTML_QuickForm_radio'
2373 'HTML/QuickForm/button.php',
2374 'HTML_QuickForm_button'
2377 'HTML/QuickForm/submit.php',
2378 'HTML_QuickForm_submit'
2381 'HTML/QuickForm/select.php',
2382 'HTML_QuickForm_select'
2384 'hiddenselect' => array(
2385 'HTML/QuickForm/hiddenselect.php',
2386 'HTML_QuickForm_hiddenselect'
2389 'HTML/QuickForm/text.php',
2390 'HTML_QuickForm_text'
2392 'textarea' => array(
2393 'HTML/QuickForm/textarea.php',
2394 'HTML_QuickForm_textarea'
2396 'fckeditor' => array(
2397 'HTML/QuickForm/fckeditor.php',
2398 'HTML_QuickForm_FCKEditor'
2401 'HTML/QuickForm/tinymce.php',
2402 'HTML_QuickForm_TinyMCE'
2404 'dojoeditor' => array(
2405 'HTML/QuickForm/dojoeditor.php',
2406 'HTML_QuickForm_dojoeditor'
2409 'HTML/QuickForm/link.php',
2410 'HTML_QuickForm_link'
2412 'advcheckbox' => array(
2413 'HTML/QuickForm/advcheckbox.php',
2414 'HTML_QuickForm_advcheckbox'
2417 'HTML/QuickForm/date.php',
2418 'HTML_QuickForm_date'
2421 'HTML/QuickForm/static.php',
2422 'HTML_QuickForm_static'
2425 'HTML/QuickForm/header.php',
2426 'HTML_QuickForm_header'
2429 'HTML/QuickForm/html.php',
2430 'HTML_QuickForm_html'
2432 'hierselect' => array(
2433 'HTML/QuickForm/hierselect.php',
2434 'HTML_QuickForm_hierselect'
2436 'autocomplete' => array(
2437 'HTML/QuickForm/autocomplete.php',
2438 'HTML_QuickForm_autocomplete'
2441 'HTML/QuickForm/xbutton.php',
2442 'HTML_QuickForm_xbutton'
2444 'advmultiselect' => array(
2445 'HTML/QuickForm/advmultiselect.php',
2446 'HTML_QuickForm_advmultiselect'
2452 * Create an instance of the paypal processor
2453 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2454 * this parent class & we don't have a structure for that yet
2455 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2456 * & the best protection agains that is the functions this class affords
2458 function paymentProcessorCreate($params = array()) {
2459 $params = array_merge(array(
2461 'domain_id' => CRM_Core_Config
::domainID(),
2462 'payment_processor_type_id' => 'PayPal',
2466 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2467 'password' => '1183377788',
2468 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2469 'url_site' => 'https://www.sandbox.paypal.com/',
2470 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2471 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2472 'class_name' => 'Payment_PayPalImpl',
2473 'billing_mode' => 3,
2474 'financial_type_id' => 1,
2477 if(!is_numeric($params['payment_processor_type_id'])) {
2478 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2480 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2481 'name' => $params['payment_processor_type_id'],
2485 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2486 return $result['id'];
2490 function CiviUnitTestCase_fatalErrorHandler($message) {
2491 throw new Exception("{$message['message']}: {$message['code']}");