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_port'],
152 $GLOBALS['mysql_user'],
153 $GLOBALS['mysql_pass']
156 // also load the class loader
157 require_once 'CRM/Core/ClassLoader.php';
158 CRM_Core_ClassLoader
::singleton()->register();
159 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
160 _civix_phpunit_setUp();
164 function requireDBReset() {
165 return $this->DBResetRequired
;
168 static function getDBName() {
169 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
174 * Create database connection for this instance
176 * Initialize the test database if it hasn't been initialized
178 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
180 protected function getConnection() {
181 $dbName = self
::$_dbName;
182 if (!self
::$dbInit) {
183 $dbName = self
::getDBName();
185 // install test database
186 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
188 static::_populateDB(FALSE, $this);
190 self
::$dbInit = TRUE;
192 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
196 * Required implementation of abstract method
198 protected function getDataSet() {
202 * @param bool $perClass
203 * @param null $object
204 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
206 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
208 if ($perClass ||
$object == NULL) {
212 $dbreset = $object->requireDBReset();
215 if (self
::$populateOnce ||
!$dbreset) {
218 self
::$populateOnce = NULL;
220 $dbName = self
::getDBName();
221 $pdo = self
::$utils->pdo
;
222 // only consider real tables and not views
223 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
224 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
226 $truncates = array();
228 foreach ($tables as $table) {
230 if (substr($table['table_name'], 0, 4) == 'log_') {
234 // don't change list of installed extensions
235 if ($table['table_name'] == 'civicrm_extension') {
239 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
240 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
243 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
249 "SET foreign_key_checks = 0",
250 // SQL mode needs to be strict, that's our standard
251 "SET SQL_MODE='STRICT_ALL_TABLES';",
252 "SET global innodb_flush_log_at_trx_commit = 2;",
254 $queries = array_merge($queries, $truncates);
255 $queries = array_merge($queries, $drops);
256 foreach ($queries as $query) {
257 if (self
::$utils->do_query($query) === FALSE) {
258 // failed to create test database
259 echo "failed to create test db.";
264 // initialize test database
265 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
266 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
267 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
269 $query2 = file_get_contents($sql_file2);
270 $query3 = file_get_contents($sql_file3);
271 $query4 = file_get_contents($sql_file4);
272 if (self
::$utils->do_query($query2) === FALSE) {
273 echo "Cannot load civicrm_data.mysql. Aborting.";
276 if (self
::$utils->do_query($query3) === FALSE) {
277 echo "Cannot load test_data.mysql. Aborting.";
280 if (self
::$utils->do_query($query4) === FALSE) {
281 echo "Cannot load test_data.mysql. Aborting.";
285 // done with all the loading, get transactions back
286 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
287 echo "Cannot set global? Huh?";
291 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
292 echo "Cannot get foreign keys back? Huh?";
296 unset($query, $query2, $query3);
299 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
304 public static function setUpBeforeClass() {
305 static::_populateDB(TRUE);
307 // also set this global hack
308 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
312 * Common setup functions for all unit tests
314 protected function setUp() {
315 CRM_Utils_Hook
::singleton(TRUE);
316 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
317 // Use a temporary file for STDIN
318 $GLOBALS['stdin'] = tmpfile();
319 if ($GLOBALS['stdin'] === FALSE) {
320 echo "Couldn't open temporary file\n";
324 // Get and save a connection to the database
325 $this->_dbconn
= $this->getConnection();
327 // reload database before each test
328 // $this->_populateDB();
330 // "initialize" CiviCRM to avoid problems when running single tests
331 // FIXME: look at it closer in second stage
333 // initialize the object once db is loaded
334 CRM_Core_Config
::$_mail = NULL;
335 $config = CRM_Core_Config
::singleton();
337 // when running unit tests, use mockup user framework
338 $config->setUserFramework('UnitTests');
340 // also fix the fatal error handler to throw exceptions,
342 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
344 // enable backtrace to get meaningful errors
345 $config->backtrace
= 1;
347 // disable any left-over test extensions
348 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
350 // reset all the caches
351 CRM_Utils_System
::flushCache();
353 // clear permissions stub to not check permissions
354 $config = CRM_Core_Config
::singleton();
355 $config->userPermissionClass
->permissions
= NULL;
357 //flush component settings
358 CRM_Core_Component
::getEnabledComponents(TRUE);
360 if ($this->_eNoticeCompliant
) {
361 error_reporting(E_ALL
);
364 error_reporting(E_ALL
& ~E_NOTICE
);
369 * emulate a logged in user since certain functions use that
370 * value to store a record in the DB (like activity)
373 public function createLoggedInUser() {
375 'first_name' => 'Logged In',
376 'last_name' => 'User ' . rand(),
377 'contact_type' => 'Individual',
379 $contactID = $this->individualCreate($params);
381 $session = CRM_Core_Session
::singleton();
382 $session->set('userID', $contactID);
385 public function cleanDB() {
386 self
::$populateOnce = NULL;
387 $this->DBResetRequired
= TRUE;
389 $this->_dbconn
= $this->getConnection();
390 static::_populateDB();
391 $this->tempDirs
= array();
395 * Common teardown functions for all unit tests
397 protected function tearDown() {
398 error_reporting(E_ALL
& ~E_NOTICE
);
399 $tablesToTruncate = array('civicrm_contact');
400 $this->quickCleanup($tablesToTruncate);
401 $this->cleanTempDirs();
402 $this->unsetExtensionSystem();
406 * FIXME: Maybe a better way to do it
408 function foreignKeyChecksOff() {
409 self
::$utils = new Utils($GLOBALS['mysql_host'],
410 $GLOBALS['mysql_port'],
411 $GLOBALS['mysql_user'],
412 $GLOBALS['mysql_pass']
414 $dbName = self
::getDBName();
415 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
416 if (self
::$utils->do_query($query) === FALSE) {
418 echo 'Cannot set foreign_key_checks = 0';
424 function foreignKeyChecksOn() {
425 // FIXME: might not be needed if previous fixme implemented
429 * Generic function to compare expected values after an api call to retrieved
432 * @daoName string DAO Name of object we're evaluating.
433 * @id int Id of object
434 * @match array Associative array of field name => expected value. Empty if asserting
435 * that a DELETE occurred
436 * @delete boolean True if we're checking that a DELETE action occurred.
438 function assertDBState($daoName, $id, $match, $delete = FALSE) {
440 // adding this here since developers forget to check for an id
441 // and hence we get the first value in the db
442 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
445 $object = new $daoName();
449 // If we're asserting successful record deletion, make sure object is NOT found.
451 if ($object->find(TRUE)) {
452 $this->fail("Object not deleted by delete operation: $daoName, $id");
457 // Otherwise check matches of DAO field values against expected values in $match.
458 if ($object->find(TRUE)) {
459 $fields = & $object->fields();
460 foreach ($fields as $name => $value) {
461 $dbName = $value['name'];
462 if (isset($match[$name])) {
464 $this->assertEquals($object->$dbName, $match[$name]);
466 elseif (isset($match[$dbName])) {
468 $this->assertEquals($object->$dbName, $match[$dbName]);
473 $this->fail("Could not retrieve object: $daoName, $id");
476 $matchSize = count($match);
477 if ($verifiedCount != $matchSize) {
478 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
482 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
483 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
484 if (empty($searchValue)) {
485 $this->fail("empty value passed to assertDBNotNull");
487 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
488 $this->assertNotNull($value, $message);
493 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
494 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
495 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
496 $this->assertNull($value, $message);
499 // Request a record from the DB by id. Success if row not found.
500 function assertDBRowNotExist($daoName, $id, $message = NULL) {
501 $message = $message ?
$message : "$daoName (#$id) should not exist";
502 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
503 $this->assertNull($value, $message);
506 // Request a record from the DB by id. Success if row not found.
507 function assertDBRowExist($daoName, $id, $message = NULL) {
508 $message = $message ?
$message : "$daoName (#$id) should exist";
509 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
510 $this->assertEquals($id, $value, $message);
513 // Compare a single column value in a retrieved DB record to an expected value
514 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
515 $expectedValue, $message
517 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
518 $this->assertEquals($value, $expectedValue, $message);
521 // Compare all values in a single retrieved DB record to an array of expected values
522 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
523 //get the values from db
525 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
527 // compare db values with expected values
528 self
::assertAttributesEquals($expectedValues, $dbValues);
532 * Assert that a SQL query returns a given value
534 * The first argument is an expected value. The remaining arguments are passed
535 * to CRM_Core_DAO::singleValueQuery
537 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
538 * array(1 => array("Whiz", "String")));
540 function assertDBQuery($expected, $query, $params = array()) {
541 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
542 $this->assertEquals($expected, $actual,
543 sprintf('expected=[%s] actual=[%s] query=[%s]',
544 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
550 * Assert that two array-trees are exactly equal, notwithstanding
551 * the sorting of keys
553 * @param array $expected
554 * @param array $actual
556 function assertTreeEquals($expected, $actual) {
559 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
560 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
564 $this->assertEquals($e, $a);
568 * Assert that two numbers are approximately equal
570 * @param int|float $expected
571 * @param int|float $actual
572 * @param int|float $tolerance
573 * @param string $message
575 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
576 if ($message === NULL) {
577 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
579 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
582 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
583 foreach ($expectedValues as $paramName => $paramValue) {
584 if (isset($actualValues[$paramName])) {
585 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
588 $this->fail("Attribute '$paramName' not present in actual array.");
593 function assertArrayKeyExists($key, &$list) {
594 $result = isset($list[$key]) ?
TRUE : FALSE;
595 $this->assertTrue($result, ts("%1 element exists?",
600 function assertArrayValueNotNull($key, &$list) {
601 $this->assertArrayKeyExists($key, $list);
603 $value = isset($list[$key]) ?
$list[$key] : NULL;
604 $this->assertTrue($value,
605 ts("%1 element not null?",
612 * check that api returned 'is_error' => 0
613 * else provide full message
614 * @param array $apiResult api result
615 * @param string $prefix extra test to add to message
617 function assertAPISuccess($apiResult, $prefix = '') {
618 if (!empty($prefix)) {
621 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
623 if(!empty($apiResult['debug_information'])) {
624 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
626 if(!empty($apiResult['trace'])){
627 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
629 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
633 * check that api returned 'is_error' => 1
634 * else provide full message
635 * @param array $apiResult api result
636 * @param string $prefix extra test to add to message
638 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
639 if (!empty($prefix)) {
642 if($expectedError && !empty($apiResult['is_error'])){
643 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
645 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
646 $this->assertNotEmpty($apiResult['error_message']);
649 function assertType($expected, $actual, $message = '') {
650 return $this->assertInternalType($expected, $actual, $message);
654 * check that a deleted item has been deleted
656 function assertAPIDeleted($entity, $id) {
657 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
662 * check that api returned 'is_error' => 1
663 * else provide full message
664 * @param array $apiResult api result
665 * @param string $prefix extra test to add to message
667 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
668 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
669 foreach ($valuesToExclude as $value) {
670 if(isset($result[$value])) {
671 unset($result[$value]);
673 if(isset($expected[$value])) {
674 unset($expected[$value]);
677 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
681 * This function exists to wrap api functions
682 * so we can ensure they succeed & throw exceptions without litterering the test with checks
683 * @param string $entity
684 * @param string $action
685 * @param array $params
686 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
687 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
688 * for getsingle the array is compared against an array passed in - the id is not compared (for
691 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
692 $params = array_merge(array(
693 'version' => $this->_apiversion
,
698 switch (strtolower($action)) {
700 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
702 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
704 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
706 $result = civicrm_api($entity, $action, $params);
707 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
712 * This function exists to wrap api getValue function & check the result
713 * so we can ensure they succeed & throw exceptions without litterering the test with checks
714 * There is a type check in this
715 * @param string $entity
716 * @param array $params
717 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
725 function callAPISuccessGetValue($entity, $params, $type = NULL) {
727 'version' => $this->_apiversion
,
730 $result = civicrm_api($entity, 'getvalue', $params);
732 if($type == 'integer'){
733 // api seems to return integers as strings
734 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
737 $this->assertType($type, $result, "returned result should have been of type $type but was " );
744 * This function exists to wrap api getsingle function & check the result
745 * so we can ensure they succeed & throw exceptions without litterering the test with checks
746 * @param string $entity
747 * @param array $params
748 * @param array $checkAgainst - array to compare result against
756 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
758 'version' => $this->_apiversion
,
761 $result = civicrm_api($entity, 'getsingle', $params);
762 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
763 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
766 // @todo - have gone with the fn that unsets id? should we check id?
767 $this->checkArrayEquals($result, $checkAgainst);
772 * This function exists to wrap api getValue function & check the result
773 * so we can ensure they succeed & throw exceptions without litterering the test with checks
774 * There is a type check in this
775 * @param string $entity
776 * @param array $params
777 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
785 function callAPISuccessGetCount($entity, $params, $count = NULL) {
787 'version' => $this->_apiversion
,
790 $result = civicrm_api($entity, 'getcount', $params);
791 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
792 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
795 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
801 * This function exists to wrap api functions
802 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
804 * @param string $entity
805 * @param string $action
806 * @param array $params
807 * @param string $function - pass this in to create a generated example
808 * @param string $file - pass this in to create a generated example
809 * @param string $description
810 * @param string|null $subfile
811 * @param string|null $actionName
814 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
815 $params['version'] = $this->_apiversion
;
816 $result = $this->callAPISuccess($entity, $action, $params);
817 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
822 * This function exists to wrap api functions
823 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
824 * @param string $entity
825 * @param string $action
826 * @param array $params
827 * @param string $expectedErrorMessage error
829 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
830 if (is_array($params)) {
832 'version' => $this->_apiversion
,
835 $result = civicrm_api($entity, $action, $params);
836 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
841 * Create required data based on $this->entity & $this->params
842 * This is just a way to set up the test data for delete & get functions
843 * so the distinction between set
844 * up & tested functions is clearer
846 * @return array api Result
848 public function createTestEntity(){
849 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
853 * Generic function to create Organisation, to be used in test cases
855 * @param array parameters for civicrm_contact_add api function call
857 * @return int id of Organisation created
859 function organizationCreate($params = array()) {
864 'organization_name' => 'Unit Test Organization',
865 'contact_type' => 'Organization',
867 return $this->_contactCreate(array_merge($orgParams, $params));
871 * Generic function to create Individual, to be used in test cases
873 * @param array parameters for civicrm_contact_add api function call
875 * @return int id of Individual created
877 function individualCreate($params = array()) {
878 $params = array_merge(array(
879 'first_name' => 'Anthony',
880 'middle_name' => 'J.',
881 'last_name' => 'Anderson',
884 'email' => 'anthony_anderson@civicrm.org',
885 'contact_type' => 'Individual',
888 return $this->_contactCreate($params);
892 * Generic function to create Household, to be used in test cases
894 * @param array parameters for civicrm_contact_add api function call
896 * @return int id of Household created
898 function householdCreate($params = array()) {
899 $params = array_merge(array(
900 'household_name' => 'Unit Test household',
901 'contact_type' => 'Household',
903 return $this->_contactCreate($params);
907 * Private helper function for calling civicrm_contact_add
912 * @internal param \parameters $array for civicrm_contact_add api function call
914 * @return int id of Household created
916 private function _contactCreate($params) {
917 $result = $this->callAPISuccess('contact', 'create', $params);
918 if (!empty($result['is_error']) ||
empty($result['id'])) {
919 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
921 return $result['id'];
924 function contactDelete($contactID) {
927 'skip_undelete' => 1,
930 $domain = new CRM_Core_BAO_Domain
;
931 $domain->contact_id
= $contactID;
932 if ($domain->find(TRUE)) {
933 // we are finding tests trying to delete the domain contact in cleanup
934 //since this is mainly for cleanup lets put a safeguard here
937 $result = $this->callAPISuccess('contact', 'delete', $params);
941 function contactTypeDelete($contactTypeId) {
942 require_once 'CRM/Contact/BAO/ContactType.php';
943 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
945 throw new Exception('Could not delete contact type');
949 function membershipTypeCreate($params = array()) {
950 CRM_Member_PseudoConstant
::flush('membershipType');
951 CRM_Core_Config
::clearDBCache();
952 $params = array_merge(array(
954 'duration_unit' => 'year',
955 'duration_interval' => 1,
956 'period_type' => 'rolling',
957 'member_of_contact_id' => 1,
959 'financial_type_id' => 1,
965 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
967 CRM_Member_PseudoConstant
::flush('membershipType');
968 CRM_Utils_Cache
::singleton()->flush();
970 return $result['id'];
973 function contactMembershipCreate($params) {
975 'join_date' => '2007-01-21',
976 'start_date' => '2007-01-21',
977 'end_date' => '2007-12-21',
978 'source' => 'Payment',
981 foreach ($pre as $key => $val) {
982 if (!isset($params[$key])) {
983 $params[$key] = $val;
987 $result = $this->callAPISuccess('Membership', 'create', $params);
988 return $result['id'];
992 * Function to delete Membership Type
994 * @param int $membershipTypeID
996 function membershipTypeDelete($params) {
997 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1001 function membershipDelete($membershipID) {
1002 $deleteParams = array('id' => $membershipID);
1003 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1007 function membershipStatusCreate($name = 'test member status') {
1008 $params['name'] = $name;
1009 $params['start_event'] = 'start_date';
1010 $params['end_event'] = 'end_date';
1011 $params['is_current_member'] = 1;
1012 $params['is_active'] = 1;
1014 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1015 CRM_Member_PseudoConstant
::flush('membershipStatus');
1016 return $result['id'];
1019 function membershipStatusDelete($membershipStatusID) {
1020 if (!$membershipStatusID) {
1023 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1027 function relationshipTypeCreate($params = array()) {
1028 $params = array_merge(array(
1029 'name_a_b' => 'Relation 1 for relationship type create',
1030 'name_b_a' => 'Relation 2 for relationship type create',
1031 'contact_type_a' => 'Individual',
1032 'contact_type_b' => 'Organization',
1039 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1040 CRM_Core_PseudoConstant
::flush('relationshipType');
1042 return $result['id'];
1046 * Function to delete Relatinship Type
1048 * @param int $relationshipTypeID
1050 function relationshipTypeDelete($relationshipTypeID) {
1051 $params['id'] = $relationshipTypeID;
1052 $this->callAPISuccess('relationship_type', 'delete', $params);
1055 function paymentProcessorTypeCreate($params = NULL) {
1056 if (is_null($params)) {
1058 'name' => 'API_Test_PP',
1059 'title' => 'API Test Payment Processor',
1060 'class_name' => 'CRM_Core_Payment_APITest',
1061 'billing_mode' => 'form',
1067 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1069 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1071 return $result['id'];
1075 * Function to create Participant
1077 * @param array $params array of contact id and event id values
1079 * @return int $id of participant created
1081 function participantCreate($params) {
1082 if(empty($params['contact_id'])){
1083 $params['contact_id'] = $this->individualCreate();
1085 if(empty($params['event_id'])){
1086 $event = $this->eventCreate();
1087 $params['event_id'] = $event['id'];
1092 'register_date' => 20070219,
1093 'source' => 'Wimbeldon',
1094 'event_level' => 'Payment',
1098 $params = array_merge($defaults, $params);
1099 $result = $this->callAPISuccess('Participant', 'create', $params);
1100 return $result['id'];
1104 * Function to create Payment Processor
1106 * @return object of Payment Processsor
1108 function processorCreate() {
1109 $processorParams = array(
1112 'payment_processor_type_id' => 10,
1113 'financial_account_id' => 12,
1116 'url_site' => 'http://dummy.com',
1117 'url_recur' => 'http://dummy.com',
1118 'billing_mode' => 1,
1120 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1121 return $paymentProcessor;
1125 * Function to create contribution page
1127 * @return object of contribution page
1129 function contributionPageCreate($params) {
1130 $this->_pageParams
= array(
1131 'title' => 'Test Contribution Page',
1132 'financial_type_id' => 1,
1133 'currency' => 'USD',
1134 'financial_account_id' => 1,
1135 'payment_processor' => $params['processor_id'],
1137 'is_allow_other_amount' => 1,
1139 'max_amount' => 1000,
1141 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1142 return $contributionPage;
1146 * Function to create Tag
1148 * @return array result of created tag
1150 function tagCreate($params = array()) {
1152 'name' => 'New Tag3',
1153 'description' => 'This is description for Our New Tag ',
1156 $params = array_merge($defaults, $params);
1157 $result = $this->callAPISuccess('Tag', 'create', $params);
1158 return $result['values'][$result['id']];
1162 * Function to delete Tag
1164 * @param int $tagId id of the tag to be deleted
1166 function tagDelete($tagId) {
1167 require_once 'api/api.php';
1171 $result = $this->callAPISuccess('Tag', 'delete', $params);
1172 return $result['id'];
1176 * Add entity(s) to the tag
1178 * @param array $params
1180 function entityTagAdd($params) {
1181 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1186 * Function to create contribution
1188 * @param int $cID contact_id
1189 * @param int $cTypeID id of financial type
1191 * @return int id of created contribution
1193 function pledgeCreate($cID) {
1195 'contact_id' => $cID,
1196 'pledge_create_date' => date('Ymd'),
1197 'start_date' => date('Ymd'),
1198 'scheduled_date' => date('Ymd'),
1200 'pledge_status_id' => '2',
1201 'financial_type_id' => '1',
1202 'pledge_original_installment_amount' => 20,
1203 'frequency_interval' => 5,
1204 'frequency_unit' => 'year',
1205 'frequency_day' => 15,
1206 'installments' => 5,
1209 $result = $this->callAPISuccess('Pledge', 'create', $params);
1210 return $result['id'];
1214 * Function to delete contribution
1216 * @param int $contributionId
1218 function pledgeDelete($pledgeId) {
1220 'pledge_id' => $pledgeId,
1222 $this->callAPISuccess('Pledge', 'delete', $params);
1226 * Function to create contribution
1228 * @param int $cID contact_id
1229 * @param int $cTypeID id of financial type
1231 * @return int id of created contribution
1233 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1236 'contact_id' => $cID,
1237 'receive_date' => date('Ymd'),
1238 'total_amount' => 100.00,
1239 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1240 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1241 'non_deductible_amount' => 10.00,
1242 'trxn_id' => $trxnID,
1243 'invoice_id' => $invoiceID,
1245 'contribution_status_id' => 1,
1246 // 'note' => 'Donating for Nobel Cause', *Fixme
1250 $params['fee_amount'] = 5.00;
1251 $params['net_amount'] = 95.00;
1254 $result = $this->callAPISuccess('contribution', 'create', $params);
1255 return $result['id'];
1259 * Function to create online contribution
1261 * @param int $financialType id of financial type
1263 * @return int id of created contribution
1265 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1266 $contribParams = array(
1267 'contact_id' => $params['contact_id'],
1268 'receive_date' => date('Ymd'),
1269 'total_amount' => 100.00,
1270 'financial_type_id' => $financialType,
1271 'contribution_page_id' => $params['contribution_page_id'],
1273 'invoice_id' => 67890,
1276 $contribParams = array_merge($contribParams, $params);
1277 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1279 return $result['id'];
1283 * Function to delete contribution
1285 * @param int $contributionId
1287 function contributionDelete($contributionId) {
1289 'contribution_id' => $contributionId,
1291 $result = $this->callAPISuccess('contribution', 'delete', $params);
1296 * Function to create an Event
1298 * @param array $params name-value pair for an event
1300 * @return array $event
1302 function eventCreate($params = array()) {
1303 // if no contact was passed, make up a dummy event creator
1304 if (!isset($params['contact_id'])) {
1305 $params['contact_id'] = $this->_contactCreate(array(
1306 'contact_type' => 'Individual',
1307 'first_name' => 'Event',
1308 'last_name' => 'Creator',
1312 // set defaults for missing params
1313 $params = array_merge(array(
1314 'title' => 'Annual CiviCRM meet',
1315 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1316 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1317 'event_type_id' => 1,
1319 'start_date' => 20081021,
1320 'end_date' => 20081023,
1321 'is_online_registration' => 1,
1322 'registration_start_date' => 20080601,
1323 'registration_end_date' => 20081015,
1324 'max_participants' => 100,
1325 'event_full_text' => 'Sorry! We are already full',
1328 'is_show_location' => 0,
1331 return $this->callAPISuccess('Event', 'create', $params);
1335 * Function to delete event
1337 * @param int $id ID of the event
1339 function eventDelete($id) {
1343 return $this->callAPISuccess('event', 'delete', $params);
1347 * Function to delete participant
1349 * @param int $participantID
1351 function participantDelete($participantID) {
1353 'id' => $participantID,
1355 return $this->callAPISuccess('Participant', 'delete', $params);
1359 * Function to create participant payment
1361 * @return int $id of created payment
1363 function participantPaymentCreate($participantID, $contributionID = NULL) {
1364 //Create Participant Payment record With Values
1366 'participant_id' => $participantID,
1367 'contribution_id' => $contributionID,
1370 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1371 return $result['id'];
1375 * Function to delete participant payment
1377 * @param int $paymentID
1379 function participantPaymentDelete($paymentID) {
1383 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1387 * Function to add a Location
1389 * @return int location id of created location
1391 function locationAdd($contactID) {
1394 'location_type' => 'New Location Type',
1396 'name' => 'Saint Helier St',
1397 'county' => 'Marin',
1398 'country' => 'United States',
1399 'state_province' => 'Michigan',
1400 'supplemental_address_1' => 'Hallmark Ct',
1401 'supplemental_address_2' => 'Jersey Village',
1406 'contact_id' => $contactID,
1407 'address' => $address,
1408 'location_format' => '2.0',
1409 'location_type' => 'New Location Type',
1412 $result = $this->callAPISuccess('Location', 'create', $params);
1417 * Function to delete Locations of contact
1419 * @params array $pamars parameters
1421 function locationDelete($params) {
1422 $result = $this->callAPISuccess('Location', 'delete', $params);
1426 * Function to add a Location Type
1428 * @return int location id of created location
1430 function locationTypeCreate($params = NULL) {
1431 if ($params === NULL) {
1433 'name' => 'New Location Type',
1434 'vcard_name' => 'New Location Type',
1435 'description' => 'Location Type for Delete',
1440 $locationType = new CRM_Core_DAO_LocationType();
1441 $locationType->copyValues($params);
1442 $locationType->save();
1443 // clear getfields cache
1444 CRM_Core_PseudoConstant
::flush();
1445 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1446 return $locationType;
1450 * Function to delete a Location Type
1452 * @param int location type id
1454 function locationTypeDelete($locationTypeId) {
1455 $locationType = new CRM_Core_DAO_LocationType();
1456 $locationType->id
= $locationTypeId;
1457 $locationType->delete();
1461 * Function to add a Group
1463 * @params array to add group
1465 * @return int groupId of created group
1468 function groupCreate($params = array()) {
1469 $params = array_merge(array(
1470 'name' => 'Test Group 1',
1472 'title' => 'New Test Group Created',
1473 'description' => 'New Test Group Created',
1475 'visibility' => 'Public Pages',
1476 'group_type' => array(
1482 $result = $this->callAPISuccess('Group', 'create', $params);
1483 return $result['id'];
1487 * Function to delete a Group
1491 function groupDelete($gid) {
1497 $this->callAPISuccess('Group', 'delete', $params);
1502 * @param array $params
1504 function uFFieldCreate($params = array()) {
1505 $params = array_merge(array(
1507 'field_name' => 'first_name',
1510 'visibility' => 'Public Pages and Listings',
1511 'is_searchable' => '1',
1512 'label' => 'first_name',
1513 'field_type' => 'Individual',
1516 $this->callAPISuccess('uf_field', 'create', $params);
1519 * Function to add a UF Join Entry
1521 * @return int $id of created UF Join
1523 function ufjoinCreate($params = NULL) {
1524 if ($params === NULL) {
1527 'module' => 'CiviEvent',
1528 'entity_table' => 'civicrm_event',
1534 $result = $this->callAPISuccess('uf_join', 'create', $params);
1539 * Function to delete a UF Join Entry
1541 * @param array with missing uf_group_id
1543 function ufjoinDelete($params = NULL) {
1544 if ($params === NULL) {
1547 'module' => 'CiviEvent',
1548 'entity_table' => 'civicrm_event',
1551 'uf_group_id' => '',
1555 crm_add_uf_join($params);
1559 * Function to create Group for a contact
1561 * @param int $contactId
1563 function contactGroupCreate($contactId) {
1565 'contact_id.1' => $contactId,
1569 $this->callAPISuccess('GroupContact', 'Create', $params);
1573 * Function to delete Group for a contact
1575 * @param array $params
1577 function contactGroupDelete($contactId) {
1579 'contact_id.1' => $contactId,
1582 civicrm_api('GroupContact', 'Delete', $params);
1586 * Function to create Activity
1588 * @param int $contactId
1590 function activityCreate($params = NULL) {
1592 if ($params === NULL) {
1593 $individualSourceID = $this->individualCreate();
1595 $contactParams = array(
1596 'first_name' => 'Julia',
1597 'Last_name' => 'Anderson',
1599 'email' => 'julia_anderson@civicrm.org',
1600 'contact_type' => 'Individual',
1603 $individualTargetID = $this->individualCreate($contactParams);
1606 'source_contact_id' => $individualSourceID,
1607 'target_contact_id' => array($individualTargetID),
1608 'assignee_contact_id' => array($individualTargetID),
1609 'subject' => 'Discussion on warm beer',
1610 'activity_date_time' => date('Ymd'),
1611 'duration_hours' => 30,
1612 'duration_minutes' => 20,
1613 'location' => 'Baker Street',
1614 'details' => 'Lets schedule a meeting',
1616 'activity_name' => 'Meeting',
1620 $result = $this->callAPISuccess('Activity', 'create', $params);
1622 $result['target_contact_id'] = $individualTargetID;
1623 $result['assignee_contact_id'] = $individualTargetID;
1628 * Function to create an activity type
1630 * @params array $params parameters
1632 function activityTypeCreate($params) {
1633 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1638 * Function to delete activity type
1640 * @params Integer $activityTypeId id of the activity type
1642 function activityTypeDelete($activityTypeId) {
1643 $params['activity_type_id'] = $activityTypeId;
1644 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1649 * Function to create custom group
1651 * @param string $className
1652 * @param string $title name of custom group
1654 function customGroupCreate($params = array()) {
1656 'title' => 'new custom group',
1657 'extends' => 'Contact',
1659 'style' => 'Inline',
1663 $params = array_merge($defaults, $params);
1665 if (strlen($params['title']) > 13) {
1666 $params['title'] = substr($params['title'], 0, 13);
1669 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1670 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1672 return $this->callAPISuccess('custom_group', 'create', $params);
1676 * existing function doesn't allow params to be over-ridden so need a new one
1677 * this one allows you to only pass in the params you want to change
1679 function CustomGroupCreateByParams($params = array()) {
1681 'title' => "API Custom Group",
1682 'extends' => 'Contact',
1684 'style' => 'Inline',
1687 $params = array_merge($defaults, $params);
1688 return $this->callAPISuccess('custom_group', 'create', $params);
1692 * Create custom group with multi fields
1694 function CustomGroupMultipleCreateByParams($params = array()) {
1699 $params = array_merge($defaults, $params);
1700 return $this->CustomGroupCreateByParams($params);
1704 * Create custom group with multi fields
1706 function CustomGroupMultipleCreateWithFields($params = array()) {
1707 // also need to pass on $params['custom_field'] if not set but not in place yet
1709 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1710 $ids['custom_group_id'] = $customGroup['id'];
1712 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1714 $ids['custom_field_id'][] = $customField['id'];
1716 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1717 $ids['custom_field_id'][] = $customField['id'];
1719 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1720 $ids['custom_field_id'][] = $customField['id'];
1726 * Create a custom group with a single text custom field. See
1727 * participant:testCreateWithCustom for how to use this
1729 * @param string $function __FUNCTION__
1730 * @param string $file __FILE__
1732 * @return array $ids ids of created objects
1735 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1736 $params = array('title' => $function);
1737 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1738 $params['extends'] = $entity ?
$entity : 'Contact';
1739 $customGroup = $this->CustomGroupCreate($params);
1740 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1741 CRM_Core_PseudoConstant
::flush();
1743 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1747 * Function to delete custom group
1749 * @param int $customGroupID
1751 function customGroupDelete($customGroupID) {
1752 $params['id'] = $customGroupID;
1753 return $this->callAPISuccess('custom_group', 'delete', $params);
1757 * Function to create custom field
1759 * @param array $params (custom_group_id) is required
1760 * @param string $name name of custom field
1761 * @param int $apiversion API version to use
1763 function customFieldCreate($params) {
1764 $params = array_merge(array(
1765 'label' => 'Custom Field',
1766 'data_type' => 'String',
1767 'html_type' => 'Text',
1768 'is_searchable' => 1,
1770 'default_value' => 'defaultValue',
1773 $result = $this->callAPISuccess('custom_field', 'create', $params);
1775 if ($result['is_error'] == 0 && isset($result['id'])) {
1776 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1777 // force reset of enabled components to help grab custom fields
1778 CRM_Core_Component
::getEnabledComponents(1);
1784 * Function to delete custom field
1786 * @param int $customFieldID
1788 function customFieldDelete($customFieldID) {
1790 $params['id'] = $customFieldID;
1791 return $this->callAPISuccess('custom_field', 'delete', $params);
1795 * Function to create note
1797 * @params array $params name-value pair for an event
1799 * @return array $note
1801 function noteCreate($cId) {
1803 'entity_table' => 'civicrm_contact',
1804 'entity_id' => $cId,
1805 'note' => 'hello I am testing Note',
1806 'contact_id' => $cId,
1807 'modified_date' => date('Ymd'),
1808 'subject' => 'Test Note',
1811 return $this->callAPISuccess('Note', 'create', $params);
1815 * Enable CiviCampaign Component
1817 function enableCiviCampaign() {
1818 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1819 // force reload of config object
1820 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1821 //flush cache by calling with reset
1822 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1826 * Create test generated example in api/v3/examples.
1827 * To turn this off (e.g. on the server) set
1828 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1829 * in your settings file
1830 * @param array $params array as passed to civicrm_api function
1831 * @param array $result array as received from the civicrm_api function
1832 * @param string $function calling function - generally __FUNCTION__
1833 * @param string $filename called from file - generally __FILE__
1834 * @param string $description descriptive text for the example file
1835 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1836 * @param string $action - optional action - otherwise taken from function name
1838 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1839 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1842 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1843 //todo - this is a bit cludgey
1844 if (empty($action)) {
1845 if (strstr($function, 'Create')) {
1846 $action = empty($action) ?
'create' : $action;
1847 $entityAction = 'Create';
1849 elseif (strstr($function, 'GetSingle')) {
1850 $action = empty($action) ?
'getsingle' : $action;
1851 $entityAction = 'GetSingle';
1853 elseif (strstr($function, 'GetValue')) {
1854 $action = empty($action) ?
'getvalue' : $action;
1855 $entityAction = 'GetValue';
1857 elseif (strstr($function, 'GetCount')) {
1858 $action = empty($action) ?
'getcount' : $action;
1859 $entityAction = 'GetCount';
1861 elseif (strstr($function, 'GetFields')) {
1862 $action = empty($action) ?
'getfields' : $action;
1863 $entityAction = 'GetFields';
1865 elseif (strstr($function, 'GetList')) {
1866 $action = empty($action) ?
'getlist' : $action;
1867 $entityAction = 'GetList';
1869 elseif (strstr($function, 'Get')) {
1870 $action = empty($action) ?
'get' : $action;
1871 $entityAction = 'Get';
1873 elseif (strstr($function, 'Delete')) {
1874 $action = empty($action) ?
'delete' : $action;
1875 $entityAction = 'Delete';
1877 elseif (strstr($function, 'Update')) {
1878 $action = empty($action) ?
'update' : $action;
1879 $entityAction = 'Update';
1881 elseif (strstr($function, 'Subscribe')) {
1882 $action = empty($action) ?
'subscribe' : $action;
1883 $entityAction = 'Subscribe';
1885 elseif (strstr($function, 'Submit')) {
1886 $action = empty($action) ?
'submit' : $action;
1887 $entityAction = 'Submit';
1889 elseif (strstr($function, 'Apply')) {
1890 $action = empty($action) ?
'apply' : $action;
1891 $entityAction = 'Apply';
1893 elseif (strstr($function, 'Replace')) {
1894 $action = empty($action) ?
'replace' : $action;
1895 $entityAction = 'Replace';
1899 $entityAction = ucwords($action);
1902 $this->tidyExampleResult($result);
1903 if(isset($params['version'])) {
1904 unset($params['version']);
1906 // a cleverer person than me would do it in a single regex
1907 if (strstr($entity, 'UF')) {
1908 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1911 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1913 $smarty = CRM_Core_Smarty
::singleton();
1914 $smarty->assign('testfunction', $function);
1915 $function = $fnPrefix . "_" . strtolower($action);
1916 $smarty->assign('function', $function);
1917 $smarty->assign('fnPrefix', $fnPrefix);
1918 $smarty->assign('params', $params);
1919 $smarty->assign('entity', $entity);
1920 $smarty->assign('filename', basename($filename));
1921 $smarty->assign('description', $description);
1922 $smarty->assign('result', $result);
1924 $smarty->assign('action', $action);
1925 if (empty($subfile)) {
1926 $subfile = $entityAction;
1928 if (file_exists('../tests/templates/documentFunction.tpl')) {
1929 if (!is_dir("../api/v3/examples/$entity")) {
1930 mkdir("../api/v3/examples/$entity");
1932 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1933 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1939 * Tidy up examples array so that fields that change often ..don't
1940 * and debug related fields are unset
1941 * @param array $params
1943 function tidyExampleResult(&$result){
1944 if(!is_array($result)) {
1947 $fieldsToChange = array(
1948 'hash' => '67eac7789eaee00',
1949 'modified_date' => '2012-11-14 16:02:35',
1950 'created_date' => '2013-07-28 08:49:19',
1951 'create_date' => '20120130621222105',
1952 'application_received_date' => '20130728084957',
1953 'in_date' => '2013-07-28 08:50:19',
1954 'scheduled_date' => '20130728085413',
1955 'approval_date' => '20130728085413',
1956 'pledge_start_date_high' => '20130726090416',
1957 'start_date' => '2013-07-29 00:00:00',
1958 'event_start_date' => '2013-07-29 00:00:00',
1959 'end_date' => '2013-08-04 00:00:00',
1960 'event_end_date' => '2013-08-04 00:00:00',
1961 'decision_date' => '20130805000000',
1964 $keysToUnset = array('xdebug', 'undefined_fields',);
1965 foreach ($keysToUnset as $unwantedKey) {
1966 if(isset($result[$unwantedKey])) {
1967 unset($result[$unwantedKey]);
1970 if (isset($result['values'])) {
1971 if(!is_array($result['values'])) {
1974 $resultArray = &$result['values'];
1976 elseif(is_array($result)) {
1977 $resultArray = &$result;
1983 foreach ($resultArray as $index => &$values) {
1984 if(!is_array($values)) {
1987 foreach($values as $key => &$value) {
1988 if(substr($key, 0, 3) == 'api' && is_array($value)) {
1989 if(isset($value['is_error'])) {
1990 // we have a std nested result format
1991 $this->tidyExampleResult($value);
1994 foreach ($value as &$nestedResult) {
1995 // this is an alternative syntax for nested results a keyed array of results
1996 $this->tidyExampleResult($nestedResult);
2000 if(in_array($key, $keysToUnset)) {
2001 unset($values[$key]);
2004 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2005 $value = $fieldsToChange[$key];
2007 if(is_string($value)) {
2008 $value = addslashes($value);
2015 * Function to delete note
2017 * @params int $noteID
2020 function noteDelete($params) {
2021 return $this->callAPISuccess('Note', 'delete', $params);
2025 * Function to create custom field with Option Values
2027 * @param array $customGroup
2028 * @param string $name name of custom field
2030 function customFieldOptionValueCreate($customGroup, $name) {
2031 $fieldParams = array(
2032 'custom_group_id' => $customGroup['id'],
2033 'name' => 'test_custom_group',
2034 'label' => 'Country',
2035 'html_type' => 'Select',
2036 'data_type' => 'String',
2039 'is_searchable' => 0,
2043 $optionGroup = array(
2045 'name' => 'option_group1',
2046 'label' => 'option_group_label1',
2049 $optionValue = array(
2050 'option_label' => array('Label1', 'Label2'),
2051 'option_value' => array('value1', 'value2'),
2052 'option_name' => array($name . '_1', $name . '_2'),
2053 'option_weight' => array(1, 2),
2054 'option_status' => 1,
2057 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2059 return $this->callAPISuccess('custom_field', 'create', $params);
2062 function confirmEntitiesDeleted($entities) {
2063 foreach ($entities as $entity) {
2065 $result = $this->callAPISuccess($entity, 'Get', array());
2066 if ($result['error'] == 1 ||
$result['count'] > 0) {
2067 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2073 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2074 if ($dropCustomValueTables) {
2075 $tablesToTruncate[] = 'civicrm_custom_group';
2076 $tablesToTruncate[] = 'civicrm_custom_field';
2079 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2080 foreach ($tablesToTruncate as $table) {
2081 $sql = "TRUNCATE TABLE $table";
2082 CRM_Core_DAO
::executeQuery($sql);
2084 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2086 if ($dropCustomValueTables) {
2087 $dbName = self
::getDBName();
2089 SELECT TABLE_NAME as tableName
2090 FROM INFORMATION_SCHEMA.TABLES
2091 WHERE TABLE_SCHEMA = '{$dbName}'
2092 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2095 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2096 while ($tableDAO->fetch()) {
2097 $sql = "DROP TABLE {$tableDAO->tableName}";
2098 CRM_Core_DAO
::executeQuery($sql);
2104 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2105 * Default behaviour is to also delete the entity
2106 * @param array $params params array to check agains
2107 * @param int $id id of the entity concerned
2108 * @param string $entity name of entity concerned (e.g. membership)
2109 * @param bool $delete should the entity be deleted as part of this check
2110 * @param string $errorText text to print on error
2113 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2115 $result = $this->callAPISuccessGetSingle($entity, array(
2120 $this->callAPISuccess($entity, 'Delete', array(
2124 $dateFields = $keys = $dateTimeFields = array();
2125 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2126 foreach ($fields['values'] as $field => $settings) {
2127 if (array_key_exists($field, $result)) {
2128 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2131 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2133 $type = CRM_Utils_Array
::value('type', $settings);
2134 if ($type == CRM_Utils_Type
::T_DATE
) {
2135 $dateFields[] = $settings['name'];
2136 // we should identify both real names & unique names as dates
2137 if($field != $settings['name']) {
2138 $dateFields[] = $field;
2141 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2142 $dateTimeFields[] = $settings['name'];
2143 // we should identify both real names & unique names as dates
2144 if($field != $settings['name']) {
2145 $dateTimeFields[] = $field;
2150 if (strtolower($entity) == 'contribution') {
2151 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2152 // this is not returned in id format
2153 unset($params['payment_instrument_id']);
2154 $params['contribution_source'] = $params['source'];
2155 unset($params['source']);
2158 foreach ($params as $key => $value) {
2159 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2162 if (in_array($key, $dateFields)) {
2163 $value = date('Y-m-d', strtotime($value));
2164 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2166 if (in_array($key, $dateTimeFields)) {
2167 $value = date('Y-m-d H:i:s', strtotime($value));
2168 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2170 $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);
2175 * Function to get formatted values in the actual and expected result
2176 * @param array $actual actual calculated values
2177 * @param array $expected expected values
2180 function checkArrayEquals(&$actual, &$expected) {
2181 self
::unsetId($actual);
2182 self
::unsetId($expected);
2183 $this->assertEquals($actual, $expected);
2187 * Function to unset the key 'id' from the array
2188 * @param array $unformattedArray The array from which the 'id' has to be unset
2191 static function unsetId(&$unformattedArray) {
2192 $formattedArray = array();
2193 if (array_key_exists('id', $unformattedArray)) {
2194 unset($unformattedArray['id']);
2196 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2197 foreach ($unformattedArray['values'] as $key => $value) {
2198 if (is_Array($value)) {
2199 foreach ($value as $k => $v) {
2205 elseif ($key == 'id') {
2206 $unformattedArray[$key];
2208 $formattedArray = array($value);
2210 $unformattedArray['values'] = $formattedArray;
2215 * Helper to enable/disable custom directory support
2217 * @param array $customDirs with members:
2218 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2219 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2221 function customDirectories($customDirs) {
2222 require_once 'CRM/Core/Config.php';
2223 $config = CRM_Core_Config
::singleton();
2225 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2226 unset($config->customPHPPathDir
);
2228 elseif ($customDirs['php_path'] === TRUE) {
2229 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2232 $config->customPHPPathDir
= $php_path;
2235 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2236 unset($config->customTemplateDir
);
2238 elseif ($customDirs['template_path'] === TRUE) {
2239 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2242 $config->customTemplateDir
= $template_path;
2247 * Generate a temporary folder
2251 function createTempDir($prefix = 'test-') {
2252 $tempDir = CRM_Utils_File
::tempdir($prefix);
2253 $this->tempDirs
[] = $tempDir;
2257 function cleanTempDirs() {
2258 if (!is_array($this->tempDirs
)) {
2259 // fix test errors where this is not set
2262 foreach ($this->tempDirs
as $tempDir) {
2263 if (is_dir($tempDir)) {
2264 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2270 * Temporarily replace the singleton extension with a different one
2272 function setExtensionSystem(CRM_Extension_System
$system) {
2273 if ($this->origExtensionSystem
== NULL) {
2274 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2276 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2279 function unsetExtensionSystem() {
2280 if ($this->origExtensionSystem
!== NULL) {
2281 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2282 $this->origExtensionSystem
= NULL;
2287 * Temporarily alter the settings-metadata to add a mock setting.
2289 * WARNING: The setting metadata will disappear on the next cache-clear.
2294 function setMockSettingsMetaData($extras) {
2295 CRM_Core_BAO_Setting
::$_cache = array();
2296 $this->callAPISuccess('system','flush', array());
2297 CRM_Core_BAO_Setting
::$_cache = array();
2299 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2300 $metadata = array_merge($metadata, $extras);
2303 $fields = $this->callAPISuccess('setting', 'getfields', array());
2304 foreach ($extras as $key => $spec) {
2305 $this->assertNotEmpty($spec['title']);
2306 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2310 function financialAccountDelete($name) {
2311 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2312 $financialAccount->name
= $name;
2313 if($financialAccount->find(TRUE)) {
2314 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2315 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2316 $entityFinancialType->delete();
2317 $financialAccount->delete();
2322 * Use $ids as an instruction to do test cleanup
2324 function deleteFromIDSArray() {
2325 foreach ($this->ids
as $entity => $ids) {
2326 foreach ($ids as $id) {
2327 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2333 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2334 * (NB unclear if this is still required)
2336 function _sethtmlGlobals() {
2337 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2338 'required' => array(
2339 'html_quickform_rule_required',
2340 'HTML/QuickForm/Rule/Required.php'
2342 'maxlength' => array(
2343 'html_quickform_rule_range',
2344 'HTML/QuickForm/Rule/Range.php'
2346 'minlength' => array(
2347 'html_quickform_rule_range',
2348 'HTML/QuickForm/Rule/Range.php'
2350 'rangelength' => array(
2351 'html_quickform_rule_range',
2352 'HTML/QuickForm/Rule/Range.php'
2355 'html_quickform_rule_email',
2356 'HTML/QuickForm/Rule/Email.php'
2359 'html_quickform_rule_regex',
2360 'HTML/QuickForm/Rule/Regex.php'
2362 'lettersonly' => array(
2363 'html_quickform_rule_regex',
2364 'HTML/QuickForm/Rule/Regex.php'
2366 'alphanumeric' => array(
2367 'html_quickform_rule_regex',
2368 'HTML/QuickForm/Rule/Regex.php'
2371 'html_quickform_rule_regex',
2372 'HTML/QuickForm/Rule/Regex.php'
2374 'nopunctuation' => array(
2375 'html_quickform_rule_regex',
2376 'HTML/QuickForm/Rule/Regex.php'
2379 'html_quickform_rule_regex',
2380 'HTML/QuickForm/Rule/Regex.php'
2382 'callback' => array(
2383 'html_quickform_rule_callback',
2384 'HTML/QuickForm/Rule/Callback.php'
2387 'html_quickform_rule_compare',
2388 'HTML/QuickForm/Rule/Compare.php'
2391 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2392 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2394 'HTML/QuickForm/group.php',
2395 'HTML_QuickForm_group'
2398 'HTML/QuickForm/hidden.php',
2399 'HTML_QuickForm_hidden'
2402 'HTML/QuickForm/reset.php',
2403 'HTML_QuickForm_reset'
2405 'checkbox' => array(
2406 'HTML/QuickForm/checkbox.php',
2407 'HTML_QuickForm_checkbox'
2410 'HTML/QuickForm/file.php',
2411 'HTML_QuickForm_file'
2414 'HTML/QuickForm/image.php',
2415 'HTML_QuickForm_image'
2417 'password' => array(
2418 'HTML/QuickForm/password.php',
2419 'HTML_QuickForm_password'
2422 'HTML/QuickForm/radio.php',
2423 'HTML_QuickForm_radio'
2426 'HTML/QuickForm/button.php',
2427 'HTML_QuickForm_button'
2430 'HTML/QuickForm/submit.php',
2431 'HTML_QuickForm_submit'
2434 'HTML/QuickForm/select.php',
2435 'HTML_QuickForm_select'
2437 'hiddenselect' => array(
2438 'HTML/QuickForm/hiddenselect.php',
2439 'HTML_QuickForm_hiddenselect'
2442 'HTML/QuickForm/text.php',
2443 'HTML_QuickForm_text'
2445 'textarea' => array(
2446 'HTML/QuickForm/textarea.php',
2447 'HTML_QuickForm_textarea'
2449 'fckeditor' => array(
2450 'HTML/QuickForm/fckeditor.php',
2451 'HTML_QuickForm_FCKEditor'
2454 'HTML/QuickForm/tinymce.php',
2455 'HTML_QuickForm_TinyMCE'
2457 'dojoeditor' => array(
2458 'HTML/QuickForm/dojoeditor.php',
2459 'HTML_QuickForm_dojoeditor'
2462 'HTML/QuickForm/link.php',
2463 'HTML_QuickForm_link'
2465 'advcheckbox' => array(
2466 'HTML/QuickForm/advcheckbox.php',
2467 'HTML_QuickForm_advcheckbox'
2470 'HTML/QuickForm/date.php',
2471 'HTML_QuickForm_date'
2474 'HTML/QuickForm/static.php',
2475 'HTML_QuickForm_static'
2478 'HTML/QuickForm/header.php',
2479 'HTML_QuickForm_header'
2482 'HTML/QuickForm/html.php',
2483 'HTML_QuickForm_html'
2485 'hierselect' => array(
2486 'HTML/QuickForm/hierselect.php',
2487 'HTML_QuickForm_hierselect'
2489 'autocomplete' => array(
2490 'HTML/QuickForm/autocomplete.php',
2491 'HTML_QuickForm_autocomplete'
2494 'HTML/QuickForm/xbutton.php',
2495 'HTML_QuickForm_xbutton'
2497 'advmultiselect' => array(
2498 'HTML/QuickForm/advmultiselect.php',
2499 'HTML_QuickForm_advmultiselect'
2505 * Create an instance of the paypal processor
2506 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2507 * this parent class & we don't have a structure for that yet
2508 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2509 * & the best protection agains that is the functions this class affords
2511 function paymentProcessorCreate($params = array()) {
2512 $params = array_merge(array(
2514 'domain_id' => CRM_Core_Config
::domainID(),
2515 'payment_processor_type_id' => 'PayPal',
2519 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2520 'password' => '1183377788',
2521 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2522 'url_site' => 'https://www.sandbox.paypal.com/',
2523 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2524 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2525 'class_name' => 'Payment_PayPalImpl',
2526 'billing_mode' => 3,
2527 'financial_type_id' => 1,
2530 if(!is_numeric($params['payment_processor_type_id'])) {
2531 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2533 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2534 'name' => $params['payment_processor_type_id'],
2538 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2539 return $result['id'];
2543 function CiviUnitTestCase_fatalErrorHandler($message) {
2544 throw new Exception("{$message['message']}: {$message['code']}");