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 * Track tables we have modified during a test
88 protected $_tablesToTruncate = array();
91 * @var array of temporary directory names
101 * @var boolean populateOnce allows to skip db resets in setUp
103 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
104 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
107 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
109 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
111 public static $populateOnce = FALSE;
114 * Allow classes to state E-notice compliance
116 public $_eNoticeCompliant = TRUE;
119 * @var boolean DBResetRequired allows skipping DB reset
120 * in specific test case. If you still need
121 * to reset single test (method) of such case, call
122 * $this->cleanDB() in the first line of this
125 public $DBResetRequired = TRUE;
130 * Because we are overriding the parent class constructor, we
131 * need to show the same arguments as exist in the constructor of
132 * PHPUnit_Framework_TestCase, since
133 * PHPUnit_Framework_TestSuite::createTest() creates a
134 * ReflectionClass of the Test class and checks the constructor
135 * of that class to decide how to set up the test.
137 * @param string $name
139 * @param string $dataName
141 function __construct($name = NULL, array$data = array(), $dataName = '') {
142 parent
::__construct($name, $data, $dataName);
144 // we need full error reporting
145 error_reporting(E_ALL
& ~E_NOTICE
);
147 if (!empty($GLOBALS['mysql_db'])) {
148 self
::$_dbName = $GLOBALS['mysql_db'];
151 self
::$_dbName = 'civicrm_tests_dev';
154 // create test database
155 self
::$utils = new Utils($GLOBALS['mysql_host'],
156 $GLOBALS['mysql_port'],
157 $GLOBALS['mysql_user'],
158 $GLOBALS['mysql_pass']
161 // also load the class loader
162 require_once 'CRM/Core/ClassLoader.php';
163 CRM_Core_ClassLoader
::singleton()->register();
164 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
165 _civix_phpunit_setUp();
169 function requireDBReset() {
170 return $this->DBResetRequired
;
173 static function getDBName() {
174 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
179 * Create database connection for this instance
181 * Initialize the test database if it hasn't been initialized
183 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
185 protected function getConnection() {
186 $dbName = self
::$_dbName;
187 if (!self
::$dbInit) {
188 $dbName = self
::getDBName();
190 // install test database
191 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
193 static::_populateDB(FALSE, $this);
195 self
::$dbInit = TRUE;
197 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
201 * Required implementation of abstract method
203 protected function getDataSet() {
207 * @param bool $perClass
208 * @param null $object
209 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
211 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
213 if ($perClass ||
$object == NULL) {
217 $dbreset = $object->requireDBReset();
220 if (self
::$populateOnce ||
!$dbreset) {
223 self
::$populateOnce = NULL;
225 $dbName = self
::getDBName();
226 $pdo = self
::$utils->pdo
;
227 // only consider real tables and not views
228 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
229 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
231 $truncates = array();
233 foreach ($tables as $table) {
235 if (substr($table['table_name'], 0, 4) == 'log_') {
239 // don't change list of installed extensions
240 if ($table['table_name'] == 'civicrm_extension') {
244 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
245 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
248 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
254 "SET foreign_key_checks = 0",
255 // SQL mode needs to be strict, that's our standard
256 "SET SQL_MODE='STRICT_ALL_TABLES';",
257 "SET global innodb_flush_log_at_trx_commit = 2;",
259 $queries = array_merge($queries, $truncates);
260 $queries = array_merge($queries, $drops);
261 foreach ($queries as $query) {
262 if (self
::$utils->do_query($query) === FALSE) {
263 // failed to create test database
264 echo "failed to create test db.";
269 // initialize test database
270 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
271 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
272 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
274 $query2 = file_get_contents($sql_file2);
275 $query3 = file_get_contents($sql_file3);
276 $query4 = file_get_contents($sql_file4);
277 if (self
::$utils->do_query($query2) === FALSE) {
278 echo "Cannot load civicrm_data.mysql. Aborting.";
281 if (self
::$utils->do_query($query3) === FALSE) {
282 echo "Cannot load test_data.mysql. Aborting.";
285 if (self
::$utils->do_query($query4) === FALSE) {
286 echo "Cannot load test_data.mysql. Aborting.";
290 // done with all the loading, get transactions back
291 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
292 echo "Cannot set global? Huh?";
296 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
297 echo "Cannot get foreign keys back? Huh?";
301 unset($query, $query2, $query3);
304 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
309 public static function setUpBeforeClass() {
310 static::_populateDB(TRUE);
312 // also set this global hack
313 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
315 $env = new CRM_Utils_Check_Env();
316 CRM_Utils_Check
::singleton()->assertValid($env->checkAll());
320 * Common setup functions for all unit tests
322 protected function setUp() {
323 CRM_Utils_Hook
::singleton(TRUE);
324 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
325 // Use a temporary file for STDIN
326 $GLOBALS['stdin'] = tmpfile();
327 if ($GLOBALS['stdin'] === FALSE) {
328 echo "Couldn't open temporary file\n";
332 // Get and save a connection to the database
333 $this->_dbconn
= $this->getConnection();
335 // reload database before each test
336 // $this->_populateDB();
338 // "initialize" CiviCRM to avoid problems when running single tests
339 // FIXME: look at it closer in second stage
341 // initialize the object once db is loaded
342 CRM_Core_Config
::$_mail = NULL;
343 $config = CRM_Core_Config
::singleton();
345 // when running unit tests, use mockup user framework
346 $config->setUserFramework('UnitTests');
348 // also fix the fatal error handler to throw exceptions,
350 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
352 // enable backtrace to get meaningful errors
353 $config->backtrace
= 1;
355 // disable any left-over test extensions
356 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
358 // reset all the caches
359 CRM_Utils_System
::flushCache();
361 // clear permissions stub to not check permissions
362 $config = CRM_Core_Config
::singleton();
363 $config->userPermissionClass
->permissions
= NULL;
365 //flush component settings
366 CRM_Core_Component
::getEnabledComponents(TRUE);
368 if ($this->_eNoticeCompliant
) {
369 error_reporting(E_ALL
);
372 error_reporting(E_ALL
& ~E_NOTICE
);
377 * Read everything from the datasets directory and insert into the db
379 public function loadAllFixtures() {
380 $fixturesDir = __DIR__
. '/../../fixtures';
382 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
384 $xmlFiles = glob($fixturesDir . '/*.xml');
385 foreach ($xmlFiles as $xmlFixture) {
386 $op = new PHPUnit_Extensions_Database_Operation_Insert();
387 $dataset = new PHPUnit_Extensions_Database_DataSet_XMLDataSet($xmlFixture);
388 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
389 $op->execute($this->_dbconn
, $dataset);
392 $yamlFiles = glob($fixturesDir . '/*.yaml');
393 foreach ($yamlFiles as $yamlFixture) {
394 $op = new PHPUnit_Extensions_Database_Operation_Insert();
395 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
396 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
397 $op->execute($this->_dbconn
, $dataset);
400 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
404 * emulate a logged in user since certain functions use that
405 * value to store a record in the DB (like activity)
408 public function createLoggedInUser() {
410 'first_name' => 'Logged In',
411 'last_name' => 'User ' . rand(),
412 'contact_type' => 'Individual',
414 $contactID = $this->individualCreate($params);
416 $session = CRM_Core_Session
::singleton();
417 $session->set('userID', $contactID);
420 public function cleanDB() {
421 self
::$populateOnce = NULL;
422 $this->DBResetRequired
= TRUE;
424 $this->_dbconn
= $this->getConnection();
425 static::_populateDB();
426 $this->tempDirs
= array();
430 * Common teardown functions for all unit tests
432 protected function tearDown() {
433 error_reporting(E_ALL
& ~E_NOTICE
);
434 $tablesToTruncate = array('civicrm_contact');
435 $this->quickCleanup($tablesToTruncate);
436 $this->cleanTempDirs();
437 $this->unsetExtensionSystem();
441 * FIXME: Maybe a better way to do it
443 function foreignKeyChecksOff() {
444 self
::$utils = new Utils($GLOBALS['mysql_host'],
445 $GLOBALS['mysql_port'],
446 $GLOBALS['mysql_user'],
447 $GLOBALS['mysql_pass']
449 $dbName = self
::getDBName();
450 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
451 if (self
::$utils->do_query($query) === FALSE) {
453 echo 'Cannot set foreign_key_checks = 0';
459 function foreignKeyChecksOn() {
460 // FIXME: might not be needed if previous fixme implemented
464 * Generic function to compare expected values after an api call to retrieved
467 * @daoName string DAO Name of object we're evaluating.
468 * @id int Id of object
469 * @match array Associative array of field name => expected value. Empty if asserting
470 * that a DELETE occurred
471 * @delete boolean True if we're checking that a DELETE action occurred.
473 function assertDBState($daoName, $id, $match, $delete = FALSE) {
475 // adding this here since developers forget to check for an id
476 // and hence we get the first value in the db
477 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
480 $object = new $daoName();
484 // If we're asserting successful record deletion, make sure object is NOT found.
486 if ($object->find(TRUE)) {
487 $this->fail("Object not deleted by delete operation: $daoName, $id");
492 // Otherwise check matches of DAO field values against expected values in $match.
493 if ($object->find(TRUE)) {
494 $fields = & $object->fields();
495 foreach ($fields as $name => $value) {
496 $dbName = $value['name'];
497 if (isset($match[$name])) {
499 $this->assertEquals($object->$dbName, $match[$name]);
501 elseif (isset($match[$dbName])) {
503 $this->assertEquals($object->$dbName, $match[$dbName]);
508 $this->fail("Could not retrieve object: $daoName, $id");
511 $matchSize = count($match);
512 if ($verifiedCount != $matchSize) {
513 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
517 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
518 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
519 if (empty($searchValue)) {
520 $this->fail("empty value passed to assertDBNotNull");
522 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
523 $this->assertNotNull($value, $message);
528 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
529 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
530 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
531 $this->assertNull($value, $message);
534 // Request a record from the DB by id. Success if row not found.
535 function assertDBRowNotExist($daoName, $id, $message = NULL) {
536 $message = $message ?
$message : "$daoName (#$id) should not exist";
537 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
538 $this->assertNull($value, $message);
541 // Request a record from the DB by id. Success if row not found.
542 function assertDBRowExist($daoName, $id, $message = NULL) {
543 $message = $message ?
$message : "$daoName (#$id) should exist";
544 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
545 $this->assertEquals($id, $value, $message);
548 // Compare a single column value in a retrieved DB record to an expected value
549 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
550 $expectedValue, $message
552 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
553 $this->assertEquals($value, $expectedValue, $message);
556 // Compare all values in a single retrieved DB record to an array of expected values
557 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
558 //get the values from db
560 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
562 // compare db values with expected values
563 self
::assertAttributesEquals($expectedValues, $dbValues);
567 * Assert that a SQL query returns a given value
569 * The first argument is an expected value. The remaining arguments are passed
570 * to CRM_Core_DAO::singleValueQuery
572 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
573 * array(1 => array("Whiz", "String")));
575 function assertDBQuery($expected, $query, $params = array()) {
576 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
577 $this->assertEquals($expected, $actual,
578 sprintf('expected=[%s] actual=[%s] query=[%s]',
579 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
585 * Assert that two array-trees are exactly equal, notwithstanding
586 * the sorting of keys
588 * @param array $expected
589 * @param array $actual
591 function assertTreeEquals($expected, $actual) {
594 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
595 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
599 $this->assertEquals($e, $a);
603 * Assert that two numbers are approximately equal
605 * @param int|float $expected
606 * @param int|float $actual
607 * @param int|float $tolerance
608 * @param string $message
610 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
611 if ($message === NULL) {
612 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
614 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
617 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
618 foreach ($expectedValues as $paramName => $paramValue) {
619 if (isset($actualValues[$paramName])) {
620 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
623 $this->fail("Attribute '$paramName' not present in actual array.");
628 function assertArrayKeyExists($key, &$list) {
629 $result = isset($list[$key]) ?
TRUE : FALSE;
630 $this->assertTrue($result, ts("%1 element exists?",
635 function assertArrayValueNotNull($key, &$list) {
636 $this->assertArrayKeyExists($key, $list);
638 $value = isset($list[$key]) ?
$list[$key] : NULL;
639 $this->assertTrue($value,
640 ts("%1 element not null?",
647 * check that api returned 'is_error' => 0
648 * else provide full message
649 * @param array $apiResult api result
650 * @param string $prefix extra test to add to message
652 function assertAPISuccess($apiResult, $prefix = '') {
653 if (!empty($prefix)) {
656 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
658 if(!empty($apiResult['debug_information'])) {
659 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
661 if(!empty($apiResult['trace'])){
662 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
664 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
668 * check that api returned 'is_error' => 1
669 * else provide full message
670 * @param array $apiResult api result
671 * @param string $prefix extra test to add to message
673 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
674 if (!empty($prefix)) {
677 if($expectedError && !empty($apiResult['is_error'])){
678 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
680 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
681 $this->assertNotEmpty($apiResult['error_message']);
684 function assertType($expected, $actual, $message = '') {
685 return $this->assertInternalType($expected, $actual, $message);
689 * check that a deleted item has been deleted
691 function assertAPIDeleted($entity, $id) {
692 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
697 * check that api returned 'is_error' => 1
698 * else provide full message
699 * @param array $apiResult api result
700 * @param string $prefix extra test to add to message
702 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
703 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
704 foreach ($valuesToExclude as $value) {
705 if(isset($result[$value])) {
706 unset($result[$value]);
708 if(isset($expected[$value])) {
709 unset($expected[$value]);
712 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
716 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
723 function civicrm_api($entity, $action, $params) {
724 return civicrm_api($entity, $action, $params);
728 * This function exists to wrap api functions
729 * so we can ensure they succeed & throw exceptions without litterering the test with checks
730 * @param string $entity
731 * @param string $action
732 * @param array $params
733 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
734 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
735 * for getsingle the array is compared against an array passed in - the id is not compared (for
738 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
739 $params = array_merge(array(
740 'version' => $this->_apiversion
,
745 switch (strtolower($action)) {
747 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
749 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
751 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
753 $result = $this->civicrm_api($entity, $action, $params);
754 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
759 * This function exists to wrap api getValue function & check the result
760 * so we can ensure they succeed & throw exceptions without litterering the test with checks
761 * There is a type check in this
762 * @param string $entity
763 * @param array $params
764 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
772 function callAPISuccessGetValue($entity, $params, $type = NULL) {
774 'version' => $this->_apiversion
,
777 $result = $this->civicrm_api($entity, 'getvalue', $params);
779 if($type == 'integer'){
780 // api seems to return integers as strings
781 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
784 $this->assertType($type, $result, "returned result should have been of type $type but was " );
791 * This function exists to wrap api getsingle function & check the result
792 * so we can ensure they succeed & throw exceptions without litterering the test with checks
793 * @param string $entity
794 * @param array $params
795 * @param array $checkAgainst - array to compare result against
803 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
805 'version' => $this->_apiversion
,
808 $result = $this->civicrm_api($entity, 'getsingle', $params);
809 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
810 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
813 // @todo - have gone with the fn that unsets id? should we check id?
814 $this->checkArrayEquals($result, $checkAgainst);
819 * This function exists to wrap api getValue function & check the result
820 * so we can ensure they succeed & throw exceptions without litterering the test with checks
821 * There is a type check in this
822 * @param string $entity
823 * @param array $params
824 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
832 function callAPISuccessGetCount($entity, $params, $count = NULL) {
834 'version' => $this->_apiversion
,
837 $result = $this->civicrm_api($entity, 'getcount', $params);
838 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
839 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
842 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
848 * This function exists to wrap api functions
849 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
851 * @param string $entity
852 * @param string $action
853 * @param array $params
854 * @param string $function - pass this in to create a generated example
855 * @param string $file - pass this in to create a generated example
856 * @param string $description
857 * @param string|null $subfile
858 * @param string|null $actionName
861 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
862 $params['version'] = $this->_apiversion
;
863 $result = $this->callAPISuccess($entity, $action, $params);
864 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
869 * This function exists to wrap api functions
870 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
871 * @param string $entity
872 * @param string $action
873 * @param array $params
874 * @param string $expectedErrorMessage error
876 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
877 if (is_array($params)) {
879 'version' => $this->_apiversion
,
882 $result = $this->civicrm_api($entity, $action, $params);
883 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
888 * Create required data based on $this->entity & $this->params
889 * This is just a way to set up the test data for delete & get functions
890 * so the distinction between set
891 * up & tested functions is clearer
893 * @return array api Result
895 public function createTestEntity(){
896 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
900 * Generic function to create Organisation, to be used in test cases
902 * @param array parameters for civicrm_contact_add api function call
904 * @return int id of Organisation created
906 function organizationCreate($params = array()) {
911 'organization_name' => 'Unit Test Organization',
912 'contact_type' => 'Organization',
914 return $this->_contactCreate(array_merge($orgParams, $params));
918 * Generic function to create Individual, to be used in test cases
920 * @param array parameters for civicrm_contact_add api function call
922 * @return int id of Individual created
924 function individualCreate($params = array()) {
925 $params = array_merge(array(
926 'first_name' => 'Anthony',
927 'middle_name' => 'J.',
928 'last_name' => 'Anderson',
931 'email' => 'anthony_anderson@civicrm.org',
932 'contact_type' => 'Individual',
935 return $this->_contactCreate($params);
939 * Generic function to create Household, to be used in test cases
941 * @param array parameters for civicrm_contact_add api function call
943 * @return int id of Household created
945 function householdCreate($params = array()) {
946 $params = array_merge(array(
947 'household_name' => 'Unit Test household',
948 'contact_type' => 'Household',
950 return $this->_contactCreate($params);
954 * Private helper function for calling civicrm_contact_add
959 * @internal param \parameters $array for civicrm_contact_add api function call
961 * @return int id of Household created
963 private function _contactCreate($params) {
964 $result = $this->callAPISuccess('contact', 'create', $params);
965 if (!empty($result['is_error']) ||
empty($result['id'])) {
966 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
968 return $result['id'];
971 function contactDelete($contactID) {
974 'skip_undelete' => 1,
977 $domain = new CRM_Core_BAO_Domain
;
978 $domain->contact_id
= $contactID;
979 if ($domain->find(TRUE)) {
980 // we are finding tests trying to delete the domain contact in cleanup
981 //since this is mainly for cleanup lets put a safeguard here
984 $result = $this->callAPISuccess('contact', 'delete', $params);
988 function contactTypeDelete($contactTypeId) {
989 require_once 'CRM/Contact/BAO/ContactType.php';
990 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
992 throw new Exception('Could not delete contact type');
996 function membershipTypeCreate($params = array()) {
997 CRM_Member_PseudoConstant
::flush('membershipType');
998 CRM_Core_Config
::clearDBCache();
999 $memberOfOrganization = $this->organizationCreate();
1000 $params = array_merge(array(
1001 'name' => 'General',
1002 'duration_unit' => 'year',
1003 'duration_interval' => 1,
1004 'period_type' => 'rolling',
1005 'member_of_contact_id' => $memberOfOrganization,
1007 'financial_type_id' => 1,
1013 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1015 CRM_Member_PseudoConstant
::flush('membershipType');
1016 CRM_Utils_Cache
::singleton()->flush();
1018 return $result['id'];
1021 function contactMembershipCreate($params) {
1023 'join_date' => '2007-01-21',
1024 'start_date' => '2007-01-21',
1025 'end_date' => '2007-12-21',
1026 'source' => 'Payment',
1029 foreach ($pre as $key => $val) {
1030 if (!isset($params[$key])) {
1031 $params[$key] = $val;
1035 $result = $this->callAPISuccess('Membership', 'create', $params);
1036 return $result['id'];
1040 * Function to delete Membership Type
1042 * @param int $membershipTypeID
1044 function membershipTypeDelete($params) {
1045 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1049 function membershipDelete($membershipID) {
1050 $deleteParams = array('id' => $membershipID);
1051 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1055 function membershipStatusCreate($name = 'test member status') {
1056 $params['name'] = $name;
1057 $params['start_event'] = 'start_date';
1058 $params['end_event'] = 'end_date';
1059 $params['is_current_member'] = 1;
1060 $params['is_active'] = 1;
1062 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1063 CRM_Member_PseudoConstant
::flush('membershipStatus');
1064 return $result['id'];
1067 function membershipStatusDelete($membershipStatusID) {
1068 if (!$membershipStatusID) {
1071 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1075 function relationshipTypeCreate($params = array()) {
1076 $params = array_merge(array(
1077 'name_a_b' => 'Relation 1 for relationship type create',
1078 'name_b_a' => 'Relation 2 for relationship type create',
1079 'contact_type_a' => 'Individual',
1080 'contact_type_b' => 'Organization',
1087 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1088 CRM_Core_PseudoConstant
::flush('relationshipType');
1090 return $result['id'];
1094 * Function to delete Relatinship Type
1096 * @param int $relationshipTypeID
1098 function relationshipTypeDelete($relationshipTypeID) {
1099 $params['id'] = $relationshipTypeID;
1100 $this->callAPISuccess('relationship_type', 'delete', $params);
1103 function paymentProcessorTypeCreate($params = NULL) {
1104 if (is_null($params)) {
1106 'name' => 'API_Test_PP',
1107 'title' => 'API Test Payment Processor',
1108 'class_name' => 'CRM_Core_Payment_APITest',
1109 'billing_mode' => 'form',
1115 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1117 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1119 return $result['id'];
1123 * Function to create Participant
1125 * @param array $params array of contact id and event id values
1127 * @return int $id of participant created
1129 function participantCreate($params) {
1130 if(empty($params['contact_id'])){
1131 $params['contact_id'] = $this->individualCreate();
1133 if(empty($params['event_id'])){
1134 $event = $this->eventCreate();
1135 $params['event_id'] = $event['id'];
1140 'register_date' => 20070219,
1141 'source' => 'Wimbeldon',
1142 'event_level' => 'Payment',
1146 $params = array_merge($defaults, $params);
1147 $result = $this->callAPISuccess('Participant', 'create', $params);
1148 return $result['id'];
1152 * Function to create Payment Processor
1154 * @return object of Payment Processsor
1156 function processorCreate() {
1157 $processorParams = array(
1160 'payment_processor_type_id' => 10,
1161 'financial_account_id' => 12,
1164 'url_site' => 'http://dummy.com',
1165 'url_recur' => 'http://dummy.com',
1166 'billing_mode' => 1,
1168 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1169 return $paymentProcessor;
1173 * Function to create contribution page
1175 * @return object of contribution page
1177 function contributionPageCreate($params) {
1178 $this->_pageParams
= array(
1179 'title' => 'Test Contribution Page',
1180 'financial_type_id' => 1,
1181 'currency' => 'USD',
1182 'financial_account_id' => 1,
1183 'payment_processor' => $params['processor_id'],
1185 'is_allow_other_amount' => 1,
1187 'max_amount' => 1000,
1189 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1190 return $contributionPage;
1194 * Function to create Tag
1196 * @return array result of created tag
1198 function tagCreate($params = array()) {
1200 'name' => 'New Tag3',
1201 'description' => 'This is description for Our New Tag ',
1204 $params = array_merge($defaults, $params);
1205 $result = $this->callAPISuccess('Tag', 'create', $params);
1206 return $result['values'][$result['id']];
1210 * Function to delete Tag
1212 * @param int $tagId id of the tag to be deleted
1214 function tagDelete($tagId) {
1215 require_once 'api/api.php';
1219 $result = $this->callAPISuccess('Tag', 'delete', $params);
1220 return $result['id'];
1224 * Add entity(s) to the tag
1226 * @param array $params
1228 function entityTagAdd($params) {
1229 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1234 * Function to create contribution
1236 * @param int $cID contact_id
1237 * @param int $cTypeID id of financial type
1239 * @return int id of created contribution
1241 function pledgeCreate($cID) {
1243 'contact_id' => $cID,
1244 'pledge_create_date' => date('Ymd'),
1245 'start_date' => date('Ymd'),
1246 'scheduled_date' => date('Ymd'),
1248 'pledge_status_id' => '2',
1249 'financial_type_id' => '1',
1250 'pledge_original_installment_amount' => 20,
1251 'frequency_interval' => 5,
1252 'frequency_unit' => 'year',
1253 'frequency_day' => 15,
1254 'installments' => 5,
1257 $result = $this->callAPISuccess('Pledge', 'create', $params);
1258 return $result['id'];
1262 * Function to delete contribution
1264 * @param int $contributionId
1266 function pledgeDelete($pledgeId) {
1268 'pledge_id' => $pledgeId,
1270 $this->callAPISuccess('Pledge', 'delete', $params);
1274 * Function to create contribution
1276 * @param int $cID contact_id
1277 * @param int $cTypeID id of financial type
1279 * @return int id of created contribution
1281 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1284 'contact_id' => $cID,
1285 'receive_date' => date('Ymd'),
1286 'total_amount' => 100.00,
1287 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1288 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1289 'non_deductible_amount' => 10.00,
1290 'trxn_id' => $trxnID,
1291 'invoice_id' => $invoiceID,
1293 'contribution_status_id' => 1,
1294 // 'note' => 'Donating for Nobel Cause', *Fixme
1298 $params['fee_amount'] = 5.00;
1299 $params['net_amount'] = 95.00;
1302 $result = $this->callAPISuccess('contribution', 'create', $params);
1303 return $result['id'];
1307 * Function to create online contribution
1309 * @param int $financialType id of financial type
1311 * @return int id of created contribution
1313 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1314 $contribParams = array(
1315 'contact_id' => $params['contact_id'],
1316 'receive_date' => date('Ymd'),
1317 'total_amount' => 100.00,
1318 'financial_type_id' => $financialType,
1319 'contribution_page_id' => $params['contribution_page_id'],
1321 'invoice_id' => 67890,
1324 $contribParams = array_merge($contribParams, $params);
1325 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1327 return $result['id'];
1331 * Function to delete contribution
1333 * @param int $contributionId
1335 function contributionDelete($contributionId) {
1337 'contribution_id' => $contributionId,
1339 $result = $this->callAPISuccess('contribution', 'delete', $params);
1344 * Function to create an Event
1346 * @param array $params name-value pair for an event
1348 * @return array $event
1350 function eventCreate($params = array()) {
1351 // if no contact was passed, make up a dummy event creator
1352 if (!isset($params['contact_id'])) {
1353 $params['contact_id'] = $this->_contactCreate(array(
1354 'contact_type' => 'Individual',
1355 'first_name' => 'Event',
1356 'last_name' => 'Creator',
1360 // set defaults for missing params
1361 $params = array_merge(array(
1362 'title' => 'Annual CiviCRM meet',
1363 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1364 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1365 'event_type_id' => 1,
1367 'start_date' => 20081021,
1368 'end_date' => 20081023,
1369 'is_online_registration' => 1,
1370 'registration_start_date' => 20080601,
1371 'registration_end_date' => 20081015,
1372 'max_participants' => 100,
1373 'event_full_text' => 'Sorry! We are already full',
1376 'is_show_location' => 0,
1379 return $this->callAPISuccess('Event', 'create', $params);
1383 * Function to delete event
1385 * @param int $id ID of the event
1387 function eventDelete($id) {
1391 return $this->callAPISuccess('event', 'delete', $params);
1395 * Function to delete participant
1397 * @param int $participantID
1399 function participantDelete($participantID) {
1401 'id' => $participantID,
1403 return $this->callAPISuccess('Participant', 'delete', $params);
1407 * Function to create participant payment
1409 * @return int $id of created payment
1411 function participantPaymentCreate($participantID, $contributionID = NULL) {
1412 //Create Participant Payment record With Values
1414 'participant_id' => $participantID,
1415 'contribution_id' => $contributionID,
1418 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1419 return $result['id'];
1423 * Function to delete participant payment
1425 * @param int $paymentID
1427 function participantPaymentDelete($paymentID) {
1431 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1435 * Function to add a Location
1437 * @return int location id of created location
1439 function locationAdd($contactID) {
1442 'location_type' => 'New Location Type',
1444 'name' => 'Saint Helier St',
1445 'county' => 'Marin',
1446 'country' => 'United States',
1447 'state_province' => 'Michigan',
1448 'supplemental_address_1' => 'Hallmark Ct',
1449 'supplemental_address_2' => 'Jersey Village',
1454 'contact_id' => $contactID,
1455 'address' => $address,
1456 'location_format' => '2.0',
1457 'location_type' => 'New Location Type',
1460 $result = $this->callAPISuccess('Location', 'create', $params);
1465 * Function to delete Locations of contact
1467 * @params array $pamars parameters
1469 function locationDelete($params) {
1470 $result = $this->callAPISuccess('Location', 'delete', $params);
1474 * Function to add a Location Type
1476 * @return int location id of created location
1478 function locationTypeCreate($params = NULL) {
1479 if ($params === NULL) {
1481 'name' => 'New Location Type',
1482 'vcard_name' => 'New Location Type',
1483 'description' => 'Location Type for Delete',
1488 $locationType = new CRM_Core_DAO_LocationType();
1489 $locationType->copyValues($params);
1490 $locationType->save();
1491 // clear getfields cache
1492 CRM_Core_PseudoConstant
::flush();
1493 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1494 return $locationType;
1498 * Function to delete a Location Type
1500 * @param int location type id
1502 function locationTypeDelete($locationTypeId) {
1503 $locationType = new CRM_Core_DAO_LocationType();
1504 $locationType->id
= $locationTypeId;
1505 $locationType->delete();
1509 * Function to add a Group
1511 * @params array to add group
1513 * @return int groupId of created group
1516 function groupCreate($params = array()) {
1517 $params = array_merge(array(
1518 'name' => 'Test Group 1',
1520 'title' => 'New Test Group Created',
1521 'description' => 'New Test Group Created',
1523 'visibility' => 'Public Pages',
1524 'group_type' => array(
1530 $result = $this->callAPISuccess('Group', 'create', $params);
1531 return $result['id'];
1535 * Function to delete a Group
1539 function groupDelete($gid) {
1545 $this->callAPISuccess('Group', 'delete', $params);
1550 * @param array $params
1552 function uFFieldCreate($params = array()) {
1553 $params = array_merge(array(
1555 'field_name' => 'first_name',
1558 'visibility' => 'Public Pages and Listings',
1559 'is_searchable' => '1',
1560 'label' => 'first_name',
1561 'field_type' => 'Individual',
1564 $this->callAPISuccess('uf_field', 'create', $params);
1567 * Function to add a UF Join Entry
1569 * @return int $id of created UF Join
1571 function ufjoinCreate($params = NULL) {
1572 if ($params === NULL) {
1575 'module' => 'CiviEvent',
1576 'entity_table' => 'civicrm_event',
1582 $result = $this->callAPISuccess('uf_join', 'create', $params);
1587 * Function to delete a UF Join Entry
1589 * @param array with missing uf_group_id
1591 function ufjoinDelete($params = NULL) {
1592 if ($params === NULL) {
1595 'module' => 'CiviEvent',
1596 'entity_table' => 'civicrm_event',
1599 'uf_group_id' => '',
1603 crm_add_uf_join($params);
1607 * Function to create Group for a contact
1609 * @param int $contactId
1611 function contactGroupCreate($contactId) {
1613 'contact_id.1' => $contactId,
1617 $this->callAPISuccess('GroupContact', 'Create', $params);
1621 * Function to delete Group for a contact
1623 * @param array $params
1625 function contactGroupDelete($contactId) {
1627 'contact_id.1' => $contactId,
1630 $this->civicrm_api('GroupContact', 'Delete', $params);
1634 * Function to create Activity
1636 * @param int $contactId
1638 function activityCreate($params = NULL) {
1640 if ($params === NULL) {
1641 $individualSourceID = $this->individualCreate();
1643 $contactParams = array(
1644 'first_name' => 'Julia',
1645 'Last_name' => 'Anderson',
1647 'email' => 'julia_anderson@civicrm.org',
1648 'contact_type' => 'Individual',
1651 $individualTargetID = $this->individualCreate($contactParams);
1654 'source_contact_id' => $individualSourceID,
1655 'target_contact_id' => array($individualTargetID),
1656 'assignee_contact_id' => array($individualTargetID),
1657 'subject' => 'Discussion on warm beer',
1658 'activity_date_time' => date('Ymd'),
1659 'duration_hours' => 30,
1660 'duration_minutes' => 20,
1661 'location' => 'Baker Street',
1662 'details' => 'Lets schedule a meeting',
1664 'activity_name' => 'Meeting',
1668 $result = $this->callAPISuccess('Activity', 'create', $params);
1670 $result['target_contact_id'] = $individualTargetID;
1671 $result['assignee_contact_id'] = $individualTargetID;
1676 * Function to create an activity type
1678 * @params array $params parameters
1680 function activityTypeCreate($params) {
1681 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1686 * Function to delete activity type
1688 * @params Integer $activityTypeId id of the activity type
1690 function activityTypeDelete($activityTypeId) {
1691 $params['activity_type_id'] = $activityTypeId;
1692 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1697 * Function to create custom group
1699 * @param string $className
1700 * @param string $title name of custom group
1702 function customGroupCreate($params = array()) {
1704 'title' => 'new custom group',
1705 'extends' => 'Contact',
1707 'style' => 'Inline',
1711 $params = array_merge($defaults, $params);
1713 if (strlen($params['title']) > 13) {
1714 $params['title'] = substr($params['title'], 0, 13);
1717 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1718 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1720 return $this->callAPISuccess('custom_group', 'create', $params);
1724 * existing function doesn't allow params to be over-ridden so need a new one
1725 * this one allows you to only pass in the params you want to change
1727 function CustomGroupCreateByParams($params = array()) {
1729 'title' => "API Custom Group",
1730 'extends' => 'Contact',
1732 'style' => 'Inline',
1735 $params = array_merge($defaults, $params);
1736 return $this->callAPISuccess('custom_group', 'create', $params);
1740 * Create custom group with multi fields
1742 function CustomGroupMultipleCreateByParams($params = array()) {
1747 $params = array_merge($defaults, $params);
1748 return $this->CustomGroupCreateByParams($params);
1752 * Create custom group with multi fields
1754 function CustomGroupMultipleCreateWithFields($params = array()) {
1755 // also need to pass on $params['custom_field'] if not set but not in place yet
1757 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1758 $ids['custom_group_id'] = $customGroup['id'];
1760 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1762 $ids['custom_field_id'][] = $customField['id'];
1764 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1765 $ids['custom_field_id'][] = $customField['id'];
1767 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1768 $ids['custom_field_id'][] = $customField['id'];
1774 * Create a custom group with a single text custom field. See
1775 * participant:testCreateWithCustom for how to use this
1777 * @param string $function __FUNCTION__
1778 * @param string $file __FILE__
1780 * @return array $ids ids of created objects
1783 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1784 $params = array('title' => $function);
1785 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1786 $params['extends'] = $entity ?
$entity : 'Contact';
1787 $customGroup = $this->CustomGroupCreate($params);
1788 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1789 CRM_Core_PseudoConstant
::flush();
1791 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1795 * Function to delete custom group
1797 * @param int $customGroupID
1799 function customGroupDelete($customGroupID) {
1800 $params['id'] = $customGroupID;
1801 return $this->callAPISuccess('custom_group', 'delete', $params);
1805 * Function to create custom field
1807 * @param array $params (custom_group_id) is required
1808 * @param string $name name of custom field
1809 * @param int $apiversion API version to use
1811 function customFieldCreate($params) {
1812 $params = array_merge(array(
1813 'label' => 'Custom Field',
1814 'data_type' => 'String',
1815 'html_type' => 'Text',
1816 'is_searchable' => 1,
1818 'default_value' => 'defaultValue',
1821 $result = $this->callAPISuccess('custom_field', 'create', $params);
1823 if ($result['is_error'] == 0 && isset($result['id'])) {
1824 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1825 // force reset of enabled components to help grab custom fields
1826 CRM_Core_Component
::getEnabledComponents(1);
1832 * Function to delete custom field
1834 * @param int $customFieldID
1836 function customFieldDelete($customFieldID) {
1838 $params['id'] = $customFieldID;
1839 return $this->callAPISuccess('custom_field', 'delete', $params);
1843 * Function to create note
1845 * @params array $params name-value pair for an event
1847 * @return array $note
1849 function noteCreate($cId) {
1851 'entity_table' => 'civicrm_contact',
1852 'entity_id' => $cId,
1853 'note' => 'hello I am testing Note',
1854 'contact_id' => $cId,
1855 'modified_date' => date('Ymd'),
1856 'subject' => 'Test Note',
1859 return $this->callAPISuccess('Note', 'create', $params);
1863 * Enable CiviCampaign Component
1865 function enableCiviCampaign() {
1866 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1867 // force reload of config object
1868 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1869 //flush cache by calling with reset
1870 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1874 * Create test generated example in api/v3/examples.
1875 * To turn this off (e.g. on the server) set
1876 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1877 * in your settings file
1878 * @param array $params array as passed to civicrm_api function
1879 * @param array $result array as received from the civicrm_api function
1880 * @param string $function calling function - generally __FUNCTION__
1881 * @param string $filename called from file - generally __FILE__
1882 * @param string $description descriptive text for the example file
1883 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1884 * @param string $action - optional action - otherwise taken from function name
1886 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1887 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1890 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1891 //todo - this is a bit cludgey
1892 if (empty($action)) {
1893 if (strstr($function, 'Create')) {
1894 $action = empty($action) ?
'create' : $action;
1895 $entityAction = 'Create';
1897 elseif (strstr($function, 'GetSingle')) {
1898 $action = empty($action) ?
'getsingle' : $action;
1899 $entityAction = 'GetSingle';
1901 elseif (strstr($function, 'GetValue')) {
1902 $action = empty($action) ?
'getvalue' : $action;
1903 $entityAction = 'GetValue';
1905 elseif (strstr($function, 'GetCount')) {
1906 $action = empty($action) ?
'getcount' : $action;
1907 $entityAction = 'GetCount';
1909 elseif (strstr($function, 'GetFields')) {
1910 $action = empty($action) ?
'getfields' : $action;
1911 $entityAction = 'GetFields';
1913 elseif (strstr($function, 'GetList')) {
1914 $action = empty($action) ?
'getlist' : $action;
1915 $entityAction = 'GetList';
1917 elseif (strstr($function, 'Get')) {
1918 $action = empty($action) ?
'get' : $action;
1919 $entityAction = 'Get';
1921 elseif (strstr($function, 'Delete')) {
1922 $action = empty($action) ?
'delete' : $action;
1923 $entityAction = 'Delete';
1925 elseif (strstr($function, 'Update')) {
1926 $action = empty($action) ?
'update' : $action;
1927 $entityAction = 'Update';
1929 elseif (strstr($function, 'Subscribe')) {
1930 $action = empty($action) ?
'subscribe' : $action;
1931 $entityAction = 'Subscribe';
1933 elseif (strstr($function, 'Submit')) {
1934 $action = empty($action) ?
'submit' : $action;
1935 $entityAction = 'Submit';
1937 elseif (strstr($function, 'Apply')) {
1938 $action = empty($action) ?
'apply' : $action;
1939 $entityAction = 'Apply';
1941 elseif (strstr($function, 'Replace')) {
1942 $action = empty($action) ?
'replace' : $action;
1943 $entityAction = 'Replace';
1947 $entityAction = ucwords($action);
1950 $this->tidyExampleResult($result);
1951 if(isset($params['version'])) {
1952 unset($params['version']);
1954 // a cleverer person than me would do it in a single regex
1955 if (strstr($entity, 'UF')) {
1956 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1959 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1961 $smarty = CRM_Core_Smarty
::singleton();
1962 $smarty->assign('testfunction', $function);
1963 $function = $fnPrefix . "_" . strtolower($action);
1964 $smarty->assign('function', $function);
1965 $smarty->assign('fnPrefix', $fnPrefix);
1966 $smarty->assign('params', $params);
1967 $smarty->assign('entity', $entity);
1968 $smarty->assign('filename', basename($filename));
1969 $smarty->assign('description', $description);
1970 $smarty->assign('result', $result);
1972 $smarty->assign('action', $action);
1973 if (empty($subfile)) {
1974 $subfile = $entityAction;
1976 if (file_exists('../tests/templates/documentFunction.tpl')) {
1977 if (!is_dir("../api/v3/examples/$entity")) {
1978 mkdir("../api/v3/examples/$entity");
1980 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1981 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1987 * Tidy up examples array so that fields that change often ..don't
1988 * and debug related fields are unset
1989 * @param array $params
1991 function tidyExampleResult(&$result){
1992 if(!is_array($result)) {
1995 $fieldsToChange = array(
1996 'hash' => '67eac7789eaee00',
1997 'modified_date' => '2012-11-14 16:02:35',
1998 'created_date' => '2013-07-28 08:49:19',
1999 'create_date' => '20120130621222105',
2000 'application_received_date' => '20130728084957',
2001 'in_date' => '2013-07-28 08:50:19',
2002 'scheduled_date' => '20130728085413',
2003 'approval_date' => '20130728085413',
2004 'pledge_start_date_high' => '20130726090416',
2005 'start_date' => '2013-07-29 00:00:00',
2006 'event_start_date' => '2013-07-29 00:00:00',
2007 'end_date' => '2013-08-04 00:00:00',
2008 'event_end_date' => '2013-08-04 00:00:00',
2009 'decision_date' => '20130805000000',
2012 $keysToUnset = array('xdebug', 'undefined_fields',);
2013 foreach ($keysToUnset as $unwantedKey) {
2014 if(isset($result[$unwantedKey])) {
2015 unset($result[$unwantedKey]);
2018 if (isset($result['values'])) {
2019 if(!is_array($result['values'])) {
2022 $resultArray = &$result['values'];
2024 elseif(is_array($result)) {
2025 $resultArray = &$result;
2031 foreach ($resultArray as $index => &$values) {
2032 if(!is_array($values)) {
2035 foreach($values as $key => &$value) {
2036 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2037 if(isset($value['is_error'])) {
2038 // we have a std nested result format
2039 $this->tidyExampleResult($value);
2042 foreach ($value as &$nestedResult) {
2043 // this is an alternative syntax for nested results a keyed array of results
2044 $this->tidyExampleResult($nestedResult);
2048 if(in_array($key, $keysToUnset)) {
2049 unset($values[$key]);
2052 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2053 $value = $fieldsToChange[$key];
2055 if(is_string($value)) {
2056 $value = addslashes($value);
2063 * Function to delete note
2065 * @params int $noteID
2068 function noteDelete($params) {
2069 return $this->callAPISuccess('Note', 'delete', $params);
2073 * Function to create custom field with Option Values
2075 * @param array $customGroup
2076 * @param string $name name of custom field
2078 function customFieldOptionValueCreate($customGroup, $name) {
2079 $fieldParams = array(
2080 'custom_group_id' => $customGroup['id'],
2081 'name' => 'test_custom_group',
2082 'label' => 'Country',
2083 'html_type' => 'Select',
2084 'data_type' => 'String',
2087 'is_searchable' => 0,
2091 $optionGroup = array(
2093 'name' => 'option_group1',
2094 'label' => 'option_group_label1',
2097 $optionValue = array(
2098 'option_label' => array('Label1', 'Label2'),
2099 'option_value' => array('value1', 'value2'),
2100 'option_name' => array($name . '_1', $name . '_2'),
2101 'option_weight' => array(1, 2),
2102 'option_status' => 1,
2105 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2107 return $this->callAPISuccess('custom_field', 'create', $params);
2110 function confirmEntitiesDeleted($entities) {
2111 foreach ($entities as $entity) {
2113 $result = $this->callAPISuccess($entity, 'Get', array());
2114 if ($result['error'] == 1 ||
$result['count'] > 0) {
2115 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2121 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2122 if ($dropCustomValueTables) {
2123 $tablesToTruncate[] = 'civicrm_custom_group';
2124 $tablesToTruncate[] = 'civicrm_custom_field';
2127 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2129 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2130 foreach ($tablesToTruncate as $table) {
2131 $sql = "TRUNCATE TABLE $table";
2132 CRM_Core_DAO
::executeQuery($sql);
2134 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2136 if ($dropCustomValueTables) {
2137 $dbName = self
::getDBName();
2139 SELECT TABLE_NAME as tableName
2140 FROM INFORMATION_SCHEMA.TABLES
2141 WHERE TABLE_SCHEMA = '{$dbName}'
2142 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2145 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2146 while ($tableDAO->fetch()) {
2147 $sql = "DROP TABLE {$tableDAO->tableName}";
2148 CRM_Core_DAO
::executeQuery($sql);
2154 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2156 function quickCleanUpFinancialEntities() {
2157 $tablesToTruncate = array(
2158 'civicrm_contribution',
2159 'civicrm_financial_trxn',
2160 'civicrm_contribution_recur',
2161 'civicrm_line_item',
2162 'civicrm_contribution_page',
2163 'civicrm_payment_processor',
2164 'civicrm_entity_financial_trxn',
2165 'civicrm_membership',
2166 'civicrm_membership_type',
2167 'civicrm_membership_payment',
2168 'civicrm_membership_status',
2170 'civicrm_participant',
2171 'civicrm_participant_payment',
2174 $this->quickCleanup($tablesToTruncate);
2177 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2178 * Default behaviour is to also delete the entity
2179 * @param array $params params array to check agains
2180 * @param int $id id of the entity concerned
2181 * @param string $entity name of entity concerned (e.g. membership)
2182 * @param bool $delete should the entity be deleted as part of this check
2183 * @param string $errorText text to print on error
2186 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2188 $result = $this->callAPISuccessGetSingle($entity, array(
2193 $this->callAPISuccess($entity, 'Delete', array(
2197 $dateFields = $keys = $dateTimeFields = array();
2198 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2199 foreach ($fields['values'] as $field => $settings) {
2200 if (array_key_exists($field, $result)) {
2201 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2204 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2206 $type = CRM_Utils_Array
::value('type', $settings);
2207 if ($type == CRM_Utils_Type
::T_DATE
) {
2208 $dateFields[] = $settings['name'];
2209 // we should identify both real names & unique names as dates
2210 if($field != $settings['name']) {
2211 $dateFields[] = $field;
2214 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2215 $dateTimeFields[] = $settings['name'];
2216 // we should identify both real names & unique names as dates
2217 if($field != $settings['name']) {
2218 $dateTimeFields[] = $field;
2223 if (strtolower($entity) == 'contribution') {
2224 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2225 // this is not returned in id format
2226 unset($params['payment_instrument_id']);
2227 $params['contribution_source'] = $params['source'];
2228 unset($params['source']);
2231 foreach ($params as $key => $value) {
2232 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2235 if (in_array($key, $dateFields)) {
2236 $value = date('Y-m-d', strtotime($value));
2237 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2239 if (in_array($key, $dateTimeFields)) {
2240 $value = date('Y-m-d H:i:s', strtotime($value));
2241 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2243 $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);
2248 * Function to get formatted values in the actual and expected result
2249 * @param array $actual actual calculated values
2250 * @param array $expected expected values
2253 function checkArrayEquals(&$actual, &$expected) {
2254 self
::unsetId($actual);
2255 self
::unsetId($expected);
2256 $this->assertEquals($actual, $expected);
2260 * Function to unset the key 'id' from the array
2261 * @param array $unformattedArray The array from which the 'id' has to be unset
2264 static function unsetId(&$unformattedArray) {
2265 $formattedArray = array();
2266 if (array_key_exists('id', $unformattedArray)) {
2267 unset($unformattedArray['id']);
2269 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2270 foreach ($unformattedArray['values'] as $key => $value) {
2271 if (is_Array($value)) {
2272 foreach ($value as $k => $v) {
2278 elseif ($key == 'id') {
2279 $unformattedArray[$key];
2281 $formattedArray = array($value);
2283 $unformattedArray['values'] = $formattedArray;
2288 * Helper to enable/disable custom directory support
2290 * @param array $customDirs with members:
2291 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2292 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2294 function customDirectories($customDirs) {
2295 require_once 'CRM/Core/Config.php';
2296 $config = CRM_Core_Config
::singleton();
2298 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2299 unset($config->customPHPPathDir
);
2301 elseif ($customDirs['php_path'] === TRUE) {
2302 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2305 $config->customPHPPathDir
= $php_path;
2308 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2309 unset($config->customTemplateDir
);
2311 elseif ($customDirs['template_path'] === TRUE) {
2312 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2315 $config->customTemplateDir
= $template_path;
2320 * Generate a temporary folder
2324 function createTempDir($prefix = 'test-') {
2325 $tempDir = CRM_Utils_File
::tempdir($prefix);
2326 $this->tempDirs
[] = $tempDir;
2330 function cleanTempDirs() {
2331 if (!is_array($this->tempDirs
)) {
2332 // fix test errors where this is not set
2335 foreach ($this->tempDirs
as $tempDir) {
2336 if (is_dir($tempDir)) {
2337 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2343 * Temporarily replace the singleton extension with a different one
2345 function setExtensionSystem(CRM_Extension_System
$system) {
2346 if ($this->origExtensionSystem
== NULL) {
2347 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2349 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2352 function unsetExtensionSystem() {
2353 if ($this->origExtensionSystem
!== NULL) {
2354 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2355 $this->origExtensionSystem
= NULL;
2360 * Temporarily alter the settings-metadata to add a mock setting.
2362 * WARNING: The setting metadata will disappear on the next cache-clear.
2367 function setMockSettingsMetaData($extras) {
2368 CRM_Core_BAO_Setting
::$_cache = array();
2369 $this->callAPISuccess('system','flush', array());
2370 CRM_Core_BAO_Setting
::$_cache = array();
2372 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2373 $metadata = array_merge($metadata, $extras);
2376 $fields = $this->callAPISuccess('setting', 'getfields', array());
2377 foreach ($extras as $key => $spec) {
2378 $this->assertNotEmpty($spec['title']);
2379 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2383 function financialAccountDelete($name) {
2384 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2385 $financialAccount->name
= $name;
2386 if($financialAccount->find(TRUE)) {
2387 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2388 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2389 $entityFinancialType->delete();
2390 $financialAccount->delete();
2395 * Use $ids as an instruction to do test cleanup
2397 function deleteFromIDSArray() {
2398 foreach ($this->ids
as $entity => $ids) {
2399 foreach ($ids as $id) {
2400 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2406 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2407 * (NB unclear if this is still required)
2409 function _sethtmlGlobals() {
2410 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2411 'required' => array(
2412 'html_quickform_rule_required',
2413 'HTML/QuickForm/Rule/Required.php'
2415 'maxlength' => array(
2416 'html_quickform_rule_range',
2417 'HTML/QuickForm/Rule/Range.php'
2419 'minlength' => array(
2420 'html_quickform_rule_range',
2421 'HTML/QuickForm/Rule/Range.php'
2423 'rangelength' => array(
2424 'html_quickform_rule_range',
2425 'HTML/QuickForm/Rule/Range.php'
2428 'html_quickform_rule_email',
2429 'HTML/QuickForm/Rule/Email.php'
2432 'html_quickform_rule_regex',
2433 'HTML/QuickForm/Rule/Regex.php'
2435 'lettersonly' => array(
2436 'html_quickform_rule_regex',
2437 'HTML/QuickForm/Rule/Regex.php'
2439 'alphanumeric' => array(
2440 'html_quickform_rule_regex',
2441 'HTML/QuickForm/Rule/Regex.php'
2444 'html_quickform_rule_regex',
2445 'HTML/QuickForm/Rule/Regex.php'
2447 'nopunctuation' => array(
2448 'html_quickform_rule_regex',
2449 'HTML/QuickForm/Rule/Regex.php'
2452 'html_quickform_rule_regex',
2453 'HTML/QuickForm/Rule/Regex.php'
2455 'callback' => array(
2456 'html_quickform_rule_callback',
2457 'HTML/QuickForm/Rule/Callback.php'
2460 'html_quickform_rule_compare',
2461 'HTML/QuickForm/Rule/Compare.php'
2464 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2465 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2467 'HTML/QuickForm/group.php',
2468 'HTML_QuickForm_group'
2471 'HTML/QuickForm/hidden.php',
2472 'HTML_QuickForm_hidden'
2475 'HTML/QuickForm/reset.php',
2476 'HTML_QuickForm_reset'
2478 'checkbox' => array(
2479 'HTML/QuickForm/checkbox.php',
2480 'HTML_QuickForm_checkbox'
2483 'HTML/QuickForm/file.php',
2484 'HTML_QuickForm_file'
2487 'HTML/QuickForm/image.php',
2488 'HTML_QuickForm_image'
2490 'password' => array(
2491 'HTML/QuickForm/password.php',
2492 'HTML_QuickForm_password'
2495 'HTML/QuickForm/radio.php',
2496 'HTML_QuickForm_radio'
2499 'HTML/QuickForm/button.php',
2500 'HTML_QuickForm_button'
2503 'HTML/QuickForm/submit.php',
2504 'HTML_QuickForm_submit'
2507 'HTML/QuickForm/select.php',
2508 'HTML_QuickForm_select'
2510 'hiddenselect' => array(
2511 'HTML/QuickForm/hiddenselect.php',
2512 'HTML_QuickForm_hiddenselect'
2515 'HTML/QuickForm/text.php',
2516 'HTML_QuickForm_text'
2518 'textarea' => array(
2519 'HTML/QuickForm/textarea.php',
2520 'HTML_QuickForm_textarea'
2522 'fckeditor' => array(
2523 'HTML/QuickForm/fckeditor.php',
2524 'HTML_QuickForm_FCKEditor'
2527 'HTML/QuickForm/tinymce.php',
2528 'HTML_QuickForm_TinyMCE'
2530 'dojoeditor' => array(
2531 'HTML/QuickForm/dojoeditor.php',
2532 'HTML_QuickForm_dojoeditor'
2535 'HTML/QuickForm/link.php',
2536 'HTML_QuickForm_link'
2538 'advcheckbox' => array(
2539 'HTML/QuickForm/advcheckbox.php',
2540 'HTML_QuickForm_advcheckbox'
2543 'HTML/QuickForm/date.php',
2544 'HTML_QuickForm_date'
2547 'HTML/QuickForm/static.php',
2548 'HTML_QuickForm_static'
2551 'HTML/QuickForm/header.php',
2552 'HTML_QuickForm_header'
2555 'HTML/QuickForm/html.php',
2556 'HTML_QuickForm_html'
2558 'hierselect' => array(
2559 'HTML/QuickForm/hierselect.php',
2560 'HTML_QuickForm_hierselect'
2562 'autocomplete' => array(
2563 'HTML/QuickForm/autocomplete.php',
2564 'HTML_QuickForm_autocomplete'
2567 'HTML/QuickForm/xbutton.php',
2568 'HTML_QuickForm_xbutton'
2570 'advmultiselect' => array(
2571 'HTML/QuickForm/advmultiselect.php',
2572 'HTML_QuickForm_advmultiselect'
2578 * Set up an acl allowing contact to see 2 specified groups
2579 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2581 * You need to have precreated these groups & created the user e.g
2582 * $this->createLoggedInUser();
2583 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2584 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2587 function setupACL() {
2588 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2589 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2590 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2591 'label' => 'pick me',
2596 CRM_Core_DAO
::executeQuery("
2597 TRUNCATE civicrm_acl_cache
2600 CRM_Core_DAO
::executeQuery("
2601 TRUNCATE civicrm_acl_contact_cache
2605 CRM_Core_DAO
::executeQuery("
2606 INSERT INTO civicrm_acl_entity_role (
2607 `acl_role_id`, `entity_table`, `entity_id`
2608 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2611 CRM_Core_DAO
::executeQuery("
2612 INSERT INTO civicrm_acl (
2613 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2616 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2620 CRM_Core_DAO
::executeQuery("
2621 INSERT INTO civicrm_acl (
2622 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2625 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2628 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2629 $this->callAPISuccess('group_contact', 'create', array(
2630 'group_id' => $this->_permissionedGroup
,
2631 'contact_id' => $this->_loggedInUser
,
2634 CRM_ACL_BAO_Cache
::resetCache();
2635 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2639 * Create an instance of the paypal processor
2640 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2641 * this parent class & we don't have a structure for that yet
2642 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2643 * & the best protection agains that is the functions this class affords
2645 function paymentProcessorCreate($params = array()) {
2646 $params = array_merge(array(
2648 'domain_id' => CRM_Core_Config
::domainID(),
2649 'payment_processor_type_id' => 'PayPal',
2653 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2654 'password' => '1183377788',
2655 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2656 'url_site' => 'https://www.sandbox.paypal.com/',
2657 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2658 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2659 'class_name' => 'Payment_PayPalImpl',
2660 'billing_mode' => 3,
2661 'financial_type_id' => 1,
2664 if(!is_numeric($params['payment_processor_type_id'])) {
2665 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2667 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2668 'name' => $params['payment_processor_type_id'],
2672 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2673 return $result['id'];
2677 function CiviUnitTestCase_fatalErrorHandler($message) {
2678 throw new Exception("{$message['message']}: {$message['code']}");