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 $env = new CRM_Utils_Check_Env();
311 CRM_Utils_Check
::singleton()->assertValid($env->checkAll());
315 * Common setup functions for all unit tests
317 protected function setUp() {
318 CRM_Utils_Hook
::singleton(TRUE);
319 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
320 // Use a temporary file for STDIN
321 $GLOBALS['stdin'] = tmpfile();
322 if ($GLOBALS['stdin'] === FALSE) {
323 echo "Couldn't open temporary file\n";
327 // Get and save a connection to the database
328 $this->_dbconn
= $this->getConnection();
330 // reload database before each test
331 // $this->_populateDB();
333 // "initialize" CiviCRM to avoid problems when running single tests
334 // FIXME: look at it closer in second stage
336 // initialize the object once db is loaded
337 CRM_Core_Config
::$_mail = NULL;
338 $config = CRM_Core_Config
::singleton();
340 // when running unit tests, use mockup user framework
341 $config->setUserFramework('UnitTests');
343 // also fix the fatal error handler to throw exceptions,
345 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
347 // enable backtrace to get meaningful errors
348 $config->backtrace
= 1;
350 // disable any left-over test extensions
351 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
353 // reset all the caches
354 CRM_Utils_System
::flushCache();
356 // clear permissions stub to not check permissions
357 $config = CRM_Core_Config
::singleton();
358 $config->userPermissionClass
->permissions
= NULL;
360 //flush component settings
361 CRM_Core_Component
::getEnabledComponents(TRUE);
363 if ($this->_eNoticeCompliant
) {
364 error_reporting(E_ALL
);
367 error_reporting(E_ALL
& ~E_NOTICE
);
372 * emulate a logged in user since certain functions use that
373 * value to store a record in the DB (like activity)
376 public function createLoggedInUser() {
378 'first_name' => 'Logged In',
379 'last_name' => 'User ' . rand(),
380 'contact_type' => 'Individual',
382 $contactID = $this->individualCreate($params);
384 $session = CRM_Core_Session
::singleton();
385 $session->set('userID', $contactID);
388 public function cleanDB() {
389 self
::$populateOnce = NULL;
390 $this->DBResetRequired
= TRUE;
392 $this->_dbconn
= $this->getConnection();
393 static::_populateDB();
394 $this->tempDirs
= array();
398 * Common teardown functions for all unit tests
400 protected function tearDown() {
401 error_reporting(E_ALL
& ~E_NOTICE
);
402 $tablesToTruncate = array('civicrm_contact');
403 $this->quickCleanup($tablesToTruncate);
404 $this->cleanTempDirs();
405 $this->unsetExtensionSystem();
409 * FIXME: Maybe a better way to do it
411 function foreignKeyChecksOff() {
412 self
::$utils = new Utils($GLOBALS['mysql_host'],
413 $GLOBALS['mysql_port'],
414 $GLOBALS['mysql_user'],
415 $GLOBALS['mysql_pass']
417 $dbName = self
::getDBName();
418 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
419 if (self
::$utils->do_query($query) === FALSE) {
421 echo 'Cannot set foreign_key_checks = 0';
427 function foreignKeyChecksOn() {
428 // FIXME: might not be needed if previous fixme implemented
432 * Generic function to compare expected values after an api call to retrieved
435 * @daoName string DAO Name of object we're evaluating.
436 * @id int Id of object
437 * @match array Associative array of field name => expected value. Empty if asserting
438 * that a DELETE occurred
439 * @delete boolean True if we're checking that a DELETE action occurred.
441 function assertDBState($daoName, $id, $match, $delete = FALSE) {
443 // adding this here since developers forget to check for an id
444 // and hence we get the first value in the db
445 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
448 $object = new $daoName();
452 // If we're asserting successful record deletion, make sure object is NOT found.
454 if ($object->find(TRUE)) {
455 $this->fail("Object not deleted by delete operation: $daoName, $id");
460 // Otherwise check matches of DAO field values against expected values in $match.
461 if ($object->find(TRUE)) {
462 $fields = & $object->fields();
463 foreach ($fields as $name => $value) {
464 $dbName = $value['name'];
465 if (isset($match[$name])) {
467 $this->assertEquals($object->$dbName, $match[$name]);
469 elseif (isset($match[$dbName])) {
471 $this->assertEquals($object->$dbName, $match[$dbName]);
476 $this->fail("Could not retrieve object: $daoName, $id");
479 $matchSize = count($match);
480 if ($verifiedCount != $matchSize) {
481 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
485 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
486 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
487 if (empty($searchValue)) {
488 $this->fail("empty value passed to assertDBNotNull");
490 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
491 $this->assertNotNull($value, $message);
496 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
497 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
498 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
499 $this->assertNull($value, $message);
502 // Request a record from the DB by id. Success if row not found.
503 function assertDBRowNotExist($daoName, $id, $message = NULL) {
504 $message = $message ?
$message : "$daoName (#$id) should not exist";
505 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
506 $this->assertNull($value, $message);
509 // Request a record from the DB by id. Success if row not found.
510 function assertDBRowExist($daoName, $id, $message = NULL) {
511 $message = $message ?
$message : "$daoName (#$id) should exist";
512 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
513 $this->assertEquals($id, $value, $message);
516 // Compare a single column value in a retrieved DB record to an expected value
517 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
518 $expectedValue, $message
520 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
521 $this->assertEquals($value, $expectedValue, $message);
524 // Compare all values in a single retrieved DB record to an array of expected values
525 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
526 //get the values from db
528 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
530 // compare db values with expected values
531 self
::assertAttributesEquals($expectedValues, $dbValues);
535 * Assert that a SQL query returns a given value
537 * The first argument is an expected value. The remaining arguments are passed
538 * to CRM_Core_DAO::singleValueQuery
540 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
541 * array(1 => array("Whiz", "String")));
543 function assertDBQuery($expected, $query, $params = array()) {
544 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
545 $this->assertEquals($expected, $actual,
546 sprintf('expected=[%s] actual=[%s] query=[%s]',
547 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
553 * Assert that two array-trees are exactly equal, notwithstanding
554 * the sorting of keys
556 * @param array $expected
557 * @param array $actual
559 function assertTreeEquals($expected, $actual) {
562 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
563 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
567 $this->assertEquals($e, $a);
571 * Assert that two numbers are approximately equal
573 * @param int|float $expected
574 * @param int|float $actual
575 * @param int|float $tolerance
576 * @param string $message
578 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
579 if ($message === NULL) {
580 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
582 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
585 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
586 foreach ($expectedValues as $paramName => $paramValue) {
587 if (isset($actualValues[$paramName])) {
588 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
591 $this->fail("Attribute '$paramName' not present in actual array.");
596 function assertArrayKeyExists($key, &$list) {
597 $result = isset($list[$key]) ?
TRUE : FALSE;
598 $this->assertTrue($result, ts("%1 element exists?",
603 function assertArrayValueNotNull($key, &$list) {
604 $this->assertArrayKeyExists($key, $list);
606 $value = isset($list[$key]) ?
$list[$key] : NULL;
607 $this->assertTrue($value,
608 ts("%1 element not null?",
615 * check that api returned 'is_error' => 0
616 * else provide full message
617 * @param array $apiResult api result
618 * @param string $prefix extra test to add to message
620 function assertAPISuccess($apiResult, $prefix = '') {
621 if (!empty($prefix)) {
624 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
626 if(!empty($apiResult['debug_information'])) {
627 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
629 if(!empty($apiResult['trace'])){
630 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
632 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
636 * check that api returned 'is_error' => 1
637 * else provide full message
638 * @param array $apiResult api result
639 * @param string $prefix extra test to add to message
641 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
642 if (!empty($prefix)) {
645 if($expectedError && !empty($apiResult['is_error'])){
646 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
648 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
649 $this->assertNotEmpty($apiResult['error_message']);
652 function assertType($expected, $actual, $message = '') {
653 return $this->assertInternalType($expected, $actual, $message);
657 * check that a deleted item has been deleted
659 function assertAPIDeleted($entity, $id) {
660 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
665 * check that api returned 'is_error' => 1
666 * else provide full message
667 * @param array $apiResult api result
668 * @param string $prefix extra test to add to message
670 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
671 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
672 foreach ($valuesToExclude as $value) {
673 if(isset($result[$value])) {
674 unset($result[$value]);
676 if(isset($expected[$value])) {
677 unset($expected[$value]);
680 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
684 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
691 function civicrm_api($entity, $action, $params) {
692 return civicrm_api($entity, $action, $params);
696 * This function exists to wrap api functions
697 * so we can ensure they succeed & throw exceptions without litterering the test with checks
698 * @param string $entity
699 * @param string $action
700 * @param array $params
701 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
702 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
703 * for getsingle the array is compared against an array passed in - the id is not compared (for
706 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
707 $params = array_merge(array(
708 'version' => $this->_apiversion
,
713 switch (strtolower($action)) {
715 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
717 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
719 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
721 $result = $this->civicrm_api($entity, $action, $params);
722 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
727 * This function exists to wrap api getValue function & check the result
728 * so we can ensure they succeed & throw exceptions without litterering the test with checks
729 * There is a type check in this
730 * @param string $entity
731 * @param array $params
732 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
740 function callAPISuccessGetValue($entity, $params, $type = NULL) {
742 'version' => $this->_apiversion
,
745 $result = $this->civicrm_api($entity, 'getvalue', $params);
747 if($type == 'integer'){
748 // api seems to return integers as strings
749 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
752 $this->assertType($type, $result, "returned result should have been of type $type but was " );
759 * This function exists to wrap api getsingle function & check the result
760 * so we can ensure they succeed & throw exceptions without litterering the test with checks
761 * @param string $entity
762 * @param array $params
763 * @param array $checkAgainst - array to compare result against
771 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
773 'version' => $this->_apiversion
,
776 $result = $this->civicrm_api($entity, 'getsingle', $params);
777 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
778 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
781 // @todo - have gone with the fn that unsets id? should we check id?
782 $this->checkArrayEquals($result, $checkAgainst);
787 * This function exists to wrap api getValue function & check the result
788 * so we can ensure they succeed & throw exceptions without litterering the test with checks
789 * There is a type check in this
790 * @param string $entity
791 * @param array $params
792 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
800 function callAPISuccessGetCount($entity, $params, $count = NULL) {
802 'version' => $this->_apiversion
,
805 $result = $this->civicrm_api($entity, 'getcount', $params);
806 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
807 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
810 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
816 * This function exists to wrap api functions
817 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
819 * @param string $entity
820 * @param string $action
821 * @param array $params
822 * @param string $function - pass this in to create a generated example
823 * @param string $file - pass this in to create a generated example
824 * @param string $description
825 * @param string|null $subfile
826 * @param string|null $actionName
829 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
830 $params['version'] = $this->_apiversion
;
831 $result = $this->callAPISuccess($entity, $action, $params);
832 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
837 * This function exists to wrap api functions
838 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
839 * @param string $entity
840 * @param string $action
841 * @param array $params
842 * @param string $expectedErrorMessage error
844 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
845 if (is_array($params)) {
847 'version' => $this->_apiversion
,
850 $result = $this->civicrm_api($entity, $action, $params);
851 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
856 * Create required data based on $this->entity & $this->params
857 * This is just a way to set up the test data for delete & get functions
858 * so the distinction between set
859 * up & tested functions is clearer
861 * @return array api Result
863 public function createTestEntity(){
864 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
868 * Generic function to create Organisation, to be used in test cases
870 * @param array parameters for civicrm_contact_add api function call
872 * @return int id of Organisation created
874 function organizationCreate($params = array()) {
879 'organization_name' => 'Unit Test Organization',
880 'contact_type' => 'Organization',
882 return $this->_contactCreate(array_merge($orgParams, $params));
886 * Generic function to create Individual, to be used in test cases
888 * @param array parameters for civicrm_contact_add api function call
890 * @return int id of Individual created
892 function individualCreate($params = array()) {
893 $params = array_merge(array(
894 'first_name' => 'Anthony',
895 'middle_name' => 'J.',
896 'last_name' => 'Anderson',
899 'email' => 'anthony_anderson@civicrm.org',
900 'contact_type' => 'Individual',
903 return $this->_contactCreate($params);
907 * Generic function to create Household, to be used in test cases
909 * @param array parameters for civicrm_contact_add api function call
911 * @return int id of Household created
913 function householdCreate($params = array()) {
914 $params = array_merge(array(
915 'household_name' => 'Unit Test household',
916 'contact_type' => 'Household',
918 return $this->_contactCreate($params);
922 * Private helper function for calling civicrm_contact_add
927 * @internal param \parameters $array for civicrm_contact_add api function call
929 * @return int id of Household created
931 private function _contactCreate($params) {
932 $result = $this->callAPISuccess('contact', 'create', $params);
933 if (!empty($result['is_error']) ||
empty($result['id'])) {
934 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
936 return $result['id'];
939 function contactDelete($contactID) {
942 'skip_undelete' => 1,
945 $domain = new CRM_Core_BAO_Domain
;
946 $domain->contact_id
= $contactID;
947 if ($domain->find(TRUE)) {
948 // we are finding tests trying to delete the domain contact in cleanup
949 //since this is mainly for cleanup lets put a safeguard here
952 $result = $this->callAPISuccess('contact', 'delete', $params);
956 function contactTypeDelete($contactTypeId) {
957 require_once 'CRM/Contact/BAO/ContactType.php';
958 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
960 throw new Exception('Could not delete contact type');
964 function membershipTypeCreate($params = array()) {
965 CRM_Member_PseudoConstant
::flush('membershipType');
966 CRM_Core_Config
::clearDBCache();
967 $params = array_merge(array(
969 'duration_unit' => 'year',
970 'duration_interval' => 1,
971 'period_type' => 'rolling',
972 'member_of_contact_id' => 1,
974 'financial_type_id' => 1,
980 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
982 CRM_Member_PseudoConstant
::flush('membershipType');
983 CRM_Utils_Cache
::singleton()->flush();
985 return $result['id'];
988 function contactMembershipCreate($params) {
990 'join_date' => '2007-01-21',
991 'start_date' => '2007-01-21',
992 'end_date' => '2007-12-21',
993 'source' => 'Payment',
996 foreach ($pre as $key => $val) {
997 if (!isset($params[$key])) {
998 $params[$key] = $val;
1002 $result = $this->callAPISuccess('Membership', 'create', $params);
1003 return $result['id'];
1007 * Function to delete Membership Type
1009 * @param int $membershipTypeID
1011 function membershipTypeDelete($params) {
1012 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1016 function membershipDelete($membershipID) {
1017 $deleteParams = array('id' => $membershipID);
1018 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1022 function membershipStatusCreate($name = 'test member status') {
1023 $params['name'] = $name;
1024 $params['start_event'] = 'start_date';
1025 $params['end_event'] = 'end_date';
1026 $params['is_current_member'] = 1;
1027 $params['is_active'] = 1;
1029 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1030 CRM_Member_PseudoConstant
::flush('membershipStatus');
1031 return $result['id'];
1034 function membershipStatusDelete($membershipStatusID) {
1035 if (!$membershipStatusID) {
1038 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1042 function relationshipTypeCreate($params = array()) {
1043 $params = array_merge(array(
1044 'name_a_b' => 'Relation 1 for relationship type create',
1045 'name_b_a' => 'Relation 2 for relationship type create',
1046 'contact_type_a' => 'Individual',
1047 'contact_type_b' => 'Organization',
1054 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1055 CRM_Core_PseudoConstant
::flush('relationshipType');
1057 return $result['id'];
1061 * Function to delete Relatinship Type
1063 * @param int $relationshipTypeID
1065 function relationshipTypeDelete($relationshipTypeID) {
1066 $params['id'] = $relationshipTypeID;
1067 $this->callAPISuccess('relationship_type', 'delete', $params);
1070 function paymentProcessorTypeCreate($params = NULL) {
1071 if (is_null($params)) {
1073 'name' => 'API_Test_PP',
1074 'title' => 'API Test Payment Processor',
1075 'class_name' => 'CRM_Core_Payment_APITest',
1076 'billing_mode' => 'form',
1082 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1084 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1086 return $result['id'];
1090 * Function to create Participant
1092 * @param array $params array of contact id and event id values
1094 * @return int $id of participant created
1096 function participantCreate($params) {
1097 if(empty($params['contact_id'])){
1098 $params['contact_id'] = $this->individualCreate();
1100 if(empty($params['event_id'])){
1101 $event = $this->eventCreate();
1102 $params['event_id'] = $event['id'];
1107 'register_date' => 20070219,
1108 'source' => 'Wimbeldon',
1109 'event_level' => 'Payment',
1113 $params = array_merge($defaults, $params);
1114 $result = $this->callAPISuccess('Participant', 'create', $params);
1115 return $result['id'];
1119 * Function to create Payment Processor
1121 * @return object of Payment Processsor
1123 function processorCreate() {
1124 $processorParams = array(
1127 'payment_processor_type_id' => 10,
1128 'financial_account_id' => 12,
1131 'url_site' => 'http://dummy.com',
1132 'url_recur' => 'http://dummy.com',
1133 'billing_mode' => 1,
1135 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1136 return $paymentProcessor;
1140 * Function to create contribution page
1142 * @return object of contribution page
1144 function contributionPageCreate($params) {
1145 $this->_pageParams
= array(
1146 'title' => 'Test Contribution Page',
1147 'financial_type_id' => 1,
1148 'currency' => 'USD',
1149 'financial_account_id' => 1,
1150 'payment_processor' => $params['processor_id'],
1152 'is_allow_other_amount' => 1,
1154 'max_amount' => 1000,
1156 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1157 return $contributionPage;
1161 * Function to create Tag
1163 * @return array result of created tag
1165 function tagCreate($params = array()) {
1167 'name' => 'New Tag3',
1168 'description' => 'This is description for Our New Tag ',
1171 $params = array_merge($defaults, $params);
1172 $result = $this->callAPISuccess('Tag', 'create', $params);
1173 return $result['values'][$result['id']];
1177 * Function to delete Tag
1179 * @param int $tagId id of the tag to be deleted
1181 function tagDelete($tagId) {
1182 require_once 'api/api.php';
1186 $result = $this->callAPISuccess('Tag', 'delete', $params);
1187 return $result['id'];
1191 * Add entity(s) to the tag
1193 * @param array $params
1195 function entityTagAdd($params) {
1196 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1201 * Function to create contribution
1203 * @param int $cID contact_id
1204 * @param int $cTypeID id of financial type
1206 * @return int id of created contribution
1208 function pledgeCreate($cID) {
1210 'contact_id' => $cID,
1211 'pledge_create_date' => date('Ymd'),
1212 'start_date' => date('Ymd'),
1213 'scheduled_date' => date('Ymd'),
1215 'pledge_status_id' => '2',
1216 'financial_type_id' => '1',
1217 'pledge_original_installment_amount' => 20,
1218 'frequency_interval' => 5,
1219 'frequency_unit' => 'year',
1220 'frequency_day' => 15,
1221 'installments' => 5,
1224 $result = $this->callAPISuccess('Pledge', 'create', $params);
1225 return $result['id'];
1229 * Function to delete contribution
1231 * @param int $contributionId
1233 function pledgeDelete($pledgeId) {
1235 'pledge_id' => $pledgeId,
1237 $this->callAPISuccess('Pledge', 'delete', $params);
1241 * Function to create contribution
1243 * @param int $cID contact_id
1244 * @param int $cTypeID id of financial type
1246 * @return int id of created contribution
1248 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1251 'contact_id' => $cID,
1252 'receive_date' => date('Ymd'),
1253 'total_amount' => 100.00,
1254 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1255 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1256 'non_deductible_amount' => 10.00,
1257 'trxn_id' => $trxnID,
1258 'invoice_id' => $invoiceID,
1260 'contribution_status_id' => 1,
1261 // 'note' => 'Donating for Nobel Cause', *Fixme
1265 $params['fee_amount'] = 5.00;
1266 $params['net_amount'] = 95.00;
1269 $result = $this->callAPISuccess('contribution', 'create', $params);
1270 return $result['id'];
1274 * Function to create online contribution
1276 * @param int $financialType id of financial type
1278 * @return int id of created contribution
1280 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1281 $contribParams = array(
1282 'contact_id' => $params['contact_id'],
1283 'receive_date' => date('Ymd'),
1284 'total_amount' => 100.00,
1285 'financial_type_id' => $financialType,
1286 'contribution_page_id' => $params['contribution_page_id'],
1288 'invoice_id' => 67890,
1291 $contribParams = array_merge($contribParams, $params);
1292 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1294 return $result['id'];
1298 * Function to delete contribution
1300 * @param int $contributionId
1302 function contributionDelete($contributionId) {
1304 'contribution_id' => $contributionId,
1306 $result = $this->callAPISuccess('contribution', 'delete', $params);
1311 * Function to create an Event
1313 * @param array $params name-value pair for an event
1315 * @return array $event
1317 function eventCreate($params = array()) {
1318 // if no contact was passed, make up a dummy event creator
1319 if (!isset($params['contact_id'])) {
1320 $params['contact_id'] = $this->_contactCreate(array(
1321 'contact_type' => 'Individual',
1322 'first_name' => 'Event',
1323 'last_name' => 'Creator',
1327 // set defaults for missing params
1328 $params = array_merge(array(
1329 'title' => 'Annual CiviCRM meet',
1330 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1331 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1332 'event_type_id' => 1,
1334 'start_date' => 20081021,
1335 'end_date' => 20081023,
1336 'is_online_registration' => 1,
1337 'registration_start_date' => 20080601,
1338 'registration_end_date' => 20081015,
1339 'max_participants' => 100,
1340 'event_full_text' => 'Sorry! We are already full',
1343 'is_show_location' => 0,
1346 return $this->callAPISuccess('Event', 'create', $params);
1350 * Function to delete event
1352 * @param int $id ID of the event
1354 function eventDelete($id) {
1358 return $this->callAPISuccess('event', 'delete', $params);
1362 * Function to delete participant
1364 * @param int $participantID
1366 function participantDelete($participantID) {
1368 'id' => $participantID,
1370 return $this->callAPISuccess('Participant', 'delete', $params);
1374 * Function to create participant payment
1376 * @return int $id of created payment
1378 function participantPaymentCreate($participantID, $contributionID = NULL) {
1379 //Create Participant Payment record With Values
1381 'participant_id' => $participantID,
1382 'contribution_id' => $contributionID,
1385 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1386 return $result['id'];
1390 * Function to delete participant payment
1392 * @param int $paymentID
1394 function participantPaymentDelete($paymentID) {
1398 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1402 * Function to add a Location
1404 * @return int location id of created location
1406 function locationAdd($contactID) {
1409 'location_type' => 'New Location Type',
1411 'name' => 'Saint Helier St',
1412 'county' => 'Marin',
1413 'country' => 'United States',
1414 'state_province' => 'Michigan',
1415 'supplemental_address_1' => 'Hallmark Ct',
1416 'supplemental_address_2' => 'Jersey Village',
1421 'contact_id' => $contactID,
1422 'address' => $address,
1423 'location_format' => '2.0',
1424 'location_type' => 'New Location Type',
1427 $result = $this->callAPISuccess('Location', 'create', $params);
1432 * Function to delete Locations of contact
1434 * @params array $pamars parameters
1436 function locationDelete($params) {
1437 $result = $this->callAPISuccess('Location', 'delete', $params);
1441 * Function to add a Location Type
1443 * @return int location id of created location
1445 function locationTypeCreate($params = NULL) {
1446 if ($params === NULL) {
1448 'name' => 'New Location Type',
1449 'vcard_name' => 'New Location Type',
1450 'description' => 'Location Type for Delete',
1455 $locationType = new CRM_Core_DAO_LocationType();
1456 $locationType->copyValues($params);
1457 $locationType->save();
1458 // clear getfields cache
1459 CRM_Core_PseudoConstant
::flush();
1460 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1461 return $locationType;
1465 * Function to delete a Location Type
1467 * @param int location type id
1469 function locationTypeDelete($locationTypeId) {
1470 $locationType = new CRM_Core_DAO_LocationType();
1471 $locationType->id
= $locationTypeId;
1472 $locationType->delete();
1476 * Function to add a Group
1478 * @params array to add group
1480 * @return int groupId of created group
1483 function groupCreate($params = array()) {
1484 $params = array_merge(array(
1485 'name' => 'Test Group 1',
1487 'title' => 'New Test Group Created',
1488 'description' => 'New Test Group Created',
1490 'visibility' => 'Public Pages',
1491 'group_type' => array(
1497 $result = $this->callAPISuccess('Group', 'create', $params);
1498 return $result['id'];
1502 * Function to delete a Group
1506 function groupDelete($gid) {
1512 $this->callAPISuccess('Group', 'delete', $params);
1517 * @param array $params
1519 function uFFieldCreate($params = array()) {
1520 $params = array_merge(array(
1522 'field_name' => 'first_name',
1525 'visibility' => 'Public Pages and Listings',
1526 'is_searchable' => '1',
1527 'label' => 'first_name',
1528 'field_type' => 'Individual',
1531 $this->callAPISuccess('uf_field', 'create', $params);
1534 * Function to add a UF Join Entry
1536 * @return int $id of created UF Join
1538 function ufjoinCreate($params = NULL) {
1539 if ($params === NULL) {
1542 'module' => 'CiviEvent',
1543 'entity_table' => 'civicrm_event',
1549 $result = $this->callAPISuccess('uf_join', 'create', $params);
1554 * Function to delete a UF Join Entry
1556 * @param array with missing uf_group_id
1558 function ufjoinDelete($params = NULL) {
1559 if ($params === NULL) {
1562 'module' => 'CiviEvent',
1563 'entity_table' => 'civicrm_event',
1566 'uf_group_id' => '',
1570 crm_add_uf_join($params);
1574 * Function to create Group for a contact
1576 * @param int $contactId
1578 function contactGroupCreate($contactId) {
1580 'contact_id.1' => $contactId,
1584 $this->callAPISuccess('GroupContact', 'Create', $params);
1588 * Function to delete Group for a contact
1590 * @param array $params
1592 function contactGroupDelete($contactId) {
1594 'contact_id.1' => $contactId,
1597 $this->civicrm_api('GroupContact', 'Delete', $params);
1601 * Function to create Activity
1603 * @param int $contactId
1605 function activityCreate($params = NULL) {
1607 if ($params === NULL) {
1608 $individualSourceID = $this->individualCreate();
1610 $contactParams = array(
1611 'first_name' => 'Julia',
1612 'Last_name' => 'Anderson',
1614 'email' => 'julia_anderson@civicrm.org',
1615 'contact_type' => 'Individual',
1618 $individualTargetID = $this->individualCreate($contactParams);
1621 'source_contact_id' => $individualSourceID,
1622 'target_contact_id' => array($individualTargetID),
1623 'assignee_contact_id' => array($individualTargetID),
1624 'subject' => 'Discussion on warm beer',
1625 'activity_date_time' => date('Ymd'),
1626 'duration_hours' => 30,
1627 'duration_minutes' => 20,
1628 'location' => 'Baker Street',
1629 'details' => 'Lets schedule a meeting',
1631 'activity_name' => 'Meeting',
1635 $result = $this->callAPISuccess('Activity', 'create', $params);
1637 $result['target_contact_id'] = $individualTargetID;
1638 $result['assignee_contact_id'] = $individualTargetID;
1643 * Function to create an activity type
1645 * @params array $params parameters
1647 function activityTypeCreate($params) {
1648 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1653 * Function to delete activity type
1655 * @params Integer $activityTypeId id of the activity type
1657 function activityTypeDelete($activityTypeId) {
1658 $params['activity_type_id'] = $activityTypeId;
1659 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1664 * Function to create custom group
1666 * @param string $className
1667 * @param string $title name of custom group
1669 function customGroupCreate($params = array()) {
1671 'title' => 'new custom group',
1672 'extends' => 'Contact',
1674 'style' => 'Inline',
1678 $params = array_merge($defaults, $params);
1680 if (strlen($params['title']) > 13) {
1681 $params['title'] = substr($params['title'], 0, 13);
1684 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1685 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1687 return $this->callAPISuccess('custom_group', 'create', $params);
1691 * existing function doesn't allow params to be over-ridden so need a new one
1692 * this one allows you to only pass in the params you want to change
1694 function CustomGroupCreateByParams($params = array()) {
1696 'title' => "API Custom Group",
1697 'extends' => 'Contact',
1699 'style' => 'Inline',
1702 $params = array_merge($defaults, $params);
1703 return $this->callAPISuccess('custom_group', 'create', $params);
1707 * Create custom group with multi fields
1709 function CustomGroupMultipleCreateByParams($params = array()) {
1714 $params = array_merge($defaults, $params);
1715 return $this->CustomGroupCreateByParams($params);
1719 * Create custom group with multi fields
1721 function CustomGroupMultipleCreateWithFields($params = array()) {
1722 // also need to pass on $params['custom_field'] if not set but not in place yet
1724 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1725 $ids['custom_group_id'] = $customGroup['id'];
1727 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1729 $ids['custom_field_id'][] = $customField['id'];
1731 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1732 $ids['custom_field_id'][] = $customField['id'];
1734 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1735 $ids['custom_field_id'][] = $customField['id'];
1741 * Create a custom group with a single text custom field. See
1742 * participant:testCreateWithCustom for how to use this
1744 * @param string $function __FUNCTION__
1745 * @param string $file __FILE__
1747 * @return array $ids ids of created objects
1750 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1751 $params = array('title' => $function);
1752 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1753 $params['extends'] = $entity ?
$entity : 'Contact';
1754 $customGroup = $this->CustomGroupCreate($params);
1755 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1756 CRM_Core_PseudoConstant
::flush();
1758 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1762 * Function to delete custom group
1764 * @param int $customGroupID
1766 function customGroupDelete($customGroupID) {
1767 $params['id'] = $customGroupID;
1768 return $this->callAPISuccess('custom_group', 'delete', $params);
1772 * Function to create custom field
1774 * @param array $params (custom_group_id) is required
1775 * @param string $name name of custom field
1776 * @param int $apiversion API version to use
1778 function customFieldCreate($params) {
1779 $params = array_merge(array(
1780 'label' => 'Custom Field',
1781 'data_type' => 'String',
1782 'html_type' => 'Text',
1783 'is_searchable' => 1,
1785 'default_value' => 'defaultValue',
1788 $result = $this->callAPISuccess('custom_field', 'create', $params);
1790 if ($result['is_error'] == 0 && isset($result['id'])) {
1791 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1792 // force reset of enabled components to help grab custom fields
1793 CRM_Core_Component
::getEnabledComponents(1);
1799 * Function to delete custom field
1801 * @param int $customFieldID
1803 function customFieldDelete($customFieldID) {
1805 $params['id'] = $customFieldID;
1806 return $this->callAPISuccess('custom_field', 'delete', $params);
1810 * Function to create note
1812 * @params array $params name-value pair for an event
1814 * @return array $note
1816 function noteCreate($cId) {
1818 'entity_table' => 'civicrm_contact',
1819 'entity_id' => $cId,
1820 'note' => 'hello I am testing Note',
1821 'contact_id' => $cId,
1822 'modified_date' => date('Ymd'),
1823 'subject' => 'Test Note',
1826 return $this->callAPISuccess('Note', 'create', $params);
1830 * Enable CiviCampaign Component
1832 function enableCiviCampaign() {
1833 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1834 // force reload of config object
1835 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1836 //flush cache by calling with reset
1837 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1841 * Create test generated example in api/v3/examples.
1842 * To turn this off (e.g. on the server) set
1843 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1844 * in your settings file
1845 * @param array $params array as passed to civicrm_api function
1846 * @param array $result array as received from the civicrm_api function
1847 * @param string $function calling function - generally __FUNCTION__
1848 * @param string $filename called from file - generally __FILE__
1849 * @param string $description descriptive text for the example file
1850 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1851 * @param string $action - optional action - otherwise taken from function name
1853 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1854 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1857 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1858 //todo - this is a bit cludgey
1859 if (empty($action)) {
1860 if (strstr($function, 'Create')) {
1861 $action = empty($action) ?
'create' : $action;
1862 $entityAction = 'Create';
1864 elseif (strstr($function, 'GetSingle')) {
1865 $action = empty($action) ?
'getsingle' : $action;
1866 $entityAction = 'GetSingle';
1868 elseif (strstr($function, 'GetValue')) {
1869 $action = empty($action) ?
'getvalue' : $action;
1870 $entityAction = 'GetValue';
1872 elseif (strstr($function, 'GetCount')) {
1873 $action = empty($action) ?
'getcount' : $action;
1874 $entityAction = 'GetCount';
1876 elseif (strstr($function, 'GetFields')) {
1877 $action = empty($action) ?
'getfields' : $action;
1878 $entityAction = 'GetFields';
1880 elseif (strstr($function, 'GetList')) {
1881 $action = empty($action) ?
'getlist' : $action;
1882 $entityAction = 'GetList';
1884 elseif (strstr($function, 'Get')) {
1885 $action = empty($action) ?
'get' : $action;
1886 $entityAction = 'Get';
1888 elseif (strstr($function, 'Delete')) {
1889 $action = empty($action) ?
'delete' : $action;
1890 $entityAction = 'Delete';
1892 elseif (strstr($function, 'Update')) {
1893 $action = empty($action) ?
'update' : $action;
1894 $entityAction = 'Update';
1896 elseif (strstr($function, 'Subscribe')) {
1897 $action = empty($action) ?
'subscribe' : $action;
1898 $entityAction = 'Subscribe';
1900 elseif (strstr($function, 'Submit')) {
1901 $action = empty($action) ?
'submit' : $action;
1902 $entityAction = 'Submit';
1904 elseif (strstr($function, 'Apply')) {
1905 $action = empty($action) ?
'apply' : $action;
1906 $entityAction = 'Apply';
1908 elseif (strstr($function, 'Replace')) {
1909 $action = empty($action) ?
'replace' : $action;
1910 $entityAction = 'Replace';
1914 $entityAction = ucwords($action);
1917 $this->tidyExampleResult($result);
1918 if(isset($params['version'])) {
1919 unset($params['version']);
1921 // a cleverer person than me would do it in a single regex
1922 if (strstr($entity, 'UF')) {
1923 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1926 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1928 $smarty = CRM_Core_Smarty
::singleton();
1929 $smarty->assign('testfunction', $function);
1930 $function = $fnPrefix . "_" . strtolower($action);
1931 $smarty->assign('function', $function);
1932 $smarty->assign('fnPrefix', $fnPrefix);
1933 $smarty->assign('params', $params);
1934 $smarty->assign('entity', $entity);
1935 $smarty->assign('filename', basename($filename));
1936 $smarty->assign('description', $description);
1937 $smarty->assign('result', $result);
1939 $smarty->assign('action', $action);
1940 if (empty($subfile)) {
1941 $subfile = $entityAction;
1943 if (file_exists('../tests/templates/documentFunction.tpl')) {
1944 if (!is_dir("../api/v3/examples/$entity")) {
1945 mkdir("../api/v3/examples/$entity");
1947 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1948 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1954 * Tidy up examples array so that fields that change often ..don't
1955 * and debug related fields are unset
1956 * @param array $params
1958 function tidyExampleResult(&$result){
1959 if(!is_array($result)) {
1962 $fieldsToChange = array(
1963 'hash' => '67eac7789eaee00',
1964 'modified_date' => '2012-11-14 16:02:35',
1965 'created_date' => '2013-07-28 08:49:19',
1966 'create_date' => '20120130621222105',
1967 'application_received_date' => '20130728084957',
1968 'in_date' => '2013-07-28 08:50:19',
1969 'scheduled_date' => '20130728085413',
1970 'approval_date' => '20130728085413',
1971 'pledge_start_date_high' => '20130726090416',
1972 'start_date' => '2013-07-29 00:00:00',
1973 'event_start_date' => '2013-07-29 00:00:00',
1974 'end_date' => '2013-08-04 00:00:00',
1975 'event_end_date' => '2013-08-04 00:00:00',
1976 'decision_date' => '20130805000000',
1979 $keysToUnset = array('xdebug', 'undefined_fields',);
1980 foreach ($keysToUnset as $unwantedKey) {
1981 if(isset($result[$unwantedKey])) {
1982 unset($result[$unwantedKey]);
1985 if (isset($result['values'])) {
1986 if(!is_array($result['values'])) {
1989 $resultArray = &$result['values'];
1991 elseif(is_array($result)) {
1992 $resultArray = &$result;
1998 foreach ($resultArray as $index => &$values) {
1999 if(!is_array($values)) {
2002 foreach($values as $key => &$value) {
2003 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2004 if(isset($value['is_error'])) {
2005 // we have a std nested result format
2006 $this->tidyExampleResult($value);
2009 foreach ($value as &$nestedResult) {
2010 // this is an alternative syntax for nested results a keyed array of results
2011 $this->tidyExampleResult($nestedResult);
2015 if(in_array($key, $keysToUnset)) {
2016 unset($values[$key]);
2019 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2020 $value = $fieldsToChange[$key];
2022 if(is_string($value)) {
2023 $value = addslashes($value);
2030 * Function to delete note
2032 * @params int $noteID
2035 function noteDelete($params) {
2036 return $this->callAPISuccess('Note', 'delete', $params);
2040 * Function to create custom field with Option Values
2042 * @param array $customGroup
2043 * @param string $name name of custom field
2045 function customFieldOptionValueCreate($customGroup, $name) {
2046 $fieldParams = array(
2047 'custom_group_id' => $customGroup['id'],
2048 'name' => 'test_custom_group',
2049 'label' => 'Country',
2050 'html_type' => 'Select',
2051 'data_type' => 'String',
2054 'is_searchable' => 0,
2058 $optionGroup = array(
2060 'name' => 'option_group1',
2061 'label' => 'option_group_label1',
2064 $optionValue = array(
2065 'option_label' => array('Label1', 'Label2'),
2066 'option_value' => array('value1', 'value2'),
2067 'option_name' => array($name . '_1', $name . '_2'),
2068 'option_weight' => array(1, 2),
2069 'option_status' => 1,
2072 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2074 return $this->callAPISuccess('custom_field', 'create', $params);
2077 function confirmEntitiesDeleted($entities) {
2078 foreach ($entities as $entity) {
2080 $result = $this->callAPISuccess($entity, 'Get', array());
2081 if ($result['error'] == 1 ||
$result['count'] > 0) {
2082 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2088 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2089 if ($dropCustomValueTables) {
2090 $tablesToTruncate[] = 'civicrm_custom_group';
2091 $tablesToTruncate[] = 'civicrm_custom_field';
2094 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2095 foreach ($tablesToTruncate as $table) {
2096 $sql = "TRUNCATE TABLE $table";
2097 CRM_Core_DAO
::executeQuery($sql);
2099 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2101 if ($dropCustomValueTables) {
2102 $dbName = self
::getDBName();
2104 SELECT TABLE_NAME as tableName
2105 FROM INFORMATION_SCHEMA.TABLES
2106 WHERE TABLE_SCHEMA = '{$dbName}'
2107 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2110 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2111 while ($tableDAO->fetch()) {
2112 $sql = "DROP TABLE {$tableDAO->tableName}";
2113 CRM_Core_DAO
::executeQuery($sql);
2119 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2121 function quickCleanUpFinancialEntities() {
2122 $tablesToTruncate = array(
2123 'civicrm_contribution',
2124 'civicrm_financial_trxn',
2125 'civicrm_contribution_recur',
2126 'civicrm_line_item',
2127 'civicrm_contribution_page',
2128 'civicrm_payment_processor',
2129 'civicrm_entity_financial_trxn',
2130 'civicrm_membership',
2131 'civicrm_membership_type',
2132 'civicrm_membership_payment',
2133 'civicrm_membership_status',
2135 'civicrm_participant',
2136 'civicrm_participant_payment',
2139 $this->quickCleanup($tablesToTruncate);
2142 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2143 * Default behaviour is to also delete the entity
2144 * @param array $params params array to check agains
2145 * @param int $id id of the entity concerned
2146 * @param string $entity name of entity concerned (e.g. membership)
2147 * @param bool $delete should the entity be deleted as part of this check
2148 * @param string $errorText text to print on error
2151 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2153 $result = $this->callAPISuccessGetSingle($entity, array(
2158 $this->callAPISuccess($entity, 'Delete', array(
2162 $dateFields = $keys = $dateTimeFields = array();
2163 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2164 foreach ($fields['values'] as $field => $settings) {
2165 if (array_key_exists($field, $result)) {
2166 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2169 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2171 $type = CRM_Utils_Array
::value('type', $settings);
2172 if ($type == CRM_Utils_Type
::T_DATE
) {
2173 $dateFields[] = $settings['name'];
2174 // we should identify both real names & unique names as dates
2175 if($field != $settings['name']) {
2176 $dateFields[] = $field;
2179 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2180 $dateTimeFields[] = $settings['name'];
2181 // we should identify both real names & unique names as dates
2182 if($field != $settings['name']) {
2183 $dateTimeFields[] = $field;
2188 if (strtolower($entity) == 'contribution') {
2189 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2190 // this is not returned in id format
2191 unset($params['payment_instrument_id']);
2192 $params['contribution_source'] = $params['source'];
2193 unset($params['source']);
2196 foreach ($params as $key => $value) {
2197 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2200 if (in_array($key, $dateFields)) {
2201 $value = date('Y-m-d', strtotime($value));
2202 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2204 if (in_array($key, $dateTimeFields)) {
2205 $value = date('Y-m-d H:i:s', strtotime($value));
2206 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2208 $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);
2213 * Function to get formatted values in the actual and expected result
2214 * @param array $actual actual calculated values
2215 * @param array $expected expected values
2218 function checkArrayEquals(&$actual, &$expected) {
2219 self
::unsetId($actual);
2220 self
::unsetId($expected);
2221 $this->assertEquals($actual, $expected);
2225 * Function to unset the key 'id' from the array
2226 * @param array $unformattedArray The array from which the 'id' has to be unset
2229 static function unsetId(&$unformattedArray) {
2230 $formattedArray = array();
2231 if (array_key_exists('id', $unformattedArray)) {
2232 unset($unformattedArray['id']);
2234 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2235 foreach ($unformattedArray['values'] as $key => $value) {
2236 if (is_Array($value)) {
2237 foreach ($value as $k => $v) {
2243 elseif ($key == 'id') {
2244 $unformattedArray[$key];
2246 $formattedArray = array($value);
2248 $unformattedArray['values'] = $formattedArray;
2253 * Helper to enable/disable custom directory support
2255 * @param array $customDirs with members:
2256 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2257 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2259 function customDirectories($customDirs) {
2260 require_once 'CRM/Core/Config.php';
2261 $config = CRM_Core_Config
::singleton();
2263 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2264 unset($config->customPHPPathDir
);
2266 elseif ($customDirs['php_path'] === TRUE) {
2267 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2270 $config->customPHPPathDir
= $php_path;
2273 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2274 unset($config->customTemplateDir
);
2276 elseif ($customDirs['template_path'] === TRUE) {
2277 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2280 $config->customTemplateDir
= $template_path;
2285 * Generate a temporary folder
2289 function createTempDir($prefix = 'test-') {
2290 $tempDir = CRM_Utils_File
::tempdir($prefix);
2291 $this->tempDirs
[] = $tempDir;
2295 function cleanTempDirs() {
2296 if (!is_array($this->tempDirs
)) {
2297 // fix test errors where this is not set
2300 foreach ($this->tempDirs
as $tempDir) {
2301 if (is_dir($tempDir)) {
2302 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2308 * Temporarily replace the singleton extension with a different one
2310 function setExtensionSystem(CRM_Extension_System
$system) {
2311 if ($this->origExtensionSystem
== NULL) {
2312 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2314 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2317 function unsetExtensionSystem() {
2318 if ($this->origExtensionSystem
!== NULL) {
2319 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2320 $this->origExtensionSystem
= NULL;
2325 * Temporarily alter the settings-metadata to add a mock setting.
2327 * WARNING: The setting metadata will disappear on the next cache-clear.
2332 function setMockSettingsMetaData($extras) {
2333 CRM_Core_BAO_Setting
::$_cache = array();
2334 $this->callAPISuccess('system','flush', array());
2335 CRM_Core_BAO_Setting
::$_cache = array();
2337 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2338 $metadata = array_merge($metadata, $extras);
2341 $fields = $this->callAPISuccess('setting', 'getfields', array());
2342 foreach ($extras as $key => $spec) {
2343 $this->assertNotEmpty($spec['title']);
2344 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2348 function financialAccountDelete($name) {
2349 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2350 $financialAccount->name
= $name;
2351 if($financialAccount->find(TRUE)) {
2352 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2353 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2354 $entityFinancialType->delete();
2355 $financialAccount->delete();
2360 * Use $ids as an instruction to do test cleanup
2362 function deleteFromIDSArray() {
2363 foreach ($this->ids
as $entity => $ids) {
2364 foreach ($ids as $id) {
2365 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2371 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2372 * (NB unclear if this is still required)
2374 function _sethtmlGlobals() {
2375 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2376 'required' => array(
2377 'html_quickform_rule_required',
2378 'HTML/QuickForm/Rule/Required.php'
2380 'maxlength' => array(
2381 'html_quickform_rule_range',
2382 'HTML/QuickForm/Rule/Range.php'
2384 'minlength' => array(
2385 'html_quickform_rule_range',
2386 'HTML/QuickForm/Rule/Range.php'
2388 'rangelength' => array(
2389 'html_quickform_rule_range',
2390 'HTML/QuickForm/Rule/Range.php'
2393 'html_quickform_rule_email',
2394 'HTML/QuickForm/Rule/Email.php'
2397 'html_quickform_rule_regex',
2398 'HTML/QuickForm/Rule/Regex.php'
2400 'lettersonly' => array(
2401 'html_quickform_rule_regex',
2402 'HTML/QuickForm/Rule/Regex.php'
2404 'alphanumeric' => array(
2405 'html_quickform_rule_regex',
2406 'HTML/QuickForm/Rule/Regex.php'
2409 'html_quickform_rule_regex',
2410 'HTML/QuickForm/Rule/Regex.php'
2412 'nopunctuation' => array(
2413 'html_quickform_rule_regex',
2414 'HTML/QuickForm/Rule/Regex.php'
2417 'html_quickform_rule_regex',
2418 'HTML/QuickForm/Rule/Regex.php'
2420 'callback' => array(
2421 'html_quickform_rule_callback',
2422 'HTML/QuickForm/Rule/Callback.php'
2425 'html_quickform_rule_compare',
2426 'HTML/QuickForm/Rule/Compare.php'
2429 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2430 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2432 'HTML/QuickForm/group.php',
2433 'HTML_QuickForm_group'
2436 'HTML/QuickForm/hidden.php',
2437 'HTML_QuickForm_hidden'
2440 'HTML/QuickForm/reset.php',
2441 'HTML_QuickForm_reset'
2443 'checkbox' => array(
2444 'HTML/QuickForm/checkbox.php',
2445 'HTML_QuickForm_checkbox'
2448 'HTML/QuickForm/file.php',
2449 'HTML_QuickForm_file'
2452 'HTML/QuickForm/image.php',
2453 'HTML_QuickForm_image'
2455 'password' => array(
2456 'HTML/QuickForm/password.php',
2457 'HTML_QuickForm_password'
2460 'HTML/QuickForm/radio.php',
2461 'HTML_QuickForm_radio'
2464 'HTML/QuickForm/button.php',
2465 'HTML_QuickForm_button'
2468 'HTML/QuickForm/submit.php',
2469 'HTML_QuickForm_submit'
2472 'HTML/QuickForm/select.php',
2473 'HTML_QuickForm_select'
2475 'hiddenselect' => array(
2476 'HTML/QuickForm/hiddenselect.php',
2477 'HTML_QuickForm_hiddenselect'
2480 'HTML/QuickForm/text.php',
2481 'HTML_QuickForm_text'
2483 'textarea' => array(
2484 'HTML/QuickForm/textarea.php',
2485 'HTML_QuickForm_textarea'
2487 'fckeditor' => array(
2488 'HTML/QuickForm/fckeditor.php',
2489 'HTML_QuickForm_FCKEditor'
2492 'HTML/QuickForm/tinymce.php',
2493 'HTML_QuickForm_TinyMCE'
2495 'dojoeditor' => array(
2496 'HTML/QuickForm/dojoeditor.php',
2497 'HTML_QuickForm_dojoeditor'
2500 'HTML/QuickForm/link.php',
2501 'HTML_QuickForm_link'
2503 'advcheckbox' => array(
2504 'HTML/QuickForm/advcheckbox.php',
2505 'HTML_QuickForm_advcheckbox'
2508 'HTML/QuickForm/date.php',
2509 'HTML_QuickForm_date'
2512 'HTML/QuickForm/static.php',
2513 'HTML_QuickForm_static'
2516 'HTML/QuickForm/header.php',
2517 'HTML_QuickForm_header'
2520 'HTML/QuickForm/html.php',
2521 'HTML_QuickForm_html'
2523 'hierselect' => array(
2524 'HTML/QuickForm/hierselect.php',
2525 'HTML_QuickForm_hierselect'
2527 'autocomplete' => array(
2528 'HTML/QuickForm/autocomplete.php',
2529 'HTML_QuickForm_autocomplete'
2532 'HTML/QuickForm/xbutton.php',
2533 'HTML_QuickForm_xbutton'
2535 'advmultiselect' => array(
2536 'HTML/QuickForm/advmultiselect.php',
2537 'HTML_QuickForm_advmultiselect'
2543 * Set up an acl allowing contact to see 2 specified groups
2544 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2546 * You need to have precreated these groups & created the user e.g
2547 * $this->createLoggedInUser();
2548 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2549 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2552 function setupACL() {
2553 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2554 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2555 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2556 'label' => 'pick me',
2561 CRM_Core_DAO
::executeQuery("
2562 TRUNCATE civicrm_acl_cache
2565 CRM_Core_DAO
::executeQuery("
2566 TRUNCATE civicrm_acl_contact_cache
2570 CRM_Core_DAO
::executeQuery("
2571 INSERT INTO civicrm_acl_entity_role (
2572 `acl_role_id`, `entity_table`, `entity_id`
2573 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2576 CRM_Core_DAO
::executeQuery("
2577 INSERT INTO civicrm_acl (
2578 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2581 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2585 CRM_Core_DAO
::executeQuery("
2586 INSERT INTO civicrm_acl (
2587 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2590 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2593 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2594 $this->callAPISuccess('group_contact', 'create', array(
2595 'group_id' => $this->_permissionedGroup
,
2596 'contact_id' => $this->_loggedInUser
,
2599 CRM_ACL_BAO_Cache
::resetCache();
2600 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2604 * Create an instance of the paypal processor
2605 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2606 * this parent class & we don't have a structure for that yet
2607 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2608 * & the best protection agains that is the functions this class affords
2610 function paymentProcessorCreate($params = array()) {
2611 $params = array_merge(array(
2613 'domain_id' => CRM_Core_Config
::domainID(),
2614 'payment_processor_type_id' => 'PayPal',
2618 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2619 'password' => '1183377788',
2620 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2621 'url_site' => 'https://www.sandbox.paypal.com/',
2622 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2623 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2624 'class_name' => 'Payment_PayPalImpl',
2625 'billing_mode' => 3,
2626 'financial_type_id' => 1,
2629 if(!is_numeric($params['payment_processor_type_id'])) {
2630 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2632 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2633 'name' => $params['payment_processor_type_id'],
2637 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2638 return $result['id'];
2642 function CiviUnitTestCase_fatalErrorHandler($message) {
2643 throw new Exception("{$message['message']}: {$message['code']}");