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
818 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
820 'version' => $this->_apiversion
,
823 $result = $this->civicrm_api($entity, 'getsingle', $params);
824 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
825 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
828 // @todo - have gone with the fn that unsets id? should we check id?
829 $this->checkArrayEquals($result, $checkAgainst);
835 * This function exists to wrap api getValue function & check the result
836 * so we can ensure they succeed & throw exceptions without litterering the test with checks
837 * There is a type check in this
838 * @param string $entity
839 * @param array $params
843 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
851 function callAPISuccessGetCount($entity, $params, $count = NULL) {
853 'version' => $this->_apiversion
,
856 $result = $this->civicrm_api($entity, 'getcount', $params);
857 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
858 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
861 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
867 * This function exists to wrap api functions
868 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
870 * @param string $entity
871 * @param string $action
872 * @param array $params
873 * @param string $function - pass this in to create a generated example
874 * @param string $file - pass this in to create a generated example
875 * @param string $description
876 * @param string|null $subfile
877 * @param string|null $actionName
880 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
881 $params['version'] = $this->_apiversion
;
882 $result = $this->callAPISuccess($entity, $action, $params);
883 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
888 * This function exists to wrap api functions
889 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
890 * @param string $entity
891 * @param string $action
892 * @param array $params
893 * @param string $expectedErrorMessage error
894 * @param null $extraOutput
897 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
898 if (is_array($params)) {
900 'version' => $this->_apiversion
,
903 $result = $this->civicrm_api($entity, $action, $params);
904 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
909 * Create required data based on $this->entity & $this->params
910 * This is just a way to set up the test data for delete & get functions
911 * so the distinction between set
912 * up & tested functions is clearer
914 * @return array api Result
916 public function createTestEntity(){
917 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
921 * Generic function to create Organisation, to be used in test cases
923 * @param array parameters for civicrm_contact_add api function call
925 * @return int id of Organisation created
927 function organizationCreate($params = array()) {
932 'organization_name' => 'Unit Test Organization',
933 'contact_type' => 'Organization',
935 return $this->_contactCreate(array_merge($orgParams, $params));
939 * Generic function to create Individual, to be used in test cases
941 * @param array parameters for civicrm_contact_add api function call
943 * @return int id of Individual created
945 function individualCreate($params = array()) {
946 $params = array_merge(array(
947 'first_name' => 'Anthony',
948 'middle_name' => 'J.',
949 'last_name' => 'Anderson',
952 'email' => 'anthony_anderson@civicrm.org',
953 'contact_type' => 'Individual',
956 return $this->_contactCreate($params);
960 * Generic function to create Household, to be used in test cases
962 * @param array parameters for civicrm_contact_add api function call
964 * @return int id of Household created
966 function householdCreate($params = array()) {
967 $params = array_merge(array(
968 'household_name' => 'Unit Test household',
969 'contact_type' => 'Household',
971 return $this->_contactCreate($params);
975 * Private helper function for calling civicrm_contact_add
980 * @internal param \parameters $array for civicrm_contact_add api function call
982 * @return int id of Household created
984 private function _contactCreate($params) {
985 $result = $this->callAPISuccess('contact', 'create', $params);
986 if (!empty($result['is_error']) ||
empty($result['id'])) {
987 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
989 return $result['id'];
992 function contactDelete($contactID) {
995 'skip_undelete' => 1,
998 $domain = new CRM_Core_BAO_Domain
;
999 $domain->contact_id
= $contactID;
1000 if ($domain->find(TRUE)) {
1001 // we are finding tests trying to delete the domain contact in cleanup
1002 //since this is mainly for cleanup lets put a safeguard here
1005 $result = $this->callAPISuccess('contact', 'delete', $params);
1009 function contactTypeDelete($contactTypeId) {
1010 require_once 'CRM/Contact/BAO/ContactType.php';
1011 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1013 throw new Exception('Could not delete contact type');
1017 function membershipTypeCreate($params = array()) {
1018 CRM_Member_PseudoConstant
::flush('membershipType');
1019 CRM_Core_Config
::clearDBCache();
1020 $memberOfOrganization = $this->organizationCreate();
1021 $params = array_merge(array(
1022 'name' => 'General',
1023 'duration_unit' => 'year',
1024 'duration_interval' => 1,
1025 'period_type' => 'rolling',
1026 'member_of_contact_id' => $memberOfOrganization,
1028 'financial_type_id' => 1,
1031 'visibility' => 'Public',
1034 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1036 CRM_Member_PseudoConstant
::flush('membershipType');
1037 CRM_Utils_Cache
::singleton()->flush();
1039 return $result['id'];
1042 function contactMembershipCreate($params) {
1044 'join_date' => '2007-01-21',
1045 'start_date' => '2007-01-21',
1046 'end_date' => '2007-12-21',
1047 'source' => 'Payment',
1050 foreach ($pre as $key => $val) {
1051 if (!isset($params[$key])) {
1052 $params[$key] = $val;
1056 $result = $this->callAPISuccess('Membership', 'create', $params);
1057 return $result['id'];
1061 * Function to delete Membership Type
1064 * @internal param int $membershipTypeID
1066 function membershipTypeDelete($params) {
1067 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1071 function membershipDelete($membershipID) {
1072 $deleteParams = array('id' => $membershipID);
1073 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1077 function membershipStatusCreate($name = 'test member status') {
1078 $params['name'] = $name;
1079 $params['start_event'] = 'start_date';
1080 $params['end_event'] = 'end_date';
1081 $params['is_current_member'] = 1;
1082 $params['is_active'] = 1;
1084 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1085 CRM_Member_PseudoConstant
::flush('membershipStatus');
1086 return $result['id'];
1089 function membershipStatusDelete($membershipStatusID) {
1090 if (!$membershipStatusID) {
1093 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1097 function relationshipTypeCreate($params = array()) {
1098 $params = array_merge(array(
1099 'name_a_b' => 'Relation 1 for relationship type create',
1100 'name_b_a' => 'Relation 2 for relationship type create',
1101 'contact_type_a' => 'Individual',
1102 'contact_type_b' => 'Organization',
1109 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1110 CRM_Core_PseudoConstant
::flush('relationshipType');
1112 return $result['id'];
1116 * Function to delete Relatinship Type
1118 * @param int $relationshipTypeID
1120 function relationshipTypeDelete($relationshipTypeID) {
1121 $params['id'] = $relationshipTypeID;
1122 $this->callAPISuccess('relationship_type', 'delete', $params);
1125 function paymentProcessorTypeCreate($params = NULL) {
1126 if (is_null($params)) {
1128 'name' => 'API_Test_PP',
1129 'title' => 'API Test Payment Processor',
1130 'class_name' => 'CRM_Core_Payment_APITest',
1131 'billing_mode' => 'form',
1137 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1139 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1141 return $result['id'];
1145 * Function to create Participant
1147 * @param array $params array of contact id and event id values
1149 * @return int $id of participant created
1151 function participantCreate($params) {
1152 if(empty($params['contact_id'])){
1153 $params['contact_id'] = $this->individualCreate();
1155 if(empty($params['event_id'])){
1156 $event = $this->eventCreate();
1157 $params['event_id'] = $event['id'];
1162 'register_date' => 20070219,
1163 'source' => 'Wimbeldon',
1164 'event_level' => 'Payment',
1168 $params = array_merge($defaults, $params);
1169 $result = $this->callAPISuccess('Participant', 'create', $params);
1170 return $result['id'];
1174 * Function to create Payment Processor
1176 * @return object of Payment Processsor
1178 function processorCreate() {
1179 $processorParams = array(
1182 'payment_processor_type_id' => 10,
1183 'financial_account_id' => 12,
1186 'url_site' => 'http://dummy.com',
1187 'url_recur' => 'http://dummy.com',
1188 'billing_mode' => 1,
1190 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1191 return $paymentProcessor;
1195 * Function to create contribution page
1198 * @return object of contribution page
1200 function contributionPageCreate($params) {
1201 $this->_pageParams
= array(
1202 'title' => 'Test Contribution Page',
1203 'financial_type_id' => 1,
1204 'currency' => 'USD',
1205 'financial_account_id' => 1,
1206 'payment_processor' => $params['processor_id'],
1208 'is_allow_other_amount' => 1,
1210 'max_amount' => 1000,
1212 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1213 return $contributionPage;
1217 * Function to create Tag
1219 * @param array $params
1220 * @return array result of created tag
1222 function tagCreate($params = array()) {
1224 'name' => 'New Tag3',
1225 'description' => 'This is description for Our New Tag ',
1228 $params = array_merge($defaults, $params);
1229 $result = $this->callAPISuccess('Tag', 'create', $params);
1230 return $result['values'][$result['id']];
1234 * Function to delete Tag
1236 * @param int $tagId id of the tag to be deleted
1238 function tagDelete($tagId) {
1239 require_once 'api/api.php';
1243 $result = $this->callAPISuccess('Tag', 'delete', $params);
1244 return $result['id'];
1248 * Add entity(s) to the tag
1250 * @param array $params
1254 function entityTagAdd($params) {
1255 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1260 * Function to create contribution
1262 * @param int $cID contact_id
1264 * @internal param int $cTypeID id of financial type
1266 * @return int id of created contribution
1268 function pledgeCreate($cID) {
1270 'contact_id' => $cID,
1271 'pledge_create_date' => date('Ymd'),
1272 'start_date' => date('Ymd'),
1273 'scheduled_date' => date('Ymd'),
1275 'pledge_status_id' => '2',
1276 'financial_type_id' => '1',
1277 'pledge_original_installment_amount' => 20,
1278 'frequency_interval' => 5,
1279 'frequency_unit' => 'year',
1280 'frequency_day' => 15,
1281 'installments' => 5,
1284 $result = $this->callAPISuccess('Pledge', 'create', $params);
1285 return $result['id'];
1289 * Function to delete contribution
1292 * @internal param int $contributionId
1294 function pledgeDelete($pledgeId) {
1296 'pledge_id' => $pledgeId,
1298 $this->callAPISuccess('Pledge', 'delete', $params);
1302 * Function to create contribution
1304 * @param int $cID contact_id
1305 * @param int $cTypeID id of financial type
1307 * @param int $invoiceID
1308 * @param int $trxnID
1309 * @param int $paymentInstrumentID
1310 * @param bool $isFee
1311 * @return int id of created contribution
1313 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1316 'contact_id' => $cID,
1317 'receive_date' => date('Ymd'),
1318 'total_amount' => 100.00,
1319 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1320 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1321 'non_deductible_amount' => 10.00,
1322 'trxn_id' => $trxnID,
1323 'invoice_id' => $invoiceID,
1325 'contribution_status_id' => 1,
1326 // 'note' => 'Donating for Nobel Cause', *Fixme
1330 $params['fee_amount'] = 5.00;
1331 $params['net_amount'] = 95.00;
1334 $result = $this->callAPISuccess('contribution', 'create', $params);
1335 return $result['id'];
1339 * Function to create online contribution
1342 * @param int $financialType id of financial type
1344 * @param int $invoiceID
1345 * @param int $trxnID
1346 * @return int id of created contribution
1348 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1349 $contribParams = array(
1350 'contact_id' => $params['contact_id'],
1351 'receive_date' => date('Ymd'),
1352 'total_amount' => 100.00,
1353 'financial_type_id' => $financialType,
1354 'contribution_page_id' => $params['contribution_page_id'],
1356 'invoice_id' => 67890,
1359 $contribParams = array_merge($contribParams, $params);
1360 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1362 return $result['id'];
1366 * Function to delete contribution
1368 * @param int $contributionId
1372 function contributionDelete($contributionId) {
1374 'contribution_id' => $contributionId,
1376 $result = $this->callAPISuccess('contribution', 'delete', $params);
1381 * Function to create an Event
1383 * @param array $params name-value pair for an event
1385 * @return array $event
1387 function eventCreate($params = array()) {
1388 // if no contact was passed, make up a dummy event creator
1389 if (!isset($params['contact_id'])) {
1390 $params['contact_id'] = $this->_contactCreate(array(
1391 'contact_type' => 'Individual',
1392 'first_name' => 'Event',
1393 'last_name' => 'Creator',
1397 // set defaults for missing params
1398 $params = array_merge(array(
1399 'title' => 'Annual CiviCRM meet',
1400 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1401 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1402 'event_type_id' => 1,
1404 'start_date' => 20081021,
1405 'end_date' => 20081023,
1406 'is_online_registration' => 1,
1407 'registration_start_date' => 20080601,
1408 'registration_end_date' => 20081015,
1409 'max_participants' => 100,
1410 'event_full_text' => 'Sorry! We are already full',
1413 'is_show_location' => 0,
1416 return $this->callAPISuccess('Event', 'create', $params);
1420 * Function to delete event
1422 * @param int $id ID of the event
1426 function eventDelete($id) {
1430 return $this->callAPISuccess('event', 'delete', $params);
1434 * Function to delete participant
1436 * @param int $participantID
1440 function participantDelete($participantID) {
1442 'id' => $participantID,
1444 return $this->callAPISuccess('Participant', 'delete', $params);
1448 * Function to create participant payment
1450 * @param $participantID
1451 * @param null $contributionID
1452 * @return int $id of created payment
1454 function participantPaymentCreate($participantID, $contributionID = NULL) {
1455 //Create Participant Payment record With Values
1457 'participant_id' => $participantID,
1458 'contribution_id' => $contributionID,
1461 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1462 return $result['id'];
1466 * Function to delete participant payment
1468 * @param int $paymentID
1470 function participantPaymentDelete($paymentID) {
1474 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1478 * Function to add a Location
1481 * @return int location id of created location
1483 function locationAdd($contactID) {
1486 'location_type' => 'New Location Type',
1488 'name' => 'Saint Helier St',
1489 'county' => 'Marin',
1490 'country' => 'United States',
1491 'state_province' => 'Michigan',
1492 'supplemental_address_1' => 'Hallmark Ct',
1493 'supplemental_address_2' => 'Jersey Village',
1498 'contact_id' => $contactID,
1499 'address' => $address,
1500 'location_format' => '2.0',
1501 'location_type' => 'New Location Type',
1504 $result = $this->callAPISuccess('Location', 'create', $params);
1509 * Function to delete Locations of contact
1511 * @params array $pamars parameters
1513 function locationDelete($params) {
1514 $result = $this->callAPISuccess('Location', 'delete', $params);
1518 * Function to add a Location Type
1520 * @param null $params
1521 * @return int location id of created location
1523 function locationTypeCreate($params = NULL) {
1524 if ($params === NULL) {
1526 'name' => 'New Location Type',
1527 'vcard_name' => 'New Location Type',
1528 'description' => 'Location Type for Delete',
1533 $locationType = new CRM_Core_DAO_LocationType();
1534 $locationType->copyValues($params);
1535 $locationType->save();
1536 // clear getfields cache
1537 CRM_Core_PseudoConstant
::flush();
1538 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1539 return $locationType;
1543 * Function to delete a Location Type
1545 * @param int location type id
1547 function locationTypeDelete($locationTypeId) {
1548 $locationType = new CRM_Core_DAO_LocationType();
1549 $locationType->id
= $locationTypeId;
1550 $locationType->delete();
1554 * Function to add a Group
1556 * @params array to add group
1558 * @param array $params
1559 * @return int groupId of created group
1561 function groupCreate($params = array()) {
1562 $params = array_merge(array(
1563 'name' => 'Test Group 1',
1565 'title' => 'New Test Group Created',
1566 'description' => 'New Test Group Created',
1568 'visibility' => 'Public Pages',
1569 'group_type' => array(
1575 $result = $this->callAPISuccess('Group', 'create', $params);
1576 return $result['id'];
1580 * Function to delete a Group
1583 * @internal param int $id
1585 function groupDelete($gid) {
1591 $this->callAPISuccess('Group', 'delete', $params);
1596 * @param array $params
1598 function uFFieldCreate($params = array()) {
1599 $params = array_merge(array(
1601 'field_name' => 'first_name',
1604 'visibility' => 'Public Pages and Listings',
1605 'is_searchable' => '1',
1606 'label' => 'first_name',
1607 'field_type' => 'Individual',
1610 $this->callAPISuccess('uf_field', 'create', $params);
1614 * Function to add a UF Join Entry
1616 * @param null $params
1617 * @return int $id of created UF Join
1619 function ufjoinCreate($params = NULL) {
1620 if ($params === NULL) {
1623 'module' => 'CiviEvent',
1624 'entity_table' => 'civicrm_event',
1630 $result = $this->callAPISuccess('uf_join', 'create', $params);
1635 * Function to delete a UF Join Entry
1637 * @param array with missing uf_group_id
1639 function ufjoinDelete($params = NULL) {
1640 if ($params === NULL) {
1643 'module' => 'CiviEvent',
1644 'entity_table' => 'civicrm_event',
1647 'uf_group_id' => '',
1651 crm_add_uf_join($params);
1655 * Function to create Group for a contact
1657 * @param int $contactId
1659 function contactGroupCreate($contactId) {
1661 'contact_id.1' => $contactId,
1665 $this->callAPISuccess('GroupContact', 'Create', $params);
1669 * Function to delete Group for a contact
1672 * @internal param array $params
1674 function contactGroupDelete($contactId) {
1676 'contact_id.1' => $contactId,
1679 $this->civicrm_api('GroupContact', 'Delete', $params);
1683 * Function to create Activity
1685 * @param null $params
1687 * @internal param int $contactId
1689 function activityCreate($params = NULL) {
1691 if ($params === NULL) {
1692 $individualSourceID = $this->individualCreate();
1694 $contactParams = array(
1695 'first_name' => 'Julia',
1696 'Last_name' => 'Anderson',
1698 'email' => 'julia_anderson@civicrm.org',
1699 'contact_type' => 'Individual',
1702 $individualTargetID = $this->individualCreate($contactParams);
1705 'source_contact_id' => $individualSourceID,
1706 'target_contact_id' => array($individualTargetID),
1707 'assignee_contact_id' => array($individualTargetID),
1708 'subject' => 'Discussion on warm beer',
1709 'activity_date_time' => date('Ymd'),
1710 'duration_hours' => 30,
1711 'duration_minutes' => 20,
1712 'location' => 'Baker Street',
1713 'details' => 'Lets schedule a meeting',
1715 'activity_name' => 'Meeting',
1719 $result = $this->callAPISuccess('Activity', 'create', $params);
1721 $result['target_contact_id'] = $individualTargetID;
1722 $result['assignee_contact_id'] = $individualTargetID;
1727 * Function to create an activity type
1729 * @params array $params parameters
1731 function activityTypeCreate($params) {
1732 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1737 * Function to delete activity type
1739 * @params Integer $activityTypeId id of the activity type
1741 function activityTypeDelete($activityTypeId) {
1742 $params['activity_type_id'] = $activityTypeId;
1743 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1748 * Function to create custom group
1750 * @param array $params
1752 * @internal param string $className
1753 * @internal param string $title name of custom group
1755 function customGroupCreate($params = array()) {
1757 'title' => 'new custom group',
1758 'extends' => 'Contact',
1760 'style' => 'Inline',
1764 $params = array_merge($defaults, $params);
1766 if (strlen($params['title']) > 13) {
1767 $params['title'] = substr($params['title'], 0, 13);
1770 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1771 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1773 return $this->callAPISuccess('custom_group', 'create', $params);
1777 * existing function doesn't allow params to be over-ridden so need a new one
1778 * this one allows you to only pass in the params you want to change
1780 function CustomGroupCreateByParams($params = array()) {
1782 'title' => "API Custom Group",
1783 'extends' => 'Contact',
1785 'style' => 'Inline',
1788 $params = array_merge($defaults, $params);
1789 return $this->callAPISuccess('custom_group', 'create', $params);
1793 * Create custom group with multi fields
1795 function CustomGroupMultipleCreateByParams($params = array()) {
1800 $params = array_merge($defaults, $params);
1801 return $this->CustomGroupCreateByParams($params);
1805 * Create custom group with multi fields
1807 function CustomGroupMultipleCreateWithFields($params = array()) {
1808 // also need to pass on $params['custom_field'] if not set but not in place yet
1810 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1811 $ids['custom_group_id'] = $customGroup['id'];
1813 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1815 $ids['custom_field_id'][] = $customField['id'];
1817 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1818 $ids['custom_field_id'][] = $customField['id'];
1820 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1821 $ids['custom_field_id'][] = $customField['id'];
1827 * Create a custom group with a single text custom field. See
1828 * participant:testCreateWithCustom for how to use this
1830 * @param string $function __FUNCTION__
1832 * @internal param string $file __FILE__
1834 * @return array $ids ids of created objects
1836 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1837 $params = array('title' => $function);
1838 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1839 $params['extends'] = $entity ?
$entity : 'Contact';
1840 $customGroup = $this->CustomGroupCreate($params);
1841 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1842 CRM_Core_PseudoConstant
::flush();
1844 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1848 * Function to delete custom group
1850 * @param int $customGroupID
1854 function customGroupDelete($customGroupID) {
1855 $params['id'] = $customGroupID;
1856 return $this->callAPISuccess('custom_group', 'delete', $params);
1860 * Function to create custom field
1862 * @param array $params (custom_group_id) is required
1864 * @internal param string $name name of custom field
1865 * @internal param int $apiversion API version to use
1867 function customFieldCreate($params) {
1868 $params = array_merge(array(
1869 'label' => 'Custom Field',
1870 'data_type' => 'String',
1871 'html_type' => 'Text',
1872 'is_searchable' => 1,
1874 'default_value' => 'defaultValue',
1877 $result = $this->callAPISuccess('custom_field', 'create', $params);
1879 if ($result['is_error'] == 0 && isset($result['id'])) {
1880 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1881 // force reset of enabled components to help grab custom fields
1882 CRM_Core_Component
::getEnabledComponents(1);
1888 * Function to delete custom field
1890 * @param int $customFieldID
1894 function customFieldDelete($customFieldID) {
1896 $params['id'] = $customFieldID;
1897 return $this->callAPISuccess('custom_field', 'delete', $params);
1901 * Function to create note
1903 * @params array $params name-value pair for an event
1906 * @return array $note
1908 function noteCreate($cId) {
1910 'entity_table' => 'civicrm_contact',
1911 'entity_id' => $cId,
1912 'note' => 'hello I am testing Note',
1913 'contact_id' => $cId,
1914 'modified_date' => date('Ymd'),
1915 'subject' => 'Test Note',
1918 return $this->callAPISuccess('Note', 'create', $params);
1922 * Enable CiviCampaign Component
1924 function enableCiviCampaign() {
1925 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1926 // force reload of config object
1927 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1928 //flush cache by calling with reset
1929 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1933 * Create test generated example in api/v3/examples.
1934 * To turn this off (e.g. on the server) set
1935 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1936 * in your settings file
1937 * @param array $params array as passed to civicrm_api function
1938 * @param array $result array as received from the civicrm_api function
1939 * @param string $function calling function - generally __FUNCTION__
1940 * @param string $filename called from file - generally __FILE__
1941 * @param string $description descriptive text for the example file
1942 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1943 * @param string $action - optional action - otherwise taken from function name
1945 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1946 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1949 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1950 //todo - this is a bit cludgey
1951 if (empty($action)) {
1952 if (strstr($function, 'Create')) {
1953 $action = empty($action) ?
'create' : $action;
1954 $entityAction = 'Create';
1956 elseif (strstr($function, 'GetSingle')) {
1957 $action = empty($action) ?
'getsingle' : $action;
1958 $entityAction = 'GetSingle';
1960 elseif (strstr($function, 'GetValue')) {
1961 $action = empty($action) ?
'getvalue' : $action;
1962 $entityAction = 'GetValue';
1964 elseif (strstr($function, 'GetCount')) {
1965 $action = empty($action) ?
'getcount' : $action;
1966 $entityAction = 'GetCount';
1968 elseif (strstr($function, 'GetFields')) {
1969 $action = empty($action) ?
'getfields' : $action;
1970 $entityAction = 'GetFields';
1972 elseif (strstr($function, 'GetList')) {
1973 $action = empty($action) ?
'getlist' : $action;
1974 $entityAction = 'GetList';
1976 elseif (strstr($function, 'Get')) {
1977 $action = empty($action) ?
'get' : $action;
1978 $entityAction = 'Get';
1980 elseif (strstr($function, 'Delete')) {
1981 $action = empty($action) ?
'delete' : $action;
1982 $entityAction = 'Delete';
1984 elseif (strstr($function, 'Update')) {
1985 $action = empty($action) ?
'update' : $action;
1986 $entityAction = 'Update';
1988 elseif (strstr($function, 'Subscribe')) {
1989 $action = empty($action) ?
'subscribe' : $action;
1990 $entityAction = 'Subscribe';
1992 elseif (strstr($function, 'Submit')) {
1993 $action = empty($action) ?
'submit' : $action;
1994 $entityAction = 'Submit';
1996 elseif (strstr($function, 'Apply')) {
1997 $action = empty($action) ?
'apply' : $action;
1998 $entityAction = 'Apply';
2000 elseif (strstr($function, 'Replace')) {
2001 $action = empty($action) ?
'replace' : $action;
2002 $entityAction = 'Replace';
2006 $entityAction = ucwords($action);
2009 $this->tidyExampleResult($result);
2010 if(isset($params['version'])) {
2011 unset($params['version']);
2013 // a cleverer person than me would do it in a single regex
2014 if (strstr($entity, 'UF')) {
2015 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2018 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2020 $smarty = CRM_Core_Smarty
::singleton();
2021 $smarty->assign('testfunction', $function);
2022 $function = $fnPrefix . "_" . strtolower($action);
2023 $smarty->assign('function', $function);
2024 $smarty->assign('fnPrefix', $fnPrefix);
2025 $smarty->assign('params', $params);
2026 $smarty->assign('entity', $entity);
2027 $smarty->assign('filename', basename($filename));
2028 $smarty->assign('description', $description);
2029 $smarty->assign('result', $result);
2031 $smarty->assign('action', $action);
2032 if (empty($subfile)) {
2033 $subfile = $entityAction;
2035 if (file_exists('../tests/templates/documentFunction.tpl')) {
2036 if (!is_dir("../api/v3/examples/$entity")) {
2037 mkdir("../api/v3/examples/$entity");
2039 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2040 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2046 * Tidy up examples array so that fields that change often ..don't
2047 * and debug related fields are unset
2051 * @internal param array $params
2053 function tidyExampleResult(&$result){
2054 if(!is_array($result)) {
2057 $fieldsToChange = array(
2058 'hash' => '67eac7789eaee00',
2059 'modified_date' => '2012-11-14 16:02:35',
2060 'created_date' => '2013-07-28 08:49:19',
2061 'create_date' => '20120130621222105',
2062 'application_received_date' => '20130728084957',
2063 'in_date' => '2013-07-28 08:50:19',
2064 'scheduled_date' => '20130728085413',
2065 'approval_date' => '20130728085413',
2066 'pledge_start_date_high' => '20130726090416',
2067 'start_date' => '2013-07-29 00:00:00',
2068 'event_start_date' => '2013-07-29 00:00:00',
2069 'end_date' => '2013-08-04 00:00:00',
2070 'event_end_date' => '2013-08-04 00:00:00',
2071 'decision_date' => '20130805000000',
2074 $keysToUnset = array('xdebug', 'undefined_fields',);
2075 foreach ($keysToUnset as $unwantedKey) {
2076 if(isset($result[$unwantedKey])) {
2077 unset($result[$unwantedKey]);
2080 if (isset($result['values'])) {
2081 if(!is_array($result['values'])) {
2084 $resultArray = &$result['values'];
2086 elseif(is_array($result)) {
2087 $resultArray = &$result;
2093 foreach ($resultArray as $index => &$values) {
2094 if(!is_array($values)) {
2097 foreach($values as $key => &$value) {
2098 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2099 if(isset($value['is_error'])) {
2100 // we have a std nested result format
2101 $this->tidyExampleResult($value);
2104 foreach ($value as &$nestedResult) {
2105 // this is an alternative syntax for nested results a keyed array of results
2106 $this->tidyExampleResult($nestedResult);
2110 if(in_array($key, $keysToUnset)) {
2111 unset($values[$key]);
2114 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2115 $value = $fieldsToChange[$key];
2117 if(is_string($value)) {
2118 $value = addslashes($value);
2125 * Function to delete note
2127 * @params int $noteID
2130 function noteDelete($params) {
2131 return $this->callAPISuccess('Note', 'delete', $params);
2135 * Function to create custom field with Option Values
2137 * @param array $customGroup
2138 * @param string $name name of custom field
2142 function customFieldOptionValueCreate($customGroup, $name) {
2143 $fieldParams = array(
2144 'custom_group_id' => $customGroup['id'],
2145 'name' => 'test_custom_group',
2146 'label' => 'Country',
2147 'html_type' => 'Select',
2148 'data_type' => 'String',
2151 'is_searchable' => 0,
2155 $optionGroup = array(
2157 'name' => 'option_group1',
2158 'label' => 'option_group_label1',
2161 $optionValue = array(
2162 'option_label' => array('Label1', 'Label2'),
2163 'option_value' => array('value1', 'value2'),
2164 'option_name' => array($name . '_1', $name . '_2'),
2165 'option_weight' => array(1, 2),
2166 'option_status' => 1,
2169 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2171 return $this->callAPISuccess('custom_field', 'create', $params);
2174 function confirmEntitiesDeleted($entities) {
2175 foreach ($entities as $entity) {
2177 $result = $this->callAPISuccess($entity, 'Get', array());
2178 if ($result['error'] == 1 ||
$result['count'] > 0) {
2179 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2185 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2186 if ($dropCustomValueTables) {
2187 $tablesToTruncate[] = 'civicrm_custom_group';
2188 $tablesToTruncate[] = 'civicrm_custom_field';
2191 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2193 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2194 foreach ($tablesToTruncate as $table) {
2195 $sql = "TRUNCATE TABLE $table";
2196 CRM_Core_DAO
::executeQuery($sql);
2198 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2200 if ($dropCustomValueTables) {
2201 $dbName = self
::getDBName();
2203 SELECT TABLE_NAME as tableName
2204 FROM INFORMATION_SCHEMA.TABLES
2205 WHERE TABLE_SCHEMA = '{$dbName}'
2206 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2209 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2210 while ($tableDAO->fetch()) {
2211 $sql = "DROP TABLE {$tableDAO->tableName}";
2212 CRM_Core_DAO
::executeQuery($sql);
2218 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2220 function quickCleanUpFinancialEntities() {
2221 $tablesToTruncate = array(
2222 'civicrm_contribution',
2223 'civicrm_financial_trxn',
2224 'civicrm_contribution_recur',
2225 'civicrm_line_item',
2226 'civicrm_contribution_page',
2227 'civicrm_payment_processor',
2228 'civicrm_entity_financial_trxn',
2229 'civicrm_membership',
2230 'civicrm_membership_type',
2231 'civicrm_membership_payment',
2232 'civicrm_membership_status',
2234 'civicrm_participant',
2235 'civicrm_participant_payment',
2238 $this->quickCleanup($tablesToTruncate);
2241 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2242 * Default behaviour is to also delete the entity
2243 * @param array $params params array to check agains
2244 * @param int $id id of the entity concerned
2245 * @param string $entity name of entity concerned (e.g. membership)
2246 * @param bool $delete should the entity be deleted as part of this check
2247 * @param string $errorText text to print on error
2250 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2252 $result = $this->callAPISuccessGetSingle($entity, array(
2257 $this->callAPISuccess($entity, 'Delete', array(
2261 $dateFields = $keys = $dateTimeFields = array();
2262 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2263 foreach ($fields['values'] as $field => $settings) {
2264 if (array_key_exists($field, $result)) {
2265 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2268 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2270 $type = CRM_Utils_Array
::value('type', $settings);
2271 if ($type == CRM_Utils_Type
::T_DATE
) {
2272 $dateFields[] = $settings['name'];
2273 // we should identify both real names & unique names as dates
2274 if($field != $settings['name']) {
2275 $dateFields[] = $field;
2278 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2279 $dateTimeFields[] = $settings['name'];
2280 // we should identify both real names & unique names as dates
2281 if($field != $settings['name']) {
2282 $dateTimeFields[] = $field;
2287 if (strtolower($entity) == 'contribution') {
2288 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2289 // this is not returned in id format
2290 unset($params['payment_instrument_id']);
2291 $params['contribution_source'] = $params['source'];
2292 unset($params['source']);
2295 foreach ($params as $key => $value) {
2296 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2299 if (in_array($key, $dateFields)) {
2300 $value = date('Y-m-d', strtotime($value));
2301 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2303 if (in_array($key, $dateTimeFields)) {
2304 $value = date('Y-m-d H:i:s', strtotime($value));
2305 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2307 $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);
2312 * Function to get formatted values in the actual and expected result
2313 * @param array $actual actual calculated values
2314 * @param array $expected expected values
2317 function checkArrayEquals(&$actual, &$expected) {
2318 self
::unsetId($actual);
2319 self
::unsetId($expected);
2320 $this->assertEquals($actual, $expected);
2324 * Function to unset the key 'id' from the array
2325 * @param array $unformattedArray The array from which the 'id' has to be unset
2328 static function unsetId(&$unformattedArray) {
2329 $formattedArray = array();
2330 if (array_key_exists('id', $unformattedArray)) {
2331 unset($unformattedArray['id']);
2333 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2334 foreach ($unformattedArray['values'] as $key => $value) {
2335 if (is_Array($value)) {
2336 foreach ($value as $k => $v) {
2342 elseif ($key == 'id') {
2343 $unformattedArray[$key];
2345 $formattedArray = array($value);
2347 $unformattedArray['values'] = $formattedArray;
2352 * Helper to enable/disable custom directory support
2354 * @param array $customDirs with members:
2355 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2356 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2358 function customDirectories($customDirs) {
2359 require_once 'CRM/Core/Config.php';
2360 $config = CRM_Core_Config
::singleton();
2362 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2363 unset($config->customPHPPathDir
);
2365 elseif ($customDirs['php_path'] === TRUE) {
2366 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2369 $config->customPHPPathDir
= $php_path;
2372 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2373 unset($config->customTemplateDir
);
2375 elseif ($customDirs['template_path'] === TRUE) {
2376 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2379 $config->customTemplateDir
= $template_path;
2384 * Generate a temporary folder
2386 * @param string $prefix
2387 * @return string $string
2389 function createTempDir($prefix = 'test-') {
2390 $tempDir = CRM_Utils_File
::tempdir($prefix);
2391 $this->tempDirs
[] = $tempDir;
2395 function cleanTempDirs() {
2396 if (!is_array($this->tempDirs
)) {
2397 // fix test errors where this is not set
2400 foreach ($this->tempDirs
as $tempDir) {
2401 if (is_dir($tempDir)) {
2402 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2408 * Temporarily replace the singleton extension with a different one
2410 function setExtensionSystem(CRM_Extension_System
$system) {
2411 if ($this->origExtensionSystem
== NULL) {
2412 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2414 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2417 function unsetExtensionSystem() {
2418 if ($this->origExtensionSystem
!== NULL) {
2419 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2420 $this->origExtensionSystem
= NULL;
2425 * Temporarily alter the settings-metadata to add a mock setting.
2427 * WARNING: The setting metadata will disappear on the next cache-clear.
2432 function setMockSettingsMetaData($extras) {
2433 CRM_Core_BAO_Setting
::$_cache = array();
2434 $this->callAPISuccess('system','flush', array());
2435 CRM_Core_BAO_Setting
::$_cache = array();
2437 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2438 $metadata = array_merge($metadata, $extras);
2441 $fields = $this->callAPISuccess('setting', 'getfields', array());
2442 foreach ($extras as $key => $spec) {
2443 $this->assertNotEmpty($spec['title']);
2444 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2448 function financialAccountDelete($name) {
2449 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2450 $financialAccount->name
= $name;
2451 if($financialAccount->find(TRUE)) {
2452 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2453 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2454 $entityFinancialType->delete();
2455 $financialAccount->delete();
2460 * Use $ids as an instruction to do test cleanup
2462 function deleteFromIDSArray() {
2463 foreach ($this->ids
as $entity => $ids) {
2464 foreach ($ids as $id) {
2465 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2471 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2472 * (NB unclear if this is still required)
2474 function _sethtmlGlobals() {
2475 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2476 'required' => array(
2477 'html_quickform_rule_required',
2478 'HTML/QuickForm/Rule/Required.php'
2480 'maxlength' => array(
2481 'html_quickform_rule_range',
2482 'HTML/QuickForm/Rule/Range.php'
2484 'minlength' => array(
2485 'html_quickform_rule_range',
2486 'HTML/QuickForm/Rule/Range.php'
2488 'rangelength' => array(
2489 'html_quickform_rule_range',
2490 'HTML/QuickForm/Rule/Range.php'
2493 'html_quickform_rule_email',
2494 'HTML/QuickForm/Rule/Email.php'
2497 'html_quickform_rule_regex',
2498 'HTML/QuickForm/Rule/Regex.php'
2500 'lettersonly' => array(
2501 'html_quickform_rule_regex',
2502 'HTML/QuickForm/Rule/Regex.php'
2504 'alphanumeric' => array(
2505 'html_quickform_rule_regex',
2506 'HTML/QuickForm/Rule/Regex.php'
2509 'html_quickform_rule_regex',
2510 'HTML/QuickForm/Rule/Regex.php'
2512 'nopunctuation' => array(
2513 'html_quickform_rule_regex',
2514 'HTML/QuickForm/Rule/Regex.php'
2517 'html_quickform_rule_regex',
2518 'HTML/QuickForm/Rule/Regex.php'
2520 'callback' => array(
2521 'html_quickform_rule_callback',
2522 'HTML/QuickForm/Rule/Callback.php'
2525 'html_quickform_rule_compare',
2526 'HTML/QuickForm/Rule/Compare.php'
2529 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2530 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2532 'HTML/QuickForm/group.php',
2533 'HTML_QuickForm_group'
2536 'HTML/QuickForm/hidden.php',
2537 'HTML_QuickForm_hidden'
2540 'HTML/QuickForm/reset.php',
2541 'HTML_QuickForm_reset'
2543 'checkbox' => array(
2544 'HTML/QuickForm/checkbox.php',
2545 'HTML_QuickForm_checkbox'
2548 'HTML/QuickForm/file.php',
2549 'HTML_QuickForm_file'
2552 'HTML/QuickForm/image.php',
2553 'HTML_QuickForm_image'
2555 'password' => array(
2556 'HTML/QuickForm/password.php',
2557 'HTML_QuickForm_password'
2560 'HTML/QuickForm/radio.php',
2561 'HTML_QuickForm_radio'
2564 'HTML/QuickForm/button.php',
2565 'HTML_QuickForm_button'
2568 'HTML/QuickForm/submit.php',
2569 'HTML_QuickForm_submit'
2572 'HTML/QuickForm/select.php',
2573 'HTML_QuickForm_select'
2575 'hiddenselect' => array(
2576 'HTML/QuickForm/hiddenselect.php',
2577 'HTML_QuickForm_hiddenselect'
2580 'HTML/QuickForm/text.php',
2581 'HTML_QuickForm_text'
2583 'textarea' => array(
2584 'HTML/QuickForm/textarea.php',
2585 'HTML_QuickForm_textarea'
2587 'fckeditor' => array(
2588 'HTML/QuickForm/fckeditor.php',
2589 'HTML_QuickForm_FCKEditor'
2592 'HTML/QuickForm/tinymce.php',
2593 'HTML_QuickForm_TinyMCE'
2595 'dojoeditor' => array(
2596 'HTML/QuickForm/dojoeditor.php',
2597 'HTML_QuickForm_dojoeditor'
2600 'HTML/QuickForm/link.php',
2601 'HTML_QuickForm_link'
2603 'advcheckbox' => array(
2604 'HTML/QuickForm/advcheckbox.php',
2605 'HTML_QuickForm_advcheckbox'
2608 'HTML/QuickForm/date.php',
2609 'HTML_QuickForm_date'
2612 'HTML/QuickForm/static.php',
2613 'HTML_QuickForm_static'
2616 'HTML/QuickForm/header.php',
2617 'HTML_QuickForm_header'
2620 'HTML/QuickForm/html.php',
2621 'HTML_QuickForm_html'
2623 'hierselect' => array(
2624 'HTML/QuickForm/hierselect.php',
2625 'HTML_QuickForm_hierselect'
2627 'autocomplete' => array(
2628 'HTML/QuickForm/autocomplete.php',
2629 'HTML_QuickForm_autocomplete'
2632 'HTML/QuickForm/xbutton.php',
2633 'HTML_QuickForm_xbutton'
2635 'advmultiselect' => array(
2636 'HTML/QuickForm/advmultiselect.php',
2637 'HTML_QuickForm_advmultiselect'
2643 * Set up an acl allowing contact to see 2 specified groups
2644 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2646 * You need to have precreated these groups & created the user e.g
2647 * $this->createLoggedInUser();
2648 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2649 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2652 function setupACL() {
2654 $_REQUEST = $this->_params
;
2655 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2656 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2657 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2658 'label' => 'pick me',
2663 CRM_Core_DAO
::executeQuery("
2664 TRUNCATE civicrm_acl_cache
2667 CRM_Core_DAO
::executeQuery("
2668 TRUNCATE civicrm_acl_contact_cache
2672 CRM_Core_DAO
::executeQuery("
2673 INSERT INTO civicrm_acl_entity_role (
2674 `acl_role_id`, `entity_table`, `entity_id`
2675 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2678 CRM_Core_DAO
::executeQuery("
2679 INSERT INTO civicrm_acl (
2680 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2683 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2687 CRM_Core_DAO
::executeQuery("
2688 INSERT INTO civicrm_acl (
2689 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2692 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2695 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2696 $this->callAPISuccess('group_contact', 'create', array(
2697 'group_id' => $this->_permissionedGroup
,
2698 'contact_id' => $this->_loggedInUser
,
2701 CRM_ACL_BAO_Cache
::resetCache();
2702 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2703 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2707 * Create an instance of the paypal processor
2708 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2709 * this parent class & we don't have a structure for that yet
2710 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2711 * & the best protection agains that is the functions this class affords
2713 function paymentProcessorCreate($params = array()) {
2714 $params = array_merge(array(
2716 'domain_id' => CRM_Core_Config
::domainID(),
2717 'payment_processor_type_id' => 'PayPal',
2721 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2722 'password' => '1183377788',
2723 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2724 'url_site' => 'https://www.sandbox.paypal.com/',
2725 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2726 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2727 'class_name' => 'Payment_PayPalImpl',
2728 'billing_mode' => 3,
2729 'financial_type_id' => 1,
2732 if(!is_numeric($params['payment_processor_type_id'])) {
2733 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2735 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2736 'name' => $params['payment_processor_type_id'],
2740 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2741 return $result['id'];
2745 function CiviUnitTestCase_fatalErrorHandler($message) {
2746 throw new Exception("{$message['message']}: {$message['code']}");