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));
307 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
308 'CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'
314 public static function setUpBeforeClass() {
315 static::_populateDB(TRUE);
317 // also set this global hack
318 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
320 $env = new CRM_Utils_Check_Env();
321 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
325 * Common setup functions for all unit tests
327 protected function setUp() {
328 $session = CRM_Core_Session
::singleton();
329 $session->set('userID', NULL);
331 CRM_Utils_Hook
::singleton(TRUE);
332 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
333 // Use a temporary file for STDIN
334 $GLOBALS['stdin'] = tmpfile();
335 if ($GLOBALS['stdin'] === FALSE) {
336 echo "Couldn't open temporary file\n";
340 // Get and save a connection to the database
341 $this->_dbconn
= $this->getConnection();
343 // reload database before each test
344 // $this->_populateDB();
346 // "initialize" CiviCRM to avoid problems when running single tests
347 // FIXME: look at it closer in second stage
349 // initialize the object once db is loaded
350 CRM_Core_Config
::$_mail = NULL;
351 $config = CRM_Core_Config
::singleton();
353 // when running unit tests, use mockup user framework
354 $config->setUserFramework('UnitTests');
356 // also fix the fatal error handler to throw exceptions,
358 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
360 // enable backtrace to get meaningful errors
361 $config->backtrace
= 1;
363 // disable any left-over test extensions
364 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
366 // reset all the caches
367 CRM_Utils_System
::flushCache();
369 // clear permissions stub to not check permissions
370 $config = CRM_Core_Config
::singleton();
371 $config->userPermissionClass
->permissions
= NULL;
373 //flush component settings
374 CRM_Core_Component
::getEnabledComponents(TRUE);
376 if ($this->_eNoticeCompliant
) {
377 error_reporting(E_ALL
);
380 error_reporting(E_ALL
& ~E_NOTICE
);
382 $this->_sethtmlGlobals();
386 * Read everything from the datasets directory and insert into the db
388 public function loadAllFixtures() {
389 $fixturesDir = __DIR__
. '/../../fixtures';
391 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
393 $xmlFiles = glob($fixturesDir . '/*.xml');
394 foreach ($xmlFiles as $xmlFixture) {
395 $op = new PHPUnit_Extensions_Database_Operation_Insert();
396 $dataset = $this->createXMLDataSet($xmlFixture);
397 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
398 $op->execute($this->_dbconn
, $dataset);
401 $yamlFiles = glob($fixturesDir . '/*.yaml');
402 foreach ($yamlFiles as $yamlFixture) {
403 $op = new PHPUnit_Extensions_Database_Operation_Insert();
404 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
405 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
406 $op->execute($this->_dbconn
, $dataset);
409 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
413 * emulate a logged in user since certain functions use that
414 * value to store a record in the DB (like activity)
417 public function createLoggedInUser() {
419 'first_name' => 'Logged In',
420 'last_name' => 'User ' . rand(),
421 'contact_type' => 'Individual',
423 $contactID = $this->individualCreate($params);
425 $session = CRM_Core_Session
::singleton();
426 $session->set('userID', $contactID);
429 public function cleanDB() {
430 self
::$populateOnce = NULL;
431 $this->DBResetRequired
= TRUE;
433 $this->_dbconn
= $this->getConnection();
434 static::_populateDB();
435 $this->tempDirs
= array();
439 * Common teardown functions for all unit tests
441 protected function tearDown() {
442 error_reporting(E_ALL
& ~E_NOTICE
);
443 $session = CRM_Core_Session
::singleton();
444 $session->set('userID', NULL);
445 $tablesToTruncate = array('civicrm_contact');
446 $this->quickCleanup($tablesToTruncate);
447 $this->cleanTempDirs();
448 $this->unsetExtensionSystem();
452 * FIXME: Maybe a better way to do it
454 function foreignKeyChecksOff() {
455 self
::$utils = new Utils($GLOBALS['mysql_host'],
456 $GLOBALS['mysql_port'],
457 $GLOBALS['mysql_user'],
458 $GLOBALS['mysql_pass']
460 $dbName = self
::getDBName();
461 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
462 if (self
::$utils->do_query($query) === FALSE) {
464 echo 'Cannot set foreign_key_checks = 0';
470 function foreignKeyChecksOn() {
471 // FIXME: might not be needed if previous fixme implemented
475 * Generic function to compare expected values after an api call to retrieved
478 * @daoName string DAO Name of object we're evaluating.
479 * @id int Id of object
480 * @match array Associative array of field name => expected value. Empty if asserting
481 * that a DELETE occurred
482 * @delete boolean True if we're checking that a DELETE action occurred.
484 function assertDBState($daoName, $id, $match, $delete = FALSE) {
486 // adding this here since developers forget to check for an id
487 // and hence we get the first value in the db
488 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
491 $object = new $daoName();
495 // If we're asserting successful record deletion, make sure object is NOT found.
497 if ($object->find(TRUE)) {
498 $this->fail("Object not deleted by delete operation: $daoName, $id");
503 // Otherwise check matches of DAO field values against expected values in $match.
504 if ($object->find(TRUE)) {
505 $fields = & $object->fields();
506 foreach ($fields as $name => $value) {
507 $dbName = $value['name'];
508 if (isset($match[$name])) {
510 $this->assertEquals($object->$dbName, $match[$name]);
512 elseif (isset($match[$dbName])) {
514 $this->assertEquals($object->$dbName, $match[$dbName]);
519 $this->fail("Could not retrieve object: $daoName, $id");
522 $matchSize = count($match);
523 if ($verifiedCount != $matchSize) {
524 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
528 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
531 * @param $searchValue
532 * @param $returnColumn
533 * @param $searchColumn
536 * @return null|string
537 * @throws PHPUnit_Framework_AssertionFailedError
539 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
540 if (empty($searchValue)) {
541 $this->fail("empty value passed to assertDBNotNull");
543 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
544 $this->assertNotNull($value, $message);
549 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
552 * @param $searchValue
553 * @param $returnColumn
554 * @param $searchColumn
557 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
558 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
559 $this->assertNull($value, $message);
562 // Request a record from the DB by id. Success if row not found.
566 * @param null $message
568 function assertDBRowNotExist($daoName, $id, $message = NULL) {
569 $message = $message ?
$message : "$daoName (#$id) should not exist";
570 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
571 $this->assertNull($value, $message);
574 // Request a record from the DB by id. Success if row not found.
578 * @param null $message
580 function assertDBRowExist($daoName, $id, $message = NULL) {
581 $message = $message ?
$message : "$daoName (#$id) should exist";
582 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
583 $this->assertEquals($id, $value, $message);
586 // Compare a single column value in a retrieved DB record to an expected value
589 * @param $searchValue
590 * @param $returnColumn
591 * @param $searchColumn
592 * @param $expectedValue
595 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
596 $expectedValue, $message
598 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
599 $this->assertEquals($value, $expectedValue, $message);
602 // Compare all values in a single retrieved DB record to an array of expected values
605 * @param $searchParams
606 * @param $expectedValues
608 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
609 //get the values from db
611 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
613 // compare db values with expected values
614 self
::assertAttributesEquals($expectedValues, $dbValues);
618 * Assert that a SQL query returns a given value
620 * The first argument is an expected value. The remaining arguments are passed
621 * to CRM_Core_DAO::singleValueQuery
623 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
624 * array(1 => array("Whiz", "String")));
626 function assertDBQuery($expected, $query, $params = array()) {
627 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
628 $this->assertEquals($expected, $actual,
629 sprintf('expected=[%s] actual=[%s] query=[%s]',
630 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
636 * Assert that two array-trees are exactly equal, notwithstanding
637 * the sorting of keys
639 * @param array $expected
640 * @param array $actual
642 function assertTreeEquals($expected, $actual) {
645 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
646 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
650 $this->assertEquals($e, $a);
654 * Assert that two numbers are approximately equal
656 * @param int|float $expected
657 * @param int|float $actual
658 * @param int|float $tolerance
659 * @param string $message
661 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
662 if ($message === NULL) {
663 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
665 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
669 * @param $expectedValues
670 * @param $actualValues
671 * @param null $message
673 * @throws PHPUnit_Framework_AssertionFailedError
675 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
676 foreach ($expectedValues as $paramName => $paramValue) {
677 if (isset($actualValues[$paramName])) {
678 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
681 $this->fail("Attribute '$paramName' not present in actual array.");
690 function assertArrayKeyExists($key, &$list) {
691 $result = isset($list[$key]) ?
TRUE : FALSE;
692 $this->assertTrue($result, ts("%1 element exists?",
701 function assertArrayValueNotNull($key, &$list) {
702 $this->assertArrayKeyExists($key, $list);
704 $value = isset($list[$key]) ?
$list[$key] : NULL;
705 $this->assertTrue($value,
706 ts("%1 element not null?",
713 * check that api returned 'is_error' => 0
714 * else provide full message
715 * @param array $apiResult api result
716 * @param string $prefix extra test to add to message
718 function assertAPISuccess($apiResult, $prefix = '') {
719 if (!empty($prefix)) {
722 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
724 if(!empty($apiResult['debug_information'])) {
725 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
727 if(!empty($apiResult['trace'])){
728 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
730 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
734 * check that api returned 'is_error' => 1
735 * else provide full message
737 * @param array $apiResult api result
738 * @param string $prefix extra test to add to message
739 * @param null $expectedError
741 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
742 if (!empty($prefix)) {
745 if($expectedError && !empty($apiResult['is_error'])){
746 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
748 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
749 $this->assertNotEmpty($apiResult['error_message']);
755 * @param string $message
757 function assertType($expected, $actual, $message = '') {
758 return $this->assertInternalType($expected, $actual, $message);
762 * check that a deleted item has been deleted
764 function assertAPIDeleted($entity, $id) {
765 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
770 * check that api returned 'is_error' => 1
771 * else provide full message
774 * @param array $valuesToExclude
775 * @param string $prefix extra test to add to message
776 * @internal param array $apiResult api result
778 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
779 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
780 foreach ($valuesToExclude as $value) {
781 if(isset($result[$value])) {
782 unset($result[$value]);
784 if(isset($expected[$value])) {
785 unset($expected[$value]);
788 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
792 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
799 function civicrm_api($entity, $action, $params) {
800 return civicrm_api($entity, $action, $params);
804 * This function exists to wrap api functions
805 * so we can ensure they succeed & throw exceptions without litterering the test with checks
807 * @param string $entity
808 * @param string $action
809 * @param array $params
810 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
811 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
812 * for getsingle the array is compared against an array passed in - the id is not compared (for
817 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
818 $params = array_merge(array(
819 'version' => $this->_apiversion
,
824 switch (strtolower($action)) {
826 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
828 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
830 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
832 $result = $this->civicrm_api($entity, $action, $params);
833 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
838 * This function exists to wrap api getValue function & check the result
839 * so we can ensure they succeed & throw exceptions without litterering the test with checks
840 * There is a type check in this
842 * @param string $entity
843 * @param array $params
844 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
854 function callAPISuccessGetValue($entity, $params, $type = NULL) {
856 'version' => $this->_apiversion
,
859 $result = $this->civicrm_api($entity, 'getvalue', $params);
861 if($type == 'integer'){
862 // api seems to return integers as strings
863 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
866 $this->assertType($type, $result, "returned result should have been of type $type but was " );
873 * This function exists to wrap api getsingle function & check the result
874 * so we can ensure they succeed & throw exceptions without litterering the test with checks
876 * @param string $entity
877 * @param array $params
878 * @param array $checkAgainst - array to compare result against
889 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
891 'version' => $this->_apiversion
,
894 $result = $this->civicrm_api($entity, 'getsingle', $params);
895 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
896 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
899 // @todo - have gone with the fn that unsets id? should we check id?
900 $this->checkArrayEquals($result, $checkAgainst);
906 * This function exists to wrap api getValue function & check the result
907 * so we can ensure they succeed & throw exceptions without litterering the test with checks
908 * There is a type check in this
909 * @param string $entity
910 * @param array $params
914 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
922 function callAPISuccessGetCount($entity, $params, $count = NULL) {
924 'version' => $this->_apiversion
,
927 $result = $this->civicrm_api($entity, 'getcount', $params);
928 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
929 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
932 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
938 * This function exists to wrap api functions
939 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
941 * @param string $entity
942 * @param string $action
943 * @param array $params
944 * @param string $function - pass this in to create a generated example
945 * @param string $file - pass this in to create a generated example
946 * @param string $description
947 * @param string|null $subfile
948 * @param string|null $actionName
951 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
952 $params['version'] = $this->_apiversion
;
953 $result = $this->callAPISuccess($entity, $action, $params);
954 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
959 * This function exists to wrap api functions
960 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
961 * @param string $entity
962 * @param string $action
963 * @param array $params
964 * @param string $expectedErrorMessage error
965 * @param null $extraOutput
968 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
969 if (is_array($params)) {
971 'version' => $this->_apiversion
,
974 $result = $this->civicrm_api($entity, $action, $params);
975 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
980 * Create required data based on $this->entity & $this->params
981 * This is just a way to set up the test data for delete & get functions
982 * so the distinction between set
983 * up & tested functions is clearer
985 * @return array api Result
987 public function createTestEntity(){
988 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
992 * Generic function to create Organisation, to be used in test cases
994 * @param array parameters for civicrm_contact_add api function call
995 * @param int sequence number if creating multiple organizations
997 * @return int id of Organisation created
999 function organizationCreate($params = array(), $seq = 0) {
1003 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1004 return $this->_contactCreate($params);
1008 * Generic function to create Individual, to be used in test cases
1010 * @param array parameters for civicrm_contact_add api function call
1011 * @param int sequence number if creating multiple individuals
1013 * @return int id of Individual created
1015 function individualCreate($params = array(), $seq = 0) {
1016 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1017 return $this->_contactCreate($params);
1021 * Generic function to create Household, to be used in test cases
1023 * @param array parameters for civicrm_contact_add api function call
1024 * @param int sequence number if creating multiple households
1026 * @return int id of Household created
1028 function householdCreate($params = array(), $seq = 0) {
1029 $params = array_merge($this->sampleContact('Household', $seq), $params);
1030 return $this->_contactCreate($params);
1034 * Helper function for getting sample contact properties
1036 * @param enum contact type: Individual, Organization
1037 * @param int sequence number for the values of this type
1039 * @return array properties of sample contact (ie. $params for API call)
1041 function sampleContact($contact_type, $seq = 0) {
1043 'Individual' => array(
1044 // The number of values in each list need to be coprime numbers to not have duplicates
1045 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1046 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1047 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1049 'Organization' => array(
1050 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
1052 'Household' => array(
1053 'household_name' => array('Unit Test household'),
1056 $params = array('contact_type' => $contact_type);
1057 foreach ($samples[$contact_type] as $key => $values) {
1058 $params[$key] = $values[$seq %
sizeof($values)];
1060 if ($contact_type == 'Individual' ) {
1061 $params['email'] = strtolower(
1062 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1064 $params['prefix_id'] = 3;
1065 $params['suffix_id'] = 3;
1071 * Private helper function for calling civicrm_contact_add
1076 * @internal param \parameters $array for civicrm_contact_add api function call
1078 * @return int id of Household created
1080 private function _contactCreate($params) {
1081 $result = $this->callAPISuccess('contact', 'create', $params);
1082 if (!empty($result['is_error']) ||
empty($result['id'])) {
1083 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1085 return $result['id'];
1093 function contactDelete($contactID) {
1096 'skip_undelete' => 1,
1099 $domain = new CRM_Core_BAO_Domain
;
1100 $domain->contact_id
= $contactID;
1101 if ($domain->find(TRUE)) {
1102 // we are finding tests trying to delete the domain contact in cleanup
1103 //since this is mainly for cleanup lets put a safeguard here
1106 $result = $this->callAPISuccess('contact', 'delete', $params);
1111 * @param $contactTypeId
1115 function contactTypeDelete($contactTypeId) {
1116 require_once 'CRM/Contact/BAO/ContactType.php';
1117 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1119 throw new Exception('Could not delete contact type');
1124 * @param array $params
1128 function membershipTypeCreate($params = array()) {
1129 CRM_Member_PseudoConstant
::flush('membershipType');
1130 CRM_Core_Config
::clearDBCache();
1131 $memberOfOrganization = $this->organizationCreate();
1132 $params = array_merge(array(
1133 'name' => 'General',
1134 'duration_unit' => 'year',
1135 'duration_interval' => 1,
1136 'period_type' => 'rolling',
1137 'member_of_contact_id' => $memberOfOrganization,
1139 'financial_type_id' => 1,
1142 'visibility' => 'Public',
1145 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1147 CRM_Member_PseudoConstant
::flush('membershipType');
1148 CRM_Utils_Cache
::singleton()->flush();
1150 return $result['id'];
1158 function contactMembershipCreate($params) {
1160 'join_date' => '2007-01-21',
1161 'start_date' => '2007-01-21',
1162 'end_date' => '2007-12-21',
1163 'source' => 'Payment',
1166 foreach ($pre as $key => $val) {
1167 if (!isset($params[$key])) {
1168 $params[$key] = $val;
1172 $result = $this->callAPISuccess('Membership', 'create', $params);
1173 return $result['id'];
1177 * Function to delete Membership Type
1180 * @internal param int $membershipTypeID
1182 function membershipTypeDelete($params) {
1183 $this->callAPISuccess('MembershipType', 'Delete', $params);
1187 * @param $membershipID
1189 function membershipDelete($membershipID) {
1190 $deleteParams = array('id' => $membershipID);
1191 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1196 * @param string $name
1200 function membershipStatusCreate($name = 'test member status') {
1201 $params['name'] = $name;
1202 $params['start_event'] = 'start_date';
1203 $params['end_event'] = 'end_date';
1204 $params['is_current_member'] = 1;
1205 $params['is_active'] = 1;
1207 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1208 CRM_Member_PseudoConstant
::flush('membershipStatus');
1209 return $result['id'];
1213 * @param $membershipStatusID
1215 function membershipStatusDelete($membershipStatusID) {
1216 if (!$membershipStatusID) {
1219 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1224 * @param array $params
1228 function relationshipTypeCreate($params = array()) {
1229 $params = array_merge(array(
1230 'name_a_b' => 'Relation 1 for relationship type create',
1231 'name_b_a' => 'Relation 2 for relationship type create',
1232 'contact_type_a' => 'Individual',
1233 'contact_type_b' => 'Organization',
1240 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1241 CRM_Core_PseudoConstant
::flush('relationshipType');
1243 return $result['id'];
1247 * Function to delete Relatinship Type
1249 * @param int $relationshipTypeID
1251 function relationshipTypeDelete($relationshipTypeID) {
1252 $params['id'] = $relationshipTypeID;
1253 $this->callAPISuccess('relationship_type', 'delete', $params);
1257 * @param null $params
1261 function paymentProcessorTypeCreate($params = NULL) {
1262 if (is_null($params)) {
1264 'name' => 'API_Test_PP',
1265 'title' => 'API Test Payment Processor',
1266 'class_name' => 'CRM_Core_Payment_APITest',
1267 'billing_mode' => 'form',
1273 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1275 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1277 return $result['id'];
1281 * Function to create Participant
1283 * @param array $params array of contact id and event id values
1285 * @return int $id of participant created
1287 function participantCreate($params) {
1288 if(empty($params['contact_id'])){
1289 $params['contact_id'] = $this->individualCreate();
1291 if(empty($params['event_id'])){
1292 $event = $this->eventCreate();
1293 $params['event_id'] = $event['id'];
1298 'register_date' => 20070219,
1299 'source' => 'Wimbeldon',
1300 'event_level' => 'Payment',
1304 $params = array_merge($defaults, $params);
1305 $result = $this->callAPISuccess('Participant', 'create', $params);
1306 return $result['id'];
1310 * Function to create Payment Processor
1312 * @return object of Payment Processsor
1314 function processorCreate() {
1315 $processorParams = array(
1318 'payment_processor_type_id' => 10,
1319 'financial_account_id' => 12,
1322 'url_site' => 'http://dummy.com',
1323 'url_recur' => 'http://dummy.com',
1324 'billing_mode' => 1,
1326 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1327 return $paymentProcessor;
1331 * Function to create contribution page
1334 * @return object of contribution page
1336 function contributionPageCreate($params) {
1337 $this->_pageParams
= array(
1338 'title' => 'Test Contribution Page',
1339 'financial_type_id' => 1,
1340 'currency' => 'USD',
1341 'financial_account_id' => 1,
1342 'payment_processor' => $params['processor_id'],
1344 'is_allow_other_amount' => 1,
1346 'max_amount' => 1000,
1348 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1349 return $contributionPage;
1353 * Function to create Tag
1355 * @param array $params
1356 * @return array result of created tag
1358 function tagCreate($params = array()) {
1360 'name' => 'New Tag3',
1361 'description' => 'This is description for Our New Tag ',
1364 $params = array_merge($defaults, $params);
1365 $result = $this->callAPISuccess('Tag', 'create', $params);
1366 return $result['values'][$result['id']];
1370 * Function to delete Tag
1372 * @param int $tagId id of the tag to be deleted
1374 function tagDelete($tagId) {
1375 require_once 'api/api.php';
1379 $result = $this->callAPISuccess('Tag', 'delete', $params);
1380 return $result['id'];
1384 * Add entity(s) to the tag
1386 * @param array $params
1390 function entityTagAdd($params) {
1391 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1396 * Function to create contribution
1398 * @param int $cID contact_id
1400 * @internal param int $cTypeID id of financial type
1402 * @return int id of created contribution
1404 function pledgeCreate($cID) {
1406 'contact_id' => $cID,
1407 'pledge_create_date' => date('Ymd'),
1408 'start_date' => date('Ymd'),
1409 'scheduled_date' => date('Ymd'),
1411 'pledge_status_id' => '2',
1412 'financial_type_id' => '1',
1413 'pledge_original_installment_amount' => 20,
1414 'frequency_interval' => 5,
1415 'frequency_unit' => 'year',
1416 'frequency_day' => 15,
1417 'installments' => 5,
1420 $result = $this->callAPISuccess('Pledge', 'create', $params);
1421 return $result['id'];
1425 * Function to delete contribution
1428 * @internal param int $contributionId
1430 function pledgeDelete($pledgeId) {
1432 'pledge_id' => $pledgeId,
1434 $this->callAPISuccess('Pledge', 'delete', $params);
1438 * Function to create contribution
1440 * @param int $cID contact_id
1441 * @param int $cTypeID id of financial type
1443 * @param int $invoiceID
1444 * @param int $trxnID
1445 * @param int $paymentInstrumentID
1446 * @param bool $isFee
1447 * @return int id of created contribution
1449 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1452 'contact_id' => $cID,
1453 'receive_date' => date('Ymd'),
1454 'total_amount' => 100.00,
1455 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1456 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1457 'non_deductible_amount' => 10.00,
1458 'trxn_id' => $trxnID,
1459 'invoice_id' => $invoiceID,
1461 'contribution_status_id' => 1,
1462 // 'note' => 'Donating for Nobel Cause', *Fixme
1466 $params['fee_amount'] = 5.00;
1467 $params['net_amount'] = 95.00;
1470 $result = $this->callAPISuccess('contribution', 'create', $params);
1471 return $result['id'];
1475 * Function to create online contribution
1478 * @param int $financialType id of financial type
1480 * @param int $invoiceID
1481 * @param int $trxnID
1482 * @return int id of created contribution
1484 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1485 $contribParams = array(
1486 'contact_id' => $params['contact_id'],
1487 'receive_date' => date('Ymd'),
1488 'total_amount' => 100.00,
1489 'financial_type_id' => $financialType,
1490 'contribution_page_id' => $params['contribution_page_id'],
1492 'invoice_id' => 67890,
1495 $contribParams = array_merge($contribParams, $params);
1496 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1498 return $result['id'];
1502 * Function to delete contribution
1504 * @param int $contributionId
1508 function contributionDelete($contributionId) {
1510 'contribution_id' => $contributionId,
1512 $result = $this->callAPISuccess('contribution', 'delete', $params);
1517 * Function to create an Event
1519 * @param array $params name-value pair for an event
1521 * @return array $event
1523 function eventCreate($params = array()) {
1524 // if no contact was passed, make up a dummy event creator
1525 if (!isset($params['contact_id'])) {
1526 $params['contact_id'] = $this->_contactCreate(array(
1527 'contact_type' => 'Individual',
1528 'first_name' => 'Event',
1529 'last_name' => 'Creator',
1533 // set defaults for missing params
1534 $params = array_merge(array(
1535 'title' => 'Annual CiviCRM meet',
1536 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1537 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1538 'event_type_id' => 1,
1540 'start_date' => 20081021,
1541 'end_date' => 20081023,
1542 'is_online_registration' => 1,
1543 'registration_start_date' => 20080601,
1544 'registration_end_date' => 20081015,
1545 'max_participants' => 100,
1546 'event_full_text' => 'Sorry! We are already full',
1549 'is_show_location' => 0,
1552 return $this->callAPISuccess('Event', 'create', $params);
1556 * Function to delete event
1558 * @param int $id ID of the event
1562 function eventDelete($id) {
1566 return $this->callAPISuccess('event', 'delete', $params);
1570 * Function to delete participant
1572 * @param int $participantID
1576 function participantDelete($participantID) {
1578 'id' => $participantID,
1580 return $this->callAPISuccess('Participant', 'delete', $params);
1584 * Function to create participant payment
1586 * @param $participantID
1587 * @param null $contributionID
1588 * @return int $id of created payment
1590 function participantPaymentCreate($participantID, $contributionID = NULL) {
1591 //Create Participant Payment record With Values
1593 'participant_id' => $participantID,
1594 'contribution_id' => $contributionID,
1597 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1598 return $result['id'];
1602 * Function to delete participant payment
1604 * @param int $paymentID
1606 function participantPaymentDelete($paymentID) {
1610 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1614 * Function to add a Location
1617 * @return int location id of created location
1619 function locationAdd($contactID) {
1622 'location_type' => 'New Location Type',
1624 'name' => 'Saint Helier St',
1625 'county' => 'Marin',
1626 'country' => 'United States',
1627 'state_province' => 'Michigan',
1628 'supplemental_address_1' => 'Hallmark Ct',
1629 'supplemental_address_2' => 'Jersey Village',
1634 'contact_id' => $contactID,
1635 'address' => $address,
1636 'location_format' => '2.0',
1637 'location_type' => 'New Location Type',
1640 $result = $this->callAPISuccess('Location', 'create', $params);
1645 * Function to delete Locations of contact
1647 * @params array $pamars parameters
1649 function locationDelete($params) {
1650 $result = $this->callAPISuccess('Location', 'delete', $params);
1654 * Function to add a Location Type
1656 * @param null $params
1657 * @return int location id of created location
1659 function locationTypeCreate($params = NULL) {
1660 if ($params === NULL) {
1662 'name' => 'New Location Type',
1663 'vcard_name' => 'New Location Type',
1664 'description' => 'Location Type for Delete',
1669 $locationType = new CRM_Core_DAO_LocationType();
1670 $locationType->copyValues($params);
1671 $locationType->save();
1672 // clear getfields cache
1673 CRM_Core_PseudoConstant
::flush();
1674 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1675 return $locationType;
1679 * Function to delete a Location Type
1681 * @param int location type id
1683 function locationTypeDelete($locationTypeId) {
1684 $locationType = new CRM_Core_DAO_LocationType();
1685 $locationType->id
= $locationTypeId;
1686 $locationType->delete();
1690 * Function to add a Group
1692 * @params array to add group
1694 * @param array $params
1695 * @return int groupId of created group
1697 function groupCreate($params = array()) {
1698 $params = array_merge(array(
1699 'name' => 'Test Group 1',
1701 'title' => 'New Test Group Created',
1702 'description' => 'New Test Group Created',
1704 'visibility' => 'Public Pages',
1705 'group_type' => array(
1711 $result = $this->callAPISuccess('Group', 'create', $params);
1712 return $result['id'];
1716 * Function to delete a Group
1719 * @internal param int $id
1721 function groupDelete($gid) {
1727 $this->callAPISuccess('Group', 'delete', $params);
1732 * @param array $params
1734 function uFFieldCreate($params = array()) {
1735 $params = array_merge(array(
1737 'field_name' => 'first_name',
1740 'visibility' => 'Public Pages and Listings',
1741 'is_searchable' => '1',
1742 'label' => 'first_name',
1743 'field_type' => 'Individual',
1746 $this->callAPISuccess('uf_field', 'create', $params);
1750 * Function to add a UF Join Entry
1752 * @param null $params
1753 * @return int $id of created UF Join
1755 function ufjoinCreate($params = NULL) {
1756 if ($params === NULL) {
1759 'module' => 'CiviEvent',
1760 'entity_table' => 'civicrm_event',
1766 $result = $this->callAPISuccess('uf_join', 'create', $params);
1771 * Function to delete a UF Join Entry
1773 * @param array with missing uf_group_id
1775 function ufjoinDelete($params = NULL) {
1776 if ($params === NULL) {
1779 'module' => 'CiviEvent',
1780 'entity_table' => 'civicrm_event',
1783 'uf_group_id' => '',
1787 crm_add_uf_join($params);
1791 * Function to create Group for a contact
1793 * @param int $contactId
1795 function contactGroupCreate($contactId) {
1797 'contact_id.1' => $contactId,
1801 $this->callAPISuccess('GroupContact', 'Create', $params);
1805 * Function to delete Group for a contact
1808 * @internal param array $params
1810 function contactGroupDelete($contactId) {
1812 'contact_id.1' => $contactId,
1815 $this->civicrm_api('GroupContact', 'Delete', $params);
1819 * Function to create Activity
1821 * @param null $params
1823 * @internal param int $contactId
1825 function activityCreate($params = NULL) {
1827 if ($params === NULL) {
1828 $individualSourceID = $this->individualCreate();
1830 $contactParams = array(
1831 'first_name' => 'Julia',
1832 'Last_name' => 'Anderson',
1834 'email' => 'julia_anderson@civicrm.org',
1835 'contact_type' => 'Individual',
1838 $individualTargetID = $this->individualCreate($contactParams);
1841 'source_contact_id' => $individualSourceID,
1842 'target_contact_id' => array($individualTargetID),
1843 'assignee_contact_id' => array($individualTargetID),
1844 'subject' => 'Discussion on warm beer',
1845 'activity_date_time' => date('Ymd'),
1846 'duration_hours' => 30,
1847 'duration_minutes' => 20,
1848 'location' => 'Baker Street',
1849 'details' => 'Lets schedule a meeting',
1851 'activity_name' => 'Meeting',
1855 $result = $this->callAPISuccess('Activity', 'create', $params);
1857 $result['target_contact_id'] = $individualTargetID;
1858 $result['assignee_contact_id'] = $individualTargetID;
1863 * Function to create an activity type
1865 * @params array $params parameters
1867 function activityTypeCreate($params) {
1868 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1873 * Function to delete activity type
1875 * @params Integer $activityTypeId id of the activity type
1877 function activityTypeDelete($activityTypeId) {
1878 $params['activity_type_id'] = $activityTypeId;
1879 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1884 * Function to create custom group
1886 * @param array $params
1888 * @internal param string $className
1889 * @internal param string $title name of custom group
1891 function customGroupCreate($params = array()) {
1893 'title' => 'new custom group',
1894 'extends' => 'Contact',
1896 'style' => 'Inline',
1900 $params = array_merge($defaults, $params);
1902 if (strlen($params['title']) > 13) {
1903 $params['title'] = substr($params['title'], 0, 13);
1906 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1907 $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1909 return $this->callAPISuccess('custom_group', 'create', $params);
1913 * existing function doesn't allow params to be over-ridden so need a new one
1914 * this one allows you to only pass in the params you want to change
1916 function CustomGroupCreateByParams($params = array()) {
1918 'title' => "API Custom Group",
1919 'extends' => 'Contact',
1921 'style' => 'Inline',
1924 $params = array_merge($defaults, $params);
1925 return $this->callAPISuccess('custom_group', 'create', $params);
1929 * Create custom group with multi fields
1931 function CustomGroupMultipleCreateByParams($params = array()) {
1936 $params = array_merge($defaults, $params);
1937 return $this->CustomGroupCreateByParams($params);
1941 * Create custom group with multi fields
1943 function CustomGroupMultipleCreateWithFields($params = array()) {
1944 // also need to pass on $params['custom_field'] if not set but not in place yet
1946 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1947 $ids['custom_group_id'] = $customGroup['id'];
1949 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1951 $ids['custom_field_id'][] = $customField['id'];
1953 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1954 $ids['custom_field_id'][] = $customField['id'];
1956 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1957 $ids['custom_field_id'][] = $customField['id'];
1963 * Create a custom group with a single text custom field. See
1964 * participant:testCreateWithCustom for how to use this
1966 * @param string $function __FUNCTION__
1968 * @internal param string $file __FILE__
1970 * @return array $ids ids of created objects
1972 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1973 $params = array('title' => $function);
1974 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1975 $params['extends'] = $entity ?
$entity : 'Contact';
1976 $customGroup = $this->CustomGroupCreate($params);
1977 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1978 CRM_Core_PseudoConstant
::flush();
1980 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1984 * Function to delete custom group
1986 * @param int $customGroupID
1990 function customGroupDelete($customGroupID) {
1991 $params['id'] = $customGroupID;
1992 return $this->callAPISuccess('custom_group', 'delete', $params);
1996 * Function to create custom field
1998 * @param array $params (custom_group_id) is required
2000 * @internal param string $name name of custom field
2001 * @internal param int $apiversion API version to use
2003 function customFieldCreate($params) {
2004 $params = array_merge(array(
2005 'label' => 'Custom Field',
2006 'data_type' => 'String',
2007 'html_type' => 'Text',
2008 'is_searchable' => 1,
2010 'default_value' => 'defaultValue',
2013 $result = $this->callAPISuccess('custom_field', 'create', $params);
2015 if ($result['is_error'] == 0 && isset($result['id'])) {
2016 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2017 // force reset of enabled components to help grab custom fields
2018 CRM_Core_Component
::getEnabledComponents(1);
2024 * Function to delete custom field
2026 * @param int $customFieldID
2030 function customFieldDelete($customFieldID) {
2032 $params['id'] = $customFieldID;
2033 return $this->callAPISuccess('custom_field', 'delete', $params);
2037 * Function to create note
2039 * @params array $params name-value pair for an event
2042 * @return array $note
2044 function noteCreate($cId) {
2046 'entity_table' => 'civicrm_contact',
2047 'entity_id' => $cId,
2048 'note' => 'hello I am testing Note',
2049 'contact_id' => $cId,
2050 'modified_date' => date('Ymd'),
2051 'subject' => 'Test Note',
2054 return $this->callAPISuccess('Note', 'create', $params);
2058 * Enable CiviCampaign Component
2060 function enableCiviCampaign() {
2061 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2062 // force reload of config object
2063 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2064 //flush cache by calling with reset
2065 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2069 * Create test generated example in api/v3/examples.
2070 * To turn this off (e.g. on the server) set
2071 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2072 * in your settings file
2073 * @param array $params array as passed to civicrm_api function
2074 * @param array $result array as received from the civicrm_api function
2075 * @param string $function calling function - generally __FUNCTION__
2076 * @param string $filename called from file - generally __FILE__
2077 * @param string $description descriptive text for the example file
2078 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2079 * @param string $action - optional action - otherwise taken from function name
2081 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2082 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2085 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2086 //todo - this is a bit cludgey
2087 if (empty($action)) {
2088 if (strstr($function, 'Create')) {
2089 $action = empty($action) ?
'create' : $action;
2090 $entityAction = 'Create';
2092 elseif (strstr($function, 'GetSingle')) {
2093 $action = empty($action) ?
'getsingle' : $action;
2094 $entityAction = 'GetSingle';
2096 elseif (strstr($function, 'GetValue')) {
2097 $action = empty($action) ?
'getvalue' : $action;
2098 $entityAction = 'GetValue';
2100 elseif (strstr($function, 'GetCount')) {
2101 $action = empty($action) ?
'getcount' : $action;
2102 $entityAction = 'GetCount';
2104 elseif (strstr($function, 'GetFields')) {
2105 $action = empty($action) ?
'getfields' : $action;
2106 $entityAction = 'GetFields';
2108 elseif (strstr($function, 'GetList')) {
2109 $action = empty($action) ?
'getlist' : $action;
2110 $entityAction = 'GetList';
2112 elseif (strstr($function, 'GetActions')) {
2113 $action = empty($action) ?
'getactions' : $action;
2114 $entityAction = 'GetActions';
2116 elseif (strstr($function, 'Get')) {
2117 $action = empty($action) ?
'get' : $action;
2118 $entityAction = 'Get';
2120 elseif (strstr($function, 'Delete')) {
2121 $action = empty($action) ?
'delete' : $action;
2122 $entityAction = 'Delete';
2124 elseif (strstr($function, 'Update')) {
2125 $action = empty($action) ?
'update' : $action;
2126 $entityAction = 'Update';
2128 elseif (strstr($function, 'Subscribe')) {
2129 $action = empty($action) ?
'subscribe' : $action;
2130 $entityAction = 'Subscribe';
2132 elseif (strstr($function, 'Submit')) {
2133 $action = empty($action) ?
'submit' : $action;
2134 $entityAction = 'Submit';
2136 elseif (strstr($function, 'Apply')) {
2137 $action = empty($action) ?
'apply' : $action;
2138 $entityAction = 'Apply';
2140 elseif (strstr($function, 'Replace')) {
2141 $action = empty($action) ?
'replace' : $action;
2142 $entityAction = 'Replace';
2146 $entityAction = ucwords($action);
2149 $this->tidyExampleResult($result);
2150 if(isset($params['version'])) {
2151 unset($params['version']);
2153 // a cleverer person than me would do it in a single regex
2154 if (strstr($entity, 'UF')) {
2155 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2158 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2160 $smarty = CRM_Core_Smarty
::singleton();
2161 $smarty->assign('testfunction', $function);
2162 $function = $fnPrefix . "_" . strtolower($action);
2163 $smarty->assign('function', $function);
2164 $smarty->assign('fnPrefix', $fnPrefix);
2165 $smarty->assign('params', $params);
2166 $smarty->assign('entity', $entity);
2167 $smarty->assign('filename', basename($filename));
2168 $smarty->assign('description', $description);
2169 $smarty->assign('result', $result);
2171 $smarty->assign('action', $action);
2172 if (empty($subfile)) {
2173 $subfile = $entityAction;
2175 if (file_exists('../tests/templates/documentFunction.tpl')) {
2176 if (!is_dir("../api/v3/examples/$entity")) {
2177 mkdir("../api/v3/examples/$entity");
2179 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2180 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2186 * Tidy up examples array so that fields that change often ..don't
2187 * and debug related fields are unset
2191 * @internal param array $params
2193 function tidyExampleResult(&$result){
2194 if(!is_array($result)) {
2197 $fieldsToChange = array(
2198 'hash' => '67eac7789eaee00',
2199 'modified_date' => '2012-11-14 16:02:35',
2200 'created_date' => '2013-07-28 08:49:19',
2201 'create_date' => '20120130621222105',
2202 'application_received_date' => '20130728084957',
2203 'in_date' => '2013-07-28 08:50:19',
2204 'scheduled_date' => '20130728085413',
2205 'approval_date' => '20130728085413',
2206 'pledge_start_date_high' => '20130726090416',
2207 'start_date' => '2013-07-29 00:00:00',
2208 'event_start_date' => '2013-07-29 00:00:00',
2209 'end_date' => '2013-08-04 00:00:00',
2210 'event_end_date' => '2013-08-04 00:00:00',
2211 'decision_date' => '20130805000000',
2214 $keysToUnset = array('xdebug', 'undefined_fields',);
2215 foreach ($keysToUnset as $unwantedKey) {
2216 if(isset($result[$unwantedKey])) {
2217 unset($result[$unwantedKey]);
2220 if (isset($result['values'])) {
2221 if(!is_array($result['values'])) {
2224 $resultArray = &$result['values'];
2226 elseif(is_array($result)) {
2227 $resultArray = &$result;
2233 foreach ($resultArray as $index => &$values) {
2234 if(!is_array($values)) {
2237 foreach($values as $key => &$value) {
2238 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2239 if(isset($value['is_error'])) {
2240 // we have a std nested result format
2241 $this->tidyExampleResult($value);
2244 foreach ($value as &$nestedResult) {
2245 // this is an alternative syntax for nested results a keyed array of results
2246 $this->tidyExampleResult($nestedResult);
2250 if(in_array($key, $keysToUnset)) {
2251 unset($values[$key]);
2254 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2255 $value = $fieldsToChange[$key];
2257 if(is_string($value)) {
2258 $value = addslashes($value);
2265 * Function to delete note
2267 * @params int $noteID
2270 function noteDelete($params) {
2271 return $this->callAPISuccess('Note', 'delete', $params);
2275 * Function to create custom field with Option Values
2277 * @param array $customGroup
2278 * @param string $name name of custom field
2282 function customFieldOptionValueCreate($customGroup, $name) {
2283 $fieldParams = array(
2284 'custom_group_id' => $customGroup['id'],
2285 'name' => 'test_custom_group',
2286 'label' => 'Country',
2287 'html_type' => 'Select',
2288 'data_type' => 'String',
2291 'is_searchable' => 0,
2295 $optionGroup = array(
2297 'name' => 'option_group1',
2298 'label' => 'option_group_label1',
2301 $optionValue = array(
2302 'option_label' => array('Label1', 'Label2'),
2303 'option_value' => array('value1', 'value2'),
2304 'option_name' => array($name . '_1', $name . '_2'),
2305 'option_weight' => array(1, 2),
2306 'option_status' => 1,
2309 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2311 return $this->callAPISuccess('custom_field', 'create', $params);
2319 function confirmEntitiesDeleted($entities) {
2320 foreach ($entities as $entity) {
2322 $result = $this->callAPISuccess($entity, 'Get', array());
2323 if ($result['error'] == 1 ||
$result['count'] > 0) {
2324 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2331 * @param $tablesToTruncate
2332 * @param bool $dropCustomValueTables
2334 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2335 if ($dropCustomValueTables) {
2336 $tablesToTruncate[] = 'civicrm_custom_group';
2337 $tablesToTruncate[] = 'civicrm_custom_field';
2340 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2342 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2343 foreach ($tablesToTruncate as $table) {
2344 $sql = "TRUNCATE TABLE $table";
2345 CRM_Core_DAO
::executeQuery($sql);
2347 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2349 if ($dropCustomValueTables) {
2350 $dbName = self
::getDBName();
2352 SELECT TABLE_NAME as tableName
2353 FROM INFORMATION_SCHEMA.TABLES
2354 WHERE TABLE_SCHEMA = '{$dbName}'
2355 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2358 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2359 while ($tableDAO->fetch()) {
2360 $sql = "DROP TABLE {$tableDAO->tableName}";
2361 CRM_Core_DAO
::executeQuery($sql);
2367 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2369 function quickCleanUpFinancialEntities() {
2370 $tablesToTruncate = array(
2371 'civicrm_contribution',
2372 'civicrm_contribution_soft',
2373 'civicrm_financial_trxn',
2374 'civicrm_financial_item',
2375 'civicrm_contribution_recur',
2376 'civicrm_line_item',
2377 'civicrm_contribution_page',
2378 'civicrm_payment_processor',
2379 'civicrm_entity_financial_trxn',
2380 'civicrm_membership',
2381 'civicrm_membership_type',
2382 'civicrm_membership_payment',
2383 'civicrm_membership_log',
2384 'civicrm_membership_block',
2386 'civicrm_participant',
2387 'civicrm_participant_payment',
2389 'civicrm_price_set_entity',
2390 'civicrm_price_field_value',
2391 'civicrm_price_field',
2393 $this->quickCleanup($tablesToTruncate);
2394 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2395 $this->restoreDefaultPriceSetConfig();
2397 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2400 function restoreDefaultPriceSetConfig() {
2401 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field` (`id`, `price_set_id`, `name`, `label`, `html_type`, `is_enter_qty`, `help_pre`, `help_post`, `weight`, `is_display_amounts`, `options_per_line`, `is_active`, `is_required`, `active_on`, `expire_on`, `javascript`, `visibility_id`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', 'Text', 0, NULL, NULL, 1, 1, 1, 1, 1, NULL, NULL, NULL, 1)");
2402 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2405 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2406 * Default behaviour is to also delete the entity
2407 * @param array $params params array to check agains
2408 * @param int $id id of the entity concerned
2409 * @param string $entity name of entity concerned (e.g. membership)
2410 * @param bool $delete should the entity be deleted as part of this check
2411 * @param string $errorText text to print on error
2418 * @param int $delete
2419 * @param string $errorText
2423 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2425 $result = $this->callAPISuccessGetSingle($entity, array(
2430 $this->callAPISuccess($entity, 'Delete', array(
2434 $dateFields = $keys = $dateTimeFields = array();
2435 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2436 foreach ($fields['values'] as $field => $settings) {
2437 if (array_key_exists($field, $result)) {
2438 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2441 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2443 $type = CRM_Utils_Array
::value('type', $settings);
2444 if ($type == CRM_Utils_Type
::T_DATE
) {
2445 $dateFields[] = $settings['name'];
2446 // we should identify both real names & unique names as dates
2447 if($field != $settings['name']) {
2448 $dateFields[] = $field;
2451 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2452 $dateTimeFields[] = $settings['name'];
2453 // we should identify both real names & unique names as dates
2454 if($field != $settings['name']) {
2455 $dateTimeFields[] = $field;
2460 if (strtolower($entity) == 'contribution') {
2461 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2462 // this is not returned in id format
2463 unset($params['payment_instrument_id']);
2464 $params['contribution_source'] = $params['source'];
2465 unset($params['source']);
2468 foreach ($params as $key => $value) {
2469 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2472 if (in_array($key, $dateFields)) {
2473 $value = date('Y-m-d', strtotime($value));
2474 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2476 if (in_array($key, $dateTimeFields)) {
2477 $value = date('Y-m-d H:i:s', strtotime($value));
2478 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2480 $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);
2485 * Function to get formatted values in the actual and expected result
2486 * @param array $actual actual calculated values
2487 * @param array $expected expected values
2490 function checkArrayEquals(&$actual, &$expected) {
2491 self
::unsetId($actual);
2492 self
::unsetId($expected);
2493 $this->assertEquals($actual, $expected);
2497 * Function to unset the key 'id' from the array
2498 * @param array $unformattedArray The array from which the 'id' has to be unset
2501 static function unsetId(&$unformattedArray) {
2502 $formattedArray = array();
2503 if (array_key_exists('id', $unformattedArray)) {
2504 unset($unformattedArray['id']);
2506 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2507 foreach ($unformattedArray['values'] as $key => $value) {
2508 if (is_Array($value)) {
2509 foreach ($value as $k => $v) {
2515 elseif ($key == 'id') {
2516 $unformattedArray[$key];
2518 $formattedArray = array($value);
2520 $unformattedArray['values'] = $formattedArray;
2525 * Helper to enable/disable custom directory support
2527 * @param array $customDirs with members:
2528 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2529 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2531 function customDirectories($customDirs) {
2532 require_once 'CRM/Core/Config.php';
2533 $config = CRM_Core_Config
::singleton();
2535 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2536 unset($config->customPHPPathDir
);
2538 elseif ($customDirs['php_path'] === TRUE) {
2539 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2542 $config->customPHPPathDir
= $php_path;
2545 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2546 unset($config->customTemplateDir
);
2548 elseif ($customDirs['template_path'] === TRUE) {
2549 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2552 $config->customTemplateDir
= $template_path;
2557 * Generate a temporary folder
2559 * @param string $prefix
2560 * @return string $string
2562 function createTempDir($prefix = 'test-') {
2563 $tempDir = CRM_Utils_File
::tempdir($prefix);
2564 $this->tempDirs
[] = $tempDir;
2568 function cleanTempDirs() {
2569 if (!is_array($this->tempDirs
)) {
2570 // fix test errors where this is not set
2573 foreach ($this->tempDirs
as $tempDir) {
2574 if (is_dir($tempDir)) {
2575 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2581 * Temporarily replace the singleton extension with a different one
2583 function setExtensionSystem(CRM_Extension_System
$system) {
2584 if ($this->origExtensionSystem
== NULL) {
2585 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2587 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2590 function unsetExtensionSystem() {
2591 if ($this->origExtensionSystem
!== NULL) {
2592 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2593 $this->origExtensionSystem
= NULL;
2598 * Temporarily alter the settings-metadata to add a mock setting.
2600 * WARNING: The setting metadata will disappear on the next cache-clear.
2605 function setMockSettingsMetaData($extras) {
2606 CRM_Core_BAO_Setting
::$_cache = array();
2607 $this->callAPISuccess('system','flush', array());
2608 CRM_Core_BAO_Setting
::$_cache = array();
2610 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2611 $metadata = array_merge($metadata, $extras);
2614 $fields = $this->callAPISuccess('setting', 'getfields', array());
2615 foreach ($extras as $key => $spec) {
2616 $this->assertNotEmpty($spec['title']);
2617 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2624 function financialAccountDelete($name) {
2625 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2626 $financialAccount->name
= $name;
2627 if($financialAccount->find(TRUE)) {
2628 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2629 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2630 $entityFinancialType->delete();
2631 $financialAccount->delete();
2636 * Use $ids as an instruction to do test cleanup
2638 function deleteFromIDSArray() {
2639 foreach ($this->ids
as $entity => $ids) {
2640 foreach ($ids as $id) {
2641 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2647 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2648 * (NB unclear if this is still required)
2650 function _sethtmlGlobals() {
2651 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2652 'required' => array(
2653 'html_quickform_rule_required',
2654 'HTML/QuickForm/Rule/Required.php'
2656 'maxlength' => array(
2657 'html_quickform_rule_range',
2658 'HTML/QuickForm/Rule/Range.php'
2660 'minlength' => array(
2661 'html_quickform_rule_range',
2662 'HTML/QuickForm/Rule/Range.php'
2664 'rangelength' => array(
2665 'html_quickform_rule_range',
2666 'HTML/QuickForm/Rule/Range.php'
2669 'html_quickform_rule_email',
2670 'HTML/QuickForm/Rule/Email.php'
2673 'html_quickform_rule_regex',
2674 'HTML/QuickForm/Rule/Regex.php'
2676 'lettersonly' => array(
2677 'html_quickform_rule_regex',
2678 'HTML/QuickForm/Rule/Regex.php'
2680 'alphanumeric' => array(
2681 'html_quickform_rule_regex',
2682 'HTML/QuickForm/Rule/Regex.php'
2685 'html_quickform_rule_regex',
2686 'HTML/QuickForm/Rule/Regex.php'
2688 'nopunctuation' => array(
2689 'html_quickform_rule_regex',
2690 'HTML/QuickForm/Rule/Regex.php'
2693 'html_quickform_rule_regex',
2694 'HTML/QuickForm/Rule/Regex.php'
2696 'callback' => array(
2697 'html_quickform_rule_callback',
2698 'HTML/QuickForm/Rule/Callback.php'
2701 'html_quickform_rule_compare',
2702 'HTML/QuickForm/Rule/Compare.php'
2705 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2706 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2708 'HTML/QuickForm/group.php',
2709 'HTML_QuickForm_group'
2712 'HTML/QuickForm/hidden.php',
2713 'HTML_QuickForm_hidden'
2716 'HTML/QuickForm/reset.php',
2717 'HTML_QuickForm_reset'
2719 'checkbox' => array(
2720 'HTML/QuickForm/checkbox.php',
2721 'HTML_QuickForm_checkbox'
2724 'HTML/QuickForm/file.php',
2725 'HTML_QuickForm_file'
2728 'HTML/QuickForm/image.php',
2729 'HTML_QuickForm_image'
2731 'password' => array(
2732 'HTML/QuickForm/password.php',
2733 'HTML_QuickForm_password'
2736 'HTML/QuickForm/radio.php',
2737 'HTML_QuickForm_radio'
2740 'HTML/QuickForm/button.php',
2741 'HTML_QuickForm_button'
2744 'HTML/QuickForm/submit.php',
2745 'HTML_QuickForm_submit'
2748 'HTML/QuickForm/select.php',
2749 'HTML_QuickForm_select'
2751 'hiddenselect' => array(
2752 'HTML/QuickForm/hiddenselect.php',
2753 'HTML_QuickForm_hiddenselect'
2756 'HTML/QuickForm/text.php',
2757 'HTML_QuickForm_text'
2759 'textarea' => array(
2760 'HTML/QuickForm/textarea.php',
2761 'HTML_QuickForm_textarea'
2763 'fckeditor' => array(
2764 'HTML/QuickForm/fckeditor.php',
2765 'HTML_QuickForm_FCKEditor'
2768 'HTML/QuickForm/tinymce.php',
2769 'HTML_QuickForm_TinyMCE'
2771 'dojoeditor' => array(
2772 'HTML/QuickForm/dojoeditor.php',
2773 'HTML_QuickForm_dojoeditor'
2776 'HTML/QuickForm/link.php',
2777 'HTML_QuickForm_link'
2779 'advcheckbox' => array(
2780 'HTML/QuickForm/advcheckbox.php',
2781 'HTML_QuickForm_advcheckbox'
2784 'HTML/QuickForm/date.php',
2785 'HTML_QuickForm_date'
2788 'HTML/QuickForm/static.php',
2789 'HTML_QuickForm_static'
2792 'HTML/QuickForm/header.php',
2793 'HTML_QuickForm_header'
2796 'HTML/QuickForm/html.php',
2797 'HTML_QuickForm_html'
2799 'hierselect' => array(
2800 'HTML/QuickForm/hierselect.php',
2801 'HTML_QuickForm_hierselect'
2803 'autocomplete' => array(
2804 'HTML/QuickForm/autocomplete.php',
2805 'HTML_QuickForm_autocomplete'
2808 'HTML/QuickForm/xbutton.php',
2809 'HTML_QuickForm_xbutton'
2811 'advmultiselect' => array(
2812 'HTML/QuickForm/advmultiselect.php',
2813 'HTML_QuickForm_advmultiselect'
2819 * Set up an acl allowing contact to see 2 specified groups
2820 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2822 * You need to have pre-created these groups & created the user e.g
2823 * $this->createLoggedInUser();
2824 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2825 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2828 function setupACL() {
2830 $_REQUEST = $this->_params
;
2832 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2833 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2834 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2835 'label' => 'pick me',
2840 CRM_Core_DAO
::executeQuery("
2841 TRUNCATE civicrm_acl_cache
2844 CRM_Core_DAO
::executeQuery("
2845 TRUNCATE civicrm_acl_contact_cache
2849 CRM_Core_DAO
::executeQuery("
2850 INSERT INTO civicrm_acl_entity_role (
2851 `acl_role_id`, `entity_table`, `entity_id`
2852 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2855 CRM_Core_DAO
::executeQuery("
2856 INSERT INTO civicrm_acl (
2857 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2860 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2864 CRM_Core_DAO
::executeQuery("
2865 INSERT INTO civicrm_acl (
2866 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2869 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2872 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2873 $this->callAPISuccess('group_contact', 'create', array(
2874 'group_id' => $this->_permissionedGroup
,
2875 'contact_id' => $this->_loggedInUser
,
2878 CRM_ACL_BAO_Cache
::resetCache();
2879 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2880 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2884 * alter default price set so that the field numbers are not all 1 (hiding errors)
2886 function offsetDefaultPriceSet() {
2887 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2888 $firstID = $contributionPriceSet['id'];
2889 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2890 unset($contributionPriceSet['id']);
2891 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2892 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2893 unset($priceField['id']);
2894 $priceField['price_set_id'] = $newPriceSet['id'];
2895 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2896 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2898 unset($priceFieldValue['id']);
2899 //create some padding to use up ids
2900 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2901 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2902 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2906 * Create an instance of the paypal processor
2907 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2908 * this parent class & we don't have a structure for that yet
2909 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2910 * & the best protection agains that is the functions this class affords
2912 function paymentProcessorCreate($params = array()) {
2913 $params = array_merge(array(
2915 'domain_id' => CRM_Core_Config
::domainID(),
2916 'payment_processor_type_id' => 'PayPal',
2920 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2921 'password' => '1183377788',
2922 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2923 'url_site' => 'https://www.sandbox.paypal.com/',
2924 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2925 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2926 'class_name' => 'Payment_PayPalImpl',
2927 'billing_mode' => 3,
2928 'financial_type_id' => 1,
2931 if(!is_numeric($params['payment_processor_type_id'])) {
2932 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2934 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2935 'name' => $params['payment_processor_type_id'],
2939 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2940 return $result['id'];
2944 * Set up initial recurring payment allowing subsequent IPN payments
2946 function setupRecurringPaymentProcessorTransaction() {
2947 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
2948 'contact_id' => $this->_contactID
,
2951 'installments' => 5,
2952 'frequency_unit' => 'Month',
2953 'frequency_interval' => 1,
2954 'invoice_id' => $this->_invoiceID
,
2955 'contribution_status_id' => 2,
2956 'processor_id' => $this->_paymentProcessorID
,
2957 'api.contribution.create' => array(
2958 'total_amount' => '200',
2959 'invoice_id' => $this->_invoiceID
,
2960 'financial_type_id' => 1,
2961 'contribution_status_id' => 'Pending',
2962 'contact_id' => $this->_contactID
,
2963 'contribution_page_id' => $this->_contributionPageID
,
2964 'payment_processor_id' => $this->_paymentProcessorID
,
2967 $this->_contributionRecurID
= $contributionRecur['id'];
2968 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2972 * we don't have a good way to set up a recurring contribution with a membership so let's just do one then alter it
2974 function setupMembershipRecurringPaymentProcessorTransaction() {
2975 $this->setupRecurringPaymentProcessorTransaction();
2976 $this->ids
['membership_type'] = $this->membershipTypeCreate();
2977 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2978 'contact_id' => $this->_contactID
,
2979 'membership_type_id' => $this->ids
['membership_type'],
2980 'contribution_recur_id' => $this->_contributionRecurID
,
2981 'api.membership_payment.create' => array('contribution_id' => $this->_contributionID
),
2982 'format.only_id' => TRUE,
2984 CRM_Core_DAO
::executeQuery(
2985 "UPDATE civicrm_line_item SET entity_table = 'civicrm_membership', entity_id = {$this->ids['membership']}
2986 WHERE entity_id = {$this->_contributionID} AND entity_table = 'civicrm_contribution'"
2995 function CiviUnitTestCase_fatalErrorHandler($message) {
2996 throw new Exception("{$message['message']}: {$message['code']}");