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 'tests/phpunit/Utils.php';
43 require_once 'api/api.php';
44 require_once 'CRM/Financial/BAO/FinancialType.php';
45 define('API_LATEST_VERSION', 3);
48 * Base class for CiviCRM unit tests
50 * Common functions for unit tests
53 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
56 * api version - easier to override than just a define
58 protected $_apiversion = API_LATEST_VERSION
;
60 * Database has been initialized
64 private static $dbInit = FALSE;
69 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
78 static protected $_dbName;
81 * Track tables we have modified during a test
83 protected $_tablesToTruncate = array();
86 * @var array of temporary directory names
96 * @var boolean populateOnce allows to skip db resets in setUp
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
106 public static $populateOnce = FALSE;
109 * Allow classes to state E-notice compliance
111 public $_eNoticeCompliant = TRUE;
114 * @var boolean DBResetRequired allows skipping DB reset
115 * in specific test case. If you still need
116 * to reset single test (method) of such case, call
117 * $this->cleanDB() in the first line of this
120 public $DBResetRequired = TRUE;
125 * Because we are overriding the parent class constructor, we
126 * need to show the same arguments as exist in the constructor of
127 * PHPUnit_Framework_TestCase, since
128 * PHPUnit_Framework_TestSuite::createTest() creates a
129 * ReflectionClass of the Test class and checks the constructor
130 * of that class to decide how to set up the test.
132 * @param string $name
134 * @param string $dataName
136 function __construct($name = NULL, array$data = array(), $dataName = '') {
137 parent
::__construct($name, $data, $dataName);
139 // we need full error reporting
140 error_reporting(E_ALL
& ~E_NOTICE
);
142 if (!empty($GLOBALS['mysql_db'])) {
143 self
::$_dbName = $GLOBALS['mysql_db'];
146 self
::$_dbName = 'civicrm_tests_dev';
149 // create test database
150 self
::$utils = new Utils($GLOBALS['mysql_host'],
151 $GLOBALS['mysql_port'],
152 $GLOBALS['mysql_user'],
153 $GLOBALS['mysql_pass']
156 // also load the class loader
157 require_once 'CRM/Core/ClassLoader.php';
158 CRM_Core_ClassLoader
::singleton()->register();
159 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
160 _civix_phpunit_setUp();
167 function requireDBReset() {
168 return $this->DBResetRequired
;
174 static function getDBName() {
175 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
180 * Create database connection for this instance
182 * Initialize the test database if it hasn't been initialized
184 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
186 protected function getConnection() {
187 $dbName = self
::$_dbName;
188 if (!self
::$dbInit) {
189 $dbName = self
::getDBName();
191 // install test database
192 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
194 static::_populateDB(FALSE, $this);
196 self
::$dbInit = TRUE;
198 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
202 * Required implementation of abstract method
204 protected function getDataSet() {
208 * @param bool $perClass
209 * @param null $object
210 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
212 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
214 if ($perClass ||
$object == NULL) {
218 $dbreset = $object->requireDBReset();
221 if (self
::$populateOnce ||
!$dbreset) {
224 self
::$populateOnce = NULL;
226 $dbName = self
::getDBName();
227 $pdo = self
::$utils->pdo
;
228 // only consider real tables and not views
229 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
230 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
232 $truncates = array();
234 foreach ($tables as $table) {
236 if (substr($table['table_name'], 0, 4) == 'log_') {
240 // don't change list of installed extensions
241 if ($table['table_name'] == 'civicrm_extension') {
245 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
246 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
249 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
255 "SET foreign_key_checks = 0",
256 // SQL mode needs to be strict, that's our standard
257 "SET SQL_MODE='STRICT_ALL_TABLES';",
258 "SET global innodb_flush_log_at_trx_commit = 2;",
260 $queries = array_merge($queries, $truncates);
261 $queries = array_merge($queries, $drops);
262 foreach ($queries as $query) {
263 if (self
::$utils->do_query($query) === FALSE) {
264 // failed to create test database
265 echo "failed to create test db.";
270 // initialize test database
271 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
272 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
273 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
275 $query2 = file_get_contents($sql_file2);
276 $query3 = file_get_contents($sql_file3);
277 $query4 = file_get_contents($sql_file4);
278 if (self
::$utils->do_query($query2) === FALSE) {
279 echo "Cannot load civicrm_data.mysql. Aborting.";
282 if (self
::$utils->do_query($query3) === FALSE) {
283 echo "Cannot load test_data.mysql. Aborting.";
286 if (self
::$utils->do_query($query4) === FALSE) {
287 echo "Cannot load test_data.mysql. Aborting.";
291 // done with all the loading, get transactions back
292 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
293 echo "Cannot set global? Huh?";
297 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
298 echo "Cannot get foreign keys back? Huh?";
302 unset($query, $query2, $query3);
305 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
310 public static function setUpBeforeClass() {
311 static::_populateDB(TRUE);
313 // also set this global hack
314 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
316 $env = new CRM_Utils_Check_Env();
317 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
321 * Common setup functions for all unit tests
323 protected function setUp() {
324 CRM_Utils_Hook
::singleton(TRUE);
325 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
326 // Use a temporary file for STDIN
327 $GLOBALS['stdin'] = tmpfile();
328 if ($GLOBALS['stdin'] === FALSE) {
329 echo "Couldn't open temporary file\n";
333 // Get and save a connection to the database
334 $this->_dbconn
= $this->getConnection();
336 // reload database before each test
337 // $this->_populateDB();
339 // "initialize" CiviCRM to avoid problems when running single tests
340 // FIXME: look at it closer in second stage
342 // initialize the object once db is loaded
343 CRM_Core_Config
::$_mail = NULL;
344 $config = CRM_Core_Config
::singleton();
346 // when running unit tests, use mockup user framework
347 $config->setUserFramework('UnitTests');
349 // also fix the fatal error handler to throw exceptions,
351 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
353 // enable backtrace to get meaningful errors
354 $config->backtrace
= 1;
356 // disable any left-over test extensions
357 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
359 // reset all the caches
360 CRM_Utils_System
::flushCache();
362 // clear permissions stub to not check permissions
363 $config = CRM_Core_Config
::singleton();
364 $config->userPermissionClass
->permissions
= NULL;
366 //flush component settings
367 CRM_Core_Component
::getEnabledComponents(TRUE);
369 if ($this->_eNoticeCompliant
) {
370 error_reporting(E_ALL
);
373 error_reporting(E_ALL
& ~E_NOTICE
);
375 $this->_sethtmlGlobals();
379 * Read everything from the datasets directory and insert into the db
381 public function loadAllFixtures() {
382 $fixturesDir = __DIR__
. '/../../fixtures';
384 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
386 $xmlFiles = glob($fixturesDir . '/*.xml');
387 foreach ($xmlFiles as $xmlFixture) {
388 $op = new PHPUnit_Extensions_Database_Operation_Insert();
389 $dataset = $this->createXMLDataSet($xmlFixture);
390 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
391 $op->execute($this->_dbconn
, $dataset);
394 $yamlFiles = glob($fixturesDir . '/*.yaml');
395 foreach ($yamlFiles as $yamlFixture) {
396 $op = new PHPUnit_Extensions_Database_Operation_Insert();
397 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
398 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
399 $op->execute($this->_dbconn
, $dataset);
402 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
406 * emulate a logged in user since certain functions use that
407 * value to store a record in the DB (like activity)
410 public function createLoggedInUser() {
412 'first_name' => 'Logged In',
413 'last_name' => 'User ' . rand(),
414 'contact_type' => 'Individual',
416 $contactID = $this->individualCreate($params);
418 $session = CRM_Core_Session
::singleton();
419 $session->set('userID', $contactID);
422 public function cleanDB() {
423 self
::$populateOnce = NULL;
424 $this->DBResetRequired
= TRUE;
426 $this->_dbconn
= $this->getConnection();
427 static::_populateDB();
428 $this->tempDirs
= array();
432 * Common teardown functions for all unit tests
434 protected function tearDown() {
435 error_reporting(E_ALL
& ~E_NOTICE
);
436 $session = CRM_Core_Session
::singleton();
437 $session->set('userID', NULL);
438 $tablesToTruncate = array('civicrm_contact');
439 $this->quickCleanup($tablesToTruncate);
440 $this->cleanTempDirs();
441 $this->unsetExtensionSystem();
445 * FIXME: Maybe a better way to do it
447 function foreignKeyChecksOff() {
448 self
::$utils = new Utils($GLOBALS['mysql_host'],
449 $GLOBALS['mysql_port'],
450 $GLOBALS['mysql_user'],
451 $GLOBALS['mysql_pass']
453 $dbName = self
::getDBName();
454 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
455 if (self
::$utils->do_query($query) === FALSE) {
457 echo 'Cannot set foreign_key_checks = 0';
463 function foreignKeyChecksOn() {
464 // FIXME: might not be needed if previous fixme implemented
468 * Generic function to compare expected values after an api call to retrieved
471 * @daoName string DAO Name of object we're evaluating.
472 * @id int Id of object
473 * @match array Associative array of field name => expected value. Empty if asserting
474 * that a DELETE occurred
475 * @delete boolean True if we're checking that a DELETE action occurred.
477 function assertDBState($daoName, $id, $match, $delete = FALSE) {
479 // adding this here since developers forget to check for an id
480 // and hence we get the first value in the db
481 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
484 $object = new $daoName();
488 // If we're asserting successful record deletion, make sure object is NOT found.
490 if ($object->find(TRUE)) {
491 $this->fail("Object not deleted by delete operation: $daoName, $id");
496 // Otherwise check matches of DAO field values against expected values in $match.
497 if ($object->find(TRUE)) {
498 $fields = & $object->fields();
499 foreach ($fields as $name => $value) {
500 $dbName = $value['name'];
501 if (isset($match[$name])) {
503 $this->assertEquals($object->$dbName, $match[$name]);
505 elseif (isset($match[$dbName])) {
507 $this->assertEquals($object->$dbName, $match[$dbName]);
512 $this->fail("Could not retrieve object: $daoName, $id");
515 $matchSize = count($match);
516 if ($verifiedCount != $matchSize) {
517 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
521 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
524 * @param $searchValue
525 * @param $returnColumn
526 * @param $searchColumn
529 * @return null|string
530 * @throws PHPUnit_Framework_AssertionFailedError
532 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
533 if (empty($searchValue)) {
534 $this->fail("empty value passed to assertDBNotNull");
536 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
537 $this->assertNotNull($value, $message);
542 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
545 * @param $searchValue
546 * @param $returnColumn
547 * @param $searchColumn
550 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
551 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
552 $this->assertNull($value, $message);
555 // Request a record from the DB by id. Success if row not found.
559 * @param null $message
561 function assertDBRowNotExist($daoName, $id, $message = NULL) {
562 $message = $message ?
$message : "$daoName (#$id) should not exist";
563 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
564 $this->assertNull($value, $message);
567 // Request a record from the DB by id. Success if row not found.
571 * @param null $message
573 function assertDBRowExist($daoName, $id, $message = NULL) {
574 $message = $message ?
$message : "$daoName (#$id) should exist";
575 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
576 $this->assertEquals($id, $value, $message);
579 // Compare a single column value in a retrieved DB record to an expected value
582 * @param $searchValue
583 * @param $returnColumn
584 * @param $searchColumn
585 * @param $expectedValue
588 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
589 $expectedValue, $message
591 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
592 $this->assertEquals($value, $expectedValue, $message);
595 // Compare all values in a single retrieved DB record to an array of expected values
598 * @param $searchParams
599 * @param $expectedValues
601 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
602 //get the values from db
604 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
606 // compare db values with expected values
607 self
::assertAttributesEquals($expectedValues, $dbValues);
611 * Assert that a SQL query returns a given value
613 * The first argument is an expected value. The remaining arguments are passed
614 * to CRM_Core_DAO::singleValueQuery
616 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
617 * array(1 => array("Whiz", "String")));
619 function assertDBQuery($expected, $query, $params = array()) {
620 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
621 $this->assertEquals($expected, $actual,
622 sprintf('expected=[%s] actual=[%s] query=[%s]',
623 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
629 * Assert that two array-trees are exactly equal, notwithstanding
630 * the sorting of keys
632 * @param array $expected
633 * @param array $actual
635 function assertTreeEquals($expected, $actual) {
638 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
639 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
643 $this->assertEquals($e, $a);
647 * Assert that two numbers are approximately equal
649 * @param int|float $expected
650 * @param int|float $actual
651 * @param int|float $tolerance
652 * @param string $message
654 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
655 if ($message === NULL) {
656 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
658 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
662 * @param $expectedValues
663 * @param $actualValues
664 * @param null $message
666 * @throws PHPUnit_Framework_AssertionFailedError
668 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
669 foreach ($expectedValues as $paramName => $paramValue) {
670 if (isset($actualValues[$paramName])) {
671 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
674 $this->fail("Attribute '$paramName' not present in actual array.");
683 function assertArrayKeyExists($key, &$list) {
684 $result = isset($list[$key]) ?
TRUE : FALSE;
685 $this->assertTrue($result, ts("%1 element exists?",
694 function assertArrayValueNotNull($key, &$list) {
695 $this->assertArrayKeyExists($key, $list);
697 $value = isset($list[$key]) ?
$list[$key] : NULL;
698 $this->assertTrue($value,
699 ts("%1 element not null?",
706 * check that api returned 'is_error' => 0
707 * else provide full message
708 * @param array $apiResult api result
709 * @param string $prefix extra test to add to message
711 function assertAPISuccess($apiResult, $prefix = '') {
712 if (!empty($prefix)) {
715 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
717 if(!empty($apiResult['debug_information'])) {
718 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
720 if(!empty($apiResult['trace'])){
721 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
723 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
727 * check that api returned 'is_error' => 1
728 * else provide full message
730 * @param array $apiResult api result
731 * @param string $prefix extra test to add to message
732 * @param null $expectedError
734 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
735 if (!empty($prefix)) {
738 if($expectedError && !empty($apiResult['is_error'])){
739 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
741 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
742 $this->assertNotEmpty($apiResult['error_message']);
748 * @param string $message
750 function assertType($expected, $actual, $message = '') {
751 return $this->assertInternalType($expected, $actual, $message);
755 * check that a deleted item has been deleted
757 function assertAPIDeleted($entity, $id) {
758 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
763 * check that api returned 'is_error' => 1
764 * else provide full message
767 * @param array $valuesToExclude
768 * @param string $prefix extra test to add to message
769 * @internal param array $apiResult api result
771 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
772 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
773 foreach ($valuesToExclude as $value) {
774 if(isset($result[$value])) {
775 unset($result[$value]);
777 if(isset($expected[$value])) {
778 unset($expected[$value]);
781 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
785 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
792 function civicrm_api($entity, $action, $params) {
793 return civicrm_api($entity, $action, $params);
797 * This function exists to wrap api functions
798 * so we can ensure they succeed & throw exceptions without litterering the test with checks
800 * @param string $entity
801 * @param string $action
802 * @param array $params
803 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
804 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
805 * for getsingle the array is compared against an array passed in - the id is not compared (for
810 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
811 $params = array_merge(array(
812 'version' => $this->_apiversion
,
817 switch (strtolower($action)) {
819 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
821 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
823 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
825 $result = $this->civicrm_api($entity, $action, $params);
826 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
831 * This function exists to wrap api getValue function & check the result
832 * so we can ensure they succeed & throw exceptions without litterering the test with checks
833 * There is a type check in this
835 * @param string $entity
836 * @param array $params
837 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
847 function callAPISuccessGetValue($entity, $params, $type = NULL) {
849 'version' => $this->_apiversion
,
852 $result = $this->civicrm_api($entity, 'getvalue', $params);
854 if($type == 'integer'){
855 // api seems to return integers as strings
856 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
859 $this->assertType($type, $result, "returned result should have been of type $type but was " );
866 * This function exists to wrap api getsingle function & check the result
867 * so we can ensure they succeed & throw exceptions without litterering the test with checks
869 * @param string $entity
870 * @param array $params
871 * @param array $checkAgainst - array to compare result against
882 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
884 'version' => $this->_apiversion
,
887 $result = $this->civicrm_api($entity, 'getsingle', $params);
888 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
889 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
892 // @todo - have gone with the fn that unsets id? should we check id?
893 $this->checkArrayEquals($result, $checkAgainst);
899 * This function exists to wrap api getValue function & check the result
900 * so we can ensure they succeed & throw exceptions without litterering the test with checks
901 * There is a type check in this
902 * @param string $entity
903 * @param array $params
907 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
915 function callAPISuccessGetCount($entity, $params, $count = NULL) {
917 'version' => $this->_apiversion
,
920 $result = $this->civicrm_api($entity, 'getcount', $params);
921 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
922 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
925 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
931 * This function exists to wrap api functions
932 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
934 * @param string $entity
935 * @param string $action
936 * @param array $params
937 * @param string $function - pass this in to create a generated example
938 * @param string $file - pass this in to create a generated example
939 * @param string $description
940 * @param string|null $subfile
941 * @param string|null $actionName
944 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
945 $params['version'] = $this->_apiversion
;
946 $result = $this->callAPISuccess($entity, $action, $params);
947 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
952 * This function exists to wrap api functions
953 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
954 * @param string $entity
955 * @param string $action
956 * @param array $params
957 * @param string $expectedErrorMessage error
958 * @param null $extraOutput
961 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
962 if (is_array($params)) {
964 'version' => $this->_apiversion
,
967 $result = $this->civicrm_api($entity, $action, $params);
968 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
973 * Create required data based on $this->entity & $this->params
974 * This is just a way to set up the test data for delete & get functions
975 * so the distinction between set
976 * up & tested functions is clearer
978 * @return array api Result
980 public function createTestEntity(){
981 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
985 * Generic function to create Organisation, to be used in test cases
987 * @param array parameters for civicrm_contact_add api function call
988 * @param int sequence number if creating multiple organizations
990 * @return int id of Organisation created
992 function organizationCreate($params = array(), $seq = 0) {
996 $params = array_merge($this->sampleContact('Organization', $seq), $params);
997 return $this->_contactCreate($params);
1001 * Generic function to create Individual, to be used in test cases
1003 * @param array parameters for civicrm_contact_add api function call
1004 * @param int sequence number if creating multiple individuals
1006 * @return int id of Individual created
1008 function individualCreate($params = array(), $seq = 0) {
1009 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1010 return $this->_contactCreate($params);
1014 * Generic function to create Household, to be used in test cases
1016 * @param array parameters for civicrm_contact_add api function call
1017 * @param int sequence number if creating multiple households
1019 * @return int id of Household created
1021 function householdCreate($params = array(), $seq = 0) {
1022 $params = array_merge($this->sampleContact('Household', $seq), $params);
1023 return $this->_contactCreate($params);
1027 * Helper function for getting sample contact properties
1029 * @param enum contact type: Individual, Organization
1030 * @param int sequence number for the values of this type
1032 * @return array properties of sample contact (ie. $params for API call)
1034 function sampleContact($contact_type, $seq = 0) {
1036 'Individual' => array(
1037 // The number of values in each list need to be coprime numbers to not have duplicates
1038 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1039 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1040 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1042 'Organization' => array(
1043 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
1045 'Household' => array(
1046 'household_name' => array('Unit Test household'),
1049 $params = array('contact_type' => $contact_type);
1050 foreach ($samples[$contact_type] as $key => $values) {
1051 $params[$key] = $values[$seq %
sizeof($values)];
1053 if ($contact_type == 'Individual' ) {
1054 $params['email'] = strtolower(
1055 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1057 $params['prefix_id'] = 3;
1058 $params['suffix_id'] = 3;
1064 * Private helper function for calling civicrm_contact_add
1069 * @internal param \parameters $array for civicrm_contact_add api function call
1071 * @return int id of Household created
1073 private function _contactCreate($params) {
1074 $result = $this->callAPISuccess('contact', 'create', $params);
1075 if (!empty($result['is_error']) ||
empty($result['id'])) {
1076 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1078 return $result['id'];
1086 function contactDelete($contactID) {
1089 'skip_undelete' => 1,
1092 $domain = new CRM_Core_BAO_Domain
;
1093 $domain->contact_id
= $contactID;
1094 if ($domain->find(TRUE)) {
1095 // we are finding tests trying to delete the domain contact in cleanup
1096 //since this is mainly for cleanup lets put a safeguard here
1099 $result = $this->callAPISuccess('contact', 'delete', $params);
1104 * @param $contactTypeId
1108 function contactTypeDelete($contactTypeId) {
1109 require_once 'CRM/Contact/BAO/ContactType.php';
1110 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1112 throw new Exception('Could not delete contact type');
1117 * @param array $params
1121 function membershipTypeCreate($params = array()) {
1122 CRM_Member_PseudoConstant
::flush('membershipType');
1123 CRM_Core_Config
::clearDBCache();
1124 $memberOfOrganization = $this->organizationCreate();
1125 $params = array_merge(array(
1126 'name' => 'General',
1127 'duration_unit' => 'year',
1128 'duration_interval' => 1,
1129 'period_type' => 'rolling',
1130 'member_of_contact_id' => $memberOfOrganization,
1132 'financial_type_id' => 1,
1135 'visibility' => 'Public',
1138 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1140 CRM_Member_PseudoConstant
::flush('membershipType');
1141 CRM_Utils_Cache
::singleton()->flush();
1143 return $result['id'];
1151 function contactMembershipCreate($params) {
1153 'join_date' => '2007-01-21',
1154 'start_date' => '2007-01-21',
1155 'end_date' => '2007-12-21',
1156 'source' => 'Payment',
1159 foreach ($pre as $key => $val) {
1160 if (!isset($params[$key])) {
1161 $params[$key] = $val;
1165 $result = $this->callAPISuccess('Membership', 'create', $params);
1166 return $result['id'];
1170 * Function to delete Membership Type
1173 * @internal param int $membershipTypeID
1175 function membershipTypeDelete($params) {
1176 $this->callAPISuccess('MembershipType', 'Delete', $params);
1180 * @param $membershipID
1182 function membershipDelete($membershipID) {
1183 $deleteParams = array('id' => $membershipID);
1184 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1189 * @param string $name
1193 function membershipStatusCreate($name = 'test member status') {
1194 $params['name'] = $name;
1195 $params['start_event'] = 'start_date';
1196 $params['end_event'] = 'end_date';
1197 $params['is_current_member'] = 1;
1198 $params['is_active'] = 1;
1200 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1201 CRM_Member_PseudoConstant
::flush('membershipStatus');
1202 return $result['id'];
1206 * @param $membershipStatusID
1208 function membershipStatusDelete($membershipStatusID) {
1209 if (!$membershipStatusID) {
1212 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1217 * @param array $params
1221 function relationshipTypeCreate($params = array()) {
1222 $params = array_merge(array(
1223 'name_a_b' => 'Relation 1 for relationship type create',
1224 'name_b_a' => 'Relation 2 for relationship type create',
1225 'contact_type_a' => 'Individual',
1226 'contact_type_b' => 'Organization',
1233 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1234 CRM_Core_PseudoConstant
::flush('relationshipType');
1236 return $result['id'];
1240 * Function to delete Relatinship Type
1242 * @param int $relationshipTypeID
1244 function relationshipTypeDelete($relationshipTypeID) {
1245 $params['id'] = $relationshipTypeID;
1246 $this->callAPISuccess('relationship_type', 'delete', $params);
1250 * @param null $params
1254 function paymentProcessorTypeCreate($params = NULL) {
1255 if (is_null($params)) {
1257 'name' => 'API_Test_PP',
1258 'title' => 'API Test Payment Processor',
1259 'class_name' => 'CRM_Core_Payment_APITest',
1260 'billing_mode' => 'form',
1266 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1268 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1270 return $result['id'];
1274 * Function to create Participant
1276 * @param array $params array of contact id and event id values
1278 * @return int $id of participant created
1280 function participantCreate($params) {
1281 if(empty($params['contact_id'])){
1282 $params['contact_id'] = $this->individualCreate();
1284 if(empty($params['event_id'])){
1285 $event = $this->eventCreate();
1286 $params['event_id'] = $event['id'];
1291 'register_date' => 20070219,
1292 'source' => 'Wimbeldon',
1293 'event_level' => 'Payment',
1297 $params = array_merge($defaults, $params);
1298 $result = $this->callAPISuccess('Participant', 'create', $params);
1299 return $result['id'];
1303 * Function to create Payment Processor
1305 * @return object of Payment Processsor
1307 function processorCreate() {
1308 $processorParams = array(
1311 'payment_processor_type_id' => 10,
1312 'financial_account_id' => 12,
1315 'url_site' => 'http://dummy.com',
1316 'url_recur' => 'http://dummy.com',
1317 'billing_mode' => 1,
1319 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1320 return $paymentProcessor;
1324 * Function to create contribution page
1327 * @return object of contribution page
1329 function contributionPageCreate($params) {
1330 $this->_pageParams
= array(
1331 'title' => 'Test Contribution Page',
1332 'financial_type_id' => 1,
1333 'currency' => 'USD',
1334 'financial_account_id' => 1,
1335 'payment_processor' => $params['processor_id'],
1337 'is_allow_other_amount' => 1,
1339 'max_amount' => 1000,
1341 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1342 return $contributionPage;
1346 * Function to create Tag
1348 * @param array $params
1349 * @return array result of created tag
1351 function tagCreate($params = array()) {
1353 'name' => 'New Tag3',
1354 'description' => 'This is description for Our New Tag ',
1357 $params = array_merge($defaults, $params);
1358 $result = $this->callAPISuccess('Tag', 'create', $params);
1359 return $result['values'][$result['id']];
1363 * Function to delete Tag
1365 * @param int $tagId id of the tag to be deleted
1367 function tagDelete($tagId) {
1368 require_once 'api/api.php';
1372 $result = $this->callAPISuccess('Tag', 'delete', $params);
1373 return $result['id'];
1377 * Add entity(s) to the tag
1379 * @param array $params
1383 function entityTagAdd($params) {
1384 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1389 * Function to create contribution
1391 * @param int $cID contact_id
1393 * @internal param int $cTypeID id of financial type
1395 * @return int id of created contribution
1397 function pledgeCreate($cID) {
1399 'contact_id' => $cID,
1400 'pledge_create_date' => date('Ymd'),
1401 'start_date' => date('Ymd'),
1402 'scheduled_date' => date('Ymd'),
1404 'pledge_status_id' => '2',
1405 'financial_type_id' => '1',
1406 'pledge_original_installment_amount' => 20,
1407 'frequency_interval' => 5,
1408 'frequency_unit' => 'year',
1409 'frequency_day' => 15,
1410 'installments' => 5,
1413 $result = $this->callAPISuccess('Pledge', 'create', $params);
1414 return $result['id'];
1418 * Function to delete contribution
1421 * @internal param int $contributionId
1423 function pledgeDelete($pledgeId) {
1425 'pledge_id' => $pledgeId,
1427 $this->callAPISuccess('Pledge', 'delete', $params);
1431 * Function to create contribution
1433 * @param int $cID contact_id
1434 * @param int $cTypeID id of financial type
1436 * @param int $invoiceID
1437 * @param int $trxnID
1438 * @param int $paymentInstrumentID
1439 * @param bool $isFee
1440 * @return int id of created contribution
1442 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1445 'contact_id' => $cID,
1446 'receive_date' => date('Ymd'),
1447 'total_amount' => 100.00,
1448 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1449 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1450 'non_deductible_amount' => 10.00,
1451 'trxn_id' => $trxnID,
1452 'invoice_id' => $invoiceID,
1454 'contribution_status_id' => 1,
1455 // 'note' => 'Donating for Nobel Cause', *Fixme
1459 $params['fee_amount'] = 5.00;
1460 $params['net_amount'] = 95.00;
1463 $result = $this->callAPISuccess('contribution', 'create', $params);
1464 return $result['id'];
1468 * Function to create online contribution
1471 * @param int $financialType id of financial type
1473 * @param int $invoiceID
1474 * @param int $trxnID
1475 * @return int id of created contribution
1477 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1478 $contribParams = array(
1479 'contact_id' => $params['contact_id'],
1480 'receive_date' => date('Ymd'),
1481 'total_amount' => 100.00,
1482 'financial_type_id' => $financialType,
1483 'contribution_page_id' => $params['contribution_page_id'],
1485 'invoice_id' => 67890,
1488 $contribParams = array_merge($contribParams, $params);
1489 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1491 return $result['id'];
1495 * Function to delete contribution
1497 * @param int $contributionId
1501 function contributionDelete($contributionId) {
1503 'contribution_id' => $contributionId,
1505 $result = $this->callAPISuccess('contribution', 'delete', $params);
1510 * Function to create an Event
1512 * @param array $params name-value pair for an event
1514 * @return array $event
1516 function eventCreate($params = array()) {
1517 // if no contact was passed, make up a dummy event creator
1518 if (!isset($params['contact_id'])) {
1519 $params['contact_id'] = $this->_contactCreate(array(
1520 'contact_type' => 'Individual',
1521 'first_name' => 'Event',
1522 'last_name' => 'Creator',
1526 // set defaults for missing params
1527 $params = array_merge(array(
1528 'title' => 'Annual CiviCRM meet',
1529 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1530 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1531 'event_type_id' => 1,
1533 'start_date' => 20081021,
1534 'end_date' => 20081023,
1535 'is_online_registration' => 1,
1536 'registration_start_date' => 20080601,
1537 'registration_end_date' => 20081015,
1538 'max_participants' => 100,
1539 'event_full_text' => 'Sorry! We are already full',
1542 'is_show_location' => 0,
1545 return $this->callAPISuccess('Event', 'create', $params);
1549 * Function to delete event
1551 * @param int $id ID of the event
1555 function eventDelete($id) {
1559 return $this->callAPISuccess('event', 'delete', $params);
1563 * Function to delete participant
1565 * @param int $participantID
1569 function participantDelete($participantID) {
1571 'id' => $participantID,
1573 return $this->callAPISuccess('Participant', 'delete', $params);
1577 * Function to create participant payment
1579 * @param $participantID
1580 * @param null $contributionID
1581 * @return int $id of created payment
1583 function participantPaymentCreate($participantID, $contributionID = NULL) {
1584 //Create Participant Payment record With Values
1586 'participant_id' => $participantID,
1587 'contribution_id' => $contributionID,
1590 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1591 return $result['id'];
1595 * Function to delete participant payment
1597 * @param int $paymentID
1599 function participantPaymentDelete($paymentID) {
1603 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1607 * Function to add a Location
1610 * @return int location id of created location
1612 function locationAdd($contactID) {
1615 'location_type' => 'New Location Type',
1617 'name' => 'Saint Helier St',
1618 'county' => 'Marin',
1619 'country' => 'United States',
1620 'state_province' => 'Michigan',
1621 'supplemental_address_1' => 'Hallmark Ct',
1622 'supplemental_address_2' => 'Jersey Village',
1627 'contact_id' => $contactID,
1628 'address' => $address,
1629 'location_format' => '2.0',
1630 'location_type' => 'New Location Type',
1633 $result = $this->callAPISuccess('Location', 'create', $params);
1638 * Function to delete Locations of contact
1640 * @params array $pamars parameters
1642 function locationDelete($params) {
1643 $result = $this->callAPISuccess('Location', 'delete', $params);
1647 * Function to add a Location Type
1649 * @param null $params
1650 * @return int location id of created location
1652 function locationTypeCreate($params = NULL) {
1653 if ($params === NULL) {
1655 'name' => 'New Location Type',
1656 'vcard_name' => 'New Location Type',
1657 'description' => 'Location Type for Delete',
1662 $locationType = new CRM_Core_DAO_LocationType();
1663 $locationType->copyValues($params);
1664 $locationType->save();
1665 // clear getfields cache
1666 CRM_Core_PseudoConstant
::flush();
1667 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1668 return $locationType;
1672 * Function to delete a Location Type
1674 * @param int location type id
1676 function locationTypeDelete($locationTypeId) {
1677 $locationType = new CRM_Core_DAO_LocationType();
1678 $locationType->id
= $locationTypeId;
1679 $locationType->delete();
1683 * Function to add a Group
1685 * @params array to add group
1687 * @param array $params
1688 * @return int groupId of created group
1690 function groupCreate($params = array()) {
1691 $params = array_merge(array(
1692 'name' => 'Test Group 1',
1694 'title' => 'New Test Group Created',
1695 'description' => 'New Test Group Created',
1697 'visibility' => 'Public Pages',
1698 'group_type' => array(
1704 $result = $this->callAPISuccess('Group', 'create', $params);
1705 return $result['id'];
1709 * Function to delete a Group
1712 * @internal param int $id
1714 function groupDelete($gid) {
1720 $this->callAPISuccess('Group', 'delete', $params);
1725 * @param array $params
1727 function uFFieldCreate($params = array()) {
1728 $params = array_merge(array(
1730 'field_name' => 'first_name',
1733 'visibility' => 'Public Pages and Listings',
1734 'is_searchable' => '1',
1735 'label' => 'first_name',
1736 'field_type' => 'Individual',
1739 $this->callAPISuccess('uf_field', 'create', $params);
1743 * Function to add a UF Join Entry
1745 * @param null $params
1746 * @return int $id of created UF Join
1748 function ufjoinCreate($params = NULL) {
1749 if ($params === NULL) {
1752 'module' => 'CiviEvent',
1753 'entity_table' => 'civicrm_event',
1759 $result = $this->callAPISuccess('uf_join', 'create', $params);
1764 * Function to delete a UF Join Entry
1766 * @param array with missing uf_group_id
1768 function ufjoinDelete($params = NULL) {
1769 if ($params === NULL) {
1772 'module' => 'CiviEvent',
1773 'entity_table' => 'civicrm_event',
1776 'uf_group_id' => '',
1780 crm_add_uf_join($params);
1784 * Function to create Group for a contact
1786 * @param int $contactId
1788 function contactGroupCreate($contactId) {
1790 'contact_id.1' => $contactId,
1794 $this->callAPISuccess('GroupContact', 'Create', $params);
1798 * Function to delete Group for a contact
1801 * @internal param array $params
1803 function contactGroupDelete($contactId) {
1805 'contact_id.1' => $contactId,
1808 $this->civicrm_api('GroupContact', 'Delete', $params);
1812 * Function to create Activity
1814 * @param null $params
1816 * @internal param int $contactId
1818 function activityCreate($params = NULL) {
1820 if ($params === NULL) {
1821 $individualSourceID = $this->individualCreate();
1823 $contactParams = array(
1824 'first_name' => 'Julia',
1825 'Last_name' => 'Anderson',
1827 'email' => 'julia_anderson@civicrm.org',
1828 'contact_type' => 'Individual',
1831 $individualTargetID = $this->individualCreate($contactParams);
1834 'source_contact_id' => $individualSourceID,
1835 'target_contact_id' => array($individualTargetID),
1836 'assignee_contact_id' => array($individualTargetID),
1837 'subject' => 'Discussion on warm beer',
1838 'activity_date_time' => date('Ymd'),
1839 'duration_hours' => 30,
1840 'duration_minutes' => 20,
1841 'location' => 'Baker Street',
1842 'details' => 'Lets schedule a meeting',
1844 'activity_name' => 'Meeting',
1848 $result = $this->callAPISuccess('Activity', 'create', $params);
1850 $result['target_contact_id'] = $individualTargetID;
1851 $result['assignee_contact_id'] = $individualTargetID;
1856 * Function to create an activity type
1858 * @params array $params parameters
1860 function activityTypeCreate($params) {
1861 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1866 * Function to delete activity type
1868 * @params Integer $activityTypeId id of the activity type
1870 function activityTypeDelete($activityTypeId) {
1871 $params['activity_type_id'] = $activityTypeId;
1872 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1877 * Function to create custom group
1879 * @param array $params
1881 * @internal param string $className
1882 * @internal param string $title name of custom group
1884 function customGroupCreate($params = array()) {
1886 'title' => 'new custom group',
1887 'extends' => 'Contact',
1889 'style' => 'Inline',
1893 $params = array_merge($defaults, $params);
1895 if (strlen($params['title']) > 13) {
1896 $params['title'] = substr($params['title'], 0, 13);
1899 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1900 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1902 return $this->callAPISuccess('custom_group', 'create', $params);
1906 * existing function doesn't allow params to be over-ridden so need a new one
1907 * this one allows you to only pass in the params you want to change
1909 function CustomGroupCreateByParams($params = array()) {
1911 'title' => "API Custom Group",
1912 'extends' => 'Contact',
1914 'style' => 'Inline',
1917 $params = array_merge($defaults, $params);
1918 return $this->callAPISuccess('custom_group', 'create', $params);
1922 * Create custom group with multi fields
1924 function CustomGroupMultipleCreateByParams($params = array()) {
1929 $params = array_merge($defaults, $params);
1930 return $this->CustomGroupCreateByParams($params);
1934 * Create custom group with multi fields
1936 function CustomGroupMultipleCreateWithFields($params = array()) {
1937 // also need to pass on $params['custom_field'] if not set but not in place yet
1939 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1940 $ids['custom_group_id'] = $customGroup['id'];
1942 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1944 $ids['custom_field_id'][] = $customField['id'];
1946 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1947 $ids['custom_field_id'][] = $customField['id'];
1949 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1950 $ids['custom_field_id'][] = $customField['id'];
1956 * Create a custom group with a single text custom field. See
1957 * participant:testCreateWithCustom for how to use this
1959 * @param string $function __FUNCTION__
1961 * @internal param string $file __FILE__
1963 * @return array $ids ids of created objects
1965 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1966 $params = array('title' => $function);
1967 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1968 $params['extends'] = $entity ?
$entity : 'Contact';
1969 $customGroup = $this->CustomGroupCreate($params);
1970 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1971 CRM_Core_PseudoConstant
::flush();
1973 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1977 * Function to delete custom group
1979 * @param int $customGroupID
1983 function customGroupDelete($customGroupID) {
1984 $params['id'] = $customGroupID;
1985 return $this->callAPISuccess('custom_group', 'delete', $params);
1989 * Function to create custom field
1991 * @param array $params (custom_group_id) is required
1993 * @internal param string $name name of custom field
1994 * @internal param int $apiversion API version to use
1996 function customFieldCreate($params) {
1997 $params = array_merge(array(
1998 'label' => 'Custom Field',
1999 'data_type' => 'String',
2000 'html_type' => 'Text',
2001 'is_searchable' => 1,
2003 'default_value' => 'defaultValue',
2006 $result = $this->callAPISuccess('custom_field', 'create', $params);
2008 if ($result['is_error'] == 0 && isset($result['id'])) {
2009 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2010 // force reset of enabled components to help grab custom fields
2011 CRM_Core_Component
::getEnabledComponents(1);
2017 * Function to delete custom field
2019 * @param int $customFieldID
2023 function customFieldDelete($customFieldID) {
2025 $params['id'] = $customFieldID;
2026 return $this->callAPISuccess('custom_field', 'delete', $params);
2030 * Function to create note
2032 * @params array $params name-value pair for an event
2035 * @return array $note
2037 function noteCreate($cId) {
2039 'entity_table' => 'civicrm_contact',
2040 'entity_id' => $cId,
2041 'note' => 'hello I am testing Note',
2042 'contact_id' => $cId,
2043 'modified_date' => date('Ymd'),
2044 'subject' => 'Test Note',
2047 return $this->callAPISuccess('Note', 'create', $params);
2051 * Enable CiviCampaign Component
2053 function enableCiviCampaign() {
2054 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2055 // force reload of config object
2056 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2057 //flush cache by calling with reset
2058 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2062 * Create test generated example in api/v3/examples.
2063 * To turn this off (e.g. on the server) set
2064 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2065 * in your settings file
2066 * @param array $params array as passed to civicrm_api function
2067 * @param array $result array as received from the civicrm_api function
2068 * @param string $function calling function - generally __FUNCTION__
2069 * @param string $filename called from file - generally __FILE__
2070 * @param string $description descriptive text for the example file
2071 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2072 * @param string $action - optional action - otherwise taken from function name
2074 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2075 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2078 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2079 //todo - this is a bit cludgey
2080 if (empty($action)) {
2081 if (strstr($function, 'Create')) {
2082 $action = empty($action) ?
'create' : $action;
2083 $entityAction = 'Create';
2085 elseif (strstr($function, 'GetSingle')) {
2086 $action = empty($action) ?
'getsingle' : $action;
2087 $entityAction = 'GetSingle';
2089 elseif (strstr($function, 'GetValue')) {
2090 $action = empty($action) ?
'getvalue' : $action;
2091 $entityAction = 'GetValue';
2093 elseif (strstr($function, 'GetCount')) {
2094 $action = empty($action) ?
'getcount' : $action;
2095 $entityAction = 'GetCount';
2097 elseif (strstr($function, 'GetFields')) {
2098 $action = empty($action) ?
'getfields' : $action;
2099 $entityAction = 'GetFields';
2101 elseif (strstr($function, 'GetList')) {
2102 $action = empty($action) ?
'getlist' : $action;
2103 $entityAction = 'GetList';
2105 elseif (strstr($function, 'Get')) {
2106 $action = empty($action) ?
'get' : $action;
2107 $entityAction = 'Get';
2109 elseif (strstr($function, 'Delete')) {
2110 $action = empty($action) ?
'delete' : $action;
2111 $entityAction = 'Delete';
2113 elseif (strstr($function, 'Update')) {
2114 $action = empty($action) ?
'update' : $action;
2115 $entityAction = 'Update';
2117 elseif (strstr($function, 'Subscribe')) {
2118 $action = empty($action) ?
'subscribe' : $action;
2119 $entityAction = 'Subscribe';
2121 elseif (strstr($function, 'Submit')) {
2122 $action = empty($action) ?
'submit' : $action;
2123 $entityAction = 'Submit';
2125 elseif (strstr($function, 'Apply')) {
2126 $action = empty($action) ?
'apply' : $action;
2127 $entityAction = 'Apply';
2129 elseif (strstr($function, 'Replace')) {
2130 $action = empty($action) ?
'replace' : $action;
2131 $entityAction = 'Replace';
2135 $entityAction = ucwords($action);
2138 $this->tidyExampleResult($result);
2139 if(isset($params['version'])) {
2140 unset($params['version']);
2142 // a cleverer person than me would do it in a single regex
2143 if (strstr($entity, 'UF')) {
2144 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2147 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2149 $smarty = CRM_Core_Smarty
::singleton();
2150 $smarty->assign('testfunction', $function);
2151 $function = $fnPrefix . "_" . strtolower($action);
2152 $smarty->assign('function', $function);
2153 $smarty->assign('fnPrefix', $fnPrefix);
2154 $smarty->assign('params', $params);
2155 $smarty->assign('entity', $entity);
2156 $smarty->assign('filename', basename($filename));
2157 $smarty->assign('description', $description);
2158 $smarty->assign('result', $result);
2160 $smarty->assign('action', $action);
2161 if (empty($subfile)) {
2162 $subfile = $entityAction;
2164 if (file_exists('../tests/templates/documentFunction.tpl')) {
2165 if (!is_dir("../api/v3/examples/$entity")) {
2166 mkdir("../api/v3/examples/$entity");
2168 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2169 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2175 * Tidy up examples array so that fields that change often ..don't
2176 * and debug related fields are unset
2180 * @internal param array $params
2182 function tidyExampleResult(&$result){
2183 if(!is_array($result)) {
2186 $fieldsToChange = array(
2187 'hash' => '67eac7789eaee00',
2188 'modified_date' => '2012-11-14 16:02:35',
2189 'created_date' => '2013-07-28 08:49:19',
2190 'create_date' => '20120130621222105',
2191 'application_received_date' => '20130728084957',
2192 'in_date' => '2013-07-28 08:50:19',
2193 'scheduled_date' => '20130728085413',
2194 'approval_date' => '20130728085413',
2195 'pledge_start_date_high' => '20130726090416',
2196 'start_date' => '2013-07-29 00:00:00',
2197 'event_start_date' => '2013-07-29 00:00:00',
2198 'end_date' => '2013-08-04 00:00:00',
2199 'event_end_date' => '2013-08-04 00:00:00',
2200 'decision_date' => '20130805000000',
2203 $keysToUnset = array('xdebug', 'undefined_fields',);
2204 foreach ($keysToUnset as $unwantedKey) {
2205 if(isset($result[$unwantedKey])) {
2206 unset($result[$unwantedKey]);
2209 if (isset($result['values'])) {
2210 if(!is_array($result['values'])) {
2213 $resultArray = &$result['values'];
2215 elseif(is_array($result)) {
2216 $resultArray = &$result;
2222 foreach ($resultArray as $index => &$values) {
2223 if(!is_array($values)) {
2226 foreach($values as $key => &$value) {
2227 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2228 if(isset($value['is_error'])) {
2229 // we have a std nested result format
2230 $this->tidyExampleResult($value);
2233 foreach ($value as &$nestedResult) {
2234 // this is an alternative syntax for nested results a keyed array of results
2235 $this->tidyExampleResult($nestedResult);
2239 if(in_array($key, $keysToUnset)) {
2240 unset($values[$key]);
2243 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2244 $value = $fieldsToChange[$key];
2246 if(is_string($value)) {
2247 $value = addslashes($value);
2254 * Function to delete note
2256 * @params int $noteID
2259 function noteDelete($params) {
2260 return $this->callAPISuccess('Note', 'delete', $params);
2264 * Function to create custom field with Option Values
2266 * @param array $customGroup
2267 * @param string $name name of custom field
2271 function customFieldOptionValueCreate($customGroup, $name) {
2272 $fieldParams = array(
2273 'custom_group_id' => $customGroup['id'],
2274 'name' => 'test_custom_group',
2275 'label' => 'Country',
2276 'html_type' => 'Select',
2277 'data_type' => 'String',
2280 'is_searchable' => 0,
2284 $optionGroup = array(
2286 'name' => 'option_group1',
2287 'label' => 'option_group_label1',
2290 $optionValue = array(
2291 'option_label' => array('Label1', 'Label2'),
2292 'option_value' => array('value1', 'value2'),
2293 'option_name' => array($name . '_1', $name . '_2'),
2294 'option_weight' => array(1, 2),
2295 'option_status' => 1,
2298 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2300 return $this->callAPISuccess('custom_field', 'create', $params);
2308 function confirmEntitiesDeleted($entities) {
2309 foreach ($entities as $entity) {
2311 $result = $this->callAPISuccess($entity, 'Get', array());
2312 if ($result['error'] == 1 ||
$result['count'] > 0) {
2313 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2320 * @param $tablesToTruncate
2321 * @param bool $dropCustomValueTables
2323 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2324 if ($dropCustomValueTables) {
2325 $tablesToTruncate[] = 'civicrm_custom_group';
2326 $tablesToTruncate[] = 'civicrm_custom_field';
2329 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2331 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2332 foreach ($tablesToTruncate as $table) {
2333 $sql = "TRUNCATE TABLE $table";
2334 CRM_Core_DAO
::executeQuery($sql);
2336 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2338 if ($dropCustomValueTables) {
2339 $dbName = self
::getDBName();
2341 SELECT TABLE_NAME as tableName
2342 FROM INFORMATION_SCHEMA.TABLES
2343 WHERE TABLE_SCHEMA = '{$dbName}'
2344 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2347 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2348 while ($tableDAO->fetch()) {
2349 $sql = "DROP TABLE {$tableDAO->tableName}";
2350 CRM_Core_DAO
::executeQuery($sql);
2356 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2358 function quickCleanUpFinancialEntities() {
2359 $tablesToTruncate = array(
2360 'civicrm_contribution',
2361 'civicrm_financial_trxn',
2362 'civicrm_contribution_recur',
2363 'civicrm_line_item',
2364 'civicrm_contribution_page',
2365 'civicrm_payment_processor',
2366 'civicrm_entity_financial_trxn',
2367 'civicrm_membership',
2368 'civicrm_membership_type',
2369 'civicrm_membership_payment',
2370 'civicrm_membership_log',
2371 'civicrm_membership_block',
2373 'civicrm_participant',
2374 'civicrm_participant_payment',
2376 'civicrm_price_set_entity',
2378 $this->quickCleanup($tablesToTruncate);
2379 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2382 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2383 * Default behaviour is to also delete the entity
2384 * @param array $params params array to check agains
2385 * @param int $id id of the entity concerned
2386 * @param string $entity name of entity concerned (e.g. membership)
2387 * @param bool $delete should the entity be deleted as part of this check
2388 * @param string $errorText text to print on error
2395 * @param int $delete
2396 * @param string $errorText
2400 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2402 $result = $this->callAPISuccessGetSingle($entity, array(
2407 $this->callAPISuccess($entity, 'Delete', array(
2411 $dateFields = $keys = $dateTimeFields = array();
2412 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2413 foreach ($fields['values'] as $field => $settings) {
2414 if (array_key_exists($field, $result)) {
2415 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2418 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2420 $type = CRM_Utils_Array
::value('type', $settings);
2421 if ($type == CRM_Utils_Type
::T_DATE
) {
2422 $dateFields[] = $settings['name'];
2423 // we should identify both real names & unique names as dates
2424 if($field != $settings['name']) {
2425 $dateFields[] = $field;
2428 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2429 $dateTimeFields[] = $settings['name'];
2430 // we should identify both real names & unique names as dates
2431 if($field != $settings['name']) {
2432 $dateTimeFields[] = $field;
2437 if (strtolower($entity) == 'contribution') {
2438 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2439 // this is not returned in id format
2440 unset($params['payment_instrument_id']);
2441 $params['contribution_source'] = $params['source'];
2442 unset($params['source']);
2445 foreach ($params as $key => $value) {
2446 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2449 if (in_array($key, $dateFields)) {
2450 $value = date('Y-m-d', strtotime($value));
2451 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2453 if (in_array($key, $dateTimeFields)) {
2454 $value = date('Y-m-d H:i:s', strtotime($value));
2455 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2457 $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);
2462 * Function to get formatted values in the actual and expected result
2463 * @param array $actual actual calculated values
2464 * @param array $expected expected values
2467 function checkArrayEquals(&$actual, &$expected) {
2468 self
::unsetId($actual);
2469 self
::unsetId($expected);
2470 $this->assertEquals($actual, $expected);
2474 * Function to unset the key 'id' from the array
2475 * @param array $unformattedArray The array from which the 'id' has to be unset
2478 static function unsetId(&$unformattedArray) {
2479 $formattedArray = array();
2480 if (array_key_exists('id', $unformattedArray)) {
2481 unset($unformattedArray['id']);
2483 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2484 foreach ($unformattedArray['values'] as $key => $value) {
2485 if (is_Array($value)) {
2486 foreach ($value as $k => $v) {
2492 elseif ($key == 'id') {
2493 $unformattedArray[$key];
2495 $formattedArray = array($value);
2497 $unformattedArray['values'] = $formattedArray;
2502 * Helper to enable/disable custom directory support
2504 * @param array $customDirs with members:
2505 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2506 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2508 function customDirectories($customDirs) {
2509 require_once 'CRM/Core/Config.php';
2510 $config = CRM_Core_Config
::singleton();
2512 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2513 unset($config->customPHPPathDir
);
2515 elseif ($customDirs['php_path'] === TRUE) {
2516 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2519 $config->customPHPPathDir
= $php_path;
2522 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2523 unset($config->customTemplateDir
);
2525 elseif ($customDirs['template_path'] === TRUE) {
2526 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2529 $config->customTemplateDir
= $template_path;
2534 * Generate a temporary folder
2536 * @param string $prefix
2537 * @return string $string
2539 function createTempDir($prefix = 'test-') {
2540 $tempDir = CRM_Utils_File
::tempdir($prefix);
2541 $this->tempDirs
[] = $tempDir;
2545 function cleanTempDirs() {
2546 if (!is_array($this->tempDirs
)) {
2547 // fix test errors where this is not set
2550 foreach ($this->tempDirs
as $tempDir) {
2551 if (is_dir($tempDir)) {
2552 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2558 * Temporarily replace the singleton extension with a different one
2560 function setExtensionSystem(CRM_Extension_System
$system) {
2561 if ($this->origExtensionSystem
== NULL) {
2562 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2564 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2567 function unsetExtensionSystem() {
2568 if ($this->origExtensionSystem
!== NULL) {
2569 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2570 $this->origExtensionSystem
= NULL;
2575 * Temporarily alter the settings-metadata to add a mock setting.
2577 * WARNING: The setting metadata will disappear on the next cache-clear.
2582 function setMockSettingsMetaData($extras) {
2583 CRM_Core_BAO_Setting
::$_cache = array();
2584 $this->callAPISuccess('system','flush', array());
2585 CRM_Core_BAO_Setting
::$_cache = array();
2587 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2588 $metadata = array_merge($metadata, $extras);
2591 $fields = $this->callAPISuccess('setting', 'getfields', array());
2592 foreach ($extras as $key => $spec) {
2593 $this->assertNotEmpty($spec['title']);
2594 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2601 function financialAccountDelete($name) {
2602 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2603 $financialAccount->name
= $name;
2604 if($financialAccount->find(TRUE)) {
2605 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2606 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2607 $entityFinancialType->delete();
2608 $financialAccount->delete();
2613 * Use $ids as an instruction to do test cleanup
2615 function deleteFromIDSArray() {
2616 foreach ($this->ids
as $entity => $ids) {
2617 foreach ($ids as $id) {
2618 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2624 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2625 * (NB unclear if this is still required)
2627 function _sethtmlGlobals() {
2628 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2629 'required' => array(
2630 'html_quickform_rule_required',
2631 'HTML/QuickForm/Rule/Required.php'
2633 'maxlength' => array(
2634 'html_quickform_rule_range',
2635 'HTML/QuickForm/Rule/Range.php'
2637 'minlength' => array(
2638 'html_quickform_rule_range',
2639 'HTML/QuickForm/Rule/Range.php'
2641 'rangelength' => array(
2642 'html_quickform_rule_range',
2643 'HTML/QuickForm/Rule/Range.php'
2646 'html_quickform_rule_email',
2647 'HTML/QuickForm/Rule/Email.php'
2650 'html_quickform_rule_regex',
2651 'HTML/QuickForm/Rule/Regex.php'
2653 'lettersonly' => array(
2654 'html_quickform_rule_regex',
2655 'HTML/QuickForm/Rule/Regex.php'
2657 'alphanumeric' => array(
2658 'html_quickform_rule_regex',
2659 'HTML/QuickForm/Rule/Regex.php'
2662 'html_quickform_rule_regex',
2663 'HTML/QuickForm/Rule/Regex.php'
2665 'nopunctuation' => array(
2666 'html_quickform_rule_regex',
2667 'HTML/QuickForm/Rule/Regex.php'
2670 'html_quickform_rule_regex',
2671 'HTML/QuickForm/Rule/Regex.php'
2673 'callback' => array(
2674 'html_quickform_rule_callback',
2675 'HTML/QuickForm/Rule/Callback.php'
2678 'html_quickform_rule_compare',
2679 'HTML/QuickForm/Rule/Compare.php'
2682 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2683 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2685 'HTML/QuickForm/group.php',
2686 'HTML_QuickForm_group'
2689 'HTML/QuickForm/hidden.php',
2690 'HTML_QuickForm_hidden'
2693 'HTML/QuickForm/reset.php',
2694 'HTML_QuickForm_reset'
2696 'checkbox' => array(
2697 'HTML/QuickForm/checkbox.php',
2698 'HTML_QuickForm_checkbox'
2701 'HTML/QuickForm/file.php',
2702 'HTML_QuickForm_file'
2705 'HTML/QuickForm/image.php',
2706 'HTML_QuickForm_image'
2708 'password' => array(
2709 'HTML/QuickForm/password.php',
2710 'HTML_QuickForm_password'
2713 'HTML/QuickForm/radio.php',
2714 'HTML_QuickForm_radio'
2717 'HTML/QuickForm/button.php',
2718 'HTML_QuickForm_button'
2721 'HTML/QuickForm/submit.php',
2722 'HTML_QuickForm_submit'
2725 'HTML/QuickForm/select.php',
2726 'HTML_QuickForm_select'
2728 'hiddenselect' => array(
2729 'HTML/QuickForm/hiddenselect.php',
2730 'HTML_QuickForm_hiddenselect'
2733 'HTML/QuickForm/text.php',
2734 'HTML_QuickForm_text'
2736 'textarea' => array(
2737 'HTML/QuickForm/textarea.php',
2738 'HTML_QuickForm_textarea'
2740 'fckeditor' => array(
2741 'HTML/QuickForm/fckeditor.php',
2742 'HTML_QuickForm_FCKEditor'
2745 'HTML/QuickForm/tinymce.php',
2746 'HTML_QuickForm_TinyMCE'
2748 'dojoeditor' => array(
2749 'HTML/QuickForm/dojoeditor.php',
2750 'HTML_QuickForm_dojoeditor'
2753 'HTML/QuickForm/link.php',
2754 'HTML_QuickForm_link'
2756 'advcheckbox' => array(
2757 'HTML/QuickForm/advcheckbox.php',
2758 'HTML_QuickForm_advcheckbox'
2761 'HTML/QuickForm/date.php',
2762 'HTML_QuickForm_date'
2765 'HTML/QuickForm/static.php',
2766 'HTML_QuickForm_static'
2769 'HTML/QuickForm/header.php',
2770 'HTML_QuickForm_header'
2773 'HTML/QuickForm/html.php',
2774 'HTML_QuickForm_html'
2776 'hierselect' => array(
2777 'HTML/QuickForm/hierselect.php',
2778 'HTML_QuickForm_hierselect'
2780 'autocomplete' => array(
2781 'HTML/QuickForm/autocomplete.php',
2782 'HTML_QuickForm_autocomplete'
2785 'HTML/QuickForm/xbutton.php',
2786 'HTML_QuickForm_xbutton'
2788 'advmultiselect' => array(
2789 'HTML/QuickForm/advmultiselect.php',
2790 'HTML_QuickForm_advmultiselect'
2796 * Set up an acl allowing contact to see 2 specified groups
2797 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2799 * You need to have precreated these groups & created the user e.g
2800 * $this->createLoggedInUser();
2801 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2802 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2805 function setupACL() {
2807 $_REQUEST = $this->_params
;
2808 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2809 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2810 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2811 'label' => 'pick me',
2816 CRM_Core_DAO
::executeQuery("
2817 TRUNCATE civicrm_acl_cache
2820 CRM_Core_DAO
::executeQuery("
2821 TRUNCATE civicrm_acl_contact_cache
2825 CRM_Core_DAO
::executeQuery("
2826 INSERT INTO civicrm_acl_entity_role (
2827 `acl_role_id`, `entity_table`, `entity_id`
2828 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2831 CRM_Core_DAO
::executeQuery("
2832 INSERT INTO civicrm_acl (
2833 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2836 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2840 CRM_Core_DAO
::executeQuery("
2841 INSERT INTO civicrm_acl (
2842 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2845 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2848 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2849 $this->callAPISuccess('group_contact', 'create', array(
2850 'group_id' => $this->_permissionedGroup
,
2851 'contact_id' => $this->_loggedInUser
,
2854 CRM_ACL_BAO_Cache
::resetCache();
2855 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2856 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2860 * alter default price set so that the field numbers are not all 1 (hiding errors)
2862 function offsetDefaultPriceSet() {
2863 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2864 $firstID = $contributionPriceSet['id'];
2865 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2866 unset($contributionPriceSet['id']);
2867 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2868 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2869 unset($priceField['id']);
2870 $priceField['price_set_id'] = $newPriceSet['id'];
2871 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2872 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2874 unset($priceFieldValue['id']);
2875 //create some padding to use up ids
2876 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2877 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2878 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2883 * Create an instance of the paypal processor
2884 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2885 * this parent class & we don't have a structure for that yet
2886 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2887 * & the best protection agains that is the functions this class affords
2889 function paymentProcessorCreate($params = array()) {
2890 $params = array_merge(array(
2892 'domain_id' => CRM_Core_Config
::domainID(),
2893 'payment_processor_type_id' => 'PayPal',
2897 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2898 'password' => '1183377788',
2899 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2900 'url_site' => 'https://www.sandbox.paypal.com/',
2901 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2902 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2903 'class_name' => 'Payment_PayPalImpl',
2904 'billing_mode' => 3,
2905 'financial_type_id' => 1,
2908 if(!is_numeric($params['payment_processor_type_id'])) {
2909 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2911 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2912 'name' => $params['payment_processor_type_id'],
2916 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2917 return $result['id'];
2925 */function CiviUnitTestCase_fatalErrorHandler($message) {
2926 throw new Exception("{$message['message']}: {$message['code']}");