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 define
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 * This function exists to wrap api functions
685 * so we can ensure they succeed & throw exceptions without litterering the test with checks
686 * @param string $entity
687 * @param string $action
688 * @param array $params
689 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
690 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
691 * for getsingle the array is compared against an array passed in - the id is not compared (for
694 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
695 $params = array_merge(array(
696 'version' => $this->_apiversion
,
701 switch (strtolower($action)) {
703 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
705 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
707 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
709 $result = civicrm_api($entity, $action, $params);
710 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
715 * This function exists to wrap api getValue function & check the result
716 * so we can ensure they succeed & throw exceptions without litterering the test with checks
717 * There is a type check in this
718 * @param string $entity
719 * @param array $params
720 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
728 function callAPISuccessGetValue($entity, $params, $type = NULL) {
730 'version' => $this->_apiversion
,
733 $result = civicrm_api($entity, 'getvalue', $params);
735 if($type == 'integer'){
736 // api seems to return integers as strings
737 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
740 $this->assertType($type, $result, "returned result should have been of type $type but was " );
747 * This function exists to wrap api getsingle function & check the result
748 * so we can ensure they succeed & throw exceptions without litterering the test with checks
749 * @param string $entity
750 * @param array $params
751 * @param array $checkAgainst - array to compare result against
759 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
761 'version' => $this->_apiversion
,
764 $result = civicrm_api($entity, 'getsingle', $params);
765 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
766 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
769 // @todo - have gone with the fn that unsets id? should we check id?
770 $this->checkArrayEquals($result, $checkAgainst);
775 * This function exists to wrap api getValue function & check the result
776 * so we can ensure they succeed & throw exceptions without litterering the test with checks
777 * There is a type check in this
778 * @param string $entity
779 * @param array $params
780 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
788 function callAPISuccessGetCount($entity, $params, $count = NULL) {
790 'version' => $this->_apiversion
,
793 $result = civicrm_api($entity, 'getcount', $params);
794 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
795 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
798 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
803 * This function exists to wrap api functions
804 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
806 * @param string $entity
807 * @param string $action
808 * @param array $params
809 * @param string $function - pass this in to create a generated example
810 * @param string $file - pass this in to create a generated example
812 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
813 $params['version'] = $this->_apiversion
;
814 $result = $this->callAPISuccess($entity, $action, $params);
815 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
820 * This function exists to wrap api functions
821 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
822 * @param string $entity
823 * @param string $action
824 * @param array $params
825 * @param string $expectedErrorMessage error
827 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
828 if (is_array($params)) {
830 'version' => $this->_apiversion
,
833 $result = civicrm_api($entity, $action, $params);
834 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
839 * Create required data based on $this->entity & $this->params
840 * This is just a way to set up the test data for delete & get functions
841 * so the distinction between set
842 * up & tested functions is clearer
844 * @return array api Result
846 public function createTestEntity(){
847 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
851 * Generic function to create Organisation, to be used in test cases
853 * @param array parameters for civicrm_contact_add api function call
854 * @param int sequence number if creating multiple organizations
856 * @return int id of Organisation created
858 function organizationCreate($params = array(), $seq = 0) {
862 $params = array_merge($this->sampleContact('Organization', $seq), $params);
863 return $this->_contactCreate($params);
867 * Generic function to create Individual, to be used in test cases
869 * @param array parameters for civicrm_contact_add api function call
870 * @param int sequence number if creating multiple individuals
872 * @return int id of Individual created
874 function individualCreate($params = array(), $seq = 0) {
875 $params = array_merge($this->sampleContact('Individual', $seq), $params);
876 return $this->_contactCreate($params);
880 * Generic function to create Household, to be used in test cases
882 * @param array parameters for civicrm_contact_add api function call
883 * @param int sequence number if creating multiple households
885 * @return int id of Household created
887 function householdCreate($params = array(), $seq = 0) {
888 $params = array_merge($this->sampleContact('Household', $seq), $params);
889 return $this->_contactCreate($params);
893 * Helper function for getting sample contact properties
895 * @param enum contact type: Individual, Organization
896 * @param int sequence number for the values of this type
898 * @return array properties of sample contact (ie. $params for API call)
900 function sampleContact($contact_type, $seq = 0) {
902 'Individual' => array(
903 // The number of values in each list need to be coprime numbers to not have duplicates
904 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
905 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
906 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
908 'Organization' => array(
909 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
911 'Household' => array(
912 'household_name' => array('Unit Test household'),
915 $params = array('contact_type' => $contact_type);
916 foreach ($samples[$contact_type] as $key => $values) {
917 $params[$key] = $values[$seq %
sizeof($values)];
919 if ($contact_type == 'Individual' ) {
920 $employer = $this->sampleContact('Organization', $seq);
921 $params['email'] = strtolower(
922 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
924 $params['prefix_id'] = 3;
925 $params['suffix_id'] = 3;
931 * Private helper function for calling civicrm_contact_add
936 * @internal param \parameters $array for civicrm_contact_add api function call
938 * @return int id of Household created
940 private function _contactCreate($params) {
941 $result = $this->callAPISuccess('contact', 'create', $params);
942 if (CRM_Utils_Array
::value('is_error', $result) ||
943 !CRM_Utils_Array
::value('id', $result)
945 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
947 return $result['id'];
950 function contactDelete($contactID) {
953 'skip_undelete' => 1,
956 $domain = new CRM_Core_BAO_Domain
;
957 $domain->contact_id
= $contactID;
958 if ($domain->find(TRUE)) {
959 // we are finding tests trying to delete the domain contact in cleanup
960 //since this is mainly for cleanup lets put a safeguard here
963 $result = $this->callAPISuccess('contact', 'delete', $params);
967 function contactTypeDelete($contactTypeId) {
968 require_once 'CRM/Contact/BAO/ContactType.php';
969 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
971 throw new Exception('Could not delete contact type');
975 function membershipTypeCreate($params = array()) {
976 CRM_Member_PseudoConstant
::flush('membershipType');
977 CRM_Core_Config
::clearDBCache();
978 $params = array_merge(array(
980 'duration_unit' => 'year',
981 'duration_interval' => 1,
982 'period_type' => 'rolling',
983 'member_of_contact_id' => 1,
985 'financial_type_id' => 1,
991 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
993 CRM_Member_PseudoConstant
::flush('membershipType');
994 CRM_Utils_Cache
::singleton()->flush();
996 return $result['id'];
999 function contactMembershipCreate($params) {
1001 'join_date' => '2007-01-21',
1002 'start_date' => '2007-01-21',
1003 'end_date' => '2007-12-21',
1004 'source' => 'Payment',
1007 foreach ($pre as $key => $val) {
1008 if (!isset($params[$key])) {
1009 $params[$key] = $val;
1013 $result = $this->callAPISuccess('Membership', 'create', $params);
1014 return $result['id'];
1018 * Function to delete Membership Type
1020 * @param int $membershipTypeID
1022 function membershipTypeDelete($params) {
1023 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1027 function membershipDelete($membershipID) {
1028 $deleteParams = array('id' => $membershipID);
1029 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1033 function membershipStatusCreate($name = 'test member status') {
1034 $params['name'] = $name;
1035 $params['start_event'] = 'start_date';
1036 $params['end_event'] = 'end_date';
1037 $params['is_current_member'] = 1;
1038 $params['is_active'] = 1;
1040 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1041 CRM_Member_PseudoConstant
::flush('membershipStatus');
1042 return $result['id'];
1045 function membershipStatusDelete($membershipStatusID) {
1046 if (!$membershipStatusID) {
1049 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1053 function relationshipTypeCreate($params = array()) {
1054 $params = array_merge(array(
1055 'name_a_b' => 'Relation 1 for relationship type create',
1056 'name_b_a' => 'Relation 2 for relationship type create',
1057 'contact_type_a' => 'Individual',
1058 'contact_type_b' => 'Organization',
1065 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1066 CRM_Core_PseudoConstant
::flush('relationshipType');
1068 return $result['id'];
1072 * Function to delete Relatinship Type
1074 * @param int $relationshipTypeID
1076 function relationshipTypeDelete($relationshipTypeID) {
1077 $params['id'] = $relationshipTypeID;
1078 $this->callAPISuccess('relationship_type', 'delete', $params);
1081 function paymentProcessorTypeCreate($params = NULL) {
1082 if (is_null($params)) {
1084 'name' => 'API_Test_PP',
1085 'title' => 'API Test Payment Processor',
1086 'class_name' => 'CRM_Core_Payment_APITest',
1087 'billing_mode' => 'form',
1093 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1095 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1097 return $result['id'];
1101 * Function to create Participant
1103 * @param array $params array of contact id and event id values
1105 * @return int $id of participant created
1107 function participantCreate($params) {
1108 if(empty($params['contact_id'])){
1109 $params['contact_id'] = $this->individualCreate();
1111 if(empty($params['event_id'])){
1112 $event = $this->eventCreate();
1113 $params['event_id'] = $event['id'];
1118 'register_date' => 20070219,
1119 'source' => 'Wimbeldon',
1120 'event_level' => 'Payment',
1124 $params = array_merge($defaults, $params);
1125 $result = $this->callAPISuccess('Participant', 'create', $params);
1126 return $result['id'];
1130 * Function to create Payment Processor
1132 * @return object of Payment Processsor
1134 function processorCreate() {
1135 $processorParams = array(
1138 'payment_processor_type_id' => 10,
1139 'financial_account_id' => 12,
1142 'url_site' => 'http://dummy.com',
1143 'url_recur' => 'http://dummy.com',
1144 'billing_mode' => 1,
1146 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1147 return $paymentProcessor;
1151 * Function to create contribution page
1153 * @return object of contribution page
1155 function contributionPageCreate($params) {
1156 $this->_pageParams
= array(
1157 'title' => 'Test Contribution Page',
1158 'financial_type_id' => 1,
1159 'currency' => 'USD',
1160 'financial_account_id' => 1,
1161 'payment_processor' => $params['processor_id'],
1163 'is_allow_other_amount' => 1,
1165 'max_amount' => 1000,
1167 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1168 return $contributionPage;
1172 * Function to create Tag
1174 * @return array result of created tag
1176 function tagCreate($params = array()) {
1178 'name' => 'New Tag3',
1179 'description' => 'This is description for Our New Tag ',
1182 $params = array_merge($defaults, $params);
1183 $result = $this->callAPISuccess('Tag', 'create', $params);
1184 return $result['values'][$result['id']];
1188 * Function to delete Tag
1190 * @param int $tagId id of the tag to be deleted
1192 function tagDelete($tagId) {
1193 require_once 'api/api.php';
1197 $result = $this->callAPISuccess('Tag', 'delete', $params);
1198 return $result['id'];
1202 * Add entity(s) to the tag
1204 * @param array $params
1206 function entityTagAdd($params) {
1207 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1212 * Function to create contribution
1214 * @param int $cID contact_id
1215 * @param int $cTypeID id of financial type
1217 * @return int id of created contribution
1219 function pledgeCreate($cID) {
1221 'contact_id' => $cID,
1222 'pledge_create_date' => date('Ymd'),
1223 'start_date' => date('Ymd'),
1224 'scheduled_date' => date('Ymd'),
1226 'pledge_status_id' => '2',
1227 'financial_type_id' => '1',
1228 'pledge_original_installment_amount' => 20,
1229 'frequency_interval' => 5,
1230 'frequency_unit' => 'year',
1231 'frequency_day' => 15,
1232 'installments' => 5,
1235 $result = $this->callAPISuccess('Pledge', 'create', $params);
1236 return $result['id'];
1240 * Function to delete contribution
1242 * @param int $contributionId
1244 function pledgeDelete($pledgeId) {
1246 'pledge_id' => $pledgeId,
1248 $this->callAPISuccess('Pledge', 'delete', $params);
1252 * Function to create contribution
1254 * @param int $cID contact_id
1255 * @param int $cTypeID id of financial type
1257 * @return int id of created contribution
1259 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1262 'contact_id' => $cID,
1263 'receive_date' => date('Ymd'),
1264 'total_amount' => 100.00,
1265 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1266 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1267 'non_deductible_amount' => 10.00,
1268 'trxn_id' => $trxnID,
1269 'invoice_id' => $invoiceID,
1271 'contribution_status_id' => 1,
1272 // 'note' => 'Donating for Nobel Cause', *Fixme
1276 $params['fee_amount'] = 5.00;
1277 $params['net_amount'] = 95.00;
1280 $result = $this->callAPISuccess('contribution', 'create', $params);
1281 return $result['id'];
1285 * Function to create online contribution
1287 * @param int $financialType id of financial type
1289 * @return int id of created contribution
1291 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1292 $contribParams = array(
1293 'contact_id' => $params['contact_id'],
1294 'receive_date' => date('Ymd'),
1295 'total_amount' => 100.00,
1296 'financial_type_id' => $financialType,
1297 'contribution_page_id' => $params['contribution_page_id'],
1299 'invoice_id' => 67890,
1302 $contribParams = array_merge($contribParams, $params);
1303 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1305 return $result['id'];
1309 * Function to delete contribution
1311 * @param int $contributionId
1313 function contributionDelete($contributionId) {
1315 'contribution_id' => $contributionId,
1317 $result = $this->callAPISuccess('contribution', 'delete', $params);
1322 * Function to create an Event
1324 * @param array $params name-value pair for an event
1326 * @return array $event
1328 function eventCreate($params = array()) {
1329 // if no contact was passed, make up a dummy event creator
1330 if (!isset($params['contact_id'])) {
1331 $params['contact_id'] = $this->_contactCreate(array(
1332 'contact_type' => 'Individual',
1333 'first_name' => 'Event',
1334 'last_name' => 'Creator',
1338 // set defaults for missing params
1339 $params = array_merge(array(
1340 'title' => 'Annual CiviCRM meet',
1341 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1342 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1343 'event_type_id' => 1,
1345 'start_date' => 20081021,
1346 'end_date' => 20081023,
1347 'is_online_registration' => 1,
1348 'registration_start_date' => 20080601,
1349 'registration_end_date' => 20081015,
1350 'max_participants' => 100,
1351 'event_full_text' => 'Sorry! We are already full',
1354 'is_show_location' => 0,
1357 return $this->callAPISuccess('Event', 'create', $params);
1361 * Function to delete event
1363 * @param int $id ID of the event
1365 function eventDelete($id) {
1369 return $this->callAPISuccess('event', 'delete', $params);
1373 * Function to delete participant
1375 * @param int $participantID
1377 function participantDelete($participantID) {
1379 'id' => $participantID,
1381 return $this->callAPISuccess('Participant', 'delete', $params);
1385 * Function to create participant payment
1387 * @return int $id of created payment
1389 function participantPaymentCreate($participantID, $contributionID = NULL) {
1390 //Create Participant Payment record With Values
1392 'participant_id' => $participantID,
1393 'contribution_id' => $contributionID,
1396 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1397 return $result['id'];
1401 * Function to delete participant payment
1403 * @param int $paymentID
1405 function participantPaymentDelete($paymentID) {
1409 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1413 * Function to add a Location
1415 * @return int location id of created location
1417 function locationAdd($contactID) {
1420 'location_type' => 'New Location Type',
1422 'name' => 'Saint Helier St',
1423 'county' => 'Marin',
1424 'country' => 'United States',
1425 'state_province' => 'Michigan',
1426 'supplemental_address_1' => 'Hallmark Ct',
1427 'supplemental_address_2' => 'Jersey Village',
1432 'contact_id' => $contactID,
1433 'address' => $address,
1434 'location_format' => '2.0',
1435 'location_type' => 'New Location Type',
1438 $result = $this->callAPISuccess('Location', 'create', $params);
1443 * Function to delete Locations of contact
1445 * @params array $pamars parameters
1447 function locationDelete($params) {
1448 $result = $this->callAPISuccess('Location', 'delete', $params);
1452 * Function to add a Location Type
1454 * @return int location id of created location
1456 function locationTypeCreate($params = NULL) {
1457 if ($params === NULL) {
1459 'name' => 'New Location Type',
1460 'vcard_name' => 'New Location Type',
1461 'description' => 'Location Type for Delete',
1466 $locationType = new CRM_Core_DAO_LocationType();
1467 $locationType->copyValues($params);
1468 $locationType->save();
1469 // clear getfields cache
1470 CRM_Core_PseudoConstant
::flush();
1471 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1472 return $locationType;
1476 * Function to delete a Location Type
1478 * @param int location type id
1480 function locationTypeDelete($locationTypeId) {
1481 $locationType = new CRM_Core_DAO_LocationType();
1482 $locationType->id
= $locationTypeId;
1483 $locationType->delete();
1487 * Function to add a Group
1489 * @params array to add group
1491 * @return int groupId of created group
1494 function groupCreate($params = array()) {
1495 $params = array_merge(array(
1496 'name' => 'Test Group 1',
1498 'title' => 'New Test Group Created',
1499 'description' => 'New Test Group Created',
1501 'visibility' => 'Public Pages',
1502 'group_type' => array(
1508 $result = $this->callAPISuccess('Group', 'create', $params);
1509 return $result['id'];
1513 * Function to delete a Group
1517 function groupDelete($gid) {
1523 $this->callAPISuccess('Group', 'delete', $params);
1528 * @param array $params
1530 function uFFieldCreate($params = array()) {
1531 $params = array_merge(array(
1533 'field_name' => 'first_name',
1536 'visibility' => 'Public Pages and Listings',
1537 'is_searchable' => '1',
1538 'label' => 'first_name',
1539 'field_type' => 'Individual',
1542 $this->callAPISuccess('uf_field', 'create', $params);
1545 * Function to add a UF Join Entry
1547 * @return int $id of created UF Join
1549 function ufjoinCreate($params = NULL) {
1550 if ($params === NULL) {
1553 'module' => 'CiviEvent',
1554 'entity_table' => 'civicrm_event',
1560 $result = $this->callAPISuccess('uf_join', 'create', $params);
1565 * Function to delete a UF Join Entry
1567 * @param array with missing uf_group_id
1569 function ufjoinDelete($params = NULL) {
1570 if ($params === NULL) {
1573 'module' => 'CiviEvent',
1574 'entity_table' => 'civicrm_event',
1577 'uf_group_id' => '',
1581 crm_add_uf_join($params);
1585 * Function to create Group for a contact
1587 * @param int $contactId
1589 function contactGroupCreate($contactId) {
1591 'contact_id.1' => $contactId,
1595 $this->callAPISuccess('GroupContact', 'Create', $params);
1599 * Function to delete Group for a contact
1601 * @param array $params
1603 function contactGroupDelete($contactId) {
1605 'contact_id.1' => $contactId,
1608 civicrm_api('GroupContact', 'Delete', $params);
1612 * Function to create Activity
1614 * @param int $contactId
1616 function activityCreate($params = NULL) {
1618 if ($params === NULL) {
1619 $individualSourceID = $this->individualCreate();
1621 $contactParams = array(
1622 'first_name' => 'Julia',
1623 'Last_name' => 'Anderson',
1625 'email' => 'julia_anderson@civicrm.org',
1626 'contact_type' => 'Individual',
1629 $individualTargetID = $this->individualCreate($contactParams);
1632 'source_contact_id' => $individualSourceID,
1633 'target_contact_id' => array($individualTargetID),
1634 'assignee_contact_id' => array($individualTargetID),
1635 'subject' => 'Discussion on warm beer',
1636 'activity_date_time' => date('Ymd'),
1637 'duration_hours' => 30,
1638 'duration_minutes' => 20,
1639 'location' => 'Baker Street',
1640 'details' => 'Lets schedule a meeting',
1642 'activity_name' => 'Meeting',
1646 $result = $this->callAPISuccess('Activity', 'create', $params);
1648 $result['target_contact_id'] = $individualTargetID;
1649 $result['assignee_contact_id'] = $individualTargetID;
1654 * Function to create an activity type
1656 * @params array $params parameters
1658 function activityTypeCreate($params) {
1659 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1664 * Function to delete activity type
1666 * @params Integer $activityTypeId id of the activity type
1668 function activityTypeDelete($activityTypeId) {
1669 $params['activity_type_id'] = $activityTypeId;
1670 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1675 * Function to create custom group
1677 * @param string $className
1678 * @param string $title name of custom group
1680 function customGroupCreate($params = array()) {
1682 'title' => 'new custom group',
1683 'extends' => 'Contact',
1685 'style' => 'Inline',
1689 $params = array_merge($defaults, $params);
1691 if (strlen($params['title']) > 13) {
1692 $params['title'] = substr($params['title'], 0, 13);
1695 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1696 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1698 return $this->callAPISuccess('custom_group', 'create', $params);
1702 * existing function doesn't allow params to be over-ridden so need a new one
1703 * this one allows you to only pass in the params you want to change
1705 function CustomGroupCreateByParams($params = array()) {
1707 'title' => "API Custom Group",
1708 'extends' => 'Contact',
1710 'style' => 'Inline',
1713 $params = array_merge($defaults, $params);
1714 return $this->callAPISuccess('custom_group', 'create', $params);
1718 * Create custom group with multi fields
1720 function CustomGroupMultipleCreateByParams($params = array()) {
1725 $params = array_merge($defaults, $params);
1726 return $this->CustomGroupCreateByParams($params);
1730 * Create custom group with multi fields
1732 function CustomGroupMultipleCreateWithFields($params = array()) {
1733 // also need to pass on $params['custom_field'] if not set but not in place yet
1735 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1736 $ids['custom_group_id'] = $customGroup['id'];
1738 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1740 $ids['custom_field_id'][] = $customField['id'];
1742 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1743 $ids['custom_field_id'][] = $customField['id'];
1745 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1746 $ids['custom_field_id'][] = $customField['id'];
1752 * Create a custom group with a single text custom field. See
1753 * participant:testCreateWithCustom for how to use this
1755 * @param string $function __FUNCTION__
1756 * @param string $file __FILE__
1758 * @return array $ids ids of created objects
1761 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1762 $params = array('title' => $function);
1763 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1764 $params['extends'] = $entity ?
$entity : 'Contact';
1765 $customGroup = $this->CustomGroupCreate($params);
1766 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1767 CRM_Core_PseudoConstant
::flush();
1769 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1773 * Function to delete custom group
1775 * @param int $customGroupID
1777 function customGroupDelete($customGroupID) {
1778 $params['id'] = $customGroupID;
1779 return $this->callAPISuccess('custom_group', 'delete', $params);
1783 * Function to create custom field
1785 * @param array $params (custom_group_id) is required
1786 * @param string $name name of custom field
1787 * @param int $apiversion API version to use
1789 function customFieldCreate($params) {
1790 $params = array_merge(array(
1791 'label' => 'Custom Field',
1792 'data_type' => 'String',
1793 'html_type' => 'Text',
1794 'is_searchable' => 1,
1796 'default_value' => 'defaultValue',
1799 $result = $this->callAPISuccess('custom_field', 'create', $params);
1801 if ($result['is_error'] == 0 && isset($result['id'])) {
1802 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1803 // force reset of enabled components to help grab custom fields
1804 CRM_Core_Component
::getEnabledComponents(1);
1810 * Function to delete custom field
1812 * @param int $customFieldID
1814 function customFieldDelete($customFieldID) {
1816 $params['id'] = $customFieldID;
1817 return $this->callAPISuccess('custom_field', 'delete', $params);
1821 * Function to create note
1823 * @params array $params name-value pair for an event
1825 * @return array $note
1827 function noteCreate($cId) {
1829 'entity_table' => 'civicrm_contact',
1830 'entity_id' => $cId,
1831 'note' => 'hello I am testing Note',
1832 'contact_id' => $cId,
1833 'modified_date' => date('Ymd'),
1834 'subject' => 'Test Note',
1837 return $this->callAPISuccess('Note', 'create', $params);
1841 * Enable CiviCampaign Component
1843 function enableCiviCampaign() {
1844 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1845 // force reload of config object
1846 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1847 //flush cache by calling with reset
1848 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1852 * Create test generated example in api/v3/examples.
1853 * To turn this off (e.g. on the server) set
1854 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1855 * in your settings file
1856 * @param array $params array as passed to civicrm_api function
1857 * @param array $result array as received from the civicrm_api function
1858 * @param string $function calling function - generally __FUNCTION__
1859 * @param string $filename called from file - generally __FILE__
1860 * @param string $description descriptive text for the example file
1861 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1862 * @param string $action - optional action - otherwise taken from function name
1864 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1865 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1868 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1869 //todo - this is a bit cludgey
1870 if (empty($action)) {
1871 if (strstr($function, 'Create')) {
1872 $action = empty($action) ?
'create' : $action;
1873 $entityAction = 'Create';
1875 elseif (strstr($function, 'GetSingle')) {
1876 $action = empty($action) ?
'getsingle' : $action;
1877 $entityAction = 'GetSingle';
1879 elseif (strstr($function, 'GetValue')) {
1880 $action = empty($action) ?
'getvalue' : $action;
1881 $entityAction = 'GetValue';
1883 elseif (strstr($function, 'GetCount')) {
1884 $action = empty($action) ?
'getcount' : $action;
1885 $entityAction = 'GetCount';
1887 elseif (strstr($function, 'GetFields')) {
1888 $action = empty($action) ?
'getfields' : $action;
1889 $entityAction = 'GetFields';
1891 elseif (strstr($function, 'Get')) {
1892 $action = empty($action) ?
'get' : $action;
1893 $entityAction = 'Get';
1895 elseif (strstr($function, 'Delete')) {
1896 $action = empty($action) ?
'delete' : $action;
1897 $entityAction = 'Delete';
1899 elseif (strstr($function, 'Update')) {
1900 $action = empty($action) ?
'update' : $action;
1901 $entityAction = 'Update';
1903 elseif (strstr($function, 'Subscribe')) {
1904 $action = empty($action) ?
'subscribe' : $action;
1905 $entityAction = 'Subscribe';
1907 elseif (strstr($function, 'Submit')) {
1908 $action = empty($action) ?
'submit' : $action;
1909 $entityAction = 'Submit';
1911 elseif (strstr($function, 'Apply')) {
1912 $action = empty($action) ?
'apply' : $action;
1913 $entityAction = 'Apply';
1915 elseif (strstr($function, 'Replace')) {
1916 $action = empty($action) ?
'replace' : $action;
1917 $entityAction = 'Replace';
1921 $entityAction = ucwords($action);
1924 $this->tidyExampleResult($result);
1925 if(isset($params['version'])) {
1926 unset($params['version']);
1928 // a cleverer person than me would do it in a single regex
1929 if (strstr($entity, 'UF')) {
1930 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1933 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1935 $smarty = CRM_Core_Smarty
::singleton();
1936 $smarty->assign('testfunction', $function);
1937 $function = $fnPrefix . "_" . strtolower($action);
1938 $smarty->assign('function', $function);
1939 $smarty->assign('fnPrefix', $fnPrefix);
1940 $smarty->assign('params', $params);
1941 $smarty->assign('entity', $entity);
1942 $smarty->assign('filename', basename($filename));
1943 $smarty->assign('description', $description);
1944 $smarty->assign('result', $result);
1946 $smarty->assign('action', $action);
1947 if (empty($subfile)) {
1948 $subfile = $entityAction;
1950 if (file_exists('../tests/templates/documentFunction.tpl')) {
1951 if (!is_dir("../api/v3/examples/$entity")) {
1952 mkdir("../api/v3/examples/$entity");
1954 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1955 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1961 * Tidy up examples array so that fields that change often ..don't
1962 * and debug related fields are unset
1963 * @param array $params
1965 function tidyExampleResult(&$result){
1966 if(!is_array($result)) {
1969 $fieldsToChange = array(
1970 'hash' => '67eac7789eaee00',
1971 'modified_date' => '2012-11-14 16:02:35',
1972 'created_date' => '2013-07-28 08:49:19',
1973 'create_date' => '20120130621222105',
1974 'application_received_date' => '20130728084957',
1975 'in_date' => '2013-07-28 08:50:19',
1976 'scheduled_date' => '20130728085413',
1977 'approval_date' => '20130728085413',
1978 'pledge_start_date_high' => '20130726090416',
1979 'start_date' => '2013-07-29 00:00:00',
1980 'event_start_date' => '2013-07-29 00:00:00',
1981 'end_date' => '2013-08-04 00:00:00',
1982 'event_end_date' => '2013-08-04 00:00:00',
1983 'decision_date' => '20130805000000',
1986 $keysToUnset = array('xdebug', 'undefined_fields',);
1987 foreach ($keysToUnset as $unwantedKey) {
1988 if(isset($result[$unwantedKey])) {
1989 unset($result[$unwantedKey]);
1992 if (isset($result['values'])) {
1993 if(!is_array($result['values'])) {
1996 $resultArray = &$result['values'];
1998 elseif(is_array($result)) {
1999 $resultArray = &$result;
2005 foreach ($resultArray as $index => &$values) {
2006 if(!is_array($values)) {
2009 foreach($values as $key => &$value) {
2010 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2011 if(isset($value['is_error'])) {
2012 // we have a std nested result format
2013 $this->tidyExampleResult($value);
2016 foreach ($value as &$nestedResult) {
2017 // this is an alternative syntax for nested results a keyed array of results
2018 $this->tidyExampleResult($nestedResult);
2022 if(in_array($key, $keysToUnset)) {
2023 unset($values[$key]);
2026 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2027 $value = $fieldsToChange[$key];
2029 if(is_string($value)) {
2030 $value = addslashes($value);
2037 * Function to delete note
2039 * @params int $noteID
2042 function noteDelete($params) {
2043 return $this->callAPISuccess('Note', 'delete', $params);
2047 * Function to create custom field with Option Values
2049 * @param array $customGroup
2050 * @param string $name name of custom field
2052 function customFieldOptionValueCreate($customGroup, $name) {
2053 $fieldParams = array(
2054 'custom_group_id' => $customGroup['id'],
2055 'name' => 'test_custom_group',
2056 'label' => 'Country',
2057 'html_type' => 'Select',
2058 'data_type' => 'String',
2061 'is_searchable' => 0,
2065 $optionGroup = array(
2067 'name' => 'option_group1',
2068 'label' => 'option_group_label1',
2071 $optionValue = array(
2072 'option_label' => array('Label1', 'Label2'),
2073 'option_value' => array('value1', 'value2'),
2074 'option_name' => array($name . '_1', $name . '_2'),
2075 'option_weight' => array(1, 2),
2076 'option_status' => 1,
2079 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2081 return $this->callAPISuccess('custom_field', 'create', $params);
2084 function confirmEntitiesDeleted($entities) {
2085 foreach ($entities as $entity) {
2087 $result = $this->callAPISuccess($entity, 'Get', array());
2088 if ($result['error'] == 1 ||
$result['count'] > 0) {
2089 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2095 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2096 if ($dropCustomValueTables) {
2097 $tablesToTruncate[] = 'civicrm_custom_group';
2098 $tablesToTruncate[] = 'civicrm_custom_field';
2101 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2102 foreach ($tablesToTruncate as $table) {
2103 $sql = "TRUNCATE TABLE $table";
2104 CRM_Core_DAO
::executeQuery($sql);
2106 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2108 if ($dropCustomValueTables) {
2109 $dbName = self
::getDBName();
2111 SELECT TABLE_NAME as tableName
2112 FROM INFORMATION_SCHEMA.TABLES
2113 WHERE TABLE_SCHEMA = '{$dbName}'
2114 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2117 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2118 while ($tableDAO->fetch()) {
2119 $sql = "DROP TABLE {$tableDAO->tableName}";
2120 CRM_Core_DAO
::executeQuery($sql);
2126 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2127 * Default behaviour is to also delete the entity
2128 * @param array $params params array to check agains
2129 * @param int $id id of the entity concerned
2130 * @param string $entity name of entity concerned (e.g. membership)
2131 * @param bool $delete should the entity be deleted as part of this check
2132 * @param string $errorText text to print on error
2135 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2137 $result = $this->callAPISuccessGetSingle($entity, array(
2142 $this->callAPISuccess($entity, 'Delete', array(
2146 $dateFields = $keys = $dateTimeFields = array();
2147 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2148 foreach ($fields['values'] as $field => $settings) {
2149 if (array_key_exists($field, $result)) {
2150 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2153 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2155 $type = CRM_Utils_Array
::value('type', $settings);
2156 if ($type == CRM_Utils_Type
::T_DATE
) {
2157 $dateFields[] = $settings['name'];
2158 // we should identify both real names & unique names as dates
2159 if($field != $settings['name']) {
2160 $dateFields[] = $field;
2163 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2164 $dateTimeFields[] = $settings['name'];
2165 // we should identify both real names & unique names as dates
2166 if($field != $settings['name']) {
2167 $dateTimeFields[] = $field;
2172 if (strtolower($entity) == 'contribution') {
2173 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2174 // this is not returned in id format
2175 unset($params['payment_instrument_id']);
2176 $params['contribution_source'] = $params['source'];
2177 unset($params['source']);
2180 foreach ($params as $key => $value) {
2181 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2184 if (in_array($key, $dateFields)) {
2185 $value = date('Y-m-d', strtotime($value));
2186 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2188 if (in_array($key, $dateTimeFields)) {
2189 $value = date('Y-m-d H:i:s', strtotime($value));
2190 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2192 $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);
2197 * Function to get formatted values in the actual and expected result
2198 * @param array $actual actual calculated values
2199 * @param array $expected expected values
2202 function checkArrayEquals(&$actual, &$expected) {
2203 self
::unsetId($actual);
2204 self
::unsetId($expected);
2205 $this->assertEquals($actual, $expected);
2209 * Function to unset the key 'id' from the array
2210 * @param array $unformattedArray The array from which the 'id' has to be unset
2213 static function unsetId(&$unformattedArray) {
2214 $formattedArray = array();
2215 if (array_key_exists('id', $unformattedArray)) {
2216 unset($unformattedArray['id']);
2218 if (CRM_Utils_Array
::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2219 foreach ($unformattedArray['values'] as $key => $value) {
2220 if (is_Array($value)) {
2221 foreach ($value as $k => $v) {
2227 elseif ($key == 'id') {
2228 $unformattedArray[$key];
2230 $formattedArray = array($value);
2232 $unformattedArray['values'] = $formattedArray;
2237 * Helper to enable/disable custom directory support
2239 * @param array $customDirs with members:
2240 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2241 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2243 function customDirectories($customDirs) {
2244 require_once 'CRM/Core/Config.php';
2245 $config = CRM_Core_Config
::singleton();
2247 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2248 unset($config->customPHPPathDir
);
2250 elseif ($customDirs['php_path'] === TRUE) {
2251 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2254 $config->customPHPPathDir
= $php_path;
2257 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2258 unset($config->customTemplateDir
);
2260 elseif ($customDirs['template_path'] === TRUE) {
2261 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2264 $config->customTemplateDir
= $template_path;
2269 * Generate a temporary folder
2273 function createTempDir($prefix = 'test-') {
2274 $tempDir = CRM_Utils_File
::tempdir($prefix);
2275 $this->tempDirs
[] = $tempDir;
2279 function cleanTempDirs() {
2280 if (!is_array($this->tempDirs
)) {
2281 // fix test errors where this is not set
2284 foreach ($this->tempDirs
as $tempDir) {
2285 if (is_dir($tempDir)) {
2286 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2292 * Temporarily replace the singleton extension with a different one
2294 function setExtensionSystem(CRM_Extension_System
$system) {
2295 if ($this->origExtensionSystem
== NULL) {
2296 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2298 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2301 function unsetExtensionSystem() {
2302 if ($this->origExtensionSystem
!== NULL) {
2303 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2304 $this->origExtensionSystem
= NULL;
2309 * Temporarily alter the settings-metadata to add a mock setting.
2311 * WARNING: The setting metadata will disappear on the next cache-clear.
2316 function setMockSettingsMetaData($extras) {
2317 CRM_Core_BAO_Setting
::$_cache = array();
2318 $this->callAPISuccess('system','flush', array());
2319 CRM_Core_BAO_Setting
::$_cache = array();
2321 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2322 $metadata = array_merge($metadata, $extras);
2325 $fields = $this->callAPISuccess('setting', 'getfields', array());
2326 foreach ($extras as $key => $spec) {
2327 $this->assertNotEmpty($spec['title']);
2328 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2332 function financialAccountDelete($name) {
2333 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2334 $financialAccount->name
= $name;
2335 if($financialAccount->find(TRUE)) {
2336 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2337 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2338 $entityFinancialType->delete();
2339 $financialAccount->delete();
2344 * Use $ids as an instruction to do test cleanup
2346 function deleteFromIDSArray() {
2347 foreach ($this->ids
as $entity => $ids) {
2348 foreach ($ids as $id) {
2349 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2355 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2356 * (NB unclear if this is still required)
2358 function _sethtmlGlobals() {
2359 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2360 'required' => array(
2361 'html_quickform_rule_required',
2362 'HTML/QuickForm/Rule/Required.php'
2364 'maxlength' => array(
2365 'html_quickform_rule_range',
2366 'HTML/QuickForm/Rule/Range.php'
2368 'minlength' => array(
2369 'html_quickform_rule_range',
2370 'HTML/QuickForm/Rule/Range.php'
2372 'rangelength' => array(
2373 'html_quickform_rule_range',
2374 'HTML/QuickForm/Rule/Range.php'
2377 'html_quickform_rule_email',
2378 'HTML/QuickForm/Rule/Email.php'
2381 'html_quickform_rule_regex',
2382 'HTML/QuickForm/Rule/Regex.php'
2384 'lettersonly' => array(
2385 'html_quickform_rule_regex',
2386 'HTML/QuickForm/Rule/Regex.php'
2388 'alphanumeric' => array(
2389 'html_quickform_rule_regex',
2390 'HTML/QuickForm/Rule/Regex.php'
2393 'html_quickform_rule_regex',
2394 'HTML/QuickForm/Rule/Regex.php'
2396 'nopunctuation' => array(
2397 'html_quickform_rule_regex',
2398 'HTML/QuickForm/Rule/Regex.php'
2401 'html_quickform_rule_regex',
2402 'HTML/QuickForm/Rule/Regex.php'
2404 'callback' => array(
2405 'html_quickform_rule_callback',
2406 'HTML/QuickForm/Rule/Callback.php'
2409 'html_quickform_rule_compare',
2410 'HTML/QuickForm/Rule/Compare.php'
2413 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2414 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2416 'HTML/QuickForm/group.php',
2417 'HTML_QuickForm_group'
2420 'HTML/QuickForm/hidden.php',
2421 'HTML_QuickForm_hidden'
2424 'HTML/QuickForm/reset.php',
2425 'HTML_QuickForm_reset'
2427 'checkbox' => array(
2428 'HTML/QuickForm/checkbox.php',
2429 'HTML_QuickForm_checkbox'
2432 'HTML/QuickForm/file.php',
2433 'HTML_QuickForm_file'
2436 'HTML/QuickForm/image.php',
2437 'HTML_QuickForm_image'
2439 'password' => array(
2440 'HTML/QuickForm/password.php',
2441 'HTML_QuickForm_password'
2444 'HTML/QuickForm/radio.php',
2445 'HTML_QuickForm_radio'
2448 'HTML/QuickForm/button.php',
2449 'HTML_QuickForm_button'
2452 'HTML/QuickForm/submit.php',
2453 'HTML_QuickForm_submit'
2456 'HTML/QuickForm/select.php',
2457 'HTML_QuickForm_select'
2459 'hiddenselect' => array(
2460 'HTML/QuickForm/hiddenselect.php',
2461 'HTML_QuickForm_hiddenselect'
2464 'HTML/QuickForm/text.php',
2465 'HTML_QuickForm_text'
2467 'textarea' => array(
2468 'HTML/QuickForm/textarea.php',
2469 'HTML_QuickForm_textarea'
2471 'fckeditor' => array(
2472 'HTML/QuickForm/fckeditor.php',
2473 'HTML_QuickForm_FCKEditor'
2476 'HTML/QuickForm/tinymce.php',
2477 'HTML_QuickForm_TinyMCE'
2479 'dojoeditor' => array(
2480 'HTML/QuickForm/dojoeditor.php',
2481 'HTML_QuickForm_dojoeditor'
2484 'HTML/QuickForm/link.php',
2485 'HTML_QuickForm_link'
2487 'advcheckbox' => array(
2488 'HTML/QuickForm/advcheckbox.php',
2489 'HTML_QuickForm_advcheckbox'
2492 'HTML/QuickForm/date.php',
2493 'HTML_QuickForm_date'
2496 'HTML/QuickForm/static.php',
2497 'HTML_QuickForm_static'
2500 'HTML/QuickForm/header.php',
2501 'HTML_QuickForm_header'
2504 'HTML/QuickForm/html.php',
2505 'HTML_QuickForm_html'
2507 'hierselect' => array(
2508 'HTML/QuickForm/hierselect.php',
2509 'HTML_QuickForm_hierselect'
2511 'autocomplete' => array(
2512 'HTML/QuickForm/autocomplete.php',
2513 'HTML_QuickForm_autocomplete'
2516 'HTML/QuickForm/xbutton.php',
2517 'HTML_QuickForm_xbutton'
2519 'advmultiselect' => array(
2520 'HTML/QuickForm/advmultiselect.php',
2521 'HTML_QuickForm_advmultiselect'
2527 * Set up an acl allowing contact to see 2 specified groups
2528 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2530 * You need to have precreated these groups & created the user e.g
2531 * $this->createLoggedInUser();
2532 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2533 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2536 function setupACL() {
2537 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2538 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2539 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2540 'label' => 'pick me',
2545 CRM_Core_DAO
::executeQuery("
2546 TRUNCATE civicrm_acl_cache
2549 CRM_Core_DAO
::executeQuery("
2550 TRUNCATE civicrm_acl_contact_cache
2554 CRM_Core_DAO
::executeQuery("
2555 INSERT INTO civicrm_acl_entity_role (
2556 `acl_role_id`, `entity_table`, `entity_id`
2557 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2560 CRM_Core_DAO
::executeQuery("
2561 INSERT INTO civicrm_acl (
2562 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2565 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2569 CRM_Core_DAO
::executeQuery("
2570 INSERT INTO civicrm_acl (
2571 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2574 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2577 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2578 $this->callAPISuccess('group_contact', 'create', array(
2579 'group_id' => $this->_permissionedGroup
,
2580 'contact_id' => $this->_loggedInUser
,
2583 CRM_ACL_BAO_Cache
::resetCache();
2584 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2588 * Create an instance of the paypal processor
2589 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2590 * this parent class & we don't have a structure for that yet
2591 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2592 * & the best protection agains that is the functions this class affords
2594 function paymentProcessorCreate($params = array()) {
2595 $params = array_merge(array(
2597 'domain_id' => CRM_Core_Config
::domainID(),
2598 'payment_processor_type_id' => 'PayPal',
2602 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2603 'password' => '1183377788',
2604 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2605 'url_site' => 'https://www.sandbox.paypal.com/',
2606 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2607 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2608 'class_name' => 'Payment_PayPalImpl',
2609 'billing_mode' => 3,
2610 'financial_type_id' => 1,
2613 if(!is_numeric($params['payment_processor_type_id'])) {
2614 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2616 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2617 'name' => $params['payment_processor_type_id'],
2621 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2622 return $result['id'];
2626 function CiviUnitTestCase_fatalErrorHandler($message) {
2627 throw new Exception("{$message['message']}: {$message['code']}");