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();
164 protected function runTest() {
166 return parent
::runTest();
167 } catch (PEAR_Exception
$e) {
168 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
169 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
176 function requireDBReset() {
177 return $this->DBResetRequired
;
183 static function getDBName() {
184 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
189 * Create database connection for this instance
191 * Initialize the test database if it hasn't been initialized
193 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
195 protected function getConnection() {
196 $dbName = self
::$_dbName;
197 if (!self
::$dbInit) {
198 $dbName = self
::getDBName();
200 // install test database
201 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
203 static::_populateDB(FALSE, $this);
205 self
::$dbInit = TRUE;
207 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
211 * Required implementation of abstract method
213 protected function getDataSet() {
217 * @param bool $perClass
218 * @param null $object
219 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
221 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
223 if ($perClass ||
$object == NULL) {
227 $dbreset = $object->requireDBReset();
230 if (self
::$populateOnce ||
!$dbreset) {
233 self
::$populateOnce = NULL;
235 $dbName = self
::getDBName();
236 $pdo = self
::$utils->pdo
;
237 // only consider real tables and not views
238 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
239 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
241 $truncates = array();
243 foreach ($tables as $table) {
245 if (substr($table['table_name'], 0, 4) == 'log_') {
249 // don't change list of installed extensions
250 if ($table['table_name'] == 'civicrm_extension') {
254 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
255 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
258 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
264 "SET foreign_key_checks = 0",
265 // SQL mode needs to be strict, that's our standard
266 "SET SQL_MODE='STRICT_ALL_TABLES';",
267 "SET global innodb_flush_log_at_trx_commit = 2;",
269 $queries = array_merge($queries, $truncates);
270 $queries = array_merge($queries, $drops);
271 foreach ($queries as $query) {
272 if (self
::$utils->do_query($query) === FALSE) {
273 // failed to create test database
274 echo "failed to create test db.";
279 // initialize test database
280 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
281 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
282 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
284 $query2 = file_get_contents($sql_file2);
285 $query3 = file_get_contents($sql_file3);
286 $query4 = file_get_contents($sql_file4);
287 if (self
::$utils->do_query($query2) === FALSE) {
288 echo "Cannot load civicrm_data.mysql. Aborting.";
291 if (self
::$utils->do_query($query3) === FALSE) {
292 echo "Cannot load test_data.mysql. Aborting.";
295 if (self
::$utils->do_query($query4) === FALSE) {
296 echo "Cannot load test_data.mysql. Aborting.";
300 // done with all the loading, get transactions back
301 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
302 echo "Cannot set global? Huh?";
306 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
307 echo "Cannot get foreign keys back? Huh?";
311 unset($query, $query2, $query3);
314 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
316 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
317 'CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'
323 public static function setUpBeforeClass() {
324 static::_populateDB(TRUE);
326 // also set this global hack
327 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
329 $env = new CRM_Utils_Check_Env();
330 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
334 * Common setup functions for all unit tests
336 protected function setUp() {
337 $session = CRM_Core_Session
::singleton();
338 $session->set('userID', NULL);
340 CRM_Utils_Hook
::singleton(TRUE);
341 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
342 // Use a temporary file for STDIN
343 $GLOBALS['stdin'] = tmpfile();
344 if ($GLOBALS['stdin'] === FALSE) {
345 echo "Couldn't open temporary file\n";
349 // Get and save a connection to the database
350 $this->_dbconn
= $this->getConnection();
352 // reload database before each test
353 // $this->_populateDB();
355 // "initialize" CiviCRM to avoid problems when running single tests
356 // FIXME: look at it closer in second stage
358 // initialize the object once db is loaded
359 CRM_Core_Config
::$_mail = NULL;
360 $config = CRM_Core_Config
::singleton();
362 // when running unit tests, use mockup user framework
363 $config->setUserFramework('UnitTests');
365 // also fix the fatal error handler to throw exceptions,
367 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
369 // enable backtrace to get meaningful errors
370 $config->backtrace
= 1;
372 // disable any left-over test extensions
373 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
375 // reset all the caches
376 CRM_Utils_System
::flushCache();
378 // clear permissions stub to not check permissions
379 $config = CRM_Core_Config
::singleton();
380 $config->userPermissionClass
->permissions
= NULL;
382 //flush component settings
383 CRM_Core_Component
::getEnabledComponents(TRUE);
385 if ($this->_eNoticeCompliant
) {
386 error_reporting(E_ALL
);
389 error_reporting(E_ALL
& ~E_NOTICE
);
391 $this->_sethtmlGlobals();
395 * Read everything from the datasets directory and insert into the db
397 public function loadAllFixtures() {
398 $fixturesDir = __DIR__
. '/../../fixtures';
400 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
402 $xmlFiles = glob($fixturesDir . '/*.xml');
403 foreach ($xmlFiles as $xmlFixture) {
404 $op = new PHPUnit_Extensions_Database_Operation_Insert();
405 $dataset = $this->createXMLDataSet($xmlFixture);
406 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
407 $op->execute($this->_dbconn
, $dataset);
410 $yamlFiles = glob($fixturesDir . '/*.yaml');
411 foreach ($yamlFiles as $yamlFixture) {
412 $op = new PHPUnit_Extensions_Database_Operation_Insert();
413 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
414 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
415 $op->execute($this->_dbconn
, $dataset);
418 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
422 * Emulate a logged in user since certain functions use that
423 * value to store a record in the DB (like activity)
426 public function createLoggedInUser() {
428 'first_name' => 'Logged In',
429 'last_name' => 'User ' . rand(),
430 'contact_type' => 'Individual',
432 $contactID = $this->individualCreate($params);
434 $session = CRM_Core_Session
::singleton();
435 $session->set('userID', $contactID);
438 public function cleanDB() {
439 self
::$populateOnce = NULL;
440 $this->DBResetRequired
= TRUE;
442 $this->_dbconn
= $this->getConnection();
443 static::_populateDB();
444 $this->tempDirs
= array();
448 * Common teardown functions for all unit tests
450 protected function tearDown() {
451 error_reporting(E_ALL
& ~E_NOTICE
);
452 $session = CRM_Core_Session
::singleton();
453 $session->set('userID', NULL);
454 $tablesToTruncate = array('civicrm_contact');
455 $this->quickCleanup($tablesToTruncate);
456 $this->cleanTempDirs();
457 $this->unsetExtensionSystem();
458 CRM_Core_Transaction
::forceRollbackIfEnabled();
459 \Civi\Core\Transaction\Manager
::singleton(TRUE);
463 * FIXME: Maybe a better way to do it
465 function foreignKeyChecksOff() {
466 self
::$utils = new Utils($GLOBALS['mysql_host'],
467 $GLOBALS['mysql_port'],
468 $GLOBALS['mysql_user'],
469 $GLOBALS['mysql_pass']
471 $dbName = self
::getDBName();
472 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
473 if (self
::$utils->do_query($query) === FALSE) {
475 echo 'Cannot set foreign_key_checks = 0';
481 function foreignKeyChecksOn() {
482 // FIXME: might not be needed if previous fixme implemented
486 * Generic function to compare expected values after an api call to retrieved
489 * @daoName string DAO Name of object we're evaluating.
490 * @id int Id of object
491 * @match array Associative array of field name => expected value. Empty if asserting
492 * that a DELETE occurred
493 * @delete boolean True if we're checking that a DELETE action occurred.
495 function assertDBState($daoName, $id, $match, $delete = FALSE) {
497 // adding this here since developers forget to check for an id
498 // and hence we get the first value in the db
499 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
502 $object = new $daoName();
506 // If we're asserting successful record deletion, make sure object is NOT found.
508 if ($object->find(TRUE)) {
509 $this->fail("Object not deleted by delete operation: $daoName, $id");
514 // Otherwise check matches of DAO field values against expected values in $match.
515 if ($object->find(TRUE)) {
516 $fields = & $object->fields();
517 foreach ($fields as $name => $value) {
518 $dbName = $value['name'];
519 if (isset($match[$name])) {
521 $this->assertEquals($object->$dbName, $match[$name]);
523 elseif (isset($match[$dbName])) {
525 $this->assertEquals($object->$dbName, $match[$dbName]);
530 $this->fail("Could not retrieve object: $daoName, $id");
533 $matchSize = count($match);
534 if ($verifiedCount != $matchSize) {
535 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
539 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
541 * @param string $daoName
542 * @param $searchValue
543 * @param $returnColumn
544 * @param $searchColumn
547 * @return null|string
548 * @throws PHPUnit_Framework_AssertionFailedError
550 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
551 if (empty($searchValue)) {
552 $this->fail("empty value passed to assertDBNotNull");
554 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
555 $this->assertNotNull($value, $message);
560 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
562 * @param string $daoName
563 * @param $searchValue
564 * @param $returnColumn
565 * @param $searchColumn
568 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
569 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
570 $this->assertNull($value, $message);
573 // Request a record from the DB by id. Success if row not found.
575 * @param string $daoName
577 * @param null $message
579 function assertDBRowNotExist($daoName, $id, $message = NULL) {
580 $message = $message ?
$message : "$daoName (#$id) should not exist";
581 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
582 $this->assertNull($value, $message);
585 // Request a record from the DB by id. Success if row not found.
587 * @param string $daoName
589 * @param null $message
591 function assertDBRowExist($daoName, $id, $message = NULL) {
592 $message = $message ?
$message : "$daoName (#$id) should exist";
593 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
594 $this->assertEquals($id, $value, $message);
597 // Compare a single column value in a retrieved DB record to an expected value
599 * @param string $daoName
600 * @param $searchValue
601 * @param $returnColumn
602 * @param $searchColumn
603 * @param $expectedValue
606 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
607 $expectedValue, $message
609 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
610 $this->assertEquals($value, $expectedValue, $message);
613 // Compare all values in a single retrieved DB record to an array of expected values
615 * @param string $daoName
616 * @param array $searchParams
617 * @param $expectedValues
619 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
620 //get the values from db
622 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
624 // compare db values with expected values
625 self
::assertAttributesEquals($expectedValues, $dbValues);
629 * Assert that a SQL query returns a given value
631 * The first argument is an expected value. The remaining arguments are passed
632 * to CRM_Core_DAO::singleValueQuery
634 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
635 * array(1 => array("Whiz", "String")));
637 function assertDBQuery($expected, $query, $params = array(), $message = '') {
638 if ($message) $message .= ': ';
639 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
640 $this->assertEquals($expected, $actual,
641 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
642 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
648 * Assert that two array-trees are exactly equal, notwithstanding
649 * the sorting of keys
651 * @param array $expected
652 * @param array $actual
654 function assertTreeEquals($expected, $actual) {
657 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
658 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
662 $this->assertEquals($e, $a);
666 * Assert that two numbers are approximately equal
668 * @param int|float $expected
669 * @param int|float $actual
670 * @param int|float $tolerance
671 * @param string $message
673 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
674 if ($message === NULL) {
675 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
677 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
681 * @param $expectedValues
682 * @param $actualValues
683 * @param null $message
685 * @throws PHPUnit_Framework_AssertionFailedError
687 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
688 foreach ($expectedValues as $paramName => $paramValue) {
689 if (isset($actualValues[$paramName])) {
690 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
693 $this->fail("Attribute '$paramName' not present in actual array.");
702 function assertArrayKeyExists($key, &$list) {
703 $result = isset($list[$key]) ?
TRUE : FALSE;
704 $this->assertTrue($result, ts("%1 element exists?",
713 function assertArrayValueNotNull($key, &$list) {
714 $this->assertArrayKeyExists($key, $list);
716 $value = isset($list[$key]) ?
$list[$key] : NULL;
717 $this->assertTrue($value,
718 ts("%1 element not null?",
725 * Check that api returned 'is_error' => 0
726 * else provide full message
727 * @param array $apiResult api result
728 * @param string $prefix extra test to add to message
730 function assertAPISuccess($apiResult, $prefix = '') {
731 if (!empty($prefix)) {
734 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
736 if(!empty($apiResult['debug_information'])) {
737 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
739 if(!empty($apiResult['trace'])){
740 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
742 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
746 * Check that api returned 'is_error' => 1
747 * else provide full message
749 * @param array $apiResult api result
750 * @param string $prefix extra test to add to message
751 * @param null $expectedError
753 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
754 if (!empty($prefix)) {
757 if($expectedError && !empty($apiResult['is_error'])){
758 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
760 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
761 $this->assertNotEmpty($apiResult['error_message']);
767 * @param string $message
769 function assertType($expected, $actual, $message = '') {
770 return $this->assertInternalType($expected, $actual, $message);
774 * Check that a deleted item has been deleted
776 function assertAPIDeleted($entity, $id) {
777 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
782 * Check that api returned 'is_error' => 1
783 * else provide full message
784 * @param array $result
786 * @param array $valuesToExclude
787 * @param string $prefix extra test to add to message
789 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
790 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
791 foreach ($valuesToExclude as $value) {
792 if(isset($result[$value])) {
793 unset($result[$value]);
795 if(isset($expected[$value])) {
796 unset($expected[$value]);
799 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
803 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
807 * @param array $params
810 function civicrm_api($entity, $action, $params) {
811 return civicrm_api($entity, $action, $params);
815 * This function exists to wrap api functions
816 * so we can ensure they succeed & throw exceptions without litterering the test with checks
818 * @param string $entity
819 * @param string $action
820 * @param array $params
821 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
822 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
823 * for getsingle the array is compared against an array passed in - the id is not compared (for
828 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
829 $params = array_merge(array(
830 'version' => $this->_apiversion
,
835 switch (strtolower($action)) {
837 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
839 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
841 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
843 $result = $this->civicrm_api($entity, $action, $params);
844 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
849 * This function exists to wrap api getValue function & check the result
850 * so we can ensure they succeed & throw exceptions without litterering the test with checks
851 * There is a type check in this
853 * @param string $entity
854 * @param array $params
855 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
865 function callAPISuccessGetValue($entity, $params, $type = NULL) {
867 'version' => $this->_apiversion
,
870 $result = $this->civicrm_api($entity, 'getvalue', $params);
872 if($type == 'integer'){
873 // api seems to return integers as strings
874 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
877 $this->assertType($type, $result, "returned result should have been of type $type but was " );
884 * This function exists to wrap api getsingle function & check the result
885 * so we can ensure they succeed & throw exceptions without litterering the test with checks
887 * @param string $entity
888 * @param array $params
889 * @param array $checkAgainst - array to compare result against
900 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
902 'version' => $this->_apiversion
,
905 $result = $this->civicrm_api($entity, 'getsingle', $params);
906 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
907 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
910 // @todo - have gone with the fn that unsets id? should we check id?
911 $this->checkArrayEquals($result, $checkAgainst);
917 * This function exists to wrap api getValue function & check the result
918 * so we can ensure they succeed & throw exceptions without litterering the test with checks
919 * There is a type check in this
920 * @param string $entity
921 * @param array $params
925 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
933 function callAPISuccessGetCount($entity, $params, $count = NULL) {
935 'version' => $this->_apiversion
,
938 $result = $this->civicrm_api($entity, 'getcount', $params);
939 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
940 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
943 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
949 * This function exists to wrap api functions
950 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
952 * @param string $entity
953 * @param string $action
954 * @param array $params
955 * @param string $function - pass this in to create a generated example
956 * @param string $file - pass this in to create a generated example
957 * @param string $description
958 * @param string|null $subfile
959 * @param string|null $actionName
962 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
963 $params['version'] = $this->_apiversion
;
964 $result = $this->callAPISuccess($entity, $action, $params);
965 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
970 * This function exists to wrap api functions
971 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
972 * @param string $entity
973 * @param string $action
974 * @param array $params
975 * @param string $expectedErrorMessage error
976 * @param null $extraOutput
979 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
980 if (is_array($params)) {
982 'version' => $this->_apiversion
,
985 $result = $this->civicrm_api($entity, $action, $params);
986 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
991 * Create required data based on $this->entity & $this->params
992 * This is just a way to set up the test data for delete & get functions
993 * so the distinction between set
994 * up & tested functions is clearer
996 * @return array api Result
998 public function createTestEntity(){
999 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1003 * Generic function to create Organisation, to be used in test cases
1005 * @param array parameters for civicrm_contact_add api function call
1006 * @param int sequence number if creating multiple organizations
1008 * @return int id of Organisation created
1010 function organizationCreate($params = array(), $seq = 0) {
1014 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1015 return $this->_contactCreate($params);
1019 * Generic function to create Individual, to be used in test cases
1021 * @param array parameters for civicrm_contact_add api function call
1022 * @param int sequence number if creating multiple individuals
1024 * @return int id of Individual created
1026 function individualCreate($params = array(), $seq = 0) {
1027 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1028 return $this->_contactCreate($params);
1032 * Generic function to create Household, to be used in test cases
1034 * @param array parameters for civicrm_contact_add api function call
1035 * @param int sequence number if creating multiple households
1037 * @return int id of Household created
1039 function householdCreate($params = array(), $seq = 0) {
1040 $params = array_merge($this->sampleContact('Household', $seq), $params);
1041 return $this->_contactCreate($params);
1045 * Helper function for getting sample contact properties
1047 * @param enum contact type: Individual, Organization
1048 * @param int sequence number for the values of this type
1050 * @return array properties of sample contact (ie. $params for API call)
1052 function sampleContact($contact_type, $seq = 0) {
1054 'Individual' => array(
1055 // The number of values in each list need to be coprime numbers to not have duplicates
1056 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1057 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1058 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1060 'Organization' => array(
1061 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
1063 'Household' => array(
1064 'household_name' => array('Unit Test household'),
1067 $params = array('contact_type' => $contact_type);
1068 foreach ($samples[$contact_type] as $key => $values) {
1069 $params[$key] = $values[$seq %
sizeof($values)];
1071 if ($contact_type == 'Individual' ) {
1072 $params['email'] = strtolower(
1073 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1075 $params['prefix_id'] = 3;
1076 $params['suffix_id'] = 3;
1082 * Private helper function for calling civicrm_contact_add
1084 * @param array $params for civicrm_contact_add api function call
1088 * @return int id of Household created
1090 private function _contactCreate($params) {
1091 $result = $this->callAPISuccess('contact', 'create', $params);
1092 if (!empty($result['is_error']) ||
empty($result['id'])) {
1093 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1095 return $result['id'];
1099 * @param int $contactID
1103 function contactDelete($contactID) {
1106 'skip_undelete' => 1,
1109 $domain = new CRM_Core_BAO_Domain
;
1110 $domain->contact_id
= $contactID;
1111 if ($domain->find(TRUE)) {
1112 // we are finding tests trying to delete the domain contact in cleanup
1113 //since this is mainly for cleanup lets put a safeguard here
1116 $result = $this->callAPISuccess('contact', 'delete', $params);
1121 * @param int $contactTypeId
1125 function contactTypeDelete($contactTypeId) {
1126 require_once 'CRM/Contact/BAO/ContactType.php';
1127 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1129 throw new Exception('Could not delete contact type');
1134 * @param array $params
1138 function membershipTypeCreate($params = array()) {
1139 CRM_Member_PseudoConstant
::flush('membershipType');
1140 CRM_Core_Config
::clearDBCache();
1141 $memberOfOrganization = $this->organizationCreate();
1142 $params = array_merge(array(
1143 'name' => 'General',
1144 'duration_unit' => 'year',
1145 'duration_interval' => 1,
1146 'period_type' => 'rolling',
1147 'member_of_contact_id' => $memberOfOrganization,
1149 'financial_type_id' => 1,
1152 'visibility' => 'Public',
1155 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1157 CRM_Member_PseudoConstant
::flush('membershipType');
1158 CRM_Utils_Cache
::singleton()->flush();
1160 return $result['id'];
1164 * @param array $params
1168 function contactMembershipCreate($params) {
1170 'join_date' => '2007-01-21',
1171 'start_date' => '2007-01-21',
1172 'end_date' => '2007-12-21',
1173 'source' => 'Payment',
1176 foreach ($pre as $key => $val) {
1177 if (!isset($params[$key])) {
1178 $params[$key] = $val;
1182 $result = $this->callAPISuccess('Membership', 'create', $params);
1183 return $result['id'];
1187 * Delete Membership Type
1189 * @param array $params
1191 function membershipTypeDelete($params) {
1192 $this->callAPISuccess('MembershipType', 'Delete', $params);
1196 * @param int $membershipID
1198 function membershipDelete($membershipID) {
1199 $deleteParams = array('id' => $membershipID);
1200 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1205 * @param string $name
1209 function membershipStatusCreate($name = 'test member status') {
1210 $params['name'] = $name;
1211 $params['start_event'] = 'start_date';
1212 $params['end_event'] = 'end_date';
1213 $params['is_current_member'] = 1;
1214 $params['is_active'] = 1;
1216 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1217 CRM_Member_PseudoConstant
::flush('membershipStatus');
1218 return $result['id'];
1222 * @param int $membershipStatusID
1224 function membershipStatusDelete($membershipStatusID) {
1225 if (!$membershipStatusID) {
1228 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1233 * @param array $params
1237 function relationshipTypeCreate($params = array()) {
1238 $params = array_merge(array(
1239 'name_a_b' => 'Relation 1 for relationship type create',
1240 'name_b_a' => 'Relation 2 for relationship type create',
1241 'contact_type_a' => 'Individual',
1242 'contact_type_b' => 'Organization',
1249 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1250 CRM_Core_PseudoConstant
::flush('relationshipType');
1252 return $result['id'];
1256 * Delete Relatinship Type
1258 * @param int $relationshipTypeID
1260 function relationshipTypeDelete($relationshipTypeID) {
1261 $params['id'] = $relationshipTypeID;
1262 $this->callAPISuccess('relationship_type', 'delete', $params);
1266 * @param array $params
1270 function paymentProcessorTypeCreate($params = NULL) {
1271 if (is_null($params)) {
1273 'name' => 'API_Test_PP',
1274 'title' => 'API Test Payment Processor',
1275 'class_name' => 'CRM_Core_Payment_APITest',
1276 'billing_mode' => 'form',
1282 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1284 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1286 return $result['id'];
1290 * Create Participant
1292 * @param array $params array of contact id and event id values
1294 * @return int $id of participant created
1296 function participantCreate($params) {
1297 if(empty($params['contact_id'])){
1298 $params['contact_id'] = $this->individualCreate();
1300 if(empty($params['event_id'])){
1301 $event = $this->eventCreate();
1302 $params['event_id'] = $event['id'];
1307 'register_date' => 20070219,
1308 'source' => 'Wimbeldon',
1309 'event_level' => 'Payment',
1313 $params = array_merge($defaults, $params);
1314 $result = $this->callAPISuccess('Participant', 'create', $params);
1315 return $result['id'];
1319 * Create Payment Processor
1321 * @return object of Payment Processsor
1323 function processorCreate() {
1324 $processorParams = array(
1327 'payment_processor_type_id' => 10,
1328 'financial_account_id' => 12,
1331 'url_site' => 'http://dummy.com',
1332 'url_recur' => 'http://dummy.com',
1333 'billing_mode' => 1,
1335 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1336 return $paymentProcessor;
1340 * Create contribution page
1342 * @param array $params
1343 * @return object of contribution page
1345 function contributionPageCreate($params) {
1346 $this->_pageParams
= array(
1347 'title' => 'Test Contribution Page',
1348 'financial_type_id' => 1,
1349 'currency' => 'USD',
1350 'financial_account_id' => 1,
1351 'payment_processor' => $params['processor_id'],
1353 'is_allow_other_amount' => 1,
1355 'max_amount' => 1000,
1357 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1358 return $contributionPage;
1364 * @param array $params
1365 * @return array result of created tag
1367 function tagCreate($params = array()) {
1369 'name' => 'New Tag3',
1370 'description' => 'This is description for Our New Tag ',
1373 $params = array_merge($defaults, $params);
1374 $result = $this->callAPISuccess('Tag', 'create', $params);
1375 return $result['values'][$result['id']];
1381 * @param int $tagId id of the tag to be deleted
1383 function tagDelete($tagId) {
1384 require_once 'api/api.php';
1388 $result = $this->callAPISuccess('Tag', 'delete', $params);
1389 return $result['id'];
1393 * Add entity(s) to the tag
1395 * @param array $params
1399 function entityTagAdd($params) {
1400 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1405 * Create contribution
1407 * @param int $cID contact_id
1409 * @return int id of created contribution
1411 function pledgeCreate($cID) {
1413 'contact_id' => $cID,
1414 'pledge_create_date' => date('Ymd'),
1415 'start_date' => date('Ymd'),
1416 'scheduled_date' => date('Ymd'),
1418 'pledge_status_id' => '2',
1419 'financial_type_id' => '1',
1420 'pledge_original_installment_amount' => 20,
1421 'frequency_interval' => 5,
1422 'frequency_unit' => 'year',
1423 'frequency_day' => 15,
1424 'installments' => 5,
1427 $result = $this->callAPISuccess('Pledge', 'create', $params);
1428 return $result['id'];
1432 * Delete contribution
1434 * @param int $pledgeId
1436 function pledgeDelete($pledgeId) {
1438 'pledge_id' => $pledgeId,
1440 $this->callAPISuccess('Pledge', 'delete', $params);
1444 * Create contribution
1446 * @param int $cID contact_id
1447 * @param int $cTypeID id of financial type
1449 * @param int $invoiceID
1450 * @param int $trxnID
1451 * @param int $paymentInstrumentID
1452 * @param bool $isFee
1453 * @return int id of created contribution
1455 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1458 'contact_id' => $cID,
1459 'receive_date' => date('Ymd'),
1460 'total_amount' => 100.00,
1461 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1462 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1463 'non_deductible_amount' => 10.00,
1464 'trxn_id' => $trxnID,
1465 'invoice_id' => $invoiceID,
1467 'contribution_status_id' => 1,
1468 // 'note' => 'Donating for Nobel Cause', *Fixme
1472 $params['fee_amount'] = 5.00;
1473 $params['net_amount'] = 95.00;
1476 $result = $this->callAPISuccess('contribution', 'create', $params);
1477 return $result['id'];
1481 * Create online contribution
1483 * @param array $params
1484 * @param int $financialType id of financial type
1486 * @param int $invoiceID
1487 * @param int $trxnID
1488 * @return int id of created contribution
1490 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1491 $contribParams = array(
1492 'contact_id' => $params['contact_id'],
1493 'receive_date' => date('Ymd'),
1494 'total_amount' => 100.00,
1495 'financial_type_id' => $financialType,
1496 'contribution_page_id' => $params['contribution_page_id'],
1498 'invoice_id' => 67890,
1501 $contribParams = array_merge($contribParams, $params);
1502 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1504 return $result['id'];
1508 * Delete contribution
1510 * @param int $contributionId
1514 function contributionDelete($contributionId) {
1516 'contribution_id' => $contributionId,
1518 $result = $this->callAPISuccess('contribution', 'delete', $params);
1525 * @param array $params name-value pair for an event
1527 * @return array $event
1529 function eventCreate($params = array()) {
1530 // if no contact was passed, make up a dummy event creator
1531 if (!isset($params['contact_id'])) {
1532 $params['contact_id'] = $this->_contactCreate(array(
1533 'contact_type' => 'Individual',
1534 'first_name' => 'Event',
1535 'last_name' => 'Creator',
1539 // set defaults for missing params
1540 $params = array_merge(array(
1541 'title' => 'Annual CiviCRM meet',
1542 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1543 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1544 'event_type_id' => 1,
1546 'start_date' => 20081021,
1547 'end_date' => 20081023,
1548 'is_online_registration' => 1,
1549 'registration_start_date' => 20080601,
1550 'registration_end_date' => 20081015,
1551 'max_participants' => 100,
1552 'event_full_text' => 'Sorry! We are already full',
1555 'is_show_location' => 0,
1558 return $this->callAPISuccess('Event', 'create', $params);
1564 * @param int $id ID of the event
1568 function eventDelete($id) {
1572 return $this->callAPISuccess('event', 'delete', $params);
1576 * Delete participant
1578 * @param int $participantID
1582 function participantDelete($participantID) {
1584 'id' => $participantID,
1586 return $this->callAPISuccess('Participant', 'delete', $params);
1590 * Create participant payment
1592 * @param int $participantID
1593 * @param int $contributionID
1594 * @return int $id of created payment
1596 function participantPaymentCreate($participantID, $contributionID = NULL) {
1597 //Create Participant Payment record With Values
1599 'participant_id' => $participantID,
1600 'contribution_id' => $contributionID,
1603 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1604 return $result['id'];
1608 * Delete participant payment
1610 * @param int $paymentID
1612 function participantPaymentDelete($paymentID) {
1616 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1622 * @param int $contactID
1623 * @return int location id of created location
1625 function locationAdd($contactID) {
1628 'location_type' => 'New Location Type',
1630 'name' => 'Saint Helier St',
1631 'county' => 'Marin',
1632 'country' => 'United States',
1633 'state_province' => 'Michigan',
1634 'supplemental_address_1' => 'Hallmark Ct',
1635 'supplemental_address_2' => 'Jersey Village',
1640 'contact_id' => $contactID,
1641 'address' => $address,
1642 'location_format' => '2.0',
1643 'location_type' => 'New Location Type',
1646 $result = $this->callAPISuccess('Location', 'create', $params);
1651 * Delete Locations of contact
1653 * @param array $params parameters
1655 function locationDelete($params) {
1656 $this->callAPISuccess('Location', 'delete', $params);
1660 * Add a Location Type
1662 * @param array $params
1663 * @return int location id of created location
1665 function locationTypeCreate($params = NULL) {
1666 if ($params === NULL) {
1668 'name' => 'New Location Type',
1669 'vcard_name' => 'New Location Type',
1670 'description' => 'Location Type for Delete',
1675 $locationType = new CRM_Core_DAO_LocationType();
1676 $locationType->copyValues($params);
1677 $locationType->save();
1678 // clear getfields cache
1679 CRM_Core_PseudoConstant
::flush();
1680 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1681 return $locationType;
1685 * Delete a Location Type
1687 * @param int location type id
1689 function locationTypeDelete($locationTypeId) {
1690 $locationType = new CRM_Core_DAO_LocationType();
1691 $locationType->id
= $locationTypeId;
1692 $locationType->delete();
1698 * @param array $params
1699 * @return int groupId of created group
1701 function groupCreate($params = array()) {
1702 $params = array_merge(array(
1703 'name' => 'Test Group 1',
1705 'title' => 'New Test Group Created',
1706 'description' => 'New Test Group Created',
1708 'visibility' => 'Public Pages',
1709 'group_type' => array(
1715 $result = $this->callAPISuccess('Group', 'create', $params);
1716 return $result['id'];
1724 function groupDelete($gid) {
1730 $this->callAPISuccess('Group', 'delete', $params);
1735 * @param array $params
1737 function uFFieldCreate($params = array()) {
1738 $params = array_merge(array(
1740 'field_name' => 'first_name',
1743 'visibility' => 'Public Pages and Listings',
1744 'is_searchable' => '1',
1745 'label' => 'first_name',
1746 'field_type' => 'Individual',
1749 $this->callAPISuccess('uf_field', 'create', $params);
1753 * Add a UF Join Entry
1755 * @param array $params
1756 * @return int $id of created UF Join
1758 function ufjoinCreate($params = NULL) {
1759 if ($params === NULL) {
1762 'module' => 'CiviEvent',
1763 'entity_table' => 'civicrm_event',
1769 $result = $this->callAPISuccess('uf_join', 'create', $params);
1774 * Delete a UF Join Entry
1776 * @param array with missing uf_group_id
1778 function ufjoinDelete($params = NULL) {
1779 if ($params === NULL) {
1782 'module' => 'CiviEvent',
1783 'entity_table' => 'civicrm_event',
1786 'uf_group_id' => '',
1790 crm_add_uf_join($params);
1794 * Create Group for a contact
1796 * @param int $contactId
1798 function contactGroupCreate($contactId) {
1800 'contact_id.1' => $contactId,
1804 $this->callAPISuccess('GroupContact', 'Create', $params);
1808 * Delete Group for a contact
1810 * @param int $contactId
1812 function contactGroupDelete($contactId) {
1814 'contact_id.1' => $contactId,
1817 $this->civicrm_api('GroupContact', 'Delete', $params);
1823 * @param array $params
1826 function activityCreate($params = NULL) {
1828 if ($params === NULL) {
1829 $individualSourceID = $this->individualCreate();
1831 $contactParams = array(
1832 'first_name' => 'Julia',
1833 'Last_name' => 'Anderson',
1835 'email' => 'julia_anderson@civicrm.org',
1836 'contact_type' => 'Individual',
1839 $individualTargetID = $this->individualCreate($contactParams);
1842 'source_contact_id' => $individualSourceID,
1843 'target_contact_id' => array($individualTargetID),
1844 'assignee_contact_id' => array($individualTargetID),
1845 'subject' => 'Discussion on warm beer',
1846 'activity_date_time' => date('Ymd'),
1847 'duration_hours' => 30,
1848 'duration_minutes' => 20,
1849 'location' => 'Baker Street',
1850 'details' => 'Lets schedule a meeting',
1852 'activity_name' => 'Meeting',
1856 $result = $this->callAPISuccess('Activity', 'create', $params);
1858 $result['target_contact_id'] = $individualTargetID;
1859 $result['assignee_contact_id'] = $individualTargetID;
1864 * Create an activity type
1866 * @param array $params parameters
1868 function activityTypeCreate($params) {
1869 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1874 * Delete activity type
1876 * @param int $activityTypeId id of the activity type
1878 function activityTypeDelete($activityTypeId) {
1879 $params['activity_type_id'] = $activityTypeId;
1880 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1885 * Create custom group
1887 * @param array $params
1890 function customGroupCreate($params = array()) {
1892 'title' => 'new custom group',
1893 'extends' => 'Contact',
1895 'style' => 'Inline',
1899 $params = array_merge($defaults, $params);
1901 if (strlen($params['title']) > 13) {
1902 $params['title'] = substr($params['title'], 0, 13);
1905 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1906 $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1908 return $this->callAPISuccess('custom_group', 'create', $params);
1912 * Existing function doesn't allow params to be over-ridden so need a new one
1913 * this one allows you to only pass in the params you want to change
1915 function CustomGroupCreateByParams($params = array()) {
1917 'title' => "API Custom Group",
1918 'extends' => 'Contact',
1920 'style' => 'Inline',
1923 $params = array_merge($defaults, $params);
1924 return $this->callAPISuccess('custom_group', 'create', $params);
1928 * Create custom group with multi fields
1930 function CustomGroupMultipleCreateByParams($params = array()) {
1935 $params = array_merge($defaults, $params);
1936 return $this->CustomGroupCreateByParams($params);
1940 * Create custom group with multi fields
1942 function CustomGroupMultipleCreateWithFields($params = array()) {
1943 // also need to pass on $params['custom_field'] if not set but not in place yet
1945 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1946 $ids['custom_group_id'] = $customGroup['id'];
1948 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1950 $ids['custom_field_id'][] = $customField['id'];
1952 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1953 $ids['custom_field_id'][] = $customField['id'];
1955 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1956 $ids['custom_field_id'][] = $customField['id'];
1962 * Create a custom group with a single text custom field. See
1963 * participant:testCreateWithCustom for how to use this
1965 * @param string $function __FUNCTION__
1966 * @param $filename string $file __FILE__
1968 * @return array $ids ids of created objects
1970 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1971 $params = array('title' => $function);
1972 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1973 $params['extends'] = $entity ?
$entity : 'Contact';
1974 $customGroup = $this->CustomGroupCreate($params);
1975 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1976 CRM_Core_PseudoConstant
::flush();
1978 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1982 * Delete custom group
1984 * @param int $customGroupID
1988 function customGroupDelete($customGroupID) {
1989 $params['id'] = $customGroupID;
1990 return $this->callAPISuccess('custom_group', 'delete', $params);
1994 * Create custom field
1996 * @param array $params (custom_group_id) is required
1999 function customFieldCreate($params) {
2000 $params = array_merge(array(
2001 'label' => 'Custom Field',
2002 'data_type' => 'String',
2003 'html_type' => 'Text',
2004 'is_searchable' => 1,
2006 'default_value' => 'defaultValue',
2009 $result = $this->callAPISuccess('custom_field', 'create', $params);
2011 if ($result['is_error'] == 0 && isset($result['id'])) {
2012 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2013 // force reset of enabled components to help grab custom fields
2014 CRM_Core_Component
::getEnabledComponents(1);
2020 * Delete custom field
2022 * @param int $customFieldID
2026 function customFieldDelete($customFieldID) {
2028 $params['id'] = $customFieldID;
2029 return $this->callAPISuccess('custom_field', 'delete', $params);
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') && 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, 'GetActions')) {
2107 $action = empty($action) ?
'getactions' : $action;
2108 $entityAction = 'GetActions';
2110 elseif (strstr($function, 'Get')) {
2111 $action = empty($action) ?
'get' : $action;
2112 $entityAction = 'Get';
2114 elseif (strstr($function, 'Delete')) {
2115 $action = empty($action) ?
'delete' : $action;
2116 $entityAction = 'Delete';
2118 elseif (strstr($function, 'Update')) {
2119 $action = empty($action) ?
'update' : $action;
2120 $entityAction = 'Update';
2122 elseif (strstr($function, 'Subscribe')) {
2123 $action = empty($action) ?
'subscribe' : $action;
2124 $entityAction = 'Subscribe';
2126 elseif (strstr($function, 'Submit')) {
2127 $action = empty($action) ?
'submit' : $action;
2128 $entityAction = 'Submit';
2130 elseif (strstr($function, 'Apply')) {
2131 $action = empty($action) ?
'apply' : $action;
2132 $entityAction = 'Apply';
2134 elseif (strstr($function, 'Replace')) {
2135 $action = empty($action) ?
'replace' : $action;
2136 $entityAction = 'Replace';
2140 $entityAction = ucwords($action);
2143 $this->tidyExampleResult($result);
2144 if(isset($params['version'])) {
2145 unset($params['version']);
2147 // a cleverer person than me would do it in a single regex
2148 if (strstr($entity, 'UF')) {
2149 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2152 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2154 $smarty = CRM_Core_Smarty
::singleton();
2155 $smarty->assign('testfunction', $function);
2156 $function = $fnPrefix . "_" . strtolower($action);
2157 $smarty->assign('function', $function);
2158 $smarty->assign('fnPrefix', $fnPrefix);
2159 $smarty->assign('params', $params);
2160 $smarty->assign('entity', $entity);
2161 $smarty->assign('filename', basename($filename));
2162 $smarty->assign('description', $description);
2163 $smarty->assign('result', $result);
2165 $smarty->assign('action', $action);
2166 if (empty($subfile)) {
2167 $subfile = $entityAction;
2169 if (file_exists('../tests/templates/documentFunction.tpl')) {
2170 if (!is_dir("../api/v3/examples/$entity")) {
2171 mkdir("../api/v3/examples/$entity");
2173 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2174 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2180 * Tidy up examples array so that fields that change often ..don't
2181 * and debug related fields are unset
2183 * @param array $result
2186 function tidyExampleResult(&$result){
2187 if(!is_array($result)) {
2190 $fieldsToChange = array(
2191 'hash' => '67eac7789eaee00',
2192 'modified_date' => '2012-11-14 16:02:35',
2193 'created_date' => '2013-07-28 08:49:19',
2194 'create_date' => '20120130621222105',
2195 'application_received_date' => '20130728084957',
2196 'in_date' => '2013-07-28 08:50:19',
2197 'scheduled_date' => '20130728085413',
2198 'approval_date' => '20130728085413',
2199 'pledge_start_date_high' => '20130726090416',
2200 'start_date' => '2013-07-29 00:00:00',
2201 'event_start_date' => '2013-07-29 00:00:00',
2202 'end_date' => '2013-08-04 00:00:00',
2203 'event_end_date' => '2013-08-04 00:00:00',
2204 'decision_date' => '20130805000000',
2207 $keysToUnset = array('xdebug', 'undefined_fields',);
2208 foreach ($keysToUnset as $unwantedKey) {
2209 if(isset($result[$unwantedKey])) {
2210 unset($result[$unwantedKey]);
2213 if (isset($result['values'])) {
2214 if(!is_array($result['values'])) {
2217 $resultArray = &$result['values'];
2219 elseif(is_array($result)) {
2220 $resultArray = &$result;
2226 foreach ($resultArray as $index => &$values) {
2227 if(!is_array($values)) {
2230 foreach($values as $key => &$value) {
2231 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2232 if(isset($value['is_error'])) {
2233 // we have a std nested result format
2234 $this->tidyExampleResult($value);
2237 foreach ($value as &$nestedResult) {
2238 // this is an alternative syntax for nested results a keyed array of results
2239 $this->tidyExampleResult($nestedResult);
2243 if(in_array($key, $keysToUnset)) {
2244 unset($values[$key]);
2247 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2248 $value = $fieldsToChange[$key];
2250 if(is_string($value)) {
2251 $value = addslashes($value);
2260 * @param array $params
2264 function noteDelete($params) {
2265 return $this->callAPISuccess('Note', 'delete', $params);
2269 * Create custom field with Option Values
2271 * @param array $customGroup
2272 * @param string $name name of custom field
2276 function customFieldOptionValueCreate($customGroup, $name) {
2277 $fieldParams = array(
2278 'custom_group_id' => $customGroup['id'],
2279 'name' => 'test_custom_group',
2280 'label' => 'Country',
2281 'html_type' => 'Select',
2282 'data_type' => 'String',
2285 'is_searchable' => 0,
2289 $optionGroup = array(
2291 'name' => 'option_group1',
2292 'label' => 'option_group_label1',
2295 $optionValue = array(
2296 'option_label' => array('Label1', 'Label2'),
2297 'option_value' => array('value1', 'value2'),
2298 'option_name' => array($name . '_1', $name . '_2'),
2299 'option_weight' => array(1, 2),
2300 'option_status' => 1,
2303 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2305 return $this->callAPISuccess('custom_field', 'create', $params);
2313 function confirmEntitiesDeleted($entities) {
2314 foreach ($entities as $entity) {
2316 $result = $this->callAPISuccess($entity, 'Get', array());
2317 if ($result['error'] == 1 ||
$result['count'] > 0) {
2318 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2325 * @param $tablesToTruncate
2326 * @param bool $dropCustomValueTables
2328 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2329 if ($dropCustomValueTables) {
2330 $tablesToTruncate[] = 'civicrm_custom_group';
2331 $tablesToTruncate[] = 'civicrm_custom_field';
2334 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2336 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2337 foreach ($tablesToTruncate as $table) {
2338 $sql = "TRUNCATE TABLE $table";
2339 CRM_Core_DAO
::executeQuery($sql);
2341 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2343 if ($dropCustomValueTables) {
2344 $dbName = self
::getDBName();
2346 SELECT TABLE_NAME as tableName
2347 FROM INFORMATION_SCHEMA.TABLES
2348 WHERE TABLE_SCHEMA = '{$dbName}'
2349 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2352 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2353 while ($tableDAO->fetch()) {
2354 $sql = "DROP TABLE {$tableDAO->tableName}";
2355 CRM_Core_DAO
::executeQuery($sql);
2361 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2363 function quickCleanUpFinancialEntities() {
2364 $tablesToTruncate = array(
2365 'civicrm_contribution',
2366 'civicrm_contribution_soft',
2367 'civicrm_financial_trxn',
2368 'civicrm_financial_item',
2369 'civicrm_contribution_recur',
2370 'civicrm_line_item',
2371 'civicrm_contribution_page',
2372 'civicrm_payment_processor',
2373 'civicrm_entity_financial_trxn',
2374 'civicrm_membership',
2375 'civicrm_membership_type',
2376 'civicrm_membership_payment',
2377 'civicrm_membership_log',
2378 'civicrm_membership_block',
2380 'civicrm_participant',
2381 'civicrm_participant_payment',
2383 'civicrm_price_set_entity',
2384 'civicrm_price_field_value',
2385 'civicrm_price_field',
2387 $this->quickCleanup($tablesToTruncate);
2388 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2389 $this->restoreDefaultPriceSetConfig();
2391 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2394 function restoreDefaultPriceSetConfig() {
2395 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)");
2396 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)");
2399 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2400 * Default behaviour is to also delete the entity
2401 * @param array $params params array to check agains
2402 * @param int $id id of the entity concerned
2403 * @param string $entity name of entity concerned (e.g. membership)
2404 * @param bool $delete should the entity be deleted as part of this check
2405 * @param string $errorText text to print on error
2409 * @param array $params
2412 * @param int $delete
2413 * @param string $errorText
2417 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2419 $result = $this->callAPISuccessGetSingle($entity, array(
2424 $this->callAPISuccess($entity, 'Delete', array(
2428 $dateFields = $keys = $dateTimeFields = array();
2429 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2430 foreach ($fields['values'] as $field => $settings) {
2431 if (array_key_exists($field, $result)) {
2432 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2435 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2437 $type = CRM_Utils_Array
::value('type', $settings);
2438 if ($type == CRM_Utils_Type
::T_DATE
) {
2439 $dateFields[] = $settings['name'];
2440 // we should identify both real names & unique names as dates
2441 if($field != $settings['name']) {
2442 $dateFields[] = $field;
2445 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2446 $dateTimeFields[] = $settings['name'];
2447 // we should identify both real names & unique names as dates
2448 if($field != $settings['name']) {
2449 $dateTimeFields[] = $field;
2454 if (strtolower($entity) == 'contribution') {
2455 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2456 // this is not returned in id format
2457 unset($params['payment_instrument_id']);
2458 $params['contribution_source'] = $params['source'];
2459 unset($params['source']);
2462 foreach ($params as $key => $value) {
2463 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2466 if (in_array($key, $dateFields)) {
2467 $value = date('Y-m-d', strtotime($value));
2468 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2470 if (in_array($key, $dateTimeFields)) {
2471 $value = date('Y-m-d H:i:s', strtotime($value));
2472 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2474 $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);
2479 * Get formatted values in the actual and expected result
2480 * @param array $actual actual calculated values
2481 * @param array $expected expected values
2484 function checkArrayEquals(&$actual, &$expected) {
2485 self
::unsetId($actual);
2486 self
::unsetId($expected);
2487 $this->assertEquals($actual, $expected);
2491 * Unset the key 'id' from the array
2492 * @param array $unformattedArray The array from which the 'id' has to be unset
2495 static function unsetId(&$unformattedArray) {
2496 $formattedArray = array();
2497 if (array_key_exists('id', $unformattedArray)) {
2498 unset($unformattedArray['id']);
2500 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2501 foreach ($unformattedArray['values'] as $key => $value) {
2502 if (is_Array($value)) {
2503 foreach ($value as $k => $v) {
2509 elseif ($key == 'id') {
2510 $unformattedArray[$key];
2512 $formattedArray = array($value);
2514 $unformattedArray['values'] = $formattedArray;
2519 * Helper to enable/disable custom directory support
2521 * @param array $customDirs with members:
2522 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2523 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2525 function customDirectories($customDirs) {
2526 require_once 'CRM/Core/Config.php';
2527 $config = CRM_Core_Config
::singleton();
2529 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2530 unset($config->customPHPPathDir
);
2532 elseif ($customDirs['php_path'] === TRUE) {
2533 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2536 $config->customPHPPathDir
= $php_path;
2539 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2540 unset($config->customTemplateDir
);
2542 elseif ($customDirs['template_path'] === TRUE) {
2543 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2546 $config->customTemplateDir
= $template_path;
2551 * Generate a temporary folder
2553 * @param string $prefix
2554 * @return string $string
2556 function createTempDir($prefix = 'test-') {
2557 $tempDir = CRM_Utils_File
::tempdir($prefix);
2558 $this->tempDirs
[] = $tempDir;
2562 function cleanTempDirs() {
2563 if (!is_array($this->tempDirs
)) {
2564 // fix test errors where this is not set
2567 foreach ($this->tempDirs
as $tempDir) {
2568 if (is_dir($tempDir)) {
2569 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2575 * Temporarily replace the singleton extension with a different one
2577 function setExtensionSystem(CRM_Extension_System
$system) {
2578 if ($this->origExtensionSystem
== NULL) {
2579 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2581 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2584 function unsetExtensionSystem() {
2585 if ($this->origExtensionSystem
!== NULL) {
2586 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2587 $this->origExtensionSystem
= NULL;
2592 * Temporarily alter the settings-metadata to add a mock setting.
2594 * WARNING: The setting metadata will disappear on the next cache-clear.
2599 function setMockSettingsMetaData($extras) {
2600 CRM_Core_BAO_Setting
::$_cache = array();
2601 $this->callAPISuccess('system','flush', array());
2602 CRM_Core_BAO_Setting
::$_cache = array();
2604 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2605 $metadata = array_merge($metadata, $extras);
2608 $fields = $this->callAPISuccess('setting', 'getfields', array());
2609 foreach ($extras as $key => $spec) {
2610 $this->assertNotEmpty($spec['title']);
2611 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2616 * @param string $name
2618 function financialAccountDelete($name) {
2619 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2620 $financialAccount->name
= $name;
2621 if($financialAccount->find(TRUE)) {
2622 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2623 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2624 $entityFinancialType->delete();
2625 $financialAccount->delete();
2630 * Use $ids as an instruction to do test cleanup
2632 function deleteFromIDSArray() {
2633 foreach ($this->ids
as $entity => $ids) {
2634 foreach ($ids as $id) {
2635 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2641 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2642 * (NB unclear if this is still required)
2644 function _sethtmlGlobals() {
2645 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2646 'required' => array(
2647 'html_quickform_rule_required',
2648 'HTML/QuickForm/Rule/Required.php'
2650 'maxlength' => array(
2651 'html_quickform_rule_range',
2652 'HTML/QuickForm/Rule/Range.php'
2654 'minlength' => array(
2655 'html_quickform_rule_range',
2656 'HTML/QuickForm/Rule/Range.php'
2658 'rangelength' => array(
2659 'html_quickform_rule_range',
2660 'HTML/QuickForm/Rule/Range.php'
2663 'html_quickform_rule_email',
2664 'HTML/QuickForm/Rule/Email.php'
2667 'html_quickform_rule_regex',
2668 'HTML/QuickForm/Rule/Regex.php'
2670 'lettersonly' => array(
2671 'html_quickform_rule_regex',
2672 'HTML/QuickForm/Rule/Regex.php'
2674 'alphanumeric' => array(
2675 'html_quickform_rule_regex',
2676 'HTML/QuickForm/Rule/Regex.php'
2679 'html_quickform_rule_regex',
2680 'HTML/QuickForm/Rule/Regex.php'
2682 'nopunctuation' => array(
2683 'html_quickform_rule_regex',
2684 'HTML/QuickForm/Rule/Regex.php'
2687 'html_quickform_rule_regex',
2688 'HTML/QuickForm/Rule/Regex.php'
2690 'callback' => array(
2691 'html_quickform_rule_callback',
2692 'HTML/QuickForm/Rule/Callback.php'
2695 'html_quickform_rule_compare',
2696 'HTML/QuickForm/Rule/Compare.php'
2699 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2700 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2702 'HTML/QuickForm/group.php',
2703 'HTML_QuickForm_group'
2706 'HTML/QuickForm/hidden.php',
2707 'HTML_QuickForm_hidden'
2710 'HTML/QuickForm/reset.php',
2711 'HTML_QuickForm_reset'
2713 'checkbox' => array(
2714 'HTML/QuickForm/checkbox.php',
2715 'HTML_QuickForm_checkbox'
2718 'HTML/QuickForm/file.php',
2719 'HTML_QuickForm_file'
2722 'HTML/QuickForm/image.php',
2723 'HTML_QuickForm_image'
2725 'password' => array(
2726 'HTML/QuickForm/password.php',
2727 'HTML_QuickForm_password'
2730 'HTML/QuickForm/radio.php',
2731 'HTML_QuickForm_radio'
2734 'HTML/QuickForm/button.php',
2735 'HTML_QuickForm_button'
2738 'HTML/QuickForm/submit.php',
2739 'HTML_QuickForm_submit'
2742 'HTML/QuickForm/select.php',
2743 'HTML_QuickForm_select'
2745 'hiddenselect' => array(
2746 'HTML/QuickForm/hiddenselect.php',
2747 'HTML_QuickForm_hiddenselect'
2750 'HTML/QuickForm/text.php',
2751 'HTML_QuickForm_text'
2753 'textarea' => array(
2754 'HTML/QuickForm/textarea.php',
2755 'HTML_QuickForm_textarea'
2757 'fckeditor' => array(
2758 'HTML/QuickForm/fckeditor.php',
2759 'HTML_QuickForm_FCKEditor'
2762 'HTML/QuickForm/tinymce.php',
2763 'HTML_QuickForm_TinyMCE'
2765 'dojoeditor' => array(
2766 'HTML/QuickForm/dojoeditor.php',
2767 'HTML_QuickForm_dojoeditor'
2770 'HTML/QuickForm/link.php',
2771 'HTML_QuickForm_link'
2773 'advcheckbox' => array(
2774 'HTML/QuickForm/advcheckbox.php',
2775 'HTML_QuickForm_advcheckbox'
2778 'HTML/QuickForm/date.php',
2779 'HTML_QuickForm_date'
2782 'HTML/QuickForm/static.php',
2783 'HTML_QuickForm_static'
2786 'HTML/QuickForm/header.php',
2787 'HTML_QuickForm_header'
2790 'HTML/QuickForm/html.php',
2791 'HTML_QuickForm_html'
2793 'hierselect' => array(
2794 'HTML/QuickForm/hierselect.php',
2795 'HTML_QuickForm_hierselect'
2797 'autocomplete' => array(
2798 'HTML/QuickForm/autocomplete.php',
2799 'HTML_QuickForm_autocomplete'
2802 'HTML/QuickForm/xbutton.php',
2803 'HTML_QuickForm_xbutton'
2805 'advmultiselect' => array(
2806 'HTML/QuickForm/advmultiselect.php',
2807 'HTML_QuickForm_advmultiselect'
2813 * Set up an acl allowing contact to see 2 specified groups
2814 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2816 * You need to have pre-created these groups & created the user e.g
2817 * $this->createLoggedInUser();
2818 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2819 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2822 function setupACL() {
2824 $_REQUEST = $this->_params
;
2826 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2827 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2828 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2829 'label' => 'pick me',
2834 CRM_Core_DAO
::executeQuery("
2835 TRUNCATE civicrm_acl_cache
2838 CRM_Core_DAO
::executeQuery("
2839 TRUNCATE civicrm_acl_contact_cache
2843 CRM_Core_DAO
::executeQuery("
2844 INSERT INTO civicrm_acl_entity_role (
2845 `acl_role_id`, `entity_table`, `entity_id`
2846 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2849 CRM_Core_DAO
::executeQuery("
2850 INSERT INTO civicrm_acl (
2851 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2854 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2858 CRM_Core_DAO
::executeQuery("
2859 INSERT INTO civicrm_acl (
2860 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2863 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2866 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2867 $this->callAPISuccess('group_contact', 'create', array(
2868 'group_id' => $this->_permissionedGroup
,
2869 'contact_id' => $this->_loggedInUser
,
2872 CRM_ACL_BAO_Cache
::resetCache();
2873 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2874 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2878 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2880 function offsetDefaultPriceSet() {
2881 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2882 $firstID = $contributionPriceSet['id'];
2883 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2884 unset($contributionPriceSet['id']);
2885 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2886 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2887 unset($priceField['id']);
2888 $priceField['price_set_id'] = $newPriceSet['id'];
2889 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2890 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2892 unset($priceFieldValue['id']);
2893 //create some padding to use up ids
2894 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2895 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2896 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2900 * Create an instance of the paypal processor
2901 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2902 * this parent class & we don't have a structure for that yet
2903 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2904 * & the best protection agains that is the functions this class affords
2906 function paymentProcessorCreate($params = array()) {
2907 $params = array_merge(array(
2909 'domain_id' => CRM_Core_Config
::domainID(),
2910 'payment_processor_type_id' => 'PayPal',
2914 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2915 'password' => '1183377788',
2916 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2917 'url_site' => 'https://www.sandbox.paypal.com/',
2918 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2919 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2920 'class_name' => 'Payment_PayPalImpl',
2921 'billing_mode' => 3,
2922 'financial_type_id' => 1,
2925 if(!is_numeric($params['payment_processor_type_id'])) {
2926 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2928 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2929 'name' => $params['payment_processor_type_id'],
2933 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2934 return $result['id'];
2938 * Set up initial recurring payment allowing subsequent IPN payments
2940 function setupRecurringPaymentProcessorTransaction() {
2941 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
2942 'contact_id' => $this->_contactID
,
2945 'installments' => 5,
2946 'frequency_unit' => 'Month',
2947 'frequency_interval' => 1,
2948 'invoice_id' => $this->_invoiceID
,
2949 'contribution_status_id' => 2,
2950 'processor_id' => $this->_paymentProcessorID
,
2951 'api.contribution.create' => array(
2952 'total_amount' => '200',
2953 'invoice_id' => $this->_invoiceID
,
2954 'financial_type_id' => 1,
2955 'contribution_status_id' => 'Pending',
2956 'contact_id' => $this->_contactID
,
2957 'contribution_page_id' => $this->_contributionPageID
,
2958 'payment_processor_id' => $this->_paymentProcessorID
,
2961 $this->_contributionRecurID
= $contributionRecur['id'];
2962 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2966 * 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
2968 function setupMembershipRecurringPaymentProcessorTransaction() {
2969 $this->ids
['membership_type'] = $this->membershipTypeCreate();
2970 //create a contribution so our membership & contribution don't both have id = 1
2971 $this->contributionCreate($this->_contactID
, 1, 'abcd', '345j');
2972 $this->setupRecurringPaymentProcessorTransaction();
2974 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2975 'contact_id' => $this->_contactID
,
2976 'membership_type_id' => $this->ids
['membership_type'],
2977 'contribution_recur_id' => $this->_contributionRecurID
,
2978 'format.only_id' => TRUE,
2980 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2981 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2983 $this->callAPISuccess('line_item', 'create', array(
2984 'entity_table' => 'civicrm_membership',
2985 'entity_id' => $this->ids
['membership'],
2986 'contribution_id' => $this->_contributionID
,
2987 'label' => 'General',
2989 'unit_price' => 200,
2990 'line_total' => 200,
2991 'financial_type_id' => 1,
2992 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array('return' => 'id', 'label' => 'Membership Amount')),
2993 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array('return' => 'id', 'label' => 'General')),
2995 $this->callAPISuccess('membership_payment', 'create', array('contribution_id' => $this->_contributionID
, 'membership_id' => $this->ids
['membership']));
3003 function CiviUnitTestCase_fatalErrorHandler($message) {
3004 throw new Exception("{$message['message']}: {$message['code']}");