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->checkMysqlTime());
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
671 * @param array $apiResult api result
672 * @param string $prefix extra test to add to message
673 * @param null $expectedError
675 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
676 if (!empty($prefix)) {
679 if($expectedError && !empty($apiResult['is_error'])){
680 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
682 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
683 $this->assertNotEmpty($apiResult['error_message']);
686 function assertType($expected, $actual, $message = '') {
687 return $this->assertInternalType($expected, $actual, $message);
691 * check that a deleted item has been deleted
693 function assertAPIDeleted($entity, $id) {
694 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
699 * check that api returned 'is_error' => 1
700 * else provide full message
703 * @param array $valuesToExclude
704 * @param string $prefix extra test to add to message
705 * @internal param array $apiResult api result
707 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
708 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
709 foreach ($valuesToExclude as $value) {
710 if(isset($result[$value])) {
711 unset($result[$value]);
713 if(isset($expected[$value])) {
714 unset($expected[$value]);
717 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
721 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
728 function civicrm_api($entity, $action, $params) {
729 return civicrm_api($entity, $action, $params);
733 * This function exists to wrap api functions
734 * so we can ensure they succeed & throw exceptions without litterering the test with checks
736 * @param string $entity
737 * @param string $action
738 * @param array $params
739 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
740 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
741 * for getsingle the array is compared against an array passed in - the id is not compared (for
746 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
747 $params = array_merge(array(
748 'version' => $this->_apiversion
,
753 switch (strtolower($action)) {
755 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
757 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
759 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
761 $result = $this->civicrm_api($entity, $action, $params);
762 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
767 * This function exists to wrap api getValue function & check the result
768 * so we can ensure they succeed & throw exceptions without litterering the test with checks
769 * There is a type check in this
771 * @param string $entity
772 * @param array $params
773 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
783 function callAPISuccessGetValue($entity, $params, $type = NULL) {
785 'version' => $this->_apiversion
,
788 $result = $this->civicrm_api($entity, 'getvalue', $params);
790 if($type == 'integer'){
791 // api seems to return integers as strings
792 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
795 $this->assertType($type, $result, "returned result should have been of type $type but was " );
802 * This function exists to wrap api getsingle function & check the result
803 * so we can ensure they succeed & throw exceptions without litterering the test with checks
805 * @param string $entity
806 * @param array $params
807 * @param array $checkAgainst - array to compare result against
817 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
819 'version' => $this->_apiversion
,
822 $result = $this->civicrm_api($entity, 'getsingle', $params);
823 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
824 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
827 // @todo - have gone with the fn that unsets id? should we check id?
828 $this->checkArrayEquals($result, $checkAgainst);
834 * This function exists to wrap api getValue function & check the result
835 * so we can ensure they succeed & throw exceptions without litterering the test with checks
836 * There is a type check in this
837 * @param string $entity
838 * @param array $params
842 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
850 function callAPISuccessGetCount($entity, $params, $count = NULL) {
852 'version' => $this->_apiversion
,
855 $result = $this->civicrm_api($entity, 'getcount', $params);
856 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
857 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
860 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
866 * This function exists to wrap api functions
867 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
869 * @param string $entity
870 * @param string $action
871 * @param array $params
872 * @param string $function - pass this in to create a generated example
873 * @param string $file - pass this in to create a generated example
874 * @param string $description
875 * @param string|null $subfile
876 * @param string|null $actionName
879 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
880 $params['version'] = $this->_apiversion
;
881 $result = $this->callAPISuccess($entity, $action, $params);
882 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
887 * This function exists to wrap api functions
888 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
889 * @param string $entity
890 * @param string $action
891 * @param array $params
892 * @param string $expectedErrorMessage error
893 * @param null $extraOutput
896 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
897 if (is_array($params)) {
899 'version' => $this->_apiversion
,
902 $result = $this->civicrm_api($entity, $action, $params);
903 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
908 * Create required data based on $this->entity & $this->params
909 * This is just a way to set up the test data for delete & get functions
910 * so the distinction between set
911 * up & tested functions is clearer
913 * @return array api Result
915 public function createTestEntity(){
916 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
920 * Generic function to create Organisation, to be used in test cases
922 * @param array parameters for civicrm_contact_add api function call
924 * @return int id of Organisation created
926 function organizationCreate($params = array()) {
931 'organization_name' => 'Unit Test Organization',
932 'contact_type' => 'Organization',
934 return $this->_contactCreate(array_merge($orgParams, $params));
938 * Generic function to create Individual, to be used in test cases
940 * @param array parameters for civicrm_contact_add api function call
942 * @return int id of Individual created
944 function individualCreate($params = array()) {
945 $params = array_merge(array(
946 'first_name' => 'Anthony',
947 'middle_name' => 'J.',
948 'last_name' => 'Anderson',
951 'email' => 'anthony_anderson@civicrm.org',
952 'contact_type' => 'Individual',
955 return $this->_contactCreate($params);
959 * Generic function to create Household, to be used in test cases
961 * @param array parameters for civicrm_contact_add api function call
963 * @return int id of Household created
965 function householdCreate($params = array()) {
966 $params = array_merge(array(
967 'household_name' => 'Unit Test household',
968 'contact_type' => 'Household',
970 return $this->_contactCreate($params);
974 * Private helper function for calling civicrm_contact_add
979 * @internal param \parameters $array for civicrm_contact_add api function call
981 * @return int id of Household created
983 private function _contactCreate($params) {
984 $result = $this->callAPISuccess('contact', 'create', $params);
985 if (!empty($result['is_error']) ||
empty($result['id'])) {
986 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
988 return $result['id'];
991 function contactDelete($contactID) {
994 'skip_undelete' => 1,
997 $domain = new CRM_Core_BAO_Domain
;
998 $domain->contact_id
= $contactID;
999 if ($domain->find(TRUE)) {
1000 // we are finding tests trying to delete the domain contact in cleanup
1001 //since this is mainly for cleanup lets put a safeguard here
1004 $result = $this->callAPISuccess('contact', 'delete', $params);
1008 function contactTypeDelete($contactTypeId) {
1009 require_once 'CRM/Contact/BAO/ContactType.php';
1010 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1012 throw new Exception('Could not delete contact type');
1016 function membershipTypeCreate($params = array()) {
1017 CRM_Member_PseudoConstant
::flush('membershipType');
1018 CRM_Core_Config
::clearDBCache();
1019 $memberOfOrganization = $this->organizationCreate();
1020 $params = array_merge(array(
1021 'name' => 'General',
1022 'duration_unit' => 'year',
1023 'duration_interval' => 1,
1024 'period_type' => 'rolling',
1025 'member_of_contact_id' => $memberOfOrganization,
1027 'financial_type_id' => 1,
1033 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1035 CRM_Member_PseudoConstant
::flush('membershipType');
1036 CRM_Utils_Cache
::singleton()->flush();
1038 return $result['id'];
1041 function contactMembershipCreate($params) {
1043 'join_date' => '2007-01-21',
1044 'start_date' => '2007-01-21',
1045 'end_date' => '2007-12-21',
1046 'source' => 'Payment',
1049 foreach ($pre as $key => $val) {
1050 if (!isset($params[$key])) {
1051 $params[$key] = $val;
1055 $result = $this->callAPISuccess('Membership', 'create', $params);
1056 return $result['id'];
1060 * Function to delete Membership Type
1063 * @internal param int $membershipTypeID
1065 function membershipTypeDelete($params) {
1066 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1070 function membershipDelete($membershipID) {
1071 $deleteParams = array('id' => $membershipID);
1072 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1076 function membershipStatusCreate($name = 'test member status') {
1077 $params['name'] = $name;
1078 $params['start_event'] = 'start_date';
1079 $params['end_event'] = 'end_date';
1080 $params['is_current_member'] = 1;
1081 $params['is_active'] = 1;
1083 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1084 CRM_Member_PseudoConstant
::flush('membershipStatus');
1085 return $result['id'];
1088 function membershipStatusDelete($membershipStatusID) {
1089 if (!$membershipStatusID) {
1092 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1096 function relationshipTypeCreate($params = array()) {
1097 $params = array_merge(array(
1098 'name_a_b' => 'Relation 1 for relationship type create',
1099 'name_b_a' => 'Relation 2 for relationship type create',
1100 'contact_type_a' => 'Individual',
1101 'contact_type_b' => 'Organization',
1108 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1109 CRM_Core_PseudoConstant
::flush('relationshipType');
1111 return $result['id'];
1115 * Function to delete Relatinship Type
1117 * @param int $relationshipTypeID
1119 function relationshipTypeDelete($relationshipTypeID) {
1120 $params['id'] = $relationshipTypeID;
1121 $this->callAPISuccess('relationship_type', 'delete', $params);
1124 function paymentProcessorTypeCreate($params = NULL) {
1125 if (is_null($params)) {
1127 'name' => 'API_Test_PP',
1128 'title' => 'API Test Payment Processor',
1129 'class_name' => 'CRM_Core_Payment_APITest',
1130 'billing_mode' => 'form',
1136 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1138 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1140 return $result['id'];
1144 * Function to create Participant
1146 * @param array $params array of contact id and event id values
1148 * @return int $id of participant created
1150 function participantCreate($params) {
1151 if(empty($params['contact_id'])){
1152 $params['contact_id'] = $this->individualCreate();
1154 if(empty($params['event_id'])){
1155 $event = $this->eventCreate();
1156 $params['event_id'] = $event['id'];
1161 'register_date' => 20070219,
1162 'source' => 'Wimbeldon',
1163 'event_level' => 'Payment',
1167 $params = array_merge($defaults, $params);
1168 $result = $this->callAPISuccess('Participant', 'create', $params);
1169 return $result['id'];
1173 * Function to create Payment Processor
1175 * @return object of Payment Processsor
1177 function processorCreate() {
1178 $processorParams = array(
1181 'payment_processor_type_id' => 10,
1182 'financial_account_id' => 12,
1185 'url_site' => 'http://dummy.com',
1186 'url_recur' => 'http://dummy.com',
1187 'billing_mode' => 1,
1189 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1190 return $paymentProcessor;
1194 * Function to create contribution page
1197 * @return object of contribution page
1199 function contributionPageCreate($params) {
1200 $this->_pageParams
= array(
1201 'title' => 'Test Contribution Page',
1202 'financial_type_id' => 1,
1203 'currency' => 'USD',
1204 'financial_account_id' => 1,
1205 'payment_processor' => $params['processor_id'],
1207 'is_allow_other_amount' => 1,
1209 'max_amount' => 1000,
1211 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1212 return $contributionPage;
1216 * Function to create Tag
1218 * @param array $params
1219 * @return array result of created tag
1221 function tagCreate($params = array()) {
1223 'name' => 'New Tag3',
1224 'description' => 'This is description for Our New Tag ',
1227 $params = array_merge($defaults, $params);
1228 $result = $this->callAPISuccess('Tag', 'create', $params);
1229 return $result['values'][$result['id']];
1233 * Function to delete Tag
1235 * @param int $tagId id of the tag to be deleted
1237 function tagDelete($tagId) {
1238 require_once 'api/api.php';
1242 $result = $this->callAPISuccess('Tag', 'delete', $params);
1243 return $result['id'];
1247 * Add entity(s) to the tag
1249 * @param array $params
1253 function entityTagAdd($params) {
1254 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1259 * Function to create contribution
1261 * @param int $cID contact_id
1263 * @internal param int $cTypeID id of financial type
1265 * @return int id of created contribution
1267 function pledgeCreate($cID) {
1269 'contact_id' => $cID,
1270 'pledge_create_date' => date('Ymd'),
1271 'start_date' => date('Ymd'),
1272 'scheduled_date' => date('Ymd'),
1274 'pledge_status_id' => '2',
1275 'financial_type_id' => '1',
1276 'pledge_original_installment_amount' => 20,
1277 'frequency_interval' => 5,
1278 'frequency_unit' => 'year',
1279 'frequency_day' => 15,
1280 'installments' => 5,
1283 $result = $this->callAPISuccess('Pledge', 'create', $params);
1284 return $result['id'];
1288 * Function to delete contribution
1291 * @internal param int $contributionId
1293 function pledgeDelete($pledgeId) {
1295 'pledge_id' => $pledgeId,
1297 $this->callAPISuccess('Pledge', 'delete', $params);
1301 * Function to create contribution
1303 * @param int $cID contact_id
1304 * @param int $cTypeID id of financial type
1306 * @param int $invoiceID
1307 * @param int $trxnID
1308 * @param int $paymentInstrumentID
1309 * @param bool $isFee
1310 * @return int id of created contribution
1312 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1315 'contact_id' => $cID,
1316 'receive_date' => date('Ymd'),
1317 'total_amount' => 100.00,
1318 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1319 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1320 'non_deductible_amount' => 10.00,
1321 'trxn_id' => $trxnID,
1322 'invoice_id' => $invoiceID,
1324 'contribution_status_id' => 1,
1325 // 'note' => 'Donating for Nobel Cause', *Fixme
1329 $params['fee_amount'] = 5.00;
1330 $params['net_amount'] = 95.00;
1333 $result = $this->callAPISuccess('contribution', 'create', $params);
1334 return $result['id'];
1338 * Function to create online contribution
1341 * @param int $financialType id of financial type
1343 * @param int $invoiceID
1344 * @param int $trxnID
1345 * @return int id of created contribution
1347 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1348 $contribParams = array(
1349 'contact_id' => $params['contact_id'],
1350 'receive_date' => date('Ymd'),
1351 'total_amount' => 100.00,
1352 'financial_type_id' => $financialType,
1353 'contribution_page_id' => $params['contribution_page_id'],
1355 'invoice_id' => 67890,
1358 $contribParams = array_merge($contribParams, $params);
1359 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1361 return $result['id'];
1365 * Function to delete contribution
1367 * @param int $contributionId
1371 function contributionDelete($contributionId) {
1373 'contribution_id' => $contributionId,
1375 $result = $this->callAPISuccess('contribution', 'delete', $params);
1380 * Function to create an Event
1382 * @param array $params name-value pair for an event
1384 * @return array $event
1386 function eventCreate($params = array()) {
1387 // if no contact was passed, make up a dummy event creator
1388 if (!isset($params['contact_id'])) {
1389 $params['contact_id'] = $this->_contactCreate(array(
1390 'contact_type' => 'Individual',
1391 'first_name' => 'Event',
1392 'last_name' => 'Creator',
1396 // set defaults for missing params
1397 $params = array_merge(array(
1398 'title' => 'Annual CiviCRM meet',
1399 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1400 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1401 'event_type_id' => 1,
1403 'start_date' => 20081021,
1404 'end_date' => 20081023,
1405 'is_online_registration' => 1,
1406 'registration_start_date' => 20080601,
1407 'registration_end_date' => 20081015,
1408 'max_participants' => 100,
1409 'event_full_text' => 'Sorry! We are already full',
1412 'is_show_location' => 0,
1415 return $this->callAPISuccess('Event', 'create', $params);
1419 * Function to delete event
1421 * @param int $id ID of the event
1425 function eventDelete($id) {
1429 return $this->callAPISuccess('event', 'delete', $params);
1433 * Function to delete participant
1435 * @param int $participantID
1439 function participantDelete($participantID) {
1441 'id' => $participantID,
1443 return $this->callAPISuccess('Participant', 'delete', $params);
1447 * Function to create participant payment
1449 * @param $participantID
1450 * @param null $contributionID
1451 * @return int $id of created payment
1453 function participantPaymentCreate($participantID, $contributionID = NULL) {
1454 //Create Participant Payment record With Values
1456 'participant_id' => $participantID,
1457 'contribution_id' => $contributionID,
1460 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1461 return $result['id'];
1465 * Function to delete participant payment
1467 * @param int $paymentID
1469 function participantPaymentDelete($paymentID) {
1473 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1477 * Function to add a Location
1480 * @return int location id of created location
1482 function locationAdd($contactID) {
1485 'location_type' => 'New Location Type',
1487 'name' => 'Saint Helier St',
1488 'county' => 'Marin',
1489 'country' => 'United States',
1490 'state_province' => 'Michigan',
1491 'supplemental_address_1' => 'Hallmark Ct',
1492 'supplemental_address_2' => 'Jersey Village',
1497 'contact_id' => $contactID,
1498 'address' => $address,
1499 'location_format' => '2.0',
1500 'location_type' => 'New Location Type',
1503 $result = $this->callAPISuccess('Location', 'create', $params);
1508 * Function to delete Locations of contact
1510 * @params array $pamars parameters
1512 function locationDelete($params) {
1513 $result = $this->callAPISuccess('Location', 'delete', $params);
1517 * Function to add a Location Type
1519 * @param null $params
1520 * @return int location id of created location
1522 function locationTypeCreate($params = NULL) {
1523 if ($params === NULL) {
1525 'name' => 'New Location Type',
1526 'vcard_name' => 'New Location Type',
1527 'description' => 'Location Type for Delete',
1532 $locationType = new CRM_Core_DAO_LocationType();
1533 $locationType->copyValues($params);
1534 $locationType->save();
1535 // clear getfields cache
1536 CRM_Core_PseudoConstant
::flush();
1537 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1538 return $locationType;
1542 * Function to delete a Location Type
1544 * @param int location type id
1546 function locationTypeDelete($locationTypeId) {
1547 $locationType = new CRM_Core_DAO_LocationType();
1548 $locationType->id
= $locationTypeId;
1549 $locationType->delete();
1553 * Function to add a Group
1555 * @params array to add group
1557 * @param array $params
1558 * @return int groupId of created group
1560 function groupCreate($params = array()) {
1561 $params = array_merge(array(
1562 'name' => 'Test Group 1',
1564 'title' => 'New Test Group Created',
1565 'description' => 'New Test Group Created',
1567 'visibility' => 'Public Pages',
1568 'group_type' => array(
1574 $result = $this->callAPISuccess('Group', 'create', $params);
1575 return $result['id'];
1579 * Function to delete a Group
1582 * @internal param int $id
1584 function groupDelete($gid) {
1590 $this->callAPISuccess('Group', 'delete', $params);
1595 * @param array $params
1597 function uFFieldCreate($params = array()) {
1598 $params = array_merge(array(
1600 'field_name' => 'first_name',
1603 'visibility' => 'Public Pages and Listings',
1604 'is_searchable' => '1',
1605 'label' => 'first_name',
1606 'field_type' => 'Individual',
1609 $this->callAPISuccess('uf_field', 'create', $params);
1613 * Function to add a UF Join Entry
1615 * @param null $params
1616 * @return int $id of created UF Join
1618 function ufjoinCreate($params = NULL) {
1619 if ($params === NULL) {
1622 'module' => 'CiviEvent',
1623 'entity_table' => 'civicrm_event',
1629 $result = $this->callAPISuccess('uf_join', 'create', $params);
1634 * Function to delete a UF Join Entry
1636 * @param array with missing uf_group_id
1638 function ufjoinDelete($params = NULL) {
1639 if ($params === NULL) {
1642 'module' => 'CiviEvent',
1643 'entity_table' => 'civicrm_event',
1646 'uf_group_id' => '',
1650 crm_add_uf_join($params);
1654 * Function to create Group for a contact
1656 * @param int $contactId
1658 function contactGroupCreate($contactId) {
1660 'contact_id.1' => $contactId,
1664 $this->callAPISuccess('GroupContact', 'Create', $params);
1668 * Function to delete Group for a contact
1671 * @internal param array $params
1673 function contactGroupDelete($contactId) {
1675 'contact_id.1' => $contactId,
1678 $this->civicrm_api('GroupContact', 'Delete', $params);
1682 * Function to create Activity
1684 * @param null $params
1686 * @internal param int $contactId
1688 function activityCreate($params = NULL) {
1690 if ($params === NULL) {
1691 $individualSourceID = $this->individualCreate();
1693 $contactParams = array(
1694 'first_name' => 'Julia',
1695 'Last_name' => 'Anderson',
1697 'email' => 'julia_anderson@civicrm.org',
1698 'contact_type' => 'Individual',
1701 $individualTargetID = $this->individualCreate($contactParams);
1704 'source_contact_id' => $individualSourceID,
1705 'target_contact_id' => array($individualTargetID),
1706 'assignee_contact_id' => array($individualTargetID),
1707 'subject' => 'Discussion on warm beer',
1708 'activity_date_time' => date('Ymd'),
1709 'duration_hours' => 30,
1710 'duration_minutes' => 20,
1711 'location' => 'Baker Street',
1712 'details' => 'Lets schedule a meeting',
1714 'activity_name' => 'Meeting',
1718 $result = $this->callAPISuccess('Activity', 'create', $params);
1720 $result['target_contact_id'] = $individualTargetID;
1721 $result['assignee_contact_id'] = $individualTargetID;
1726 * Function to create an activity type
1728 * @params array $params parameters
1730 function activityTypeCreate($params) {
1731 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1736 * Function to delete activity type
1738 * @params Integer $activityTypeId id of the activity type
1740 function activityTypeDelete($activityTypeId) {
1741 $params['activity_type_id'] = $activityTypeId;
1742 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1747 * Function to create custom group
1749 * @param array $params
1751 * @internal param string $className
1752 * @internal param string $title name of custom group
1754 function customGroupCreate($params = array()) {
1756 'title' => 'new custom group',
1757 'extends' => 'Contact',
1759 'style' => 'Inline',
1763 $params = array_merge($defaults, $params);
1765 if (strlen($params['title']) > 13) {
1766 $params['title'] = substr($params['title'], 0, 13);
1769 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1770 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1772 return $this->callAPISuccess('custom_group', 'create', $params);
1776 * existing function doesn't allow params to be over-ridden so need a new one
1777 * this one allows you to only pass in the params you want to change
1779 function CustomGroupCreateByParams($params = array()) {
1781 'title' => "API Custom Group",
1782 'extends' => 'Contact',
1784 'style' => 'Inline',
1787 $params = array_merge($defaults, $params);
1788 return $this->callAPISuccess('custom_group', 'create', $params);
1792 * Create custom group with multi fields
1794 function CustomGroupMultipleCreateByParams($params = array()) {
1799 $params = array_merge($defaults, $params);
1800 return $this->CustomGroupCreateByParams($params);
1804 * Create custom group with multi fields
1806 function CustomGroupMultipleCreateWithFields($params = array()) {
1807 // also need to pass on $params['custom_field'] if not set but not in place yet
1809 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1810 $ids['custom_group_id'] = $customGroup['id'];
1812 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1814 $ids['custom_field_id'][] = $customField['id'];
1816 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1817 $ids['custom_field_id'][] = $customField['id'];
1819 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1820 $ids['custom_field_id'][] = $customField['id'];
1826 * Create a custom group with a single text custom field. See
1827 * participant:testCreateWithCustom for how to use this
1829 * @param string $function __FUNCTION__
1831 * @internal param string $file __FILE__
1833 * @return array $ids ids of created objects
1835 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1836 $params = array('title' => $function);
1837 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1838 $params['extends'] = $entity ?
$entity : 'Contact';
1839 $customGroup = $this->CustomGroupCreate($params);
1840 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1841 CRM_Core_PseudoConstant
::flush();
1843 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1847 * Function to delete custom group
1849 * @param int $customGroupID
1853 function customGroupDelete($customGroupID) {
1854 $params['id'] = $customGroupID;
1855 return $this->callAPISuccess('custom_group', 'delete', $params);
1859 * Function to create custom field
1861 * @param array $params (custom_group_id) is required
1863 * @internal param string $name name of custom field
1864 * @internal param int $apiversion API version to use
1866 function customFieldCreate($params) {
1867 $params = array_merge(array(
1868 'label' => 'Custom Field',
1869 'data_type' => 'String',
1870 'html_type' => 'Text',
1871 'is_searchable' => 1,
1873 'default_value' => 'defaultValue',
1876 $result = $this->callAPISuccess('custom_field', 'create', $params);
1878 if ($result['is_error'] == 0 && isset($result['id'])) {
1879 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1880 // force reset of enabled components to help grab custom fields
1881 CRM_Core_Component
::getEnabledComponents(1);
1887 * Function to delete custom field
1889 * @param int $customFieldID
1893 function customFieldDelete($customFieldID) {
1895 $params['id'] = $customFieldID;
1896 return $this->callAPISuccess('custom_field', 'delete', $params);
1900 * Function to create note
1902 * @params array $params name-value pair for an event
1905 * @return array $note
1907 function noteCreate($cId) {
1909 'entity_table' => 'civicrm_contact',
1910 'entity_id' => $cId,
1911 'note' => 'hello I am testing Note',
1912 'contact_id' => $cId,
1913 'modified_date' => date('Ymd'),
1914 'subject' => 'Test Note',
1917 return $this->callAPISuccess('Note', 'create', $params);
1921 * Enable CiviCampaign Component
1923 function enableCiviCampaign() {
1924 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1925 // force reload of config object
1926 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1927 //flush cache by calling with reset
1928 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1932 * Create test generated example in api/v3/examples.
1933 * To turn this off (e.g. on the server) set
1934 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1935 * in your settings file
1936 * @param array $params array as passed to civicrm_api function
1937 * @param array $result array as received from the civicrm_api function
1938 * @param string $function calling function - generally __FUNCTION__
1939 * @param string $filename called from file - generally __FILE__
1940 * @param string $description descriptive text for the example file
1941 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1942 * @param string $action - optional action - otherwise taken from function name
1944 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1945 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1948 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1949 //todo - this is a bit cludgey
1950 if (empty($action)) {
1951 if (strstr($function, 'Create')) {
1952 $action = empty($action) ?
'create' : $action;
1953 $entityAction = 'Create';
1955 elseif (strstr($function, 'GetSingle')) {
1956 $action = empty($action) ?
'getsingle' : $action;
1957 $entityAction = 'GetSingle';
1959 elseif (strstr($function, 'GetValue')) {
1960 $action = empty($action) ?
'getvalue' : $action;
1961 $entityAction = 'GetValue';
1963 elseif (strstr($function, 'GetCount')) {
1964 $action = empty($action) ?
'getcount' : $action;
1965 $entityAction = 'GetCount';
1967 elseif (strstr($function, 'GetFields')) {
1968 $action = empty($action) ?
'getfields' : $action;
1969 $entityAction = 'GetFields';
1971 elseif (strstr($function, 'GetList')) {
1972 $action = empty($action) ?
'getlist' : $action;
1973 $entityAction = 'GetList';
1975 elseif (strstr($function, 'Get')) {
1976 $action = empty($action) ?
'get' : $action;
1977 $entityAction = 'Get';
1979 elseif (strstr($function, 'Delete')) {
1980 $action = empty($action) ?
'delete' : $action;
1981 $entityAction = 'Delete';
1983 elseif (strstr($function, 'Update')) {
1984 $action = empty($action) ?
'update' : $action;
1985 $entityAction = 'Update';
1987 elseif (strstr($function, 'Subscribe')) {
1988 $action = empty($action) ?
'subscribe' : $action;
1989 $entityAction = 'Subscribe';
1991 elseif (strstr($function, 'Submit')) {
1992 $action = empty($action) ?
'submit' : $action;
1993 $entityAction = 'Submit';
1995 elseif (strstr($function, 'Apply')) {
1996 $action = empty($action) ?
'apply' : $action;
1997 $entityAction = 'Apply';
1999 elseif (strstr($function, 'Replace')) {
2000 $action = empty($action) ?
'replace' : $action;
2001 $entityAction = 'Replace';
2005 $entityAction = ucwords($action);
2008 $this->tidyExampleResult($result);
2009 if(isset($params['version'])) {
2010 unset($params['version']);
2012 // a cleverer person than me would do it in a single regex
2013 if (strstr($entity, 'UF')) {
2014 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2017 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2019 $smarty = CRM_Core_Smarty
::singleton();
2020 $smarty->assign('testfunction', $function);
2021 $function = $fnPrefix . "_" . strtolower($action);
2022 $smarty->assign('function', $function);
2023 $smarty->assign('fnPrefix', $fnPrefix);
2024 $smarty->assign('params', $params);
2025 $smarty->assign('entity', $entity);
2026 $smarty->assign('filename', basename($filename));
2027 $smarty->assign('description', $description);
2028 $smarty->assign('result', $result);
2030 $smarty->assign('action', $action);
2031 if (empty($subfile)) {
2032 $subfile = $entityAction;
2034 if (file_exists('../tests/templates/documentFunction.tpl')) {
2035 if (!is_dir("../api/v3/examples/$entity")) {
2036 mkdir("../api/v3/examples/$entity");
2038 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2039 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2045 * Tidy up examples array so that fields that change often ..don't
2046 * and debug related fields are unset
2050 * @internal param array $params
2052 function tidyExampleResult(&$result){
2053 if(!is_array($result)) {
2056 $fieldsToChange = array(
2057 'hash' => '67eac7789eaee00',
2058 'modified_date' => '2012-11-14 16:02:35',
2059 'created_date' => '2013-07-28 08:49:19',
2060 'create_date' => '20120130621222105',
2061 'application_received_date' => '20130728084957',
2062 'in_date' => '2013-07-28 08:50:19',
2063 'scheduled_date' => '20130728085413',
2064 'approval_date' => '20130728085413',
2065 'pledge_start_date_high' => '20130726090416',
2066 'start_date' => '2013-07-29 00:00:00',
2067 'event_start_date' => '2013-07-29 00:00:00',
2068 'end_date' => '2013-08-04 00:00:00',
2069 'event_end_date' => '2013-08-04 00:00:00',
2070 'decision_date' => '20130805000000',
2073 $keysToUnset = array('xdebug', 'undefined_fields',);
2074 foreach ($keysToUnset as $unwantedKey) {
2075 if(isset($result[$unwantedKey])) {
2076 unset($result[$unwantedKey]);
2079 if (isset($result['values'])) {
2080 if(!is_array($result['values'])) {
2083 $resultArray = &$result['values'];
2085 elseif(is_array($result)) {
2086 $resultArray = &$result;
2092 foreach ($resultArray as $index => &$values) {
2093 if(!is_array($values)) {
2096 foreach($values as $key => &$value) {
2097 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2098 if(isset($value['is_error'])) {
2099 // we have a std nested result format
2100 $this->tidyExampleResult($value);
2103 foreach ($value as &$nestedResult) {
2104 // this is an alternative syntax for nested results a keyed array of results
2105 $this->tidyExampleResult($nestedResult);
2109 if(in_array($key, $keysToUnset)) {
2110 unset($values[$key]);
2113 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2114 $value = $fieldsToChange[$key];
2116 if(is_string($value)) {
2117 $value = addslashes($value);
2124 * Function to delete note
2126 * @params int $noteID
2129 function noteDelete($params) {
2130 return $this->callAPISuccess('Note', 'delete', $params);
2134 * Function to create custom field with Option Values
2136 * @param array $customGroup
2137 * @param string $name name of custom field
2141 function customFieldOptionValueCreate($customGroup, $name) {
2142 $fieldParams = array(
2143 'custom_group_id' => $customGroup['id'],
2144 'name' => 'test_custom_group',
2145 'label' => 'Country',
2146 'html_type' => 'Select',
2147 'data_type' => 'String',
2150 'is_searchable' => 0,
2154 $optionGroup = array(
2156 'name' => 'option_group1',
2157 'label' => 'option_group_label1',
2160 $optionValue = array(
2161 'option_label' => array('Label1', 'Label2'),
2162 'option_value' => array('value1', 'value2'),
2163 'option_name' => array($name . '_1', $name . '_2'),
2164 'option_weight' => array(1, 2),
2165 'option_status' => 1,
2168 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2170 return $this->callAPISuccess('custom_field', 'create', $params);
2173 function confirmEntitiesDeleted($entities) {
2174 foreach ($entities as $entity) {
2176 $result = $this->callAPISuccess($entity, 'Get', array());
2177 if ($result['error'] == 1 ||
$result['count'] > 0) {
2178 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2184 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2185 if ($dropCustomValueTables) {
2186 $tablesToTruncate[] = 'civicrm_custom_group';
2187 $tablesToTruncate[] = 'civicrm_custom_field';
2190 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2192 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2193 foreach ($tablesToTruncate as $table) {
2194 $sql = "TRUNCATE TABLE $table";
2195 CRM_Core_DAO
::executeQuery($sql);
2197 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2199 if ($dropCustomValueTables) {
2200 $dbName = self
::getDBName();
2202 SELECT TABLE_NAME as tableName
2203 FROM INFORMATION_SCHEMA.TABLES
2204 WHERE TABLE_SCHEMA = '{$dbName}'
2205 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2208 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2209 while ($tableDAO->fetch()) {
2210 $sql = "DROP TABLE {$tableDAO->tableName}";
2211 CRM_Core_DAO
::executeQuery($sql);
2217 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2219 function quickCleanUpFinancialEntities() {
2220 $tablesToTruncate = array(
2221 'civicrm_contribution',
2222 'civicrm_financial_trxn',
2223 'civicrm_contribution_recur',
2224 'civicrm_line_item',
2225 'civicrm_contribution_page',
2226 'civicrm_payment_processor',
2227 'civicrm_entity_financial_trxn',
2228 'civicrm_membership',
2229 'civicrm_membership_type',
2230 'civicrm_membership_payment',
2231 'civicrm_membership_status',
2233 'civicrm_participant',
2234 'civicrm_participant_payment',
2237 $this->quickCleanup($tablesToTruncate);
2240 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2241 * Default behaviour is to also delete the entity
2242 * @param array $params params array to check agains
2243 * @param int $id id of the entity concerned
2244 * @param string $entity name of entity concerned (e.g. membership)
2245 * @param bool $delete should the entity be deleted as part of this check
2246 * @param string $errorText text to print on error
2249 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2251 $result = $this->callAPISuccessGetSingle($entity, array(
2256 $this->callAPISuccess($entity, 'Delete', array(
2260 $dateFields = $keys = $dateTimeFields = array();
2261 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2262 foreach ($fields['values'] as $field => $settings) {
2263 if (array_key_exists($field, $result)) {
2264 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2267 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2269 $type = CRM_Utils_Array
::value('type', $settings);
2270 if ($type == CRM_Utils_Type
::T_DATE
) {
2271 $dateFields[] = $settings['name'];
2272 // we should identify both real names & unique names as dates
2273 if($field != $settings['name']) {
2274 $dateFields[] = $field;
2277 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2278 $dateTimeFields[] = $settings['name'];
2279 // we should identify both real names & unique names as dates
2280 if($field != $settings['name']) {
2281 $dateTimeFields[] = $field;
2286 if (strtolower($entity) == 'contribution') {
2287 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2288 // this is not returned in id format
2289 unset($params['payment_instrument_id']);
2290 $params['contribution_source'] = $params['source'];
2291 unset($params['source']);
2294 foreach ($params as $key => $value) {
2295 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2298 if (in_array($key, $dateFields)) {
2299 $value = date('Y-m-d', strtotime($value));
2300 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2302 if (in_array($key, $dateTimeFields)) {
2303 $value = date('Y-m-d H:i:s', strtotime($value));
2304 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2306 $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);
2311 * Function to get formatted values in the actual and expected result
2312 * @param array $actual actual calculated values
2313 * @param array $expected expected values
2316 function checkArrayEquals(&$actual, &$expected) {
2317 self
::unsetId($actual);
2318 self
::unsetId($expected);
2319 $this->assertEquals($actual, $expected);
2323 * Function to unset the key 'id' from the array
2324 * @param array $unformattedArray The array from which the 'id' has to be unset
2327 static function unsetId(&$unformattedArray) {
2328 $formattedArray = array();
2329 if (array_key_exists('id', $unformattedArray)) {
2330 unset($unformattedArray['id']);
2332 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2333 foreach ($unformattedArray['values'] as $key => $value) {
2334 if (is_Array($value)) {
2335 foreach ($value as $k => $v) {
2341 elseif ($key == 'id') {
2342 $unformattedArray[$key];
2344 $formattedArray = array($value);
2346 $unformattedArray['values'] = $formattedArray;
2351 * Helper to enable/disable custom directory support
2353 * @param array $customDirs with members:
2354 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2355 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2357 function customDirectories($customDirs) {
2358 require_once 'CRM/Core/Config.php';
2359 $config = CRM_Core_Config
::singleton();
2361 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2362 unset($config->customPHPPathDir
);
2364 elseif ($customDirs['php_path'] === TRUE) {
2365 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2368 $config->customPHPPathDir
= $php_path;
2371 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2372 unset($config->customTemplateDir
);
2374 elseif ($customDirs['template_path'] === TRUE) {
2375 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2378 $config->customTemplateDir
= $template_path;
2383 * Generate a temporary folder
2385 * @param string $prefix
2386 * @return string $string
2388 function createTempDir($prefix = 'test-') {
2389 $tempDir = CRM_Utils_File
::tempdir($prefix);
2390 $this->tempDirs
[] = $tempDir;
2394 function cleanTempDirs() {
2395 if (!is_array($this->tempDirs
)) {
2396 // fix test errors where this is not set
2399 foreach ($this->tempDirs
as $tempDir) {
2400 if (is_dir($tempDir)) {
2401 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2407 * Temporarily replace the singleton extension with a different one
2409 function setExtensionSystem(CRM_Extension_System
$system) {
2410 if ($this->origExtensionSystem
== NULL) {
2411 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2413 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2416 function unsetExtensionSystem() {
2417 if ($this->origExtensionSystem
!== NULL) {
2418 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2419 $this->origExtensionSystem
= NULL;
2424 * Temporarily alter the settings-metadata to add a mock setting.
2426 * WARNING: The setting metadata will disappear on the next cache-clear.
2431 function setMockSettingsMetaData($extras) {
2432 CRM_Core_BAO_Setting
::$_cache = array();
2433 $this->callAPISuccess('system','flush', array());
2434 CRM_Core_BAO_Setting
::$_cache = array();
2436 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2437 $metadata = array_merge($metadata, $extras);
2440 $fields = $this->callAPISuccess('setting', 'getfields', array());
2441 foreach ($extras as $key => $spec) {
2442 $this->assertNotEmpty($spec['title']);
2443 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2447 function financialAccountDelete($name) {
2448 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2449 $financialAccount->name
= $name;
2450 if($financialAccount->find(TRUE)) {
2451 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2452 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2453 $entityFinancialType->delete();
2454 $financialAccount->delete();
2459 * Use $ids as an instruction to do test cleanup
2461 function deleteFromIDSArray() {
2462 foreach ($this->ids
as $entity => $ids) {
2463 foreach ($ids as $id) {
2464 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2470 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2471 * (NB unclear if this is still required)
2473 function _sethtmlGlobals() {
2474 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2475 'required' => array(
2476 'html_quickform_rule_required',
2477 'HTML/QuickForm/Rule/Required.php'
2479 'maxlength' => array(
2480 'html_quickform_rule_range',
2481 'HTML/QuickForm/Rule/Range.php'
2483 'minlength' => array(
2484 'html_quickform_rule_range',
2485 'HTML/QuickForm/Rule/Range.php'
2487 'rangelength' => array(
2488 'html_quickform_rule_range',
2489 'HTML/QuickForm/Rule/Range.php'
2492 'html_quickform_rule_email',
2493 'HTML/QuickForm/Rule/Email.php'
2496 'html_quickform_rule_regex',
2497 'HTML/QuickForm/Rule/Regex.php'
2499 'lettersonly' => array(
2500 'html_quickform_rule_regex',
2501 'HTML/QuickForm/Rule/Regex.php'
2503 'alphanumeric' => array(
2504 'html_quickform_rule_regex',
2505 'HTML/QuickForm/Rule/Regex.php'
2508 'html_quickform_rule_regex',
2509 'HTML/QuickForm/Rule/Regex.php'
2511 'nopunctuation' => array(
2512 'html_quickform_rule_regex',
2513 'HTML/QuickForm/Rule/Regex.php'
2516 'html_quickform_rule_regex',
2517 'HTML/QuickForm/Rule/Regex.php'
2519 'callback' => array(
2520 'html_quickform_rule_callback',
2521 'HTML/QuickForm/Rule/Callback.php'
2524 'html_quickform_rule_compare',
2525 'HTML/QuickForm/Rule/Compare.php'
2528 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2529 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2531 'HTML/QuickForm/group.php',
2532 'HTML_QuickForm_group'
2535 'HTML/QuickForm/hidden.php',
2536 'HTML_QuickForm_hidden'
2539 'HTML/QuickForm/reset.php',
2540 'HTML_QuickForm_reset'
2542 'checkbox' => array(
2543 'HTML/QuickForm/checkbox.php',
2544 'HTML_QuickForm_checkbox'
2547 'HTML/QuickForm/file.php',
2548 'HTML_QuickForm_file'
2551 'HTML/QuickForm/image.php',
2552 'HTML_QuickForm_image'
2554 'password' => array(
2555 'HTML/QuickForm/password.php',
2556 'HTML_QuickForm_password'
2559 'HTML/QuickForm/radio.php',
2560 'HTML_QuickForm_radio'
2563 'HTML/QuickForm/button.php',
2564 'HTML_QuickForm_button'
2567 'HTML/QuickForm/submit.php',
2568 'HTML_QuickForm_submit'
2571 'HTML/QuickForm/select.php',
2572 'HTML_QuickForm_select'
2574 'hiddenselect' => array(
2575 'HTML/QuickForm/hiddenselect.php',
2576 'HTML_QuickForm_hiddenselect'
2579 'HTML/QuickForm/text.php',
2580 'HTML_QuickForm_text'
2582 'textarea' => array(
2583 'HTML/QuickForm/textarea.php',
2584 'HTML_QuickForm_textarea'
2586 'fckeditor' => array(
2587 'HTML/QuickForm/fckeditor.php',
2588 'HTML_QuickForm_FCKEditor'
2591 'HTML/QuickForm/tinymce.php',
2592 'HTML_QuickForm_TinyMCE'
2594 'dojoeditor' => array(
2595 'HTML/QuickForm/dojoeditor.php',
2596 'HTML_QuickForm_dojoeditor'
2599 'HTML/QuickForm/link.php',
2600 'HTML_QuickForm_link'
2602 'advcheckbox' => array(
2603 'HTML/QuickForm/advcheckbox.php',
2604 'HTML_QuickForm_advcheckbox'
2607 'HTML/QuickForm/date.php',
2608 'HTML_QuickForm_date'
2611 'HTML/QuickForm/static.php',
2612 'HTML_QuickForm_static'
2615 'HTML/QuickForm/header.php',
2616 'HTML_QuickForm_header'
2619 'HTML/QuickForm/html.php',
2620 'HTML_QuickForm_html'
2622 'hierselect' => array(
2623 'HTML/QuickForm/hierselect.php',
2624 'HTML_QuickForm_hierselect'
2626 'autocomplete' => array(
2627 'HTML/QuickForm/autocomplete.php',
2628 'HTML_QuickForm_autocomplete'
2631 'HTML/QuickForm/xbutton.php',
2632 'HTML_QuickForm_xbutton'
2634 'advmultiselect' => array(
2635 'HTML/QuickForm/advmultiselect.php',
2636 'HTML_QuickForm_advmultiselect'
2642 * Set up an acl allowing contact to see 2 specified groups
2643 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2645 * You need to have precreated these groups & created the user e.g
2646 * $this->createLoggedInUser();
2647 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2648 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2651 function setupACL() {
2653 $_REQUEST = $this->_params
;
2654 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2655 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2656 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2657 'label' => 'pick me',
2662 CRM_Core_DAO
::executeQuery("
2663 TRUNCATE civicrm_acl_cache
2666 CRM_Core_DAO
::executeQuery("
2667 TRUNCATE civicrm_acl_contact_cache
2671 CRM_Core_DAO
::executeQuery("
2672 INSERT INTO civicrm_acl_entity_role (
2673 `acl_role_id`, `entity_table`, `entity_id`
2674 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2677 CRM_Core_DAO
::executeQuery("
2678 INSERT INTO civicrm_acl (
2679 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2682 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2686 CRM_Core_DAO
::executeQuery("
2687 INSERT INTO civicrm_acl (
2688 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2691 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2694 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2695 $this->callAPISuccess('group_contact', 'create', array(
2696 'group_id' => $this->_permissionedGroup
,
2697 'contact_id' => $this->_loggedInUser
,
2700 CRM_ACL_BAO_Cache
::resetCache();
2701 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2702 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2706 * Create an instance of the paypal processor
2707 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2708 * this parent class & we don't have a structure for that yet
2709 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2710 * & the best protection agains that is the functions this class affords
2712 function paymentProcessorCreate($params = array()) {
2713 $params = array_merge(array(
2715 'domain_id' => CRM_Core_Config
::domainID(),
2716 'payment_processor_type_id' => 'PayPal',
2720 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2721 'password' => '1183377788',
2722 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2723 'url_site' => 'https://www.sandbox.paypal.com/',
2724 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2725 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2726 'class_name' => 'Payment_PayPalImpl',
2727 'billing_mode' => 3,
2728 'financial_type_id' => 1,
2731 if(!is_numeric($params['payment_processor_type_id'])) {
2732 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2734 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2735 'name' => $params['payment_processor_type_id'],
2739 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2740 return $result['id'];
2744 function CiviUnitTestCase_fatalErrorHandler($message) {
2745 throw new Exception("{$message['message']}: {$message['code']}");