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 CRM_Utils_Hook
::singleton(TRUE);
329 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
330 // Use a temporary file for STDIN
331 $GLOBALS['stdin'] = tmpfile();
332 if ($GLOBALS['stdin'] === FALSE) {
333 echo "Couldn't open temporary file\n";
337 // Get and save a connection to the database
338 $this->_dbconn
= $this->getConnection();
340 // reload database before each test
341 // $this->_populateDB();
343 // "initialize" CiviCRM to avoid problems when running single tests
344 // FIXME: look at it closer in second stage
346 // initialize the object once db is loaded
347 CRM_Core_Config
::$_mail = NULL;
348 $config = CRM_Core_Config
::singleton();
350 // when running unit tests, use mockup user framework
351 $config->setUserFramework('UnitTests');
353 // also fix the fatal error handler to throw exceptions,
355 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
357 // enable backtrace to get meaningful errors
358 $config->backtrace
= 1;
360 // disable any left-over test extensions
361 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
363 // reset all the caches
364 CRM_Utils_System
::flushCache();
366 // clear permissions stub to not check permissions
367 $config = CRM_Core_Config
::singleton();
368 $config->userPermissionClass
->permissions
= NULL;
370 //flush component settings
371 CRM_Core_Component
::getEnabledComponents(TRUE);
373 if ($this->_eNoticeCompliant
) {
374 error_reporting(E_ALL
);
377 error_reporting(E_ALL
& ~E_NOTICE
);
379 $this->_sethtmlGlobals();
383 * Read everything from the datasets directory and insert into the db
385 public function loadAllFixtures() {
386 $fixturesDir = __DIR__
. '/../../fixtures';
388 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
390 $xmlFiles = glob($fixturesDir . '/*.xml');
391 foreach ($xmlFiles as $xmlFixture) {
392 $op = new PHPUnit_Extensions_Database_Operation_Insert();
393 $dataset = $this->createXMLDataSet($xmlFixture);
394 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
395 $op->execute($this->_dbconn
, $dataset);
398 $yamlFiles = glob($fixturesDir . '/*.yaml');
399 foreach ($yamlFiles as $yamlFixture) {
400 $op = new PHPUnit_Extensions_Database_Operation_Insert();
401 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
402 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
403 $op->execute($this->_dbconn
, $dataset);
406 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
410 * emulate a logged in user since certain functions use that
411 * value to store a record in the DB (like activity)
414 public function createLoggedInUser() {
416 'first_name' => 'Logged In',
417 'last_name' => 'User ' . rand(),
418 'contact_type' => 'Individual',
420 $contactID = $this->individualCreate($params);
422 $session = CRM_Core_Session
::singleton();
423 $session->set('userID', $contactID);
426 public function cleanDB() {
427 self
::$populateOnce = NULL;
428 $this->DBResetRequired
= TRUE;
430 $this->_dbconn
= $this->getConnection();
431 static::_populateDB();
432 $this->tempDirs
= array();
436 * Common teardown functions for all unit tests
438 protected function tearDown() {
439 error_reporting(E_ALL
& ~E_NOTICE
);
440 $session = CRM_Core_Session
::singleton();
441 $session->set('userID', NULL);
442 $tablesToTruncate = array('civicrm_contact');
443 $this->quickCleanup($tablesToTruncate);
444 $this->cleanTempDirs();
445 $this->unsetExtensionSystem();
449 * FIXME: Maybe a better way to do it
451 function foreignKeyChecksOff() {
452 self
::$utils = new Utils($GLOBALS['mysql_host'],
453 $GLOBALS['mysql_port'],
454 $GLOBALS['mysql_user'],
455 $GLOBALS['mysql_pass']
457 $dbName = self
::getDBName();
458 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
459 if (self
::$utils->do_query($query) === FALSE) {
461 echo 'Cannot set foreign_key_checks = 0';
467 function foreignKeyChecksOn() {
468 // FIXME: might not be needed if previous fixme implemented
472 * Generic function to compare expected values after an api call to retrieved
475 * @daoName string DAO Name of object we're evaluating.
476 * @id int Id of object
477 * @match array Associative array of field name => expected value. Empty if asserting
478 * that a DELETE occurred
479 * @delete boolean True if we're checking that a DELETE action occurred.
481 function assertDBState($daoName, $id, $match, $delete = FALSE) {
483 // adding this here since developers forget to check for an id
484 // and hence we get the first value in the db
485 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
488 $object = new $daoName();
492 // If we're asserting successful record deletion, make sure object is NOT found.
494 if ($object->find(TRUE)) {
495 $this->fail("Object not deleted by delete operation: $daoName, $id");
500 // Otherwise check matches of DAO field values against expected values in $match.
501 if ($object->find(TRUE)) {
502 $fields = & $object->fields();
503 foreach ($fields as $name => $value) {
504 $dbName = $value['name'];
505 if (isset($match[$name])) {
507 $this->assertEquals($object->$dbName, $match[$name]);
509 elseif (isset($match[$dbName])) {
511 $this->assertEquals($object->$dbName, $match[$dbName]);
516 $this->fail("Could not retrieve object: $daoName, $id");
519 $matchSize = count($match);
520 if ($verifiedCount != $matchSize) {
521 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
525 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
528 * @param $searchValue
529 * @param $returnColumn
530 * @param $searchColumn
533 * @return null|string
534 * @throws PHPUnit_Framework_AssertionFailedError
536 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
537 if (empty($searchValue)) {
538 $this->fail("empty value passed to assertDBNotNull");
540 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
541 $this->assertNotNull($value, $message);
546 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
549 * @param $searchValue
550 * @param $returnColumn
551 * @param $searchColumn
554 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
555 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
556 $this->assertNull($value, $message);
559 // Request a record from the DB by id. Success if row not found.
563 * @param null $message
565 function assertDBRowNotExist($daoName, $id, $message = NULL) {
566 $message = $message ?
$message : "$daoName (#$id) should not exist";
567 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
568 $this->assertNull($value, $message);
571 // Request a record from the DB by id. Success if row not found.
575 * @param null $message
577 function assertDBRowExist($daoName, $id, $message = NULL) {
578 $message = $message ?
$message : "$daoName (#$id) should exist";
579 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
580 $this->assertEquals($id, $value, $message);
583 // Compare a single column value in a retrieved DB record to an expected value
586 * @param $searchValue
587 * @param $returnColumn
588 * @param $searchColumn
589 * @param $expectedValue
592 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
593 $expectedValue, $message
595 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
596 $this->assertEquals($value, $expectedValue, $message);
599 // Compare all values in a single retrieved DB record to an array of expected values
602 * @param $searchParams
603 * @param $expectedValues
605 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
606 //get the values from db
608 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
610 // compare db values with expected values
611 self
::assertAttributesEquals($expectedValues, $dbValues);
615 * Assert that a SQL query returns a given value
617 * The first argument is an expected value. The remaining arguments are passed
618 * to CRM_Core_DAO::singleValueQuery
620 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
621 * array(1 => array("Whiz", "String")));
623 function assertDBQuery($expected, $query, $params = array()) {
624 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
625 $this->assertEquals($expected, $actual,
626 sprintf('expected=[%s] actual=[%s] query=[%s]',
627 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
633 * Assert that two array-trees are exactly equal, notwithstanding
634 * the sorting of keys
636 * @param array $expected
637 * @param array $actual
639 function assertTreeEquals($expected, $actual) {
642 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
643 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
647 $this->assertEquals($e, $a);
651 * Assert that two numbers are approximately equal
653 * @param int|float $expected
654 * @param int|float $actual
655 * @param int|float $tolerance
656 * @param string $message
658 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
659 if ($message === NULL) {
660 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
662 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
666 * @param $expectedValues
667 * @param $actualValues
668 * @param null $message
670 * @throws PHPUnit_Framework_AssertionFailedError
672 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
673 foreach ($expectedValues as $paramName => $paramValue) {
674 if (isset($actualValues[$paramName])) {
675 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
678 $this->fail("Attribute '$paramName' not present in actual array.");
687 function assertArrayKeyExists($key, &$list) {
688 $result = isset($list[$key]) ?
TRUE : FALSE;
689 $this->assertTrue($result, ts("%1 element exists?",
698 function assertArrayValueNotNull($key, &$list) {
699 $this->assertArrayKeyExists($key, $list);
701 $value = isset($list[$key]) ?
$list[$key] : NULL;
702 $this->assertTrue($value,
703 ts("%1 element not null?",
710 * check that api returned 'is_error' => 0
711 * else provide full message
712 * @param array $apiResult api result
713 * @param string $prefix extra test to add to message
715 function assertAPISuccess($apiResult, $prefix = '') {
716 if (!empty($prefix)) {
719 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
721 if(!empty($apiResult['debug_information'])) {
722 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
724 if(!empty($apiResult['trace'])){
725 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
727 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
731 * check that api returned 'is_error' => 1
732 * else provide full message
734 * @param array $apiResult api result
735 * @param string $prefix extra test to add to message
736 * @param null $expectedError
738 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
739 if (!empty($prefix)) {
742 if($expectedError && !empty($apiResult['is_error'])){
743 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
745 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
746 $this->assertNotEmpty($apiResult['error_message']);
752 * @param string $message
754 function assertType($expected, $actual, $message = '') {
755 return $this->assertInternalType($expected, $actual, $message);
759 * check that a deleted item has been deleted
761 function assertAPIDeleted($entity, $id) {
762 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
767 * check that api returned 'is_error' => 1
768 * else provide full message
771 * @param array $valuesToExclude
772 * @param string $prefix extra test to add to message
773 * @internal param array $apiResult api result
775 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
776 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
777 foreach ($valuesToExclude as $value) {
778 if(isset($result[$value])) {
779 unset($result[$value]);
781 if(isset($expected[$value])) {
782 unset($expected[$value]);
785 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
789 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
796 function civicrm_api($entity, $action, $params) {
797 return civicrm_api($entity, $action, $params);
801 * This function exists to wrap api functions
802 * so we can ensure they succeed & throw exceptions without litterering the test with checks
804 * @param string $entity
805 * @param string $action
806 * @param array $params
807 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
808 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
809 * for getsingle the array is compared against an array passed in - the id is not compared (for
814 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
815 $params = array_merge(array(
816 'version' => $this->_apiversion
,
821 switch (strtolower($action)) {
823 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
825 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
827 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
829 $result = $this->civicrm_api($entity, $action, $params);
830 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
835 * This function exists to wrap api getValue function & check the result
836 * so we can ensure they succeed & throw exceptions without litterering the test with checks
837 * There is a type check in this
839 * @param string $entity
840 * @param array $params
841 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
851 function callAPISuccessGetValue($entity, $params, $type = NULL) {
853 'version' => $this->_apiversion
,
856 $result = $this->civicrm_api($entity, 'getvalue', $params);
858 if($type == 'integer'){
859 // api seems to return integers as strings
860 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
863 $this->assertType($type, $result, "returned result should have been of type $type but was " );
870 * This function exists to wrap api getsingle function & check the result
871 * so we can ensure they succeed & throw exceptions without litterering the test with checks
873 * @param string $entity
874 * @param array $params
875 * @param array $checkAgainst - array to compare result against
886 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
888 'version' => $this->_apiversion
,
891 $result = $this->civicrm_api($entity, 'getsingle', $params);
892 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
893 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
896 // @todo - have gone with the fn that unsets id? should we check id?
897 $this->checkArrayEquals($result, $checkAgainst);
903 * This function exists to wrap api getValue function & check the result
904 * so we can ensure they succeed & throw exceptions without litterering the test with checks
905 * There is a type check in this
906 * @param string $entity
907 * @param array $params
911 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
919 function callAPISuccessGetCount($entity, $params, $count = NULL) {
921 'version' => $this->_apiversion
,
924 $result = $this->civicrm_api($entity, 'getcount', $params);
925 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
926 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
929 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
935 * This function exists to wrap api functions
936 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
938 * @param string $entity
939 * @param string $action
940 * @param array $params
941 * @param string $function - pass this in to create a generated example
942 * @param string $file - pass this in to create a generated example
943 * @param string $description
944 * @param string|null $subfile
945 * @param string|null $actionName
948 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
949 $params['version'] = $this->_apiversion
;
950 $result = $this->callAPISuccess($entity, $action, $params);
951 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
956 * This function exists to wrap api functions
957 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
958 * @param string $entity
959 * @param string $action
960 * @param array $params
961 * @param string $expectedErrorMessage error
962 * @param null $extraOutput
965 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
966 if (is_array($params)) {
968 'version' => $this->_apiversion
,
971 $result = $this->civicrm_api($entity, $action, $params);
972 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
977 * Create required data based on $this->entity & $this->params
978 * This is just a way to set up the test data for delete & get functions
979 * so the distinction between set
980 * up & tested functions is clearer
982 * @return array api Result
984 public function createTestEntity(){
985 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
989 * Generic function to create Organisation, to be used in test cases
991 * @param array parameters for civicrm_contact_add api function call
992 * @param int sequence number if creating multiple organizations
994 * @return int id of Organisation created
996 function organizationCreate($params = array(), $seq = 0) {
1000 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1001 return $this->_contactCreate($params);
1005 * Generic function to create Individual, to be used in test cases
1007 * @param array parameters for civicrm_contact_add api function call
1008 * @param int sequence number if creating multiple individuals
1010 * @return int id of Individual created
1012 function individualCreate($params = array(), $seq = 0) {
1013 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1014 return $this->_contactCreate($params);
1018 * Generic function to create Household, to be used in test cases
1020 * @param array parameters for civicrm_contact_add api function call
1021 * @param int sequence number if creating multiple households
1023 * @return int id of Household created
1025 function householdCreate($params = array(), $seq = 0) {
1026 $params = array_merge($this->sampleContact('Household', $seq), $params);
1027 return $this->_contactCreate($params);
1031 * Helper function for getting sample contact properties
1033 * @param enum contact type: Individual, Organization
1034 * @param int sequence number for the values of this type
1036 * @return array properties of sample contact (ie. $params for API call)
1038 function sampleContact($contact_type, $seq = 0) {
1040 'Individual' => array(
1041 // The number of values in each list need to be coprime numbers to not have duplicates
1042 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1043 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1044 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1046 'Organization' => array(
1047 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
1049 'Household' => array(
1050 'household_name' => array('Unit Test household'),
1053 $params = array('contact_type' => $contact_type);
1054 foreach ($samples[$contact_type] as $key => $values) {
1055 $params[$key] = $values[$seq %
sizeof($values)];
1057 if ($contact_type == 'Individual' ) {
1058 $params['email'] = strtolower(
1059 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1061 $params['prefix_id'] = 3;
1062 $params['suffix_id'] = 3;
1068 * Private helper function for calling civicrm_contact_add
1073 * @internal param \parameters $array for civicrm_contact_add api function call
1075 * @return int id of Household created
1077 private function _contactCreate($params) {
1078 $result = $this->callAPISuccess('contact', 'create', $params);
1079 if (!empty($result['is_error']) ||
empty($result['id'])) {
1080 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1082 return $result['id'];
1090 function contactDelete($contactID) {
1093 'skip_undelete' => 1,
1096 $domain = new CRM_Core_BAO_Domain
;
1097 $domain->contact_id
= $contactID;
1098 if ($domain->find(TRUE)) {
1099 // we are finding tests trying to delete the domain contact in cleanup
1100 //since this is mainly for cleanup lets put a safeguard here
1103 $result = $this->callAPISuccess('contact', 'delete', $params);
1108 * @param $contactTypeId
1112 function contactTypeDelete($contactTypeId) {
1113 require_once 'CRM/Contact/BAO/ContactType.php';
1114 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1116 throw new Exception('Could not delete contact type');
1121 * @param array $params
1125 function membershipTypeCreate($params = array()) {
1126 CRM_Member_PseudoConstant
::flush('membershipType');
1127 CRM_Core_Config
::clearDBCache();
1128 $memberOfOrganization = $this->organizationCreate();
1129 $params = array_merge(array(
1130 'name' => 'General',
1131 'duration_unit' => 'year',
1132 'duration_interval' => 1,
1133 'period_type' => 'rolling',
1134 'member_of_contact_id' => $memberOfOrganization,
1136 'financial_type_id' => 1,
1139 'visibility' => 'Public',
1142 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1144 CRM_Member_PseudoConstant
::flush('membershipType');
1145 CRM_Utils_Cache
::singleton()->flush();
1147 return $result['id'];
1155 function contactMembershipCreate($params) {
1157 'join_date' => '2007-01-21',
1158 'start_date' => '2007-01-21',
1159 'end_date' => '2007-12-21',
1160 'source' => 'Payment',
1163 foreach ($pre as $key => $val) {
1164 if (!isset($params[$key])) {
1165 $params[$key] = $val;
1169 $result = $this->callAPISuccess('Membership', 'create', $params);
1170 return $result['id'];
1174 * Function to delete Membership Type
1177 * @internal param int $membershipTypeID
1179 function membershipTypeDelete($params) {
1180 $this->callAPISuccess('MembershipType', 'Delete', $params);
1184 * @param $membershipID
1186 function membershipDelete($membershipID) {
1187 $deleteParams = array('id' => $membershipID);
1188 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1193 * @param string $name
1197 function membershipStatusCreate($name = 'test member status') {
1198 $params['name'] = $name;
1199 $params['start_event'] = 'start_date';
1200 $params['end_event'] = 'end_date';
1201 $params['is_current_member'] = 1;
1202 $params['is_active'] = 1;
1204 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1205 CRM_Member_PseudoConstant
::flush('membershipStatus');
1206 return $result['id'];
1210 * @param $membershipStatusID
1212 function membershipStatusDelete($membershipStatusID) {
1213 if (!$membershipStatusID) {
1216 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1221 * @param array $params
1225 function relationshipTypeCreate($params = array()) {
1226 $params = array_merge(array(
1227 'name_a_b' => 'Relation 1 for relationship type create',
1228 'name_b_a' => 'Relation 2 for relationship type create',
1229 'contact_type_a' => 'Individual',
1230 'contact_type_b' => 'Organization',
1237 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1238 CRM_Core_PseudoConstant
::flush('relationshipType');
1240 return $result['id'];
1244 * Function to delete Relatinship Type
1246 * @param int $relationshipTypeID
1248 function relationshipTypeDelete($relationshipTypeID) {
1249 $params['id'] = $relationshipTypeID;
1250 $this->callAPISuccess('relationship_type', 'delete', $params);
1254 * @param null $params
1258 function paymentProcessorTypeCreate($params = NULL) {
1259 if (is_null($params)) {
1261 'name' => 'API_Test_PP',
1262 'title' => 'API Test Payment Processor',
1263 'class_name' => 'CRM_Core_Payment_APITest',
1264 'billing_mode' => 'form',
1270 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1272 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1274 return $result['id'];
1278 * Function to create Participant
1280 * @param array $params array of contact id and event id values
1282 * @return int $id of participant created
1284 function participantCreate($params) {
1285 if(empty($params['contact_id'])){
1286 $params['contact_id'] = $this->individualCreate();
1288 if(empty($params['event_id'])){
1289 $event = $this->eventCreate();
1290 $params['event_id'] = $event['id'];
1295 'register_date' => 20070219,
1296 'source' => 'Wimbeldon',
1297 'event_level' => 'Payment',
1301 $params = array_merge($defaults, $params);
1302 $result = $this->callAPISuccess('Participant', 'create', $params);
1303 return $result['id'];
1307 * Function to create Payment Processor
1309 * @return object of Payment Processsor
1311 function processorCreate() {
1312 $processorParams = array(
1315 'payment_processor_type_id' => 10,
1316 'financial_account_id' => 12,
1319 'url_site' => 'http://dummy.com',
1320 'url_recur' => 'http://dummy.com',
1321 'billing_mode' => 1,
1323 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1324 return $paymentProcessor;
1328 * Function to create contribution page
1331 * @return object of contribution page
1333 function contributionPageCreate($params) {
1334 $this->_pageParams
= array(
1335 'title' => 'Test Contribution Page',
1336 'financial_type_id' => 1,
1337 'currency' => 'USD',
1338 'financial_account_id' => 1,
1339 'payment_processor' => $params['processor_id'],
1341 'is_allow_other_amount' => 1,
1343 'max_amount' => 1000,
1345 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1346 return $contributionPage;
1350 * Function to create Tag
1352 * @param array $params
1353 * @return array result of created tag
1355 function tagCreate($params = array()) {
1357 'name' => 'New Tag3',
1358 'description' => 'This is description for Our New Tag ',
1361 $params = array_merge($defaults, $params);
1362 $result = $this->callAPISuccess('Tag', 'create', $params);
1363 return $result['values'][$result['id']];
1367 * Function to delete Tag
1369 * @param int $tagId id of the tag to be deleted
1371 function tagDelete($tagId) {
1372 require_once 'api/api.php';
1376 $result = $this->callAPISuccess('Tag', 'delete', $params);
1377 return $result['id'];
1381 * Add entity(s) to the tag
1383 * @param array $params
1387 function entityTagAdd($params) {
1388 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1393 * Function to create contribution
1395 * @param int $cID contact_id
1397 * @internal param int $cTypeID id of financial type
1399 * @return int id of created contribution
1401 function pledgeCreate($cID) {
1403 'contact_id' => $cID,
1404 'pledge_create_date' => date('Ymd'),
1405 'start_date' => date('Ymd'),
1406 'scheduled_date' => date('Ymd'),
1408 'pledge_status_id' => '2',
1409 'financial_type_id' => '1',
1410 'pledge_original_installment_amount' => 20,
1411 'frequency_interval' => 5,
1412 'frequency_unit' => 'year',
1413 'frequency_day' => 15,
1414 'installments' => 5,
1417 $result = $this->callAPISuccess('Pledge', 'create', $params);
1418 return $result['id'];
1422 * Function to delete contribution
1425 * @internal param int $contributionId
1427 function pledgeDelete($pledgeId) {
1429 'pledge_id' => $pledgeId,
1431 $this->callAPISuccess('Pledge', 'delete', $params);
1435 * Function to create contribution
1437 * @param int $cID contact_id
1438 * @param int $cTypeID id of financial type
1440 * @param int $invoiceID
1441 * @param int $trxnID
1442 * @param int $paymentInstrumentID
1443 * @param bool $isFee
1444 * @return int id of created contribution
1446 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1449 'contact_id' => $cID,
1450 'receive_date' => date('Ymd'),
1451 'total_amount' => 100.00,
1452 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1453 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1454 'non_deductible_amount' => 10.00,
1455 'trxn_id' => $trxnID,
1456 'invoice_id' => $invoiceID,
1458 'contribution_status_id' => 1,
1459 // 'note' => 'Donating for Nobel Cause', *Fixme
1463 $params['fee_amount'] = 5.00;
1464 $params['net_amount'] = 95.00;
1467 $result = $this->callAPISuccess('contribution', 'create', $params);
1468 return $result['id'];
1472 * Function to create online contribution
1475 * @param int $financialType id of financial type
1477 * @param int $invoiceID
1478 * @param int $trxnID
1479 * @return int id of created contribution
1481 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1482 $contribParams = array(
1483 'contact_id' => $params['contact_id'],
1484 'receive_date' => date('Ymd'),
1485 'total_amount' => 100.00,
1486 'financial_type_id' => $financialType,
1487 'contribution_page_id' => $params['contribution_page_id'],
1489 'invoice_id' => 67890,
1492 $contribParams = array_merge($contribParams, $params);
1493 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1495 return $result['id'];
1499 * Function to delete contribution
1501 * @param int $contributionId
1505 function contributionDelete($contributionId) {
1507 'contribution_id' => $contributionId,
1509 $result = $this->callAPISuccess('contribution', 'delete', $params);
1514 * Function to create an Event
1516 * @param array $params name-value pair for an event
1518 * @return array $event
1520 function eventCreate($params = array()) {
1521 // if no contact was passed, make up a dummy event creator
1522 if (!isset($params['contact_id'])) {
1523 $params['contact_id'] = $this->_contactCreate(array(
1524 'contact_type' => 'Individual',
1525 'first_name' => 'Event',
1526 'last_name' => 'Creator',
1530 // set defaults for missing params
1531 $params = array_merge(array(
1532 'title' => 'Annual CiviCRM meet',
1533 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1534 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1535 'event_type_id' => 1,
1537 'start_date' => 20081021,
1538 'end_date' => 20081023,
1539 'is_online_registration' => 1,
1540 'registration_start_date' => 20080601,
1541 'registration_end_date' => 20081015,
1542 'max_participants' => 100,
1543 'event_full_text' => 'Sorry! We are already full',
1546 'is_show_location' => 0,
1549 return $this->callAPISuccess('Event', 'create', $params);
1553 * Function to delete event
1555 * @param int $id ID of the event
1559 function eventDelete($id) {
1563 return $this->callAPISuccess('event', 'delete', $params);
1567 * Function to delete participant
1569 * @param int $participantID
1573 function participantDelete($participantID) {
1575 'id' => $participantID,
1577 return $this->callAPISuccess('Participant', 'delete', $params);
1581 * Function to create participant payment
1583 * @param $participantID
1584 * @param null $contributionID
1585 * @return int $id of created payment
1587 function participantPaymentCreate($participantID, $contributionID = NULL) {
1588 //Create Participant Payment record With Values
1590 'participant_id' => $participantID,
1591 'contribution_id' => $contributionID,
1594 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1595 return $result['id'];
1599 * Function to delete participant payment
1601 * @param int $paymentID
1603 function participantPaymentDelete($paymentID) {
1607 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1611 * Function to add a Location
1614 * @return int location id of created location
1616 function locationAdd($contactID) {
1619 'location_type' => 'New Location Type',
1621 'name' => 'Saint Helier St',
1622 'county' => 'Marin',
1623 'country' => 'United States',
1624 'state_province' => 'Michigan',
1625 'supplemental_address_1' => 'Hallmark Ct',
1626 'supplemental_address_2' => 'Jersey Village',
1631 'contact_id' => $contactID,
1632 'address' => $address,
1633 'location_format' => '2.0',
1634 'location_type' => 'New Location Type',
1637 $result = $this->callAPISuccess('Location', 'create', $params);
1642 * Function to delete Locations of contact
1644 * @params array $pamars parameters
1646 function locationDelete($params) {
1647 $result = $this->callAPISuccess('Location', 'delete', $params);
1651 * Function to add a Location Type
1653 * @param null $params
1654 * @return int location id of created location
1656 function locationTypeCreate($params = NULL) {
1657 if ($params === NULL) {
1659 'name' => 'New Location Type',
1660 'vcard_name' => 'New Location Type',
1661 'description' => 'Location Type for Delete',
1666 $locationType = new CRM_Core_DAO_LocationType();
1667 $locationType->copyValues($params);
1668 $locationType->save();
1669 // clear getfields cache
1670 CRM_Core_PseudoConstant
::flush();
1671 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1672 return $locationType;
1676 * Function to delete a Location Type
1678 * @param int location type id
1680 function locationTypeDelete($locationTypeId) {
1681 $locationType = new CRM_Core_DAO_LocationType();
1682 $locationType->id
= $locationTypeId;
1683 $locationType->delete();
1687 * Function to add a Group
1689 * @params array to add group
1691 * @param array $params
1692 * @return int groupId of created group
1694 function groupCreate($params = array()) {
1695 $params = array_merge(array(
1696 'name' => 'Test Group 1',
1698 'title' => 'New Test Group Created',
1699 'description' => 'New Test Group Created',
1701 'visibility' => 'Public Pages',
1702 'group_type' => array(
1708 $result = $this->callAPISuccess('Group', 'create', $params);
1709 return $result['id'];
1713 * Function to delete a Group
1716 * @internal param int $id
1718 function groupDelete($gid) {
1724 $this->callAPISuccess('Group', 'delete', $params);
1729 * @param array $params
1731 function uFFieldCreate($params = array()) {
1732 $params = array_merge(array(
1734 'field_name' => 'first_name',
1737 'visibility' => 'Public Pages and Listings',
1738 'is_searchable' => '1',
1739 'label' => 'first_name',
1740 'field_type' => 'Individual',
1743 $this->callAPISuccess('uf_field', 'create', $params);
1747 * Function to add a UF Join Entry
1749 * @param null $params
1750 * @return int $id of created UF Join
1752 function ufjoinCreate($params = NULL) {
1753 if ($params === NULL) {
1756 'module' => 'CiviEvent',
1757 'entity_table' => 'civicrm_event',
1763 $result = $this->callAPISuccess('uf_join', 'create', $params);
1768 * Function to delete a UF Join Entry
1770 * @param array with missing uf_group_id
1772 function ufjoinDelete($params = NULL) {
1773 if ($params === NULL) {
1776 'module' => 'CiviEvent',
1777 'entity_table' => 'civicrm_event',
1780 'uf_group_id' => '',
1784 crm_add_uf_join($params);
1788 * Function to create Group for a contact
1790 * @param int $contactId
1792 function contactGroupCreate($contactId) {
1794 'contact_id.1' => $contactId,
1798 $this->callAPISuccess('GroupContact', 'Create', $params);
1802 * Function to delete Group for a contact
1805 * @internal param array $params
1807 function contactGroupDelete($contactId) {
1809 'contact_id.1' => $contactId,
1812 $this->civicrm_api('GroupContact', 'Delete', $params);
1816 * Function to create Activity
1818 * @param null $params
1820 * @internal param int $contactId
1822 function activityCreate($params = NULL) {
1824 if ($params === NULL) {
1825 $individualSourceID = $this->individualCreate();
1827 $contactParams = array(
1828 'first_name' => 'Julia',
1829 'Last_name' => 'Anderson',
1831 'email' => 'julia_anderson@civicrm.org',
1832 'contact_type' => 'Individual',
1835 $individualTargetID = $this->individualCreate($contactParams);
1838 'source_contact_id' => $individualSourceID,
1839 'target_contact_id' => array($individualTargetID),
1840 'assignee_contact_id' => array($individualTargetID),
1841 'subject' => 'Discussion on warm beer',
1842 'activity_date_time' => date('Ymd'),
1843 'duration_hours' => 30,
1844 'duration_minutes' => 20,
1845 'location' => 'Baker Street',
1846 'details' => 'Lets schedule a meeting',
1848 'activity_name' => 'Meeting',
1852 $result = $this->callAPISuccess('Activity', 'create', $params);
1854 $result['target_contact_id'] = $individualTargetID;
1855 $result['assignee_contact_id'] = $individualTargetID;
1860 * Function to create an activity type
1862 * @params array $params parameters
1864 function activityTypeCreate($params) {
1865 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1870 * Function to delete activity type
1872 * @params Integer $activityTypeId id of the activity type
1874 function activityTypeDelete($activityTypeId) {
1875 $params['activity_type_id'] = $activityTypeId;
1876 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1881 * Function to create custom group
1883 * @param array $params
1885 * @internal param string $className
1886 * @internal param string $title name of custom group
1888 function customGroupCreate($params = array()) {
1890 'title' => 'new custom group',
1891 'extends' => 'Contact',
1893 'style' => 'Inline',
1897 $params = array_merge($defaults, $params);
1899 if (strlen($params['title']) > 13) {
1900 $params['title'] = substr($params['title'], 0, 13);
1903 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1904 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1906 return $this->callAPISuccess('custom_group', 'create', $params);
1910 * existing function doesn't allow params to be over-ridden so need a new one
1911 * this one allows you to only pass in the params you want to change
1913 function CustomGroupCreateByParams($params = array()) {
1915 'title' => "API Custom Group",
1916 'extends' => 'Contact',
1918 'style' => 'Inline',
1921 $params = array_merge($defaults, $params);
1922 return $this->callAPISuccess('custom_group', 'create', $params);
1926 * Create custom group with multi fields
1928 function CustomGroupMultipleCreateByParams($params = array()) {
1933 $params = array_merge($defaults, $params);
1934 return $this->CustomGroupCreateByParams($params);
1938 * Create custom group with multi fields
1940 function CustomGroupMultipleCreateWithFields($params = array()) {
1941 // also need to pass on $params['custom_field'] if not set but not in place yet
1943 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1944 $ids['custom_group_id'] = $customGroup['id'];
1946 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1948 $ids['custom_field_id'][] = $customField['id'];
1950 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $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_3' . $ids['custom_group_id']));
1954 $ids['custom_field_id'][] = $customField['id'];
1960 * Create a custom group with a single text custom field. See
1961 * participant:testCreateWithCustom for how to use this
1963 * @param string $function __FUNCTION__
1965 * @internal param string $file __FILE__
1967 * @return array $ids ids of created objects
1969 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1970 $params = array('title' => $function);
1971 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1972 $params['extends'] = $entity ?
$entity : 'Contact';
1973 $customGroup = $this->CustomGroupCreate($params);
1974 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1975 CRM_Core_PseudoConstant
::flush();
1977 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1981 * Function to delete custom group
1983 * @param int $customGroupID
1987 function customGroupDelete($customGroupID) {
1988 $params['id'] = $customGroupID;
1989 return $this->callAPISuccess('custom_group', 'delete', $params);
1993 * Function to create custom field
1995 * @param array $params (custom_group_id) is required
1997 * @internal param string $name name of custom field
1998 * @internal param int $apiversion API version to use
2000 function customFieldCreate($params) {
2001 $params = array_merge(array(
2002 'label' => 'Custom Field',
2003 'data_type' => 'String',
2004 'html_type' => 'Text',
2005 'is_searchable' => 1,
2007 'default_value' => 'defaultValue',
2010 $result = $this->callAPISuccess('custom_field', 'create', $params);
2012 if ($result['is_error'] == 0 && isset($result['id'])) {
2013 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2014 // force reset of enabled components to help grab custom fields
2015 CRM_Core_Component
::getEnabledComponents(1);
2021 * Function to delete custom field
2023 * @param int $customFieldID
2027 function customFieldDelete($customFieldID) {
2029 $params['id'] = $customFieldID;
2030 return $this->callAPISuccess('custom_field', 'delete', $params);
2034 * Function to create note
2036 * @params array $params name-value pair for an event
2039 * @return array $note
2041 function noteCreate($cId) {
2043 'entity_table' => 'civicrm_contact',
2044 'entity_id' => $cId,
2045 'note' => 'hello I am testing Note',
2046 'contact_id' => $cId,
2047 'modified_date' => date('Ymd'),
2048 'subject' => 'Test Note',
2051 return $this->callAPISuccess('Note', 'create', $params);
2055 * Enable CiviCampaign Component
2057 function enableCiviCampaign() {
2058 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2059 // force reload of config object
2060 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2061 //flush cache by calling with reset
2062 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2066 * Create test generated example in api/v3/examples.
2067 * To turn this off (e.g. on the server) set
2068 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2069 * in your settings file
2070 * @param array $params array as passed to civicrm_api function
2071 * @param array $result array as received from the civicrm_api function
2072 * @param string $function calling function - generally __FUNCTION__
2073 * @param string $filename called from file - generally __FILE__
2074 * @param string $description descriptive text for the example file
2075 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2076 * @param string $action - optional action - otherwise taken from function name
2078 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2079 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2082 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2083 //todo - this is a bit cludgey
2084 if (empty($action)) {
2085 if (strstr($function, 'Create')) {
2086 $action = empty($action) ?
'create' : $action;
2087 $entityAction = 'Create';
2089 elseif (strstr($function, 'GetSingle')) {
2090 $action = empty($action) ?
'getsingle' : $action;
2091 $entityAction = 'GetSingle';
2093 elseif (strstr($function, 'GetValue')) {
2094 $action = empty($action) ?
'getvalue' : $action;
2095 $entityAction = 'GetValue';
2097 elseif (strstr($function, 'GetCount')) {
2098 $action = empty($action) ?
'getcount' : $action;
2099 $entityAction = 'GetCount';
2101 elseif (strstr($function, 'GetFields')) {
2102 $action = empty($action) ?
'getfields' : $action;
2103 $entityAction = 'GetFields';
2105 elseif (strstr($function, 'GetList')) {
2106 $action = empty($action) ?
'getlist' : $action;
2107 $entityAction = 'GetList';
2109 elseif (strstr($function, 'Get')) {
2110 $action = empty($action) ?
'get' : $action;
2111 $entityAction = 'Get';
2113 elseif (strstr($function, 'Delete')) {
2114 $action = empty($action) ?
'delete' : $action;
2115 $entityAction = 'Delete';
2117 elseif (strstr($function, 'Update')) {
2118 $action = empty($action) ?
'update' : $action;
2119 $entityAction = 'Update';
2121 elseif (strstr($function, 'Subscribe')) {
2122 $action = empty($action) ?
'subscribe' : $action;
2123 $entityAction = 'Subscribe';
2125 elseif (strstr($function, 'Submit')) {
2126 $action = empty($action) ?
'submit' : $action;
2127 $entityAction = 'Submit';
2129 elseif (strstr($function, 'Apply')) {
2130 $action = empty($action) ?
'apply' : $action;
2131 $entityAction = 'Apply';
2133 elseif (strstr($function, 'Replace')) {
2134 $action = empty($action) ?
'replace' : $action;
2135 $entityAction = 'Replace';
2139 $entityAction = ucwords($action);
2142 $this->tidyExampleResult($result);
2143 if(isset($params['version'])) {
2144 unset($params['version']);
2146 // a cleverer person than me would do it in a single regex
2147 if (strstr($entity, 'UF')) {
2148 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2151 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2153 $smarty = CRM_Core_Smarty
::singleton();
2154 $smarty->assign('testfunction', $function);
2155 $function = $fnPrefix . "_" . strtolower($action);
2156 $smarty->assign('function', $function);
2157 $smarty->assign('fnPrefix', $fnPrefix);
2158 $smarty->assign('params', $params);
2159 $smarty->assign('entity', $entity);
2160 $smarty->assign('filename', basename($filename));
2161 $smarty->assign('description', $description);
2162 $smarty->assign('result', $result);
2164 $smarty->assign('action', $action);
2165 if (empty($subfile)) {
2166 $subfile = $entityAction;
2168 if (file_exists('../tests/templates/documentFunction.tpl')) {
2169 if (!is_dir("../api/v3/examples/$entity")) {
2170 mkdir("../api/v3/examples/$entity");
2172 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2173 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2179 * Tidy up examples array so that fields that change often ..don't
2180 * and debug related fields are unset
2184 * @internal param array $params
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);
2258 * Function to delete note
2260 * @params int $noteID
2263 function noteDelete($params) {
2264 return $this->callAPISuccess('Note', 'delete', $params);
2268 * Function to create custom field with Option Values
2270 * @param array $customGroup
2271 * @param string $name name of custom field
2275 function customFieldOptionValueCreate($customGroup, $name) {
2276 $fieldParams = array(
2277 'custom_group_id' => $customGroup['id'],
2278 'name' => 'test_custom_group',
2279 'label' => 'Country',
2280 'html_type' => 'Select',
2281 'data_type' => 'String',
2284 'is_searchable' => 0,
2288 $optionGroup = array(
2290 'name' => 'option_group1',
2291 'label' => 'option_group_label1',
2294 $optionValue = array(
2295 'option_label' => array('Label1', 'Label2'),
2296 'option_value' => array('value1', 'value2'),
2297 'option_name' => array($name . '_1', $name . '_2'),
2298 'option_weight' => array(1, 2),
2299 'option_status' => 1,
2302 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2304 return $this->callAPISuccess('custom_field', 'create', $params);
2312 function confirmEntitiesDeleted($entities) {
2313 foreach ($entities as $entity) {
2315 $result = $this->callAPISuccess($entity, 'Get', array());
2316 if ($result['error'] == 1 ||
$result['count'] > 0) {
2317 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2324 * @param $tablesToTruncate
2325 * @param bool $dropCustomValueTables
2327 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2328 if ($dropCustomValueTables) {
2329 $tablesToTruncate[] = 'civicrm_custom_group';
2330 $tablesToTruncate[] = 'civicrm_custom_field';
2333 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2335 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2336 foreach ($tablesToTruncate as $table) {
2337 $sql = "TRUNCATE TABLE $table";
2338 CRM_Core_DAO
::executeQuery($sql);
2340 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2342 if ($dropCustomValueTables) {
2343 $dbName = self
::getDBName();
2345 SELECT TABLE_NAME as tableName
2346 FROM INFORMATION_SCHEMA.TABLES
2347 WHERE TABLE_SCHEMA = '{$dbName}'
2348 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2351 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2352 while ($tableDAO->fetch()) {
2353 $sql = "DROP TABLE {$tableDAO->tableName}";
2354 CRM_Core_DAO
::executeQuery($sql);
2360 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2362 function quickCleanUpFinancialEntities() {
2363 $tablesToTruncate = array(
2364 'civicrm_contribution',
2365 'civicrm_financial_trxn',
2366 'civicrm_contribution_recur',
2367 'civicrm_line_item',
2368 'civicrm_contribution_page',
2369 'civicrm_payment_processor',
2370 'civicrm_entity_financial_trxn',
2371 'civicrm_membership',
2372 'civicrm_membership_type',
2373 'civicrm_membership_payment',
2374 'civicrm_membership_log',
2375 'civicrm_membership_block',
2377 'civicrm_participant',
2378 'civicrm_participant_payment',
2380 'civicrm_price_set_entity',
2382 $this->quickCleanup($tablesToTruncate);
2383 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2386 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2387 * Default behaviour is to also delete the entity
2388 * @param array $params params array to check agains
2389 * @param int $id id of the entity concerned
2390 * @param string $entity name of entity concerned (e.g. membership)
2391 * @param bool $delete should the entity be deleted as part of this check
2392 * @param string $errorText text to print on error
2399 * @param int $delete
2400 * @param string $errorText
2404 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2406 $result = $this->callAPISuccessGetSingle($entity, array(
2411 $this->callAPISuccess($entity, 'Delete', array(
2415 $dateFields = $keys = $dateTimeFields = array();
2416 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2417 foreach ($fields['values'] as $field => $settings) {
2418 if (array_key_exists($field, $result)) {
2419 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2422 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2424 $type = CRM_Utils_Array
::value('type', $settings);
2425 if ($type == CRM_Utils_Type
::T_DATE
) {
2426 $dateFields[] = $settings['name'];
2427 // we should identify both real names & unique names as dates
2428 if($field != $settings['name']) {
2429 $dateFields[] = $field;
2432 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2433 $dateTimeFields[] = $settings['name'];
2434 // we should identify both real names & unique names as dates
2435 if($field != $settings['name']) {
2436 $dateTimeFields[] = $field;
2441 if (strtolower($entity) == 'contribution') {
2442 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2443 // this is not returned in id format
2444 unset($params['payment_instrument_id']);
2445 $params['contribution_source'] = $params['source'];
2446 unset($params['source']);
2449 foreach ($params as $key => $value) {
2450 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2453 if (in_array($key, $dateFields)) {
2454 $value = date('Y-m-d', strtotime($value));
2455 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2457 if (in_array($key, $dateTimeFields)) {
2458 $value = date('Y-m-d H:i:s', strtotime($value));
2459 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2461 $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);
2466 * Function to get formatted values in the actual and expected result
2467 * @param array $actual actual calculated values
2468 * @param array $expected expected values
2471 function checkArrayEquals(&$actual, &$expected) {
2472 self
::unsetId($actual);
2473 self
::unsetId($expected);
2474 $this->assertEquals($actual, $expected);
2478 * Function to unset the key 'id' from the array
2479 * @param array $unformattedArray The array from which the 'id' has to be unset
2482 static function unsetId(&$unformattedArray) {
2483 $formattedArray = array();
2484 if (array_key_exists('id', $unformattedArray)) {
2485 unset($unformattedArray['id']);
2487 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2488 foreach ($unformattedArray['values'] as $key => $value) {
2489 if (is_Array($value)) {
2490 foreach ($value as $k => $v) {
2496 elseif ($key == 'id') {
2497 $unformattedArray[$key];
2499 $formattedArray = array($value);
2501 $unformattedArray['values'] = $formattedArray;
2506 * Helper to enable/disable custom directory support
2508 * @param array $customDirs with members:
2509 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2510 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2512 function customDirectories($customDirs) {
2513 require_once 'CRM/Core/Config.php';
2514 $config = CRM_Core_Config
::singleton();
2516 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2517 unset($config->customPHPPathDir
);
2519 elseif ($customDirs['php_path'] === TRUE) {
2520 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2523 $config->customPHPPathDir
= $php_path;
2526 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2527 unset($config->customTemplateDir
);
2529 elseif ($customDirs['template_path'] === TRUE) {
2530 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2533 $config->customTemplateDir
= $template_path;
2538 * Generate a temporary folder
2540 * @param string $prefix
2541 * @return string $string
2543 function createTempDir($prefix = 'test-') {
2544 $tempDir = CRM_Utils_File
::tempdir($prefix);
2545 $this->tempDirs
[] = $tempDir;
2549 function cleanTempDirs() {
2550 if (!is_array($this->tempDirs
)) {
2551 // fix test errors where this is not set
2554 foreach ($this->tempDirs
as $tempDir) {
2555 if (is_dir($tempDir)) {
2556 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2562 * Temporarily replace the singleton extension with a different one
2564 function setExtensionSystem(CRM_Extension_System
$system) {
2565 if ($this->origExtensionSystem
== NULL) {
2566 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2568 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2571 function unsetExtensionSystem() {
2572 if ($this->origExtensionSystem
!== NULL) {
2573 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2574 $this->origExtensionSystem
= NULL;
2579 * Temporarily alter the settings-metadata to add a mock setting.
2581 * WARNING: The setting metadata will disappear on the next cache-clear.
2586 function setMockSettingsMetaData($extras) {
2587 CRM_Core_BAO_Setting
::$_cache = array();
2588 $this->callAPISuccess('system','flush', array());
2589 CRM_Core_BAO_Setting
::$_cache = array();
2591 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2592 $metadata = array_merge($metadata, $extras);
2595 $fields = $this->callAPISuccess('setting', 'getfields', array());
2596 foreach ($extras as $key => $spec) {
2597 $this->assertNotEmpty($spec['title']);
2598 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2605 function financialAccountDelete($name) {
2606 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2607 $financialAccount->name
= $name;
2608 if($financialAccount->find(TRUE)) {
2609 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2610 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2611 $entityFinancialType->delete();
2612 $financialAccount->delete();
2617 * Use $ids as an instruction to do test cleanup
2619 function deleteFromIDSArray() {
2620 foreach ($this->ids
as $entity => $ids) {
2621 foreach ($ids as $id) {
2622 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2628 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2629 * (NB unclear if this is still required)
2631 function _sethtmlGlobals() {
2632 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2633 'required' => array(
2634 'html_quickform_rule_required',
2635 'HTML/QuickForm/Rule/Required.php'
2637 'maxlength' => array(
2638 'html_quickform_rule_range',
2639 'HTML/QuickForm/Rule/Range.php'
2641 'minlength' => array(
2642 'html_quickform_rule_range',
2643 'HTML/QuickForm/Rule/Range.php'
2645 'rangelength' => array(
2646 'html_quickform_rule_range',
2647 'HTML/QuickForm/Rule/Range.php'
2650 'html_quickform_rule_email',
2651 'HTML/QuickForm/Rule/Email.php'
2654 'html_quickform_rule_regex',
2655 'HTML/QuickForm/Rule/Regex.php'
2657 'lettersonly' => array(
2658 'html_quickform_rule_regex',
2659 'HTML/QuickForm/Rule/Regex.php'
2661 'alphanumeric' => array(
2662 'html_quickform_rule_regex',
2663 'HTML/QuickForm/Rule/Regex.php'
2666 'html_quickform_rule_regex',
2667 'HTML/QuickForm/Rule/Regex.php'
2669 'nopunctuation' => array(
2670 'html_quickform_rule_regex',
2671 'HTML/QuickForm/Rule/Regex.php'
2674 'html_quickform_rule_regex',
2675 'HTML/QuickForm/Rule/Regex.php'
2677 'callback' => array(
2678 'html_quickform_rule_callback',
2679 'HTML/QuickForm/Rule/Callback.php'
2682 'html_quickform_rule_compare',
2683 'HTML/QuickForm/Rule/Compare.php'
2686 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2687 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2689 'HTML/QuickForm/group.php',
2690 'HTML_QuickForm_group'
2693 'HTML/QuickForm/hidden.php',
2694 'HTML_QuickForm_hidden'
2697 'HTML/QuickForm/reset.php',
2698 'HTML_QuickForm_reset'
2700 'checkbox' => array(
2701 'HTML/QuickForm/checkbox.php',
2702 'HTML_QuickForm_checkbox'
2705 'HTML/QuickForm/file.php',
2706 'HTML_QuickForm_file'
2709 'HTML/QuickForm/image.php',
2710 'HTML_QuickForm_image'
2712 'password' => array(
2713 'HTML/QuickForm/password.php',
2714 'HTML_QuickForm_password'
2717 'HTML/QuickForm/radio.php',
2718 'HTML_QuickForm_radio'
2721 'HTML/QuickForm/button.php',
2722 'HTML_QuickForm_button'
2725 'HTML/QuickForm/submit.php',
2726 'HTML_QuickForm_submit'
2729 'HTML/QuickForm/select.php',
2730 'HTML_QuickForm_select'
2732 'hiddenselect' => array(
2733 'HTML/QuickForm/hiddenselect.php',
2734 'HTML_QuickForm_hiddenselect'
2737 'HTML/QuickForm/text.php',
2738 'HTML_QuickForm_text'
2740 'textarea' => array(
2741 'HTML/QuickForm/textarea.php',
2742 'HTML_QuickForm_textarea'
2744 'fckeditor' => array(
2745 'HTML/QuickForm/fckeditor.php',
2746 'HTML_QuickForm_FCKEditor'
2749 'HTML/QuickForm/tinymce.php',
2750 'HTML_QuickForm_TinyMCE'
2752 'dojoeditor' => array(
2753 'HTML/QuickForm/dojoeditor.php',
2754 'HTML_QuickForm_dojoeditor'
2757 'HTML/QuickForm/link.php',
2758 'HTML_QuickForm_link'
2760 'advcheckbox' => array(
2761 'HTML/QuickForm/advcheckbox.php',
2762 'HTML_QuickForm_advcheckbox'
2765 'HTML/QuickForm/date.php',
2766 'HTML_QuickForm_date'
2769 'HTML/QuickForm/static.php',
2770 'HTML_QuickForm_static'
2773 'HTML/QuickForm/header.php',
2774 'HTML_QuickForm_header'
2777 'HTML/QuickForm/html.php',
2778 'HTML_QuickForm_html'
2780 'hierselect' => array(
2781 'HTML/QuickForm/hierselect.php',
2782 'HTML_QuickForm_hierselect'
2784 'autocomplete' => array(
2785 'HTML/QuickForm/autocomplete.php',
2786 'HTML_QuickForm_autocomplete'
2789 'HTML/QuickForm/xbutton.php',
2790 'HTML_QuickForm_xbutton'
2792 'advmultiselect' => array(
2793 'HTML/QuickForm/advmultiselect.php',
2794 'HTML_QuickForm_advmultiselect'
2800 * Set up an acl allowing contact to see 2 specified groups
2801 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2803 * You need to have precreated these groups & created the user e.g
2804 * $this->createLoggedInUser();
2805 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2806 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2809 function setupACL() {
2811 $_REQUEST = $this->_params
;
2813 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2814 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2815 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2816 'label' => 'pick me',
2821 CRM_Core_DAO
::executeQuery("
2822 TRUNCATE civicrm_acl_cache
2825 CRM_Core_DAO
::executeQuery("
2826 TRUNCATE civicrm_acl_contact_cache
2830 CRM_Core_DAO
::executeQuery("
2831 INSERT INTO civicrm_acl_entity_role (
2832 `acl_role_id`, `entity_table`, `entity_id`
2833 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2836 CRM_Core_DAO
::executeQuery("
2837 INSERT INTO civicrm_acl (
2838 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2841 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2845 CRM_Core_DAO
::executeQuery("
2846 INSERT INTO civicrm_acl (
2847 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2850 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2853 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2854 $this->callAPISuccess('group_contact', 'create', array(
2855 'group_id' => $this->_permissionedGroup
,
2856 'contact_id' => $this->_loggedInUser
,
2859 CRM_ACL_BAO_Cache
::resetCache();
2860 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2861 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2865 * alter default price set so that the field numbers are not all 1 (hiding errors)
2867 function offsetDefaultPriceSet() {
2868 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2869 $firstID = $contributionPriceSet['id'];
2870 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2871 unset($contributionPriceSet['id']);
2872 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2873 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2874 unset($priceField['id']);
2875 $priceField['price_set_id'] = $newPriceSet['id'];
2876 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2877 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2879 unset($priceFieldValue['id']);
2880 //create some padding to use up ids
2881 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2882 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2883 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2887 * Create an instance of the paypal processor
2888 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2889 * this parent class & we don't have a structure for that yet
2890 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2891 * & the best protection agains that is the functions this class affords
2893 function paymentProcessorCreate($params = array()) {
2894 $params = array_merge(array(
2896 'domain_id' => CRM_Core_Config
::domainID(),
2897 'payment_processor_type_id' => 'PayPal',
2901 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2902 'password' => '1183377788',
2903 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2904 'url_site' => 'https://www.sandbox.paypal.com/',
2905 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2906 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2907 'class_name' => 'Payment_PayPalImpl',
2908 'billing_mode' => 3,
2909 'financial_type_id' => 1,
2912 if(!is_numeric($params['payment_processor_type_id'])) {
2913 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2915 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2916 'name' => $params['payment_processor_type_id'],
2920 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2921 return $result['id'];
2929 */function CiviUnitTestCase_fatalErrorHandler($message) {
2930 throw new Exception("{$message['message']}: {$message['code']}");