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();
310 CRM_Utils_Check
::singleton()->assertValid();
314 * Common setup functions for all unit tests
316 protected function setUp() {
317 CRM_Utils_Hook
::singleton(TRUE);
318 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
319 // Use a temporary file for STDIN
320 $GLOBALS['stdin'] = tmpfile();
321 if ($GLOBALS['stdin'] === FALSE) {
322 echo "Couldn't open temporary file\n";
326 // Get and save a connection to the database
327 $this->_dbconn
= $this->getConnection();
329 // reload database before each test
330 // $this->_populateDB();
332 // "initialize" CiviCRM to avoid problems when running single tests
333 // FIXME: look at it closer in second stage
335 // initialize the object once db is loaded
336 CRM_Core_Config
::$_mail = NULL;
337 $config = CRM_Core_Config
::singleton();
339 // when running unit tests, use mockup user framework
340 $config->setUserFramework('UnitTests');
342 // also fix the fatal error handler to throw exceptions,
344 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
346 // enable backtrace to get meaningful errors
347 $config->backtrace
= 1;
349 // disable any left-over test extensions
350 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
352 // reset all the caches
353 CRM_Utils_System
::flushCache();
355 // clear permissions stub to not check permissions
356 $config = CRM_Core_Config
::singleton();
357 $config->userPermissionClass
->permissions
= NULL;
359 //flush component settings
360 CRM_Core_Component
::getEnabledComponents(TRUE);
362 if ($this->_eNoticeCompliant
) {
363 error_reporting(E_ALL
);
366 error_reporting(E_ALL
& ~E_NOTICE
);
371 * emulate a logged in user since certain functions use that
372 * value to store a record in the DB (like activity)
375 public function createLoggedInUser() {
377 'first_name' => 'Logged In',
378 'last_name' => 'User ' . rand(),
379 'contact_type' => 'Individual',
381 $contactID = $this->individualCreate($params);
383 $session = CRM_Core_Session
::singleton();
384 $session->set('userID', $contactID);
387 public function cleanDB() {
388 self
::$populateOnce = NULL;
389 $this->DBResetRequired
= TRUE;
391 $this->_dbconn
= $this->getConnection();
392 static::_populateDB();
393 $this->tempDirs
= array();
397 * Common teardown functions for all unit tests
399 protected function tearDown() {
400 error_reporting(E_ALL
& ~E_NOTICE
);
401 $tablesToTruncate = array('civicrm_contact');
402 $this->quickCleanup($tablesToTruncate);
403 $this->cleanTempDirs();
404 $this->unsetExtensionSystem();
408 * FIXME: Maybe a better way to do it
410 function foreignKeyChecksOff() {
411 self
::$utils = new Utils($GLOBALS['mysql_host'],
412 $GLOBALS['mysql_port'],
413 $GLOBALS['mysql_user'],
414 $GLOBALS['mysql_pass']
416 $dbName = self
::getDBName();
417 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
418 if (self
::$utils->do_query($query) === FALSE) {
420 echo 'Cannot set foreign_key_checks = 0';
426 function foreignKeyChecksOn() {
427 // FIXME: might not be needed if previous fixme implemented
431 * Generic function to compare expected values after an api call to retrieved
434 * @daoName string DAO Name of object we're evaluating.
435 * @id int Id of object
436 * @match array Associative array of field name => expected value. Empty if asserting
437 * that a DELETE occurred
438 * @delete boolean True if we're checking that a DELETE action occurred.
440 function assertDBState($daoName, $id, $match, $delete = FALSE) {
442 // adding this here since developers forget to check for an id
443 // and hence we get the first value in the db
444 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
447 $object = new $daoName();
451 // If we're asserting successful record deletion, make sure object is NOT found.
453 if ($object->find(TRUE)) {
454 $this->fail("Object not deleted by delete operation: $daoName, $id");
459 // Otherwise check matches of DAO field values against expected values in $match.
460 if ($object->find(TRUE)) {
461 $fields = & $object->fields();
462 foreach ($fields as $name => $value) {
463 $dbName = $value['name'];
464 if (isset($match[$name])) {
466 $this->assertEquals($object->$dbName, $match[$name]);
468 elseif (isset($match[$dbName])) {
470 $this->assertEquals($object->$dbName, $match[$dbName]);
475 $this->fail("Could not retrieve object: $daoName, $id");
478 $matchSize = count($match);
479 if ($verifiedCount != $matchSize) {
480 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
484 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
485 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
486 if (empty($searchValue)) {
487 $this->fail("empty value passed to assertDBNotNull");
489 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
490 $this->assertNotNull($value, $message);
495 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
496 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
497 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
498 $this->assertNull($value, $message);
501 // Request a record from the DB by id. Success if row not found.
502 function assertDBRowNotExist($daoName, $id, $message = NULL) {
503 $message = $message ?
$message : "$daoName (#$id) should not exist";
504 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
505 $this->assertNull($value, $message);
508 // Request a record from the DB by id. Success if row not found.
509 function assertDBRowExist($daoName, $id, $message = NULL) {
510 $message = $message ?
$message : "$daoName (#$id) should exist";
511 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
512 $this->assertEquals($id, $value, $message);
515 // Compare a single column value in a retrieved DB record to an expected value
516 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
517 $expectedValue, $message
519 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
520 $this->assertEquals($value, $expectedValue, $message);
523 // Compare all values in a single retrieved DB record to an array of expected values
524 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
525 //get the values from db
527 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
529 // compare db values with expected values
530 self
::assertAttributesEquals($expectedValues, $dbValues);
534 * Assert that a SQL query returns a given value
536 * The first argument is an expected value. The remaining arguments are passed
537 * to CRM_Core_DAO::singleValueQuery
539 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
540 * array(1 => array("Whiz", "String")));
542 function assertDBQuery($expected, $query, $params = array()) {
543 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
544 $this->assertEquals($expected, $actual,
545 sprintf('expected=[%s] actual=[%s] query=[%s]',
546 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
552 * Assert that two array-trees are exactly equal, notwithstanding
553 * the sorting of keys
555 * @param array $expected
556 * @param array $actual
558 function assertTreeEquals($expected, $actual) {
561 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
562 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
566 $this->assertEquals($e, $a);
570 * Assert that two numbers are approximately equal
572 * @param int|float $expected
573 * @param int|float $actual
574 * @param int|float $tolerance
575 * @param string $message
577 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
578 if ($message === NULL) {
579 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
581 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
584 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
585 foreach ($expectedValues as $paramName => $paramValue) {
586 if (isset($actualValues[$paramName])) {
587 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
590 $this->fail("Attribute '$paramName' not present in actual array.");
595 function assertArrayKeyExists($key, &$list) {
596 $result = isset($list[$key]) ?
TRUE : FALSE;
597 $this->assertTrue($result, ts("%1 element exists?",
602 function assertArrayValueNotNull($key, &$list) {
603 $this->assertArrayKeyExists($key, $list);
605 $value = isset($list[$key]) ?
$list[$key] : NULL;
606 $this->assertTrue($value,
607 ts("%1 element not null?",
614 * check that api returned 'is_error' => 0
615 * else provide full message
616 * @param array $apiResult api result
617 * @param string $prefix extra test to add to message
619 function assertAPISuccess($apiResult, $prefix = '') {
620 if (!empty($prefix)) {
623 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
625 if(!empty($apiResult['debug_information'])) {
626 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
628 if(!empty($apiResult['trace'])){
629 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
631 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
635 * check that api returned 'is_error' => 1
636 * else provide full message
637 * @param array $apiResult api result
638 * @param string $prefix extra test to add to message
640 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
641 if (!empty($prefix)) {
644 if($expectedError && !empty($apiResult['is_error'])){
645 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
647 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
648 $this->assertNotEmpty($apiResult['error_message']);
651 function assertType($expected, $actual, $message = '') {
652 return $this->assertInternalType($expected, $actual, $message);
656 * check that a deleted item has been deleted
658 function assertAPIDeleted($entity, $id) {
659 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
664 * check that api returned 'is_error' => 1
665 * else provide full message
666 * @param array $apiResult api result
667 * @param string $prefix extra test to add to message
669 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
670 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
671 foreach ($valuesToExclude as $value) {
672 if(isset($result[$value])) {
673 unset($result[$value]);
675 if(isset($expected[$value])) {
676 unset($expected[$value]);
679 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
683 * This function exists to wrap api functions
684 * so we can ensure they succeed & throw exceptions without litterering the test with checks
685 * @param string $entity
686 * @param string $action
687 * @param array $params
688 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
689 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
690 * for getsingle the array is compared against an array passed in - the id is not compared (for
693 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
694 $params = array_merge(array(
695 'version' => $this->_apiversion
,
700 switch (strtolower($action)) {
702 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
704 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
706 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
708 $result = civicrm_api($entity, $action, $params);
709 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
714 * This function exists to wrap api getValue function & check the result
715 * so we can ensure they succeed & throw exceptions without litterering the test with checks
716 * There is a type check in this
717 * @param string $entity
718 * @param array $params
719 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
727 function callAPISuccessGetValue($entity, $params, $type = NULL) {
729 'version' => $this->_apiversion
,
732 $result = civicrm_api($entity, 'getvalue', $params);
734 if($type == 'integer'){
735 // api seems to return integers as strings
736 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
739 $this->assertType($type, $result, "returned result should have been of type $type but was " );
746 * This function exists to wrap api getsingle function & check the result
747 * so we can ensure they succeed & throw exceptions without litterering the test with checks
748 * @param string $entity
749 * @param array $params
750 * @param array $checkAgainst - array to compare result against
758 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
760 'version' => $this->_apiversion
,
763 $result = civicrm_api($entity, 'getsingle', $params);
764 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
765 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
768 // @todo - have gone with the fn that unsets id? should we check id?
769 $this->checkArrayEquals($result, $checkAgainst);
774 * This function exists to wrap api getValue function & check the result
775 * so we can ensure they succeed & throw exceptions without litterering the test with checks
776 * There is a type check in this
777 * @param string $entity
778 * @param array $params
779 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
787 function callAPISuccessGetCount($entity, $params, $count = NULL) {
789 'version' => $this->_apiversion
,
792 $result = civicrm_api($entity, 'getcount', $params);
793 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
794 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
797 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
802 * This function exists to wrap api functions
803 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
805 * @param string $entity
806 * @param string $action
807 * @param array $params
808 * @param string $function - pass this in to create a generated example
809 * @param string $file - pass this in to create a generated example
811 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
812 $params['version'] = $this->_apiversion
;
813 $result = $this->callAPISuccess($entity, $action, $params);
814 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
819 * This function exists to wrap api functions
820 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
821 * @param string $entity
822 * @param string $action
823 * @param array $params
824 * @param string $expectedErrorMessage error
826 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
827 if (is_array($params)) {
829 'version' => $this->_apiversion
,
832 $result = civicrm_api($entity, $action, $params);
833 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
838 * Create required data based on $this->entity & $this->params
839 * This is just a way to set up the test data for delete & get functions
840 * so the distinction between set
841 * up & tested functions is clearer
843 * @return array api Result
845 public function createTestEntity(){
846 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
850 * Generic function to create Organisation, to be used in test cases
852 * @param array parameters for civicrm_contact_add api function call
854 * @return int id of Organisation created
856 function organizationCreate($params = array()) {
861 'organization_name' => 'Unit Test Organization',
862 'contact_type' => 'Organization',
864 return $this->_contactCreate(array_merge($orgParams, $params));
868 * Generic function to create Individual, to be used in test cases
870 * @param array parameters for civicrm_contact_add api function call
872 * @return int id of Individual created
874 function individualCreate($params = array()) {
875 $params = array_merge(array(
876 'first_name' => 'Anthony',
877 'middle_name' => 'J.',
878 'last_name' => 'Anderson',
881 'email' => 'anthony_anderson@civicrm.org',
882 'contact_type' => 'Individual',
885 return $this->_contactCreate($params);
889 * Generic function to create Household, to be used in test cases
891 * @param array parameters for civicrm_contact_add api function call
893 * @return int id of Household created
895 function householdCreate($params = array()) {
896 $params = array_merge(array(
897 'household_name' => 'Unit Test household',
898 'contact_type' => 'Household',
900 return $this->_contactCreate($params);
904 * Private helper function for calling civicrm_contact_add
909 * @internal param \parameters $array for civicrm_contact_add api function call
911 * @return int id of Household created
913 private function _contactCreate($params) {
914 $result = $this->callAPISuccess('contact', 'create', $params);
915 if (CRM_Utils_Array
::value('is_error', $result) ||
916 !CRM_Utils_Array
::value('id', $result)
918 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
920 return $result['id'];
923 function contactDelete($contactID) {
926 'skip_undelete' => 1,
929 $domain = new CRM_Core_BAO_Domain
;
930 $domain->contact_id
= $contactID;
931 if ($domain->find(TRUE)) {
932 // we are finding tests trying to delete the domain contact in cleanup
933 //since this is mainly for cleanup lets put a safeguard here
936 $result = $this->callAPISuccess('contact', 'delete', $params);
940 function contactTypeDelete($contactTypeId) {
941 require_once 'CRM/Contact/BAO/ContactType.php';
942 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
944 throw new Exception('Could not delete contact type');
948 function membershipTypeCreate($params = array()) {
949 CRM_Member_PseudoConstant
::flush('membershipType');
950 CRM_Core_Config
::clearDBCache();
951 $params = array_merge(array(
953 'duration_unit' => 'year',
954 'duration_interval' => 1,
955 'period_type' => 'rolling',
956 'member_of_contact_id' => 1,
958 'financial_type_id' => 1,
964 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
966 CRM_Member_PseudoConstant
::flush('membershipType');
967 CRM_Utils_Cache
::singleton()->flush();
969 return $result['id'];
972 function contactMembershipCreate($params) {
974 'join_date' => '2007-01-21',
975 'start_date' => '2007-01-21',
976 'end_date' => '2007-12-21',
977 'source' => 'Payment',
980 foreach ($pre as $key => $val) {
981 if (!isset($params[$key])) {
982 $params[$key] = $val;
986 $result = $this->callAPISuccess('Membership', 'create', $params);
987 return $result['id'];
991 * Function to delete Membership Type
993 * @param int $membershipTypeID
995 function membershipTypeDelete($params) {
996 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1000 function membershipDelete($membershipID) {
1001 $deleteParams = array('id' => $membershipID);
1002 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1006 function membershipStatusCreate($name = 'test member status') {
1007 $params['name'] = $name;
1008 $params['start_event'] = 'start_date';
1009 $params['end_event'] = 'end_date';
1010 $params['is_current_member'] = 1;
1011 $params['is_active'] = 1;
1013 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1014 CRM_Member_PseudoConstant
::flush('membershipStatus');
1015 return $result['id'];
1018 function membershipStatusDelete($membershipStatusID) {
1019 if (!$membershipStatusID) {
1022 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1026 function relationshipTypeCreate($params = array()) {
1027 $params = array_merge(array(
1028 'name_a_b' => 'Relation 1 for relationship type create',
1029 'name_b_a' => 'Relation 2 for relationship type create',
1030 'contact_type_a' => 'Individual',
1031 'contact_type_b' => 'Organization',
1038 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1039 CRM_Core_PseudoConstant
::flush('relationshipType');
1041 return $result['id'];
1045 * Function to delete Relatinship Type
1047 * @param int $relationshipTypeID
1049 function relationshipTypeDelete($relationshipTypeID) {
1050 $params['id'] = $relationshipTypeID;
1051 $this->callAPISuccess('relationship_type', 'delete', $params);
1054 function paymentProcessorTypeCreate($params = NULL) {
1055 if (is_null($params)) {
1057 'name' => 'API_Test_PP',
1058 'title' => 'API Test Payment Processor',
1059 'class_name' => 'CRM_Core_Payment_APITest',
1060 'billing_mode' => 'form',
1066 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1068 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1070 return $result['id'];
1074 * Function to create Participant
1076 * @param array $params array of contact id and event id values
1078 * @return int $id of participant created
1080 function participantCreate($params) {
1081 if(empty($params['contact_id'])){
1082 $params['contact_id'] = $this->individualCreate();
1084 if(empty($params['event_id'])){
1085 $event = $this->eventCreate();
1086 $params['event_id'] = $event['id'];
1091 'register_date' => 20070219,
1092 'source' => 'Wimbeldon',
1093 'event_level' => 'Payment',
1097 $params = array_merge($defaults, $params);
1098 $result = $this->callAPISuccess('Participant', 'create', $params);
1099 return $result['id'];
1103 * Function to create Payment Processor
1105 * @return object of Payment Processsor
1107 function processorCreate() {
1108 $processorParams = array(
1111 'payment_processor_type_id' => 10,
1112 'financial_account_id' => 12,
1115 'url_site' => 'http://dummy.com',
1116 'url_recur' => 'http://dummy.com',
1117 'billing_mode' => 1,
1119 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1120 return $paymentProcessor;
1124 * Function to create contribution page
1126 * @return object of contribution page
1128 function contributionPageCreate($params) {
1129 $this->_pageParams
= array(
1130 'title' => 'Test Contribution Page',
1131 'financial_type_id' => 1,
1132 'currency' => 'USD',
1133 'financial_account_id' => 1,
1134 'payment_processor' => $params['processor_id'],
1136 'is_allow_other_amount' => 1,
1138 'max_amount' => 1000,
1140 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1141 return $contributionPage;
1145 * Function to create Tag
1147 * @return array result of created tag
1149 function tagCreate($params = array()) {
1151 'name' => 'New Tag3',
1152 'description' => 'This is description for Our New Tag ',
1155 $params = array_merge($defaults, $params);
1156 $result = $this->callAPISuccess('Tag', 'create', $params);
1157 return $result['values'][$result['id']];
1161 * Function to delete Tag
1163 * @param int $tagId id of the tag to be deleted
1165 function tagDelete($tagId) {
1166 require_once 'api/api.php';
1170 $result = $this->callAPISuccess('Tag', 'delete', $params);
1171 return $result['id'];
1175 * Add entity(s) to the tag
1177 * @param array $params
1179 function entityTagAdd($params) {
1180 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1185 * Function to create contribution
1187 * @param int $cID contact_id
1188 * @param int $cTypeID id of financial type
1190 * @return int id of created contribution
1192 function pledgeCreate($cID) {
1194 'contact_id' => $cID,
1195 'pledge_create_date' => date('Ymd'),
1196 'start_date' => date('Ymd'),
1197 'scheduled_date' => date('Ymd'),
1199 'pledge_status_id' => '2',
1200 'financial_type_id' => '1',
1201 'pledge_original_installment_amount' => 20,
1202 'frequency_interval' => 5,
1203 'frequency_unit' => 'year',
1204 'frequency_day' => 15,
1205 'installments' => 5,
1208 $result = $this->callAPISuccess('Pledge', 'create', $params);
1209 return $result['id'];
1213 * Function to delete contribution
1215 * @param int $contributionId
1217 function pledgeDelete($pledgeId) {
1219 'pledge_id' => $pledgeId,
1221 $this->callAPISuccess('Pledge', 'delete', $params);
1225 * Function to create contribution
1227 * @param int $cID contact_id
1228 * @param int $cTypeID id of financial type
1230 * @return int id of created contribution
1232 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1235 'contact_id' => $cID,
1236 'receive_date' => date('Ymd'),
1237 'total_amount' => 100.00,
1238 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1239 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1240 'non_deductible_amount' => 10.00,
1241 'trxn_id' => $trxnID,
1242 'invoice_id' => $invoiceID,
1244 'contribution_status_id' => 1,
1245 // 'note' => 'Donating for Nobel Cause', *Fixme
1249 $params['fee_amount'] = 5.00;
1250 $params['net_amount'] = 95.00;
1253 $result = $this->callAPISuccess('contribution', 'create', $params);
1254 return $result['id'];
1258 * Function to create online contribution
1260 * @param int $financialType id of financial type
1262 * @return int id of created contribution
1264 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1265 $contribParams = array(
1266 'contact_id' => $params['contact_id'],
1267 'receive_date' => date('Ymd'),
1268 'total_amount' => 100.00,
1269 'financial_type_id' => $financialType,
1270 'contribution_page_id' => $params['contribution_page_id'],
1272 'invoice_id' => 67890,
1275 $contribParams = array_merge($contribParams, $params);
1276 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1278 return $result['id'];
1282 * Function to delete contribution
1284 * @param int $contributionId
1286 function contributionDelete($contributionId) {
1288 'contribution_id' => $contributionId,
1290 $result = $this->callAPISuccess('contribution', 'delete', $params);
1295 * Function to create an Event
1297 * @param array $params name-value pair for an event
1299 * @return array $event
1301 function eventCreate($params = array()) {
1302 // if no contact was passed, make up a dummy event creator
1303 if (!isset($params['contact_id'])) {
1304 $params['contact_id'] = $this->_contactCreate(array(
1305 'contact_type' => 'Individual',
1306 'first_name' => 'Event',
1307 'last_name' => 'Creator',
1311 // set defaults for missing params
1312 $params = array_merge(array(
1313 'title' => 'Annual CiviCRM meet',
1314 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1315 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1316 'event_type_id' => 1,
1318 'start_date' => 20081021,
1319 'end_date' => 20081023,
1320 'is_online_registration' => 1,
1321 'registration_start_date' => 20080601,
1322 'registration_end_date' => 20081015,
1323 'max_participants' => 100,
1324 'event_full_text' => 'Sorry! We are already full',
1327 'is_show_location' => 0,
1330 return $this->callAPISuccess('Event', 'create', $params);
1334 * Function to delete event
1336 * @param int $id ID of the event
1338 function eventDelete($id) {
1342 return $this->callAPISuccess('event', 'delete', $params);
1346 * Function to delete participant
1348 * @param int $participantID
1350 function participantDelete($participantID) {
1352 'id' => $participantID,
1354 return $this->callAPISuccess('Participant', 'delete', $params);
1358 * Function to create participant payment
1360 * @return int $id of created payment
1362 function participantPaymentCreate($participantID, $contributionID = NULL) {
1363 //Create Participant Payment record With Values
1365 'participant_id' => $participantID,
1366 'contribution_id' => $contributionID,
1369 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1370 return $result['id'];
1374 * Function to delete participant payment
1376 * @param int $paymentID
1378 function participantPaymentDelete($paymentID) {
1382 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1386 * Function to add a Location
1388 * @return int location id of created location
1390 function locationAdd($contactID) {
1393 'location_type' => 'New Location Type',
1395 'name' => 'Saint Helier St',
1396 'county' => 'Marin',
1397 'country' => 'United States',
1398 'state_province' => 'Michigan',
1399 'supplemental_address_1' => 'Hallmark Ct',
1400 'supplemental_address_2' => 'Jersey Village',
1405 'contact_id' => $contactID,
1406 'address' => $address,
1407 'location_format' => '2.0',
1408 'location_type' => 'New Location Type',
1411 $result = $this->callAPISuccess('Location', 'create', $params);
1416 * Function to delete Locations of contact
1418 * @params array $pamars parameters
1420 function locationDelete($params) {
1421 $result = $this->callAPISuccess('Location', 'delete', $params);
1425 * Function to add a Location Type
1427 * @return int location id of created location
1429 function locationTypeCreate($params = NULL) {
1430 if ($params === NULL) {
1432 'name' => 'New Location Type',
1433 'vcard_name' => 'New Location Type',
1434 'description' => 'Location Type for Delete',
1439 $locationType = new CRM_Core_DAO_LocationType();
1440 $locationType->copyValues($params);
1441 $locationType->save();
1442 // clear getfields cache
1443 CRM_Core_PseudoConstant
::flush();
1444 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1445 return $locationType;
1449 * Function to delete a Location Type
1451 * @param int location type id
1453 function locationTypeDelete($locationTypeId) {
1454 $locationType = new CRM_Core_DAO_LocationType();
1455 $locationType->id
= $locationTypeId;
1456 $locationType->delete();
1460 * Function to add a Group
1462 * @params array to add group
1464 * @return int groupId of created group
1467 function groupCreate($params = array()) {
1468 $params = array_merge(array(
1469 'name' => 'Test Group 1',
1471 'title' => 'New Test Group Created',
1472 'description' => 'New Test Group Created',
1474 'visibility' => 'Public Pages',
1475 'group_type' => array(
1481 $result = $this->callAPISuccess('Group', 'create', $params);
1482 return $result['id'];
1486 * Function to delete a Group
1490 function groupDelete($gid) {
1496 $this->callAPISuccess('Group', 'delete', $params);
1501 * @param array $params
1503 function uFFieldCreate($params = array()) {
1504 $params = array_merge(array(
1506 'field_name' => 'first_name',
1509 'visibility' => 'Public Pages and Listings',
1510 'is_searchable' => '1',
1511 'label' => 'first_name',
1512 'field_type' => 'Individual',
1515 $this->callAPISuccess('uf_field', 'create', $params);
1518 * Function to add a UF Join Entry
1520 * @return int $id of created UF Join
1522 function ufjoinCreate($params = NULL) {
1523 if ($params === NULL) {
1526 'module' => 'CiviEvent',
1527 'entity_table' => 'civicrm_event',
1533 $result = $this->callAPISuccess('uf_join', 'create', $params);
1538 * Function to delete a UF Join Entry
1540 * @param array with missing uf_group_id
1542 function ufjoinDelete($params = NULL) {
1543 if ($params === NULL) {
1546 'module' => 'CiviEvent',
1547 'entity_table' => 'civicrm_event',
1550 'uf_group_id' => '',
1554 crm_add_uf_join($params);
1558 * Function to create Group for a contact
1560 * @param int $contactId
1562 function contactGroupCreate($contactId) {
1564 'contact_id.1' => $contactId,
1568 $this->callAPISuccess('GroupContact', 'Create', $params);
1572 * Function to delete Group for a contact
1574 * @param array $params
1576 function contactGroupDelete($contactId) {
1578 'contact_id.1' => $contactId,
1581 civicrm_api('GroupContact', 'Delete', $params);
1585 * Function to create Activity
1587 * @param int $contactId
1589 function activityCreate($params = NULL) {
1591 if ($params === NULL) {
1592 $individualSourceID = $this->individualCreate();
1594 $contactParams = array(
1595 'first_name' => 'Julia',
1596 'Last_name' => 'Anderson',
1598 'email' => 'julia_anderson@civicrm.org',
1599 'contact_type' => 'Individual',
1602 $individualTargetID = $this->individualCreate($contactParams);
1605 'source_contact_id' => $individualSourceID,
1606 'target_contact_id' => array($individualTargetID),
1607 'assignee_contact_id' => array($individualTargetID),
1608 'subject' => 'Discussion on warm beer',
1609 'activity_date_time' => date('Ymd'),
1610 'duration_hours' => 30,
1611 'duration_minutes' => 20,
1612 'location' => 'Baker Street',
1613 'details' => 'Lets schedule a meeting',
1615 'activity_name' => 'Meeting',
1619 $result = $this->callAPISuccess('Activity', 'create', $params);
1621 $result['target_contact_id'] = $individualTargetID;
1622 $result['assignee_contact_id'] = $individualTargetID;
1627 * Function to create an activity type
1629 * @params array $params parameters
1631 function activityTypeCreate($params) {
1632 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1637 * Function to delete activity type
1639 * @params Integer $activityTypeId id of the activity type
1641 function activityTypeDelete($activityTypeId) {
1642 $params['activity_type_id'] = $activityTypeId;
1643 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1648 * Function to create custom group
1650 * @param string $className
1651 * @param string $title name of custom group
1653 function customGroupCreate($params = array()) {
1655 'title' => 'new custom group',
1656 'extends' => 'Contact',
1658 'style' => 'Inline',
1662 $params = array_merge($defaults, $params);
1664 if (strlen($params['title']) > 13) {
1665 $params['title'] = substr($params['title'], 0, 13);
1668 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1669 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1671 return $this->callAPISuccess('custom_group', 'create', $params);
1675 * existing function doesn't allow params to be over-ridden so need a new one
1676 * this one allows you to only pass in the params you want to change
1678 function CustomGroupCreateByParams($params = array()) {
1680 'title' => "API Custom Group",
1681 'extends' => 'Contact',
1683 'style' => 'Inline',
1686 $params = array_merge($defaults, $params);
1687 return $this->callAPISuccess('custom_group', 'create', $params);
1691 * Create custom group with multi fields
1693 function CustomGroupMultipleCreateByParams($params = array()) {
1698 $params = array_merge($defaults, $params);
1699 return $this->CustomGroupCreateByParams($params);
1703 * Create custom group with multi fields
1705 function CustomGroupMultipleCreateWithFields($params = array()) {
1706 // also need to pass on $params['custom_field'] if not set but not in place yet
1708 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1709 $ids['custom_group_id'] = $customGroup['id'];
1711 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1713 $ids['custom_field_id'][] = $customField['id'];
1715 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1716 $ids['custom_field_id'][] = $customField['id'];
1718 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1719 $ids['custom_field_id'][] = $customField['id'];
1725 * Create a custom group with a single text custom field. See
1726 * participant:testCreateWithCustom for how to use this
1728 * @param string $function __FUNCTION__
1729 * @param string $file __FILE__
1731 * @return array $ids ids of created objects
1734 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1735 $params = array('title' => $function);
1736 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1737 $params['extends'] = $entity ?
$entity : 'Contact';
1738 $customGroup = $this->CustomGroupCreate($params);
1739 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1740 CRM_Core_PseudoConstant
::flush();
1742 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1746 * Function to delete custom group
1748 * @param int $customGroupID
1750 function customGroupDelete($customGroupID) {
1751 $params['id'] = $customGroupID;
1752 return $this->callAPISuccess('custom_group', 'delete', $params);
1756 * Function to create custom field
1758 * @param array $params (custom_group_id) is required
1759 * @param string $name name of custom field
1760 * @param int $apiversion API version to use
1762 function customFieldCreate($params) {
1763 $params = array_merge(array(
1764 'label' => 'Custom Field',
1765 'data_type' => 'String',
1766 'html_type' => 'Text',
1767 'is_searchable' => 1,
1769 'default_value' => 'defaultValue',
1772 $result = $this->callAPISuccess('custom_field', 'create', $params);
1774 if ($result['is_error'] == 0 && isset($result['id'])) {
1775 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1776 // force reset of enabled components to help grab custom fields
1777 CRM_Core_Component
::getEnabledComponents(1);
1783 * Function to delete custom field
1785 * @param int $customFieldID
1787 function customFieldDelete($customFieldID) {
1789 $params['id'] = $customFieldID;
1790 return $this->callAPISuccess('custom_field', 'delete', $params);
1794 * Function to create note
1796 * @params array $params name-value pair for an event
1798 * @return array $note
1800 function noteCreate($cId) {
1802 'entity_table' => 'civicrm_contact',
1803 'entity_id' => $cId,
1804 'note' => 'hello I am testing Note',
1805 'contact_id' => $cId,
1806 'modified_date' => date('Ymd'),
1807 'subject' => 'Test Note',
1810 return $this->callAPISuccess('Note', 'create', $params);
1814 * Enable CiviCampaign Component
1816 function enableCiviCampaign() {
1817 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1818 // force reload of config object
1819 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1820 //flush cache by calling with reset
1821 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1825 * Create test generated example in api/v3/examples.
1826 * To turn this off (e.g. on the server) set
1827 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1828 * in your settings file
1829 * @param array $params array as passed to civicrm_api function
1830 * @param array $result array as received from the civicrm_api function
1831 * @param string $function calling function - generally __FUNCTION__
1832 * @param string $filename called from file - generally __FILE__
1833 * @param string $description descriptive text for the example file
1834 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1835 * @param string $action - optional action - otherwise taken from function name
1837 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1838 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1841 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1842 //todo - this is a bit cludgey
1843 if (empty($action)) {
1844 if (strstr($function, 'Create')) {
1845 $action = empty($action) ?
'create' : $action;
1846 $entityAction = 'Create';
1848 elseif (strstr($function, 'GetSingle')) {
1849 $action = empty($action) ?
'getsingle' : $action;
1850 $entityAction = 'GetSingle';
1852 elseif (strstr($function, 'GetValue')) {
1853 $action = empty($action) ?
'getvalue' : $action;
1854 $entityAction = 'GetValue';
1856 elseif (strstr($function, 'GetCount')) {
1857 $action = empty($action) ?
'getcount' : $action;
1858 $entityAction = 'GetCount';
1860 elseif (strstr($function, 'GetFields')) {
1861 $action = empty($action) ?
'getfields' : $action;
1862 $entityAction = 'GetFields';
1864 elseif (strstr($function, 'Get')) {
1865 $action = empty($action) ?
'get' : $action;
1866 $entityAction = 'Get';
1868 elseif (strstr($function, 'Delete')) {
1869 $action = empty($action) ?
'delete' : $action;
1870 $entityAction = 'Delete';
1872 elseif (strstr($function, 'Update')) {
1873 $action = empty($action) ?
'update' : $action;
1874 $entityAction = 'Update';
1876 elseif (strstr($function, 'Subscribe')) {
1877 $action = empty($action) ?
'subscribe' : $action;
1878 $entityAction = 'Subscribe';
1880 elseif (strstr($function, 'Submit')) {
1881 $action = empty($action) ?
'submit' : $action;
1882 $entityAction = 'Submit';
1884 elseif (strstr($function, 'Apply')) {
1885 $action = empty($action) ?
'apply' : $action;
1886 $entityAction = 'Apply';
1888 elseif (strstr($function, 'Replace')) {
1889 $action = empty($action) ?
'replace' : $action;
1890 $entityAction = 'Replace';
1894 $entityAction = ucwords($action);
1897 $this->tidyExampleResult($result);
1898 if(isset($params['version'])) {
1899 unset($params['version']);
1901 // a cleverer person than me would do it in a single regex
1902 if (strstr($entity, 'UF')) {
1903 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1906 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1908 $smarty = CRM_Core_Smarty
::singleton();
1909 $smarty->assign('testfunction', $function);
1910 $function = $fnPrefix . "_" . strtolower($action);
1911 $smarty->assign('function', $function);
1912 $smarty->assign('fnPrefix', $fnPrefix);
1913 $smarty->assign('params', $params);
1914 $smarty->assign('entity', $entity);
1915 $smarty->assign('filename', basename($filename));
1916 $smarty->assign('description', $description);
1917 $smarty->assign('result', $result);
1919 $smarty->assign('action', $action);
1920 if (empty($subfile)) {
1921 $subfile = $entityAction;
1923 if (file_exists('../tests/templates/documentFunction.tpl')) {
1924 if (!is_dir("../api/v3/examples/$entity")) {
1925 mkdir("../api/v3/examples/$entity");
1927 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1928 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1934 * Tidy up examples array so that fields that change often ..don't
1935 * and debug related fields are unset
1936 * @param array $params
1938 function tidyExampleResult(&$result){
1939 if(!is_array($result)) {
1942 $fieldsToChange = array(
1943 'hash' => '67eac7789eaee00',
1944 'modified_date' => '2012-11-14 16:02:35',
1945 'created_date' => '2013-07-28 08:49:19',
1946 'create_date' => '20120130621222105',
1947 'application_received_date' => '20130728084957',
1948 'in_date' => '2013-07-28 08:50:19',
1949 'scheduled_date' => '20130728085413',
1950 'approval_date' => '20130728085413',
1951 'pledge_start_date_high' => '20130726090416',
1952 'start_date' => '2013-07-29 00:00:00',
1953 'event_start_date' => '2013-07-29 00:00:00',
1954 'end_date' => '2013-08-04 00:00:00',
1955 'event_end_date' => '2013-08-04 00:00:00',
1956 'decision_date' => '20130805000000',
1959 $keysToUnset = array('xdebug', 'undefined_fields',);
1960 foreach ($keysToUnset as $unwantedKey) {
1961 if(isset($result[$unwantedKey])) {
1962 unset($result[$unwantedKey]);
1965 if (isset($result['values'])) {
1966 if(!is_array($result['values'])) {
1969 $resultArray = &$result['values'];
1971 elseif(is_array($result)) {
1972 $resultArray = &$result;
1978 foreach ($resultArray as $index => &$values) {
1979 if(!is_array($values)) {
1982 foreach($values as $key => &$value) {
1983 if(substr($key, 0, 3) == 'api' && is_array($value)) {
1984 if(isset($value['is_error'])) {
1985 // we have a std nested result format
1986 $this->tidyExampleResult($value);
1989 foreach ($value as &$nestedResult) {
1990 // this is an alternative syntax for nested results a keyed array of results
1991 $this->tidyExampleResult($nestedResult);
1995 if(in_array($key, $keysToUnset)) {
1996 unset($values[$key]);
1999 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2000 $value = $fieldsToChange[$key];
2002 if(is_string($value)) {
2003 $value = addslashes($value);
2010 * Function to delete note
2012 * @params int $noteID
2015 function noteDelete($params) {
2016 return $this->callAPISuccess('Note', 'delete', $params);
2020 * Function to create custom field with Option Values
2022 * @param array $customGroup
2023 * @param string $name name of custom field
2025 function customFieldOptionValueCreate($customGroup, $name) {
2026 $fieldParams = array(
2027 'custom_group_id' => $customGroup['id'],
2028 'name' => 'test_custom_group',
2029 'label' => 'Country',
2030 'html_type' => 'Select',
2031 'data_type' => 'String',
2034 'is_searchable' => 0,
2038 $optionGroup = array(
2040 'name' => 'option_group1',
2041 'label' => 'option_group_label1',
2044 $optionValue = array(
2045 'option_label' => array('Label1', 'Label2'),
2046 'option_value' => array('value1', 'value2'),
2047 'option_name' => array($name . '_1', $name . '_2'),
2048 'option_weight' => array(1, 2),
2049 'option_status' => 1,
2052 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2054 return $this->callAPISuccess('custom_field', 'create', $params);
2057 function confirmEntitiesDeleted($entities) {
2058 foreach ($entities as $entity) {
2060 $result = $this->callAPISuccess($entity, 'Get', array());
2061 if ($result['error'] == 1 ||
$result['count'] > 0) {
2062 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2068 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2069 if ($dropCustomValueTables) {
2070 $tablesToTruncate[] = 'civicrm_custom_group';
2071 $tablesToTruncate[] = 'civicrm_custom_field';
2074 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2075 foreach ($tablesToTruncate as $table) {
2076 $sql = "TRUNCATE TABLE $table";
2077 CRM_Core_DAO
::executeQuery($sql);
2079 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2081 if ($dropCustomValueTables) {
2082 $dbName = self
::getDBName();
2084 SELECT TABLE_NAME as tableName
2085 FROM INFORMATION_SCHEMA.TABLES
2086 WHERE TABLE_SCHEMA = '{$dbName}'
2087 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2090 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2091 while ($tableDAO->fetch()) {
2092 $sql = "DROP TABLE {$tableDAO->tableName}";
2093 CRM_Core_DAO
::executeQuery($sql);
2099 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2100 * Default behaviour is to also delete the entity
2101 * @param array $params params array to check agains
2102 * @param int $id id of the entity concerned
2103 * @param string $entity name of entity concerned (e.g. membership)
2104 * @param bool $delete should the entity be deleted as part of this check
2105 * @param string $errorText text to print on error
2108 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2110 $result = $this->callAPISuccessGetSingle($entity, array(
2115 $this->callAPISuccess($entity, 'Delete', array(
2119 $dateFields = $keys = $dateTimeFields = array();
2120 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2121 foreach ($fields['values'] as $field => $settings) {
2122 if (array_key_exists($field, $result)) {
2123 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2126 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2128 $type = CRM_Utils_Array
::value('type', $settings);
2129 if ($type == CRM_Utils_Type
::T_DATE
) {
2130 $dateFields[] = $settings['name'];
2131 // we should identify both real names & unique names as dates
2132 if($field != $settings['name']) {
2133 $dateFields[] = $field;
2136 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2137 $dateTimeFields[] = $settings['name'];
2138 // we should identify both real names & unique names as dates
2139 if($field != $settings['name']) {
2140 $dateTimeFields[] = $field;
2145 if (strtolower($entity) == 'contribution') {
2146 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2147 // this is not returned in id format
2148 unset($params['payment_instrument_id']);
2149 $params['contribution_source'] = $params['source'];
2150 unset($params['source']);
2153 foreach ($params as $key => $value) {
2154 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2157 if (in_array($key, $dateFields)) {
2158 $value = date('Y-m-d', strtotime($value));
2159 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2161 if (in_array($key, $dateTimeFields)) {
2162 $value = date('Y-m-d H:i:s', strtotime($value));
2163 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2165 $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);
2170 * Function to get formatted values in the actual and expected result
2171 * @param array $actual actual calculated values
2172 * @param array $expected expected values
2175 function checkArrayEquals(&$actual, &$expected) {
2176 self
::unsetId($actual);
2177 self
::unsetId($expected);
2178 $this->assertEquals($actual, $expected);
2182 * Function to unset the key 'id' from the array
2183 * @param array $unformattedArray The array from which the 'id' has to be unset
2186 static function unsetId(&$unformattedArray) {
2187 $formattedArray = array();
2188 if (array_key_exists('id', $unformattedArray)) {
2189 unset($unformattedArray['id']);
2191 if (CRM_Utils_Array
::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2192 foreach ($unformattedArray['values'] as $key => $value) {
2193 if (is_Array($value)) {
2194 foreach ($value as $k => $v) {
2200 elseif ($key == 'id') {
2201 $unformattedArray[$key];
2203 $formattedArray = array($value);
2205 $unformattedArray['values'] = $formattedArray;
2210 * Helper to enable/disable custom directory support
2212 * @param array $customDirs with members:
2213 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2214 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2216 function customDirectories($customDirs) {
2217 require_once 'CRM/Core/Config.php';
2218 $config = CRM_Core_Config
::singleton();
2220 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2221 unset($config->customPHPPathDir
);
2223 elseif ($customDirs['php_path'] === TRUE) {
2224 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2227 $config->customPHPPathDir
= $php_path;
2230 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2231 unset($config->customTemplateDir
);
2233 elseif ($customDirs['template_path'] === TRUE) {
2234 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2237 $config->customTemplateDir
= $template_path;
2242 * Generate a temporary folder
2246 function createTempDir($prefix = 'test-') {
2247 $tempDir = CRM_Utils_File
::tempdir($prefix);
2248 $this->tempDirs
[] = $tempDir;
2252 function cleanTempDirs() {
2253 if (!is_array($this->tempDirs
)) {
2254 // fix test errors where this is not set
2257 foreach ($this->tempDirs
as $tempDir) {
2258 if (is_dir($tempDir)) {
2259 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2265 * Temporarily replace the singleton extension with a different one
2267 function setExtensionSystem(CRM_Extension_System
$system) {
2268 if ($this->origExtensionSystem
== NULL) {
2269 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2271 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2274 function unsetExtensionSystem() {
2275 if ($this->origExtensionSystem
!== NULL) {
2276 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2277 $this->origExtensionSystem
= NULL;
2282 * Temporarily alter the settings-metadata to add a mock setting.
2284 * WARNING: The setting metadata will disappear on the next cache-clear.
2289 function setMockSettingsMetaData($extras) {
2290 CRM_Core_BAO_Setting
::$_cache = array();
2291 $this->callAPISuccess('system','flush', array());
2292 CRM_Core_BAO_Setting
::$_cache = array();
2294 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2295 $metadata = array_merge($metadata, $extras);
2298 $fields = $this->callAPISuccess('setting', 'getfields', array());
2299 foreach ($extras as $key => $spec) {
2300 $this->assertNotEmpty($spec['title']);
2301 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2305 function financialAccountDelete($name) {
2306 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2307 $financialAccount->name
= $name;
2308 if($financialAccount->find(TRUE)) {
2309 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2310 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2311 $entityFinancialType->delete();
2312 $financialAccount->delete();
2317 * Use $ids as an instruction to do test cleanup
2319 function deleteFromIDSArray() {
2320 foreach ($this->ids
as $entity => $ids) {
2321 foreach ($ids as $id) {
2322 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2328 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2329 * (NB unclear if this is still required)
2331 function _sethtmlGlobals() {
2332 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2333 'required' => array(
2334 'html_quickform_rule_required',
2335 'HTML/QuickForm/Rule/Required.php'
2337 'maxlength' => array(
2338 'html_quickform_rule_range',
2339 'HTML/QuickForm/Rule/Range.php'
2341 'minlength' => array(
2342 'html_quickform_rule_range',
2343 'HTML/QuickForm/Rule/Range.php'
2345 'rangelength' => array(
2346 'html_quickform_rule_range',
2347 'HTML/QuickForm/Rule/Range.php'
2350 'html_quickform_rule_email',
2351 'HTML/QuickForm/Rule/Email.php'
2354 'html_quickform_rule_regex',
2355 'HTML/QuickForm/Rule/Regex.php'
2357 'lettersonly' => array(
2358 'html_quickform_rule_regex',
2359 'HTML/QuickForm/Rule/Regex.php'
2361 'alphanumeric' => array(
2362 'html_quickform_rule_regex',
2363 'HTML/QuickForm/Rule/Regex.php'
2366 'html_quickform_rule_regex',
2367 'HTML/QuickForm/Rule/Regex.php'
2369 'nopunctuation' => array(
2370 'html_quickform_rule_regex',
2371 'HTML/QuickForm/Rule/Regex.php'
2374 'html_quickform_rule_regex',
2375 'HTML/QuickForm/Rule/Regex.php'
2377 'callback' => array(
2378 'html_quickform_rule_callback',
2379 'HTML/QuickForm/Rule/Callback.php'
2382 'html_quickform_rule_compare',
2383 'HTML/QuickForm/Rule/Compare.php'
2386 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2387 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2389 'HTML/QuickForm/group.php',
2390 'HTML_QuickForm_group'
2393 'HTML/QuickForm/hidden.php',
2394 'HTML_QuickForm_hidden'
2397 'HTML/QuickForm/reset.php',
2398 'HTML_QuickForm_reset'
2400 'checkbox' => array(
2401 'HTML/QuickForm/checkbox.php',
2402 'HTML_QuickForm_checkbox'
2405 'HTML/QuickForm/file.php',
2406 'HTML_QuickForm_file'
2409 'HTML/QuickForm/image.php',
2410 'HTML_QuickForm_image'
2412 'password' => array(
2413 'HTML/QuickForm/password.php',
2414 'HTML_QuickForm_password'
2417 'HTML/QuickForm/radio.php',
2418 'HTML_QuickForm_radio'
2421 'HTML/QuickForm/button.php',
2422 'HTML_QuickForm_button'
2425 'HTML/QuickForm/submit.php',
2426 'HTML_QuickForm_submit'
2429 'HTML/QuickForm/select.php',
2430 'HTML_QuickForm_select'
2432 'hiddenselect' => array(
2433 'HTML/QuickForm/hiddenselect.php',
2434 'HTML_QuickForm_hiddenselect'
2437 'HTML/QuickForm/text.php',
2438 'HTML_QuickForm_text'
2440 'textarea' => array(
2441 'HTML/QuickForm/textarea.php',
2442 'HTML_QuickForm_textarea'
2444 'fckeditor' => array(
2445 'HTML/QuickForm/fckeditor.php',
2446 'HTML_QuickForm_FCKEditor'
2449 'HTML/QuickForm/tinymce.php',
2450 'HTML_QuickForm_TinyMCE'
2452 'dojoeditor' => array(
2453 'HTML/QuickForm/dojoeditor.php',
2454 'HTML_QuickForm_dojoeditor'
2457 'HTML/QuickForm/link.php',
2458 'HTML_QuickForm_link'
2460 'advcheckbox' => array(
2461 'HTML/QuickForm/advcheckbox.php',
2462 'HTML_QuickForm_advcheckbox'
2465 'HTML/QuickForm/date.php',
2466 'HTML_QuickForm_date'
2469 'HTML/QuickForm/static.php',
2470 'HTML_QuickForm_static'
2473 'HTML/QuickForm/header.php',
2474 'HTML_QuickForm_header'
2477 'HTML/QuickForm/html.php',
2478 'HTML_QuickForm_html'
2480 'hierselect' => array(
2481 'HTML/QuickForm/hierselect.php',
2482 'HTML_QuickForm_hierselect'
2484 'autocomplete' => array(
2485 'HTML/QuickForm/autocomplete.php',
2486 'HTML_QuickForm_autocomplete'
2489 'HTML/QuickForm/xbutton.php',
2490 'HTML_QuickForm_xbutton'
2492 'advmultiselect' => array(
2493 'HTML/QuickForm/advmultiselect.php',
2494 'HTML_QuickForm_advmultiselect'
2500 * Create an instance of the paypal processor
2501 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2502 * this parent class & we don't have a structure for that yet
2503 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2504 * & the best protection agains that is the functions this class affords
2506 function paymentProcessorCreate($params = array()) {
2507 $params = array_merge(array(
2509 'domain_id' => CRM_Core_Config
::domainID(),
2510 'payment_processor_type_id' => 'PayPal',
2514 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2515 'password' => '1183377788',
2516 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2517 'url_site' => 'https://www.sandbox.paypal.com/',
2518 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2519 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2520 'class_name' => 'Payment_PayPalImpl',
2521 'billing_mode' => 3,
2522 'financial_type_id' => 1,
2525 if(!is_numeric($params['payment_processor_type_id'])) {
2526 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2528 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2529 'name' => $params['payment_processor_type_id'],
2533 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2534 return $result['id'];
2538 function CiviUnitTestCase_fatalErrorHandler($message) {
2539 throw new Exception("{$message['message']}: {$message['code']}");