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 $employer = $this->sampleContact('Organization', $seq);
1055 $params['email'] = strtolower(
1056 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1058 $params['prefix_id'] = 3;
1059 $params['suffix_id'] = 3;
1065 * Private helper function for calling civicrm_contact_add
1070 * @internal param \parameters $array for civicrm_contact_add api function call
1072 * @return int id of Household created
1074 private function _contactCreate($params) {
1075 $result = $this->callAPISuccess('contact', 'create', $params);
1076 if (!empty($result['is_error']) ||
empty($result['id'])) {
1077 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1079 return $result['id'];
1087 function contactDelete($contactID) {
1090 'skip_undelete' => 1,
1093 $domain = new CRM_Core_BAO_Domain
;
1094 $domain->contact_id
= $contactID;
1095 if ($domain->find(TRUE)) {
1096 // we are finding tests trying to delete the domain contact in cleanup
1097 //since this is mainly for cleanup lets put a safeguard here
1100 $result = $this->callAPISuccess('contact', 'delete', $params);
1105 * @param $contactTypeId
1109 function contactTypeDelete($contactTypeId) {
1110 require_once 'CRM/Contact/BAO/ContactType.php';
1111 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1113 throw new Exception('Could not delete contact type');
1118 * @param array $params
1122 function membershipTypeCreate($params = array()) {
1123 CRM_Member_PseudoConstant
::flush('membershipType');
1124 CRM_Core_Config
::clearDBCache();
1125 $memberOfOrganization = $this->organizationCreate();
1126 $params = array_merge(array(
1127 'name' => 'General',
1128 'duration_unit' => 'year',
1129 'duration_interval' => 1,
1130 'period_type' => 'rolling',
1131 'member_of_contact_id' => $memberOfOrganization,
1133 'financial_type_id' => 1,
1136 'visibility' => 'Public',
1139 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1141 CRM_Member_PseudoConstant
::flush('membershipType');
1142 CRM_Utils_Cache
::singleton()->flush();
1144 return $result['id'];
1152 function contactMembershipCreate($params) {
1154 'join_date' => '2007-01-21',
1155 'start_date' => '2007-01-21',
1156 'end_date' => '2007-12-21',
1157 'source' => 'Payment',
1160 foreach ($pre as $key => $val) {
1161 if (!isset($params[$key])) {
1162 $params[$key] = $val;
1166 $result = $this->callAPISuccess('Membership', 'create', $params);
1167 return $result['id'];
1171 * Function to delete Membership Type
1174 * @internal param int $membershipTypeID
1176 function membershipTypeDelete($params) {
1177 $this->callAPISuccess('MembershipType', 'Delete', $params);
1181 * @param $membershipID
1183 function membershipDelete($membershipID) {
1184 $deleteParams = array('id' => $membershipID);
1185 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1190 * @param string $name
1194 function membershipStatusCreate($name = 'test member status') {
1195 $params['name'] = $name;
1196 $params['start_event'] = 'start_date';
1197 $params['end_event'] = 'end_date';
1198 $params['is_current_member'] = 1;
1199 $params['is_active'] = 1;
1201 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1202 CRM_Member_PseudoConstant
::flush('membershipStatus');
1203 return $result['id'];
1207 * @param $membershipStatusID
1209 function membershipStatusDelete($membershipStatusID) {
1210 if (!$membershipStatusID) {
1213 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1218 * @param array $params
1222 function relationshipTypeCreate($params = array()) {
1223 $params = array_merge(array(
1224 'name_a_b' => 'Relation 1 for relationship type create',
1225 'name_b_a' => 'Relation 2 for relationship type create',
1226 'contact_type_a' => 'Individual',
1227 'contact_type_b' => 'Organization',
1234 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1235 CRM_Core_PseudoConstant
::flush('relationshipType');
1237 return $result['id'];
1241 * Function to delete Relatinship Type
1243 * @param int $relationshipTypeID
1245 function relationshipTypeDelete($relationshipTypeID) {
1246 $params['id'] = $relationshipTypeID;
1247 $this->callAPISuccess('relationship_type', 'delete', $params);
1251 * @param null $params
1255 function paymentProcessorTypeCreate($params = NULL) {
1256 if (is_null($params)) {
1258 'name' => 'API_Test_PP',
1259 'title' => 'API Test Payment Processor',
1260 'class_name' => 'CRM_Core_Payment_APITest',
1261 'billing_mode' => 'form',
1267 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1269 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1271 return $result['id'];
1275 * Function to create Participant
1277 * @param array $params array of contact id and event id values
1279 * @return int $id of participant created
1281 function participantCreate($params) {
1282 if(empty($params['contact_id'])){
1283 $params['contact_id'] = $this->individualCreate();
1285 if(empty($params['event_id'])){
1286 $event = $this->eventCreate();
1287 $params['event_id'] = $event['id'];
1292 'register_date' => 20070219,
1293 'source' => 'Wimbeldon',
1294 'event_level' => 'Payment',
1298 $params = array_merge($defaults, $params);
1299 $result = $this->callAPISuccess('Participant', 'create', $params);
1300 return $result['id'];
1304 * Function to create Payment Processor
1306 * @return object of Payment Processsor
1308 function processorCreate() {
1309 $processorParams = array(
1312 'payment_processor_type_id' => 10,
1313 'financial_account_id' => 12,
1316 'url_site' => 'http://dummy.com',
1317 'url_recur' => 'http://dummy.com',
1318 'billing_mode' => 1,
1320 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1321 return $paymentProcessor;
1325 * Function to create contribution page
1328 * @return object of contribution page
1330 function contributionPageCreate($params) {
1331 $this->_pageParams
= array(
1332 'title' => 'Test Contribution Page',
1333 'financial_type_id' => 1,
1334 'currency' => 'USD',
1335 'financial_account_id' => 1,
1336 'payment_processor' => $params['processor_id'],
1338 'is_allow_other_amount' => 1,
1340 'max_amount' => 1000,
1342 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1343 return $contributionPage;
1347 * Function to create Tag
1349 * @param array $params
1350 * @return array result of created tag
1352 function tagCreate($params = array()) {
1354 'name' => 'New Tag3',
1355 'description' => 'This is description for Our New Tag ',
1358 $params = array_merge($defaults, $params);
1359 $result = $this->callAPISuccess('Tag', 'create', $params);
1360 return $result['values'][$result['id']];
1364 * Function to delete Tag
1366 * @param int $tagId id of the tag to be deleted
1368 function tagDelete($tagId) {
1369 require_once 'api/api.php';
1373 $result = $this->callAPISuccess('Tag', 'delete', $params);
1374 return $result['id'];
1378 * Add entity(s) to the tag
1380 * @param array $params
1384 function entityTagAdd($params) {
1385 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1390 * Function to create contribution
1392 * @param int $cID contact_id
1394 * @internal param int $cTypeID id of financial type
1396 * @return int id of created contribution
1398 function pledgeCreate($cID) {
1400 'contact_id' => $cID,
1401 'pledge_create_date' => date('Ymd'),
1402 'start_date' => date('Ymd'),
1403 'scheduled_date' => date('Ymd'),
1405 'pledge_status_id' => '2',
1406 'financial_type_id' => '1',
1407 'pledge_original_installment_amount' => 20,
1408 'frequency_interval' => 5,
1409 'frequency_unit' => 'year',
1410 'frequency_day' => 15,
1411 'installments' => 5,
1414 $result = $this->callAPISuccess('Pledge', 'create', $params);
1415 return $result['id'];
1419 * Function to delete contribution
1422 * @internal param int $contributionId
1424 function pledgeDelete($pledgeId) {
1426 'pledge_id' => $pledgeId,
1428 $this->callAPISuccess('Pledge', 'delete', $params);
1432 * Function to create contribution
1434 * @param int $cID contact_id
1435 * @param int $cTypeID id of financial type
1437 * @param int $invoiceID
1438 * @param int $trxnID
1439 * @param int $paymentInstrumentID
1440 * @param bool $isFee
1441 * @return int id of created contribution
1443 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1446 'contact_id' => $cID,
1447 'receive_date' => date('Ymd'),
1448 'total_amount' => 100.00,
1449 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1450 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1451 'non_deductible_amount' => 10.00,
1452 'trxn_id' => $trxnID,
1453 'invoice_id' => $invoiceID,
1455 'contribution_status_id' => 1,
1456 // 'note' => 'Donating for Nobel Cause', *Fixme
1460 $params['fee_amount'] = 5.00;
1461 $params['net_amount'] = 95.00;
1464 $result = $this->callAPISuccess('contribution', 'create', $params);
1465 return $result['id'];
1469 * Function to create online contribution
1472 * @param int $financialType id of financial type
1474 * @param int $invoiceID
1475 * @param int $trxnID
1476 * @return int id of created contribution
1478 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1479 $contribParams = array(
1480 'contact_id' => $params['contact_id'],
1481 'receive_date' => date('Ymd'),
1482 'total_amount' => 100.00,
1483 'financial_type_id' => $financialType,
1484 'contribution_page_id' => $params['contribution_page_id'],
1486 'invoice_id' => 67890,
1489 $contribParams = array_merge($contribParams, $params);
1490 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1492 return $result['id'];
1496 * Function to delete contribution
1498 * @param int $contributionId
1502 function contributionDelete($contributionId) {
1504 'contribution_id' => $contributionId,
1506 $result = $this->callAPISuccess('contribution', 'delete', $params);
1511 * Function to create an Event
1513 * @param array $params name-value pair for an event
1515 * @return array $event
1517 function eventCreate($params = array()) {
1518 // if no contact was passed, make up a dummy event creator
1519 if (!isset($params['contact_id'])) {
1520 $params['contact_id'] = $this->_contactCreate(array(
1521 'contact_type' => 'Individual',
1522 'first_name' => 'Event',
1523 'last_name' => 'Creator',
1527 // set defaults for missing params
1528 $params = array_merge(array(
1529 'title' => 'Annual CiviCRM meet',
1530 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1531 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1532 'event_type_id' => 1,
1534 'start_date' => 20081021,
1535 'end_date' => 20081023,
1536 'is_online_registration' => 1,
1537 'registration_start_date' => 20080601,
1538 'registration_end_date' => 20081015,
1539 'max_participants' => 100,
1540 'event_full_text' => 'Sorry! We are already full',
1543 'is_show_location' => 0,
1546 return $this->callAPISuccess('Event', 'create', $params);
1550 * Function to delete event
1552 * @param int $id ID of the event
1556 function eventDelete($id) {
1560 return $this->callAPISuccess('event', 'delete', $params);
1564 * Function to delete participant
1566 * @param int $participantID
1570 function participantDelete($participantID) {
1572 'id' => $participantID,
1574 return $this->callAPISuccess('Participant', 'delete', $params);
1578 * Function to create participant payment
1580 * @param $participantID
1581 * @param null $contributionID
1582 * @return int $id of created payment
1584 function participantPaymentCreate($participantID, $contributionID = NULL) {
1585 //Create Participant Payment record With Values
1587 'participant_id' => $participantID,
1588 'contribution_id' => $contributionID,
1591 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1592 return $result['id'];
1596 * Function to delete participant payment
1598 * @param int $paymentID
1600 function participantPaymentDelete($paymentID) {
1604 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1608 * Function to add a Location
1611 * @return int location id of created location
1613 function locationAdd($contactID) {
1616 'location_type' => 'New Location Type',
1618 'name' => 'Saint Helier St',
1619 'county' => 'Marin',
1620 'country' => 'United States',
1621 'state_province' => 'Michigan',
1622 'supplemental_address_1' => 'Hallmark Ct',
1623 'supplemental_address_2' => 'Jersey Village',
1628 'contact_id' => $contactID,
1629 'address' => $address,
1630 'location_format' => '2.0',
1631 'location_type' => 'New Location Type',
1634 $result = $this->callAPISuccess('Location', 'create', $params);
1639 * Function to delete Locations of contact
1641 * @params array $pamars parameters
1643 function locationDelete($params) {
1644 $result = $this->callAPISuccess('Location', 'delete', $params);
1648 * Function to add a Location Type
1650 * @param null $params
1651 * @return int location id of created location
1653 function locationTypeCreate($params = NULL) {
1654 if ($params === NULL) {
1656 'name' => 'New Location Type',
1657 'vcard_name' => 'New Location Type',
1658 'description' => 'Location Type for Delete',
1663 $locationType = new CRM_Core_DAO_LocationType();
1664 $locationType->copyValues($params);
1665 $locationType->save();
1666 // clear getfields cache
1667 CRM_Core_PseudoConstant
::flush();
1668 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1669 return $locationType;
1673 * Function to delete a Location Type
1675 * @param int location type id
1677 function locationTypeDelete($locationTypeId) {
1678 $locationType = new CRM_Core_DAO_LocationType();
1679 $locationType->id
= $locationTypeId;
1680 $locationType->delete();
1684 * Function to add a Group
1686 * @params array to add group
1688 * @param array $params
1689 * @return int groupId of created group
1691 function groupCreate($params = array()) {
1692 $params = array_merge(array(
1693 'name' => 'Test Group 1',
1695 'title' => 'New Test Group Created',
1696 'description' => 'New Test Group Created',
1698 'visibility' => 'Public Pages',
1699 'group_type' => array(
1705 $result = $this->callAPISuccess('Group', 'create', $params);
1706 return $result['id'];
1710 * Function to delete a Group
1713 * @internal param int $id
1715 function groupDelete($gid) {
1721 $this->callAPISuccess('Group', 'delete', $params);
1726 * @param array $params
1728 function uFFieldCreate($params = array()) {
1729 $params = array_merge(array(
1731 'field_name' => 'first_name',
1734 'visibility' => 'Public Pages and Listings',
1735 'is_searchable' => '1',
1736 'label' => 'first_name',
1737 'field_type' => 'Individual',
1740 $this->callAPISuccess('uf_field', 'create', $params);
1744 * Function to add a UF Join Entry
1746 * @param null $params
1747 * @return int $id of created UF Join
1749 function ufjoinCreate($params = NULL) {
1750 if ($params === NULL) {
1753 'module' => 'CiviEvent',
1754 'entity_table' => 'civicrm_event',
1760 $result = $this->callAPISuccess('uf_join', 'create', $params);
1765 * Function to delete a UF Join Entry
1767 * @param array with missing uf_group_id
1769 function ufjoinDelete($params = NULL) {
1770 if ($params === NULL) {
1773 'module' => 'CiviEvent',
1774 'entity_table' => 'civicrm_event',
1777 'uf_group_id' => '',
1781 crm_add_uf_join($params);
1785 * Function to create Group for a contact
1787 * @param int $contactId
1789 function contactGroupCreate($contactId) {
1791 'contact_id.1' => $contactId,
1795 $this->callAPISuccess('GroupContact', 'Create', $params);
1799 * Function to delete Group for a contact
1802 * @internal param array $params
1804 function contactGroupDelete($contactId) {
1806 'contact_id.1' => $contactId,
1809 $this->civicrm_api('GroupContact', 'Delete', $params);
1813 * Function to create Activity
1815 * @param null $params
1817 * @internal param int $contactId
1819 function activityCreate($params = NULL) {
1821 if ($params === NULL) {
1822 $individualSourceID = $this->individualCreate();
1824 $contactParams = array(
1825 'first_name' => 'Julia',
1826 'Last_name' => 'Anderson',
1828 'email' => 'julia_anderson@civicrm.org',
1829 'contact_type' => 'Individual',
1832 $individualTargetID = $this->individualCreate($contactParams);
1835 'source_contact_id' => $individualSourceID,
1836 'target_contact_id' => array($individualTargetID),
1837 'assignee_contact_id' => array($individualTargetID),
1838 'subject' => 'Discussion on warm beer',
1839 'activity_date_time' => date('Ymd'),
1840 'duration_hours' => 30,
1841 'duration_minutes' => 20,
1842 'location' => 'Baker Street',
1843 'details' => 'Lets schedule a meeting',
1845 'activity_name' => 'Meeting',
1849 $result = $this->callAPISuccess('Activity', 'create', $params);
1851 $result['target_contact_id'] = $individualTargetID;
1852 $result['assignee_contact_id'] = $individualTargetID;
1857 * Function to create an activity type
1859 * @params array $params parameters
1861 function activityTypeCreate($params) {
1862 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1867 * Function to delete activity type
1869 * @params Integer $activityTypeId id of the activity type
1871 function activityTypeDelete($activityTypeId) {
1872 $params['activity_type_id'] = $activityTypeId;
1873 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1878 * Function to create custom group
1880 * @param array $params
1882 * @internal param string $className
1883 * @internal param string $title name of custom group
1885 function customGroupCreate($params = array()) {
1887 'title' => 'new custom group',
1888 'extends' => 'Contact',
1890 'style' => 'Inline',
1894 $params = array_merge($defaults, $params);
1896 if (strlen($params['title']) > 13) {
1897 $params['title'] = substr($params['title'], 0, 13);
1900 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1901 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1903 return $this->callAPISuccess('custom_group', 'create', $params);
1907 * existing function doesn't allow params to be over-ridden so need a new one
1908 * this one allows you to only pass in the params you want to change
1910 function CustomGroupCreateByParams($params = array()) {
1912 'title' => "API Custom Group",
1913 'extends' => 'Contact',
1915 'style' => 'Inline',
1918 $params = array_merge($defaults, $params);
1919 return $this->callAPISuccess('custom_group', 'create', $params);
1923 * Create custom group with multi fields
1925 function CustomGroupMultipleCreateByParams($params = array()) {
1930 $params = array_merge($defaults, $params);
1931 return $this->CustomGroupCreateByParams($params);
1935 * Create custom group with multi fields
1937 function CustomGroupMultipleCreateWithFields($params = array()) {
1938 // also need to pass on $params['custom_field'] if not set but not in place yet
1940 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1941 $ids['custom_group_id'] = $customGroup['id'];
1943 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1945 $ids['custom_field_id'][] = $customField['id'];
1947 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1948 $ids['custom_field_id'][] = $customField['id'];
1950 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1951 $ids['custom_field_id'][] = $customField['id'];
1957 * Create a custom group with a single text custom field. See
1958 * participant:testCreateWithCustom for how to use this
1960 * @param string $function __FUNCTION__
1962 * @internal param string $file __FILE__
1964 * @return array $ids ids of created objects
1966 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1967 $params = array('title' => $function);
1968 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1969 $params['extends'] = $entity ?
$entity : 'Contact';
1970 $customGroup = $this->CustomGroupCreate($params);
1971 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1972 CRM_Core_PseudoConstant
::flush();
1974 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1978 * Function to delete custom group
1980 * @param int $customGroupID
1984 function customGroupDelete($customGroupID) {
1985 $params['id'] = $customGroupID;
1986 return $this->callAPISuccess('custom_group', 'delete', $params);
1990 * Function to create custom field
1992 * @param array $params (custom_group_id) is required
1994 * @internal param string $name name of custom field
1995 * @internal param int $apiversion API version to use
1997 function customFieldCreate($params) {
1998 $params = array_merge(array(
1999 'label' => 'Custom Field',
2000 'data_type' => 'String',
2001 'html_type' => 'Text',
2002 'is_searchable' => 1,
2004 'default_value' => 'defaultValue',
2007 $result = $this->callAPISuccess('custom_field', 'create', $params);
2009 if ($result['is_error'] == 0 && isset($result['id'])) {
2010 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2011 // force reset of enabled components to help grab custom fields
2012 CRM_Core_Component
::getEnabledComponents(1);
2018 * Function to delete custom field
2020 * @param int $customFieldID
2024 function customFieldDelete($customFieldID) {
2026 $params['id'] = $customFieldID;
2027 return $this->callAPISuccess('custom_field', 'delete', $params);
2031 * Function to create note
2033 * @params array $params name-value pair for an event
2036 * @return array $note
2038 function noteCreate($cId) {
2040 'entity_table' => 'civicrm_contact',
2041 'entity_id' => $cId,
2042 'note' => 'hello I am testing Note',
2043 'contact_id' => $cId,
2044 'modified_date' => date('Ymd'),
2045 'subject' => 'Test Note',
2048 return $this->callAPISuccess('Note', 'create', $params);
2052 * Enable CiviCampaign Component
2054 function enableCiviCampaign() {
2055 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2056 // force reload of config object
2057 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2058 //flush cache by calling with reset
2059 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2063 * Create test generated example in api/v3/examples.
2064 * To turn this off (e.g. on the server) set
2065 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2066 * in your settings file
2067 * @param array $params array as passed to civicrm_api function
2068 * @param array $result array as received from the civicrm_api function
2069 * @param string $function calling function - generally __FUNCTION__
2070 * @param string $filename called from file - generally __FILE__
2071 * @param string $description descriptive text for the example file
2072 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2073 * @param string $action - optional action - otherwise taken from function name
2075 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2076 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2079 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2080 //todo - this is a bit cludgey
2081 if (empty($action)) {
2082 if (strstr($function, 'Create')) {
2083 $action = empty($action) ?
'create' : $action;
2084 $entityAction = 'Create';
2086 elseif (strstr($function, 'GetSingle')) {
2087 $action = empty($action) ?
'getsingle' : $action;
2088 $entityAction = 'GetSingle';
2090 elseif (strstr($function, 'GetValue')) {
2091 $action = empty($action) ?
'getvalue' : $action;
2092 $entityAction = 'GetValue';
2094 elseif (strstr($function, 'GetCount')) {
2095 $action = empty($action) ?
'getcount' : $action;
2096 $entityAction = 'GetCount';
2098 elseif (strstr($function, 'GetFields')) {
2099 $action = empty($action) ?
'getfields' : $action;
2100 $entityAction = 'GetFields';
2102 elseif (strstr($function, 'GetList')) {
2103 $action = empty($action) ?
'getlist' : $action;
2104 $entityAction = 'GetList';
2106 elseif (strstr($function, 'Get')) {
2107 $action = empty($action) ?
'get' : $action;
2108 $entityAction = 'Get';
2110 elseif (strstr($function, 'Delete')) {
2111 $action = empty($action) ?
'delete' : $action;
2112 $entityAction = 'Delete';
2114 elseif (strstr($function, 'Update')) {
2115 $action = empty($action) ?
'update' : $action;
2116 $entityAction = 'Update';
2118 elseif (strstr($function, 'Subscribe')) {
2119 $action = empty($action) ?
'subscribe' : $action;
2120 $entityAction = 'Subscribe';
2122 elseif (strstr($function, 'Submit')) {
2123 $action = empty($action) ?
'submit' : $action;
2124 $entityAction = 'Submit';
2126 elseif (strstr($function, 'Apply')) {
2127 $action = empty($action) ?
'apply' : $action;
2128 $entityAction = 'Apply';
2130 elseif (strstr($function, 'Replace')) {
2131 $action = empty($action) ?
'replace' : $action;
2132 $entityAction = 'Replace';
2136 $entityAction = ucwords($action);
2139 $this->tidyExampleResult($result);
2140 if(isset($params['version'])) {
2141 unset($params['version']);
2143 // a cleverer person than me would do it in a single regex
2144 if (strstr($entity, 'UF')) {
2145 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2148 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2150 $smarty = CRM_Core_Smarty
::singleton();
2151 $smarty->assign('testfunction', $function);
2152 $function = $fnPrefix . "_" . strtolower($action);
2153 $smarty->assign('function', $function);
2154 $smarty->assign('fnPrefix', $fnPrefix);
2155 $smarty->assign('params', $params);
2156 $smarty->assign('entity', $entity);
2157 $smarty->assign('filename', basename($filename));
2158 $smarty->assign('description', $description);
2159 $smarty->assign('result', $result);
2161 $smarty->assign('action', $action);
2162 if (empty($subfile)) {
2163 $subfile = $entityAction;
2165 if (file_exists('../tests/templates/documentFunction.tpl')) {
2166 if (!is_dir("../api/v3/examples/$entity")) {
2167 mkdir("../api/v3/examples/$entity");
2169 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2170 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2176 * Tidy up examples array so that fields that change often ..don't
2177 * and debug related fields are unset
2181 * @internal param array $params
2183 function tidyExampleResult(&$result){
2184 if(!is_array($result)) {
2187 $fieldsToChange = array(
2188 'hash' => '67eac7789eaee00',
2189 'modified_date' => '2012-11-14 16:02:35',
2190 'created_date' => '2013-07-28 08:49:19',
2191 'create_date' => '20120130621222105',
2192 'application_received_date' => '20130728084957',
2193 'in_date' => '2013-07-28 08:50:19',
2194 'scheduled_date' => '20130728085413',
2195 'approval_date' => '20130728085413',
2196 'pledge_start_date_high' => '20130726090416',
2197 'start_date' => '2013-07-29 00:00:00',
2198 'event_start_date' => '2013-07-29 00:00:00',
2199 'end_date' => '2013-08-04 00:00:00',
2200 'event_end_date' => '2013-08-04 00:00:00',
2201 'decision_date' => '20130805000000',
2204 $keysToUnset = array('xdebug', 'undefined_fields',);
2205 foreach ($keysToUnset as $unwantedKey) {
2206 if(isset($result[$unwantedKey])) {
2207 unset($result[$unwantedKey]);
2210 if (isset($result['values'])) {
2211 if(!is_array($result['values'])) {
2214 $resultArray = &$result['values'];
2216 elseif(is_array($result)) {
2217 $resultArray = &$result;
2223 foreach ($resultArray as $index => &$values) {
2224 if(!is_array($values)) {
2227 foreach($values as $key => &$value) {
2228 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2229 if(isset($value['is_error'])) {
2230 // we have a std nested result format
2231 $this->tidyExampleResult($value);
2234 foreach ($value as &$nestedResult) {
2235 // this is an alternative syntax for nested results a keyed array of results
2236 $this->tidyExampleResult($nestedResult);
2240 if(in_array($key, $keysToUnset)) {
2241 unset($values[$key]);
2244 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2245 $value = $fieldsToChange[$key];
2247 if(is_string($value)) {
2248 $value = addslashes($value);
2255 * Function to delete note
2257 * @params int $noteID
2260 function noteDelete($params) {
2261 return $this->callAPISuccess('Note', 'delete', $params);
2265 * Function to create custom field with Option Values
2267 * @param array $customGroup
2268 * @param string $name name of custom field
2272 function customFieldOptionValueCreate($customGroup, $name) {
2273 $fieldParams = array(
2274 'custom_group_id' => $customGroup['id'],
2275 'name' => 'test_custom_group',
2276 'label' => 'Country',
2277 'html_type' => 'Select',
2278 'data_type' => 'String',
2281 'is_searchable' => 0,
2285 $optionGroup = array(
2287 'name' => 'option_group1',
2288 'label' => 'option_group_label1',
2291 $optionValue = array(
2292 'option_label' => array('Label1', 'Label2'),
2293 'option_value' => array('value1', 'value2'),
2294 'option_name' => array($name . '_1', $name . '_2'),
2295 'option_weight' => array(1, 2),
2296 'option_status' => 1,
2299 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2301 return $this->callAPISuccess('custom_field', 'create', $params);
2309 function confirmEntitiesDeleted($entities) {
2310 foreach ($entities as $entity) {
2312 $result = $this->callAPISuccess($entity, 'Get', array());
2313 if ($result['error'] == 1 ||
$result['count'] > 0) {
2314 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2321 * @param $tablesToTruncate
2322 * @param bool $dropCustomValueTables
2324 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2325 if ($dropCustomValueTables) {
2326 $tablesToTruncate[] = 'civicrm_custom_group';
2327 $tablesToTruncate[] = 'civicrm_custom_field';
2330 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2332 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2333 foreach ($tablesToTruncate as $table) {
2334 $sql = "TRUNCATE TABLE $table";
2335 CRM_Core_DAO
::executeQuery($sql);
2337 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2339 if ($dropCustomValueTables) {
2340 $dbName = self
::getDBName();
2342 SELECT TABLE_NAME as tableName
2343 FROM INFORMATION_SCHEMA.TABLES
2344 WHERE TABLE_SCHEMA = '{$dbName}'
2345 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2348 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2349 while ($tableDAO->fetch()) {
2350 $sql = "DROP TABLE {$tableDAO->tableName}";
2351 CRM_Core_DAO
::executeQuery($sql);
2357 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2359 function quickCleanUpFinancialEntities() {
2360 $tablesToTruncate = array(
2361 'civicrm_contribution',
2362 'civicrm_financial_trxn',
2363 'civicrm_contribution_recur',
2364 'civicrm_line_item',
2365 'civicrm_contribution_page',
2366 'civicrm_payment_processor',
2367 'civicrm_entity_financial_trxn',
2368 'civicrm_membership',
2369 'civicrm_membership_type',
2370 'civicrm_membership_payment',
2371 'civicrm_membership_log',
2372 'civicrm_membership_block',
2374 'civicrm_participant',
2375 'civicrm_participant_payment',
2377 'civicrm_price_set_entity',
2379 $this->quickCleanup($tablesToTruncate);
2380 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2383 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2384 * Default behaviour is to also delete the entity
2385 * @param array $params params array to check agains
2386 * @param int $id id of the entity concerned
2387 * @param string $entity name of entity concerned (e.g. membership)
2388 * @param bool $delete should the entity be deleted as part of this check
2389 * @param string $errorText text to print on error
2396 * @param int $delete
2397 * @param string $errorText
2401 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2403 $result = $this->callAPISuccessGetSingle($entity, array(
2408 $this->callAPISuccess($entity, 'Delete', array(
2412 $dateFields = $keys = $dateTimeFields = array();
2413 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2414 foreach ($fields['values'] as $field => $settings) {
2415 if (array_key_exists($field, $result)) {
2416 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2419 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2421 $type = CRM_Utils_Array
::value('type', $settings);
2422 if ($type == CRM_Utils_Type
::T_DATE
) {
2423 $dateFields[] = $settings['name'];
2424 // we should identify both real names & unique names as dates
2425 if($field != $settings['name']) {
2426 $dateFields[] = $field;
2429 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2430 $dateTimeFields[] = $settings['name'];
2431 // we should identify both real names & unique names as dates
2432 if($field != $settings['name']) {
2433 $dateTimeFields[] = $field;
2438 if (strtolower($entity) == 'contribution') {
2439 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2440 // this is not returned in id format
2441 unset($params['payment_instrument_id']);
2442 $params['contribution_source'] = $params['source'];
2443 unset($params['source']);
2446 foreach ($params as $key => $value) {
2447 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2450 if (in_array($key, $dateFields)) {
2451 $value = date('Y-m-d', strtotime($value));
2452 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2454 if (in_array($key, $dateTimeFields)) {
2455 $value = date('Y-m-d H:i:s', strtotime($value));
2456 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2458 $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);
2463 * Function to get formatted values in the actual and expected result
2464 * @param array $actual actual calculated values
2465 * @param array $expected expected values
2468 function checkArrayEquals(&$actual, &$expected) {
2469 self
::unsetId($actual);
2470 self
::unsetId($expected);
2471 $this->assertEquals($actual, $expected);
2475 * Function to unset the key 'id' from the array
2476 * @param array $unformattedArray The array from which the 'id' has to be unset
2479 static function unsetId(&$unformattedArray) {
2480 $formattedArray = array();
2481 if (array_key_exists('id', $unformattedArray)) {
2482 unset($unformattedArray['id']);
2484 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2485 foreach ($unformattedArray['values'] as $key => $value) {
2486 if (is_Array($value)) {
2487 foreach ($value as $k => $v) {
2493 elseif ($key == 'id') {
2494 $unformattedArray[$key];
2496 $formattedArray = array($value);
2498 $unformattedArray['values'] = $formattedArray;
2503 * Helper to enable/disable custom directory support
2505 * @param array $customDirs with members:
2506 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2507 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2509 function customDirectories($customDirs) {
2510 require_once 'CRM/Core/Config.php';
2511 $config = CRM_Core_Config
::singleton();
2513 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2514 unset($config->customPHPPathDir
);
2516 elseif ($customDirs['php_path'] === TRUE) {
2517 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2520 $config->customPHPPathDir
= $php_path;
2523 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2524 unset($config->customTemplateDir
);
2526 elseif ($customDirs['template_path'] === TRUE) {
2527 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2530 $config->customTemplateDir
= $template_path;
2535 * Generate a temporary folder
2537 * @param string $prefix
2538 * @return string $string
2540 function createTempDir($prefix = 'test-') {
2541 $tempDir = CRM_Utils_File
::tempdir($prefix);
2542 $this->tempDirs
[] = $tempDir;
2546 function cleanTempDirs() {
2547 if (!is_array($this->tempDirs
)) {
2548 // fix test errors where this is not set
2551 foreach ($this->tempDirs
as $tempDir) {
2552 if (is_dir($tempDir)) {
2553 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2559 * Temporarily replace the singleton extension with a different one
2561 function setExtensionSystem(CRM_Extension_System
$system) {
2562 if ($this->origExtensionSystem
== NULL) {
2563 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2565 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2568 function unsetExtensionSystem() {
2569 if ($this->origExtensionSystem
!== NULL) {
2570 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2571 $this->origExtensionSystem
= NULL;
2576 * Temporarily alter the settings-metadata to add a mock setting.
2578 * WARNING: The setting metadata will disappear on the next cache-clear.
2583 function setMockSettingsMetaData($extras) {
2584 CRM_Core_BAO_Setting
::$_cache = array();
2585 $this->callAPISuccess('system','flush', array());
2586 CRM_Core_BAO_Setting
::$_cache = array();
2588 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2589 $metadata = array_merge($metadata, $extras);
2592 $fields = $this->callAPISuccess('setting', 'getfields', array());
2593 foreach ($extras as $key => $spec) {
2594 $this->assertNotEmpty($spec['title']);
2595 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2602 function financialAccountDelete($name) {
2603 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2604 $financialAccount->name
= $name;
2605 if($financialAccount->find(TRUE)) {
2606 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2607 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2608 $entityFinancialType->delete();
2609 $financialAccount->delete();
2614 * Use $ids as an instruction to do test cleanup
2616 function deleteFromIDSArray() {
2617 foreach ($this->ids
as $entity => $ids) {
2618 foreach ($ids as $id) {
2619 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2625 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2626 * (NB unclear if this is still required)
2628 function _sethtmlGlobals() {
2629 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2630 'required' => array(
2631 'html_quickform_rule_required',
2632 'HTML/QuickForm/Rule/Required.php'
2634 'maxlength' => array(
2635 'html_quickform_rule_range',
2636 'HTML/QuickForm/Rule/Range.php'
2638 'minlength' => array(
2639 'html_quickform_rule_range',
2640 'HTML/QuickForm/Rule/Range.php'
2642 'rangelength' => array(
2643 'html_quickform_rule_range',
2644 'HTML/QuickForm/Rule/Range.php'
2647 'html_quickform_rule_email',
2648 'HTML/QuickForm/Rule/Email.php'
2651 'html_quickform_rule_regex',
2652 'HTML/QuickForm/Rule/Regex.php'
2654 'lettersonly' => array(
2655 'html_quickform_rule_regex',
2656 'HTML/QuickForm/Rule/Regex.php'
2658 'alphanumeric' => array(
2659 'html_quickform_rule_regex',
2660 'HTML/QuickForm/Rule/Regex.php'
2663 'html_quickform_rule_regex',
2664 'HTML/QuickForm/Rule/Regex.php'
2666 'nopunctuation' => array(
2667 'html_quickform_rule_regex',
2668 'HTML/QuickForm/Rule/Regex.php'
2671 'html_quickform_rule_regex',
2672 'HTML/QuickForm/Rule/Regex.php'
2674 'callback' => array(
2675 'html_quickform_rule_callback',
2676 'HTML/QuickForm/Rule/Callback.php'
2679 'html_quickform_rule_compare',
2680 'HTML/QuickForm/Rule/Compare.php'
2683 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2684 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2686 'HTML/QuickForm/group.php',
2687 'HTML_QuickForm_group'
2690 'HTML/QuickForm/hidden.php',
2691 'HTML_QuickForm_hidden'
2694 'HTML/QuickForm/reset.php',
2695 'HTML_QuickForm_reset'
2697 'checkbox' => array(
2698 'HTML/QuickForm/checkbox.php',
2699 'HTML_QuickForm_checkbox'
2702 'HTML/QuickForm/file.php',
2703 'HTML_QuickForm_file'
2706 'HTML/QuickForm/image.php',
2707 'HTML_QuickForm_image'
2709 'password' => array(
2710 'HTML/QuickForm/password.php',
2711 'HTML_QuickForm_password'
2714 'HTML/QuickForm/radio.php',
2715 'HTML_QuickForm_radio'
2718 'HTML/QuickForm/button.php',
2719 'HTML_QuickForm_button'
2722 'HTML/QuickForm/submit.php',
2723 'HTML_QuickForm_submit'
2726 'HTML/QuickForm/select.php',
2727 'HTML_QuickForm_select'
2729 'hiddenselect' => array(
2730 'HTML/QuickForm/hiddenselect.php',
2731 'HTML_QuickForm_hiddenselect'
2734 'HTML/QuickForm/text.php',
2735 'HTML_QuickForm_text'
2737 'textarea' => array(
2738 'HTML/QuickForm/textarea.php',
2739 'HTML_QuickForm_textarea'
2741 'fckeditor' => array(
2742 'HTML/QuickForm/fckeditor.php',
2743 'HTML_QuickForm_FCKEditor'
2746 'HTML/QuickForm/tinymce.php',
2747 'HTML_QuickForm_TinyMCE'
2749 'dojoeditor' => array(
2750 'HTML/QuickForm/dojoeditor.php',
2751 'HTML_QuickForm_dojoeditor'
2754 'HTML/QuickForm/link.php',
2755 'HTML_QuickForm_link'
2757 'advcheckbox' => array(
2758 'HTML/QuickForm/advcheckbox.php',
2759 'HTML_QuickForm_advcheckbox'
2762 'HTML/QuickForm/date.php',
2763 'HTML_QuickForm_date'
2766 'HTML/QuickForm/static.php',
2767 'HTML_QuickForm_static'
2770 'HTML/QuickForm/header.php',
2771 'HTML_QuickForm_header'
2774 'HTML/QuickForm/html.php',
2775 'HTML_QuickForm_html'
2777 'hierselect' => array(
2778 'HTML/QuickForm/hierselect.php',
2779 'HTML_QuickForm_hierselect'
2781 'autocomplete' => array(
2782 'HTML/QuickForm/autocomplete.php',
2783 'HTML_QuickForm_autocomplete'
2786 'HTML/QuickForm/xbutton.php',
2787 'HTML_QuickForm_xbutton'
2789 'advmultiselect' => array(
2790 'HTML/QuickForm/advmultiselect.php',
2791 'HTML_QuickForm_advmultiselect'
2797 * Set up an acl allowing contact to see 2 specified groups
2798 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2800 * You need to have precreated these groups & created the user e.g
2801 * $this->createLoggedInUser();
2802 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2803 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2806 function setupACL() {
2808 $_REQUEST = $this->_params
;
2809 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2810 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2811 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2812 'label' => 'pick me',
2817 CRM_Core_DAO
::executeQuery("
2818 TRUNCATE civicrm_acl_cache
2821 CRM_Core_DAO
::executeQuery("
2822 TRUNCATE civicrm_acl_contact_cache
2826 CRM_Core_DAO
::executeQuery("
2827 INSERT INTO civicrm_acl_entity_role (
2828 `acl_role_id`, `entity_table`, `entity_id`
2829 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2832 CRM_Core_DAO
::executeQuery("
2833 INSERT INTO civicrm_acl (
2834 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2837 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2841 CRM_Core_DAO
::executeQuery("
2842 INSERT INTO civicrm_acl (
2843 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2846 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2849 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2850 $this->callAPISuccess('group_contact', 'create', array(
2851 'group_id' => $this->_permissionedGroup
,
2852 'contact_id' => $this->_loggedInUser
,
2855 CRM_ACL_BAO_Cache
::resetCache();
2856 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2857 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2861 * alter default price set so that the field numbers are not all 1 (hiding errors)
2863 function offsetDefaultPriceSet() {
2864 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2865 $firstID = $contributionPriceSet['id'];
2866 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2867 unset($contributionPriceSet['id']);
2868 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2869 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2870 unset($priceField['id']);
2871 $priceField['price_set_id'] = $newPriceSet['id'];
2872 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2873 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2875 unset($priceFieldValue['id']);
2876 //create some padding to use up ids
2877 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2878 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2879 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2884 * Create an instance of the paypal processor
2885 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2886 * this parent class & we don't have a structure for that yet
2887 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2888 * & the best protection agains that is the functions this class affords
2890 function paymentProcessorCreate($params = array()) {
2891 $params = array_merge(array(
2893 'domain_id' => CRM_Core_Config
::domainID(),
2894 'payment_processor_type_id' => 'PayPal',
2898 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2899 'password' => '1183377788',
2900 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2901 'url_site' => 'https://www.sandbox.paypal.com/',
2902 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2903 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2904 'class_name' => 'Payment_PayPalImpl',
2905 'billing_mode' => 3,
2906 'financial_type_id' => 1,
2909 if(!is_numeric($params['payment_processor_type_id'])) {
2910 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2912 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2913 'name' => $params['payment_processor_type_id'],
2917 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2918 return $result['id'];
2926 */function CiviUnitTestCase_fatalErrorHandler($message) {
2927 throw new Exception("{$message['message']}: {$message['code']}");