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 'PHPUnit/Extensions/Database/TestCase.php';
43 require_once 'PHPUnit/Framework/TestResult.php';
44 require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45 require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46 require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47 require_once 'tests/phpunit/Utils.php';
48 require_once 'api/api.php';
49 require_once 'CRM/Financial/BAO/FinancialType.php';
50 define('API_LATEST_VERSION', 3);
53 * Base class for CiviCRM unit tests
55 * Common functions for unit tests
58 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
61 * api version - easier to override than just a defin
63 protected $_apiversion = API_LATEST_VERSION
;
65 * Database has been initialized
69 private static $dbInit = FALSE;
74 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
83 static protected $_dbName;
86 * Track tables we have modified during a test
88 protected $_tablesToTruncate = array();
91 * @var array of temporary directory names
101 * @var boolean populateOnce allows to skip db resets in setUp
103 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
104 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
107 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
109 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
111 public static $populateOnce = FALSE;
114 * Allow classes to state E-notice compliance
116 public $_eNoticeCompliant = TRUE;
119 * @var boolean DBResetRequired allows skipping DB reset
120 * in specific test case. If you still need
121 * to reset single test (method) of such case, call
122 * $this->cleanDB() in the first line of this
125 public $DBResetRequired = TRUE;
130 * Because we are overriding the parent class constructor, we
131 * need to show the same arguments as exist in the constructor of
132 * PHPUnit_Framework_TestCase, since
133 * PHPUnit_Framework_TestSuite::createTest() creates a
134 * ReflectionClass of the Test class and checks the constructor
135 * of that class to decide how to set up the test.
137 * @param string $name
139 * @param string $dataName
141 function __construct($name = NULL, array$data = array(), $dataName = '') {
142 parent
::__construct($name, $data, $dataName);
144 // we need full error reporting
145 error_reporting(E_ALL
& ~E_NOTICE
);
147 if (!empty($GLOBALS['mysql_db'])) {
148 self
::$_dbName = $GLOBALS['mysql_db'];
151 self
::$_dbName = 'civicrm_tests_dev';
154 // create test database
155 self
::$utils = new Utils($GLOBALS['mysql_host'],
156 $GLOBALS['mysql_port'],
157 $GLOBALS['mysql_user'],
158 $GLOBALS['mysql_pass']
161 // also load the class loader
162 require_once 'CRM/Core/ClassLoader.php';
163 CRM_Core_ClassLoader
::singleton()->register();
164 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
165 _civix_phpunit_setUp();
172 function requireDBReset() {
173 return $this->DBResetRequired
;
179 static function getDBName() {
180 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
185 * Create database connection for this instance
187 * Initialize the test database if it hasn't been initialized
189 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
191 protected function getConnection() {
192 $dbName = self
::$_dbName;
193 if (!self
::$dbInit) {
194 $dbName = self
::getDBName();
196 // install test database
197 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
199 static::_populateDB(FALSE, $this);
201 self
::$dbInit = TRUE;
203 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
207 * Required implementation of abstract method
209 protected function getDataSet() {
213 * @param bool $perClass
214 * @param null $object
215 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
217 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
219 if ($perClass ||
$object == NULL) {
223 $dbreset = $object->requireDBReset();
226 if (self
::$populateOnce ||
!$dbreset) {
229 self
::$populateOnce = NULL;
231 $dbName = self
::getDBName();
232 $pdo = self
::$utils->pdo
;
233 // only consider real tables and not views
234 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
235 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
237 $truncates = array();
239 foreach ($tables as $table) {
241 if (substr($table['table_name'], 0, 4) == 'log_') {
245 // don't change list of installed extensions
246 if ($table['table_name'] == 'civicrm_extension') {
250 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
251 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
254 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
260 "SET foreign_key_checks = 0",
261 // SQL mode needs to be strict, that's our standard
262 "SET SQL_MODE='STRICT_ALL_TABLES';",
263 "SET global innodb_flush_log_at_trx_commit = 2;",
265 $queries = array_merge($queries, $truncates);
266 $queries = array_merge($queries, $drops);
267 foreach ($queries as $query) {
268 if (self
::$utils->do_query($query) === FALSE) {
269 // failed to create test database
270 echo "failed to create test db.";
275 // initialize test database
276 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
277 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
278 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
280 $query2 = file_get_contents($sql_file2);
281 $query3 = file_get_contents($sql_file3);
282 $query4 = file_get_contents($sql_file4);
283 if (self
::$utils->do_query($query2) === FALSE) {
284 echo "Cannot load civicrm_data.mysql. Aborting.";
287 if (self
::$utils->do_query($query3) === FALSE) {
288 echo "Cannot load test_data.mysql. Aborting.";
291 if (self
::$utils->do_query($query4) === FALSE) {
292 echo "Cannot load test_data.mysql. Aborting.";
296 // done with all the loading, get transactions back
297 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
298 echo "Cannot set global? Huh?";
302 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
303 echo "Cannot get foreign keys back? Huh?";
307 unset($query, $query2, $query3);
310 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
315 public static function setUpBeforeClass() {
316 static::_populateDB(TRUE);
318 // also set this global hack
319 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
321 $env = new CRM_Utils_Check_Env();
322 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
326 * Common setup functions for all unit tests
328 protected function setUp() {
329 CRM_Utils_Hook
::singleton(TRUE);
330 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
331 // Use a temporary file for STDIN
332 $GLOBALS['stdin'] = tmpfile();
333 if ($GLOBALS['stdin'] === FALSE) {
334 echo "Couldn't open temporary file\n";
338 // Get and save a connection to the database
339 $this->_dbconn
= $this->getConnection();
341 // reload database before each test
342 // $this->_populateDB();
344 // "initialize" CiviCRM to avoid problems when running single tests
345 // FIXME: look at it closer in second stage
347 // initialize the object once db is loaded
348 CRM_Core_Config
::$_mail = NULL;
349 $config = CRM_Core_Config
::singleton();
351 // when running unit tests, use mockup user framework
352 $config->setUserFramework('UnitTests');
354 // also fix the fatal error handler to throw exceptions,
356 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
358 // enable backtrace to get meaningful errors
359 $config->backtrace
= 1;
361 // disable any left-over test extensions
362 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
364 // reset all the caches
365 CRM_Utils_System
::flushCache();
367 // clear permissions stub to not check permissions
368 $config = CRM_Core_Config
::singleton();
369 $config->userPermissionClass
->permissions
= NULL;
371 //flush component settings
372 CRM_Core_Component
::getEnabledComponents(TRUE);
374 if ($this->_eNoticeCompliant
) {
375 error_reporting(E_ALL
);
378 error_reporting(E_ALL
& ~E_NOTICE
);
380 $this->_sethtmlGlobals();
384 * Read everything from the datasets directory and insert into the db
386 public function loadAllFixtures() {
387 $fixturesDir = __DIR__
. '/../../fixtures';
389 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
391 $xmlFiles = glob($fixturesDir . '/*.xml');
392 foreach ($xmlFiles as $xmlFixture) {
393 $op = new PHPUnit_Extensions_Database_Operation_Insert();
394 $dataset = new PHPUnit_Extensions_Database_DataSet_XMLDataSet($xmlFixture);
395 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
396 $op->execute($this->_dbconn
, $dataset);
399 $yamlFiles = glob($fixturesDir . '/*.yaml');
400 foreach ($yamlFiles as $yamlFixture) {
401 $op = new PHPUnit_Extensions_Database_Operation_Insert();
402 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
403 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
404 $op->execute($this->_dbconn
, $dataset);
407 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
411 * emulate a logged in user since certain functions use that
412 * value to store a record in the DB (like activity)
415 public function createLoggedInUser() {
417 'first_name' => 'Logged In',
418 'last_name' => 'User ' . rand(),
419 'contact_type' => 'Individual',
421 $contactID = $this->individualCreate($params);
423 $session = CRM_Core_Session
::singleton();
424 $session->set('userID', $contactID);
427 public function cleanDB() {
428 self
::$populateOnce = NULL;
429 $this->DBResetRequired
= TRUE;
431 $this->_dbconn
= $this->getConnection();
432 static::_populateDB();
433 $this->tempDirs
= array();
437 * Common teardown functions for all unit tests
439 protected function tearDown() {
440 error_reporting(E_ALL
& ~E_NOTICE
);
441 $tablesToTruncate = array('civicrm_contact');
442 $this->quickCleanup($tablesToTruncate);
443 $this->cleanTempDirs();
444 $this->unsetExtensionSystem();
448 * FIXME: Maybe a better way to do it
450 function foreignKeyChecksOff() {
451 self
::$utils = new Utils($GLOBALS['mysql_host'],
452 $GLOBALS['mysql_port'],
453 $GLOBALS['mysql_user'],
454 $GLOBALS['mysql_pass']
456 $dbName = self
::getDBName();
457 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
458 if (self
::$utils->do_query($query) === FALSE) {
460 echo 'Cannot set foreign_key_checks = 0';
466 function foreignKeyChecksOn() {
467 // FIXME: might not be needed if previous fixme implemented
471 * Generic function to compare expected values after an api call to retrieved
474 * @daoName string DAO Name of object we're evaluating.
475 * @id int Id of object
476 * @match array Associative array of field name => expected value. Empty if asserting
477 * that a DELETE occurred
478 * @delete boolean True if we're checking that a DELETE action occurred.
480 function assertDBState($daoName, $id, $match, $delete = FALSE) {
482 // adding this here since developers forget to check for an id
483 // and hence we get the first value in the db
484 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
487 $object = new $daoName();
491 // If we're asserting successful record deletion, make sure object is NOT found.
493 if ($object->find(TRUE)) {
494 $this->fail("Object not deleted by delete operation: $daoName, $id");
499 // Otherwise check matches of DAO field values against expected values in $match.
500 if ($object->find(TRUE)) {
501 $fields = & $object->fields();
502 foreach ($fields as $name => $value) {
503 $dbName = $value['name'];
504 if (isset($match[$name])) {
506 $this->assertEquals($object->$dbName, $match[$name]);
508 elseif (isset($match[$dbName])) {
510 $this->assertEquals($object->$dbName, $match[$dbName]);
515 $this->fail("Could not retrieve object: $daoName, $id");
518 $matchSize = count($match);
519 if ($verifiedCount != $matchSize) {
520 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
524 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
527 * @param $searchValue
528 * @param $returnColumn
529 * @param $searchColumn
532 * @return null|string
533 * @throws PHPUnit_Framework_AssertionFailedError
535 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
536 if (empty($searchValue)) {
537 $this->fail("empty value passed to assertDBNotNull");
539 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
540 $this->assertNotNull($value, $message);
545 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
548 * @param $searchValue
549 * @param $returnColumn
550 * @param $searchColumn
553 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
554 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
555 $this->assertNull($value, $message);
558 // Request a record from the DB by id. Success if row not found.
562 * @param null $message
564 function assertDBRowNotExist($daoName, $id, $message = NULL) {
565 $message = $message ?
$message : "$daoName (#$id) should not exist";
566 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
567 $this->assertNull($value, $message);
570 // Request a record from the DB by id. Success if row not found.
574 * @param null $message
576 function assertDBRowExist($daoName, $id, $message = NULL) {
577 $message = $message ?
$message : "$daoName (#$id) should exist";
578 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
579 $this->assertEquals($id, $value, $message);
582 // Compare a single column value in a retrieved DB record to an expected value
585 * @param $searchValue
586 * @param $returnColumn
587 * @param $searchColumn
588 * @param $expectedValue
591 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
592 $expectedValue, $message
594 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
595 $this->assertEquals($value, $expectedValue, $message);
598 // Compare all values in a single retrieved DB record to an array of expected values
601 * @param $searchParams
602 * @param $expectedValues
604 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
605 //get the values from db
607 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
609 // compare db values with expected values
610 self
::assertAttributesEquals($expectedValues, $dbValues);
614 * Assert that a SQL query returns a given value
616 * The first argument is an expected value. The remaining arguments are passed
617 * to CRM_Core_DAO::singleValueQuery
619 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
620 * array(1 => array("Whiz", "String")));
622 function assertDBQuery($expected, $query, $params = array()) {
623 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
624 $this->assertEquals($expected, $actual,
625 sprintf('expected=[%s] actual=[%s] query=[%s]',
626 $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
632 * Assert that two array-trees are exactly equal, notwithstanding
633 * the sorting of keys
635 * @param array $expected
636 * @param array $actual
638 function assertTreeEquals($expected, $actual) {
641 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
642 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
646 $this->assertEquals($e, $a);
650 * Assert that two numbers are approximately equal
652 * @param int|float $expected
653 * @param int|float $actual
654 * @param int|float $tolerance
655 * @param string $message
657 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
658 if ($message === NULL) {
659 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
661 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
665 * @param $expectedValues
666 * @param $actualValues
667 * @param null $message
669 * @throws PHPUnit_Framework_AssertionFailedError
671 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
672 foreach ($expectedValues as $paramName => $paramValue) {
673 if (isset($actualValues[$paramName])) {
674 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
677 $this->fail("Attribute '$paramName' not present in actual array.");
686 function assertArrayKeyExists($key, &$list) {
687 $result = isset($list[$key]) ?
TRUE : FALSE;
688 $this->assertTrue($result, ts("%1 element exists?",
697 function assertArrayValueNotNull($key, &$list) {
698 $this->assertArrayKeyExists($key, $list);
700 $value = isset($list[$key]) ?
$list[$key] : NULL;
701 $this->assertTrue($value,
702 ts("%1 element not null?",
709 * check that api returned 'is_error' => 0
710 * else provide full message
711 * @param array $apiResult api result
712 * @param string $prefix extra test to add to message
714 function assertAPISuccess($apiResult, $prefix = '') {
715 if (!empty($prefix)) {
718 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
720 if(!empty($apiResult['debug_information'])) {
721 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
723 if(!empty($apiResult['trace'])){
724 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
726 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
730 * check that api returned 'is_error' => 1
731 * else provide full message
733 * @param array $apiResult api result
734 * @param string $prefix extra test to add to message
735 * @param null $expectedError
737 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
738 if (!empty($prefix)) {
741 if($expectedError && !empty($apiResult['is_error'])){
742 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
744 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
745 $this->assertNotEmpty($apiResult['error_message']);
751 * @param string $message
753 function assertType($expected, $actual, $message = '') {
754 return $this->assertInternalType($expected, $actual, $message);
758 * check that a deleted item has been deleted
760 function assertAPIDeleted($entity, $id) {
761 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
766 * check that api returned 'is_error' => 1
767 * else provide full message
770 * @param array $valuesToExclude
771 * @param string $prefix extra test to add to message
772 * @internal param array $apiResult api result
774 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
775 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
776 foreach ($valuesToExclude as $value) {
777 if(isset($result[$value])) {
778 unset($result[$value]);
780 if(isset($expected[$value])) {
781 unset($expected[$value]);
784 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
788 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
795 function civicrm_api($entity, $action, $params) {
796 return civicrm_api($entity, $action, $params);
800 * This function exists to wrap api functions
801 * so we can ensure they succeed & throw exceptions without litterering the test with checks
803 * @param string $entity
804 * @param string $action
805 * @param array $params
806 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
807 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
808 * for getsingle the array is compared against an array passed in - the id is not compared (for
813 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
814 $params = array_merge(array(
815 'version' => $this->_apiversion
,
820 switch (strtolower($action)) {
822 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
824 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
826 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
828 $result = $this->civicrm_api($entity, $action, $params);
829 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
834 * This function exists to wrap api getValue function & check the result
835 * so we can ensure they succeed & throw exceptions without litterering the test with checks
836 * There is a type check in this
838 * @param string $entity
839 * @param array $params
840 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
850 function callAPISuccessGetValue($entity, $params, $type = NULL) {
852 'version' => $this->_apiversion
,
855 $result = $this->civicrm_api($entity, 'getvalue', $params);
857 if($type == 'integer'){
858 // api seems to return integers as strings
859 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
862 $this->assertType($type, $result, "returned result should have been of type $type but was " );
869 * This function exists to wrap api getsingle function & check the result
870 * so we can ensure they succeed & throw exceptions without litterering the test with checks
872 * @param string $entity
873 * @param array $params
874 * @param array $checkAgainst - array to compare result against
885 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
887 'version' => $this->_apiversion
,
890 $result = $this->civicrm_api($entity, 'getsingle', $params);
891 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
892 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
895 // @todo - have gone with the fn that unsets id? should we check id?
896 $this->checkArrayEquals($result, $checkAgainst);
902 * This function exists to wrap api getValue function & check the result
903 * so we can ensure they succeed & throw exceptions without litterering the test with checks
904 * There is a type check in this
905 * @param string $entity
906 * @param array $params
910 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
918 function callAPISuccessGetCount($entity, $params, $count = NULL) {
920 'version' => $this->_apiversion
,
923 $result = $this->civicrm_api($entity, 'getcount', $params);
924 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
925 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
928 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
934 * This function exists to wrap api functions
935 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
937 * @param string $entity
938 * @param string $action
939 * @param array $params
940 * @param string $function - pass this in to create a generated example
941 * @param string $file - pass this in to create a generated example
942 * @param string $description
943 * @param string|null $subfile
944 * @param string|null $actionName
947 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
948 $params['version'] = $this->_apiversion
;
949 $result = $this->callAPISuccess($entity, $action, $params);
950 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
955 * This function exists to wrap api functions
956 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
957 * @param string $entity
958 * @param string $action
959 * @param array $params
960 * @param string $expectedErrorMessage error
961 * @param null $extraOutput
964 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
965 if (is_array($params)) {
967 'version' => $this->_apiversion
,
970 $result = $this->civicrm_api($entity, $action, $params);
971 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
976 * Create required data based on $this->entity & $this->params
977 * This is just a way to set up the test data for delete & get functions
978 * so the distinction between set
979 * up & tested functions is clearer
981 * @return array api Result
983 public function createTestEntity(){
984 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
988 * Generic function to create Organisation, to be used in test cases
990 * @param array parameters for civicrm_contact_add api function call
992 * @return int id of Organisation created
994 function organizationCreate($params = array()) {
999 'organization_name' => 'Unit Test Organization',
1000 'contact_type' => 'Organization',
1002 return $this->_contactCreate(array_merge($orgParams, $params));
1006 * Generic function to create Individual, to be used in test cases
1008 * @param array parameters for civicrm_contact_add api function call
1010 * @return int id of Individual created
1012 function individualCreate($params = array()) {
1013 $params = array_merge(array(
1014 'first_name' => 'Anthony',
1015 'middle_name' => 'J.',
1016 'last_name' => 'Anderson',
1019 'email' => 'anthony_anderson@civicrm.org',
1020 'contact_type' => 'Individual',
1023 return $this->_contactCreate($params);
1027 * Generic function to create Household, to be used in test cases
1029 * @param array parameters for civicrm_contact_add api function call
1031 * @return int id of Household created
1033 function householdCreate($params = array()) {
1034 $params = array_merge(array(
1035 'household_name' => 'Unit Test household',
1036 'contact_type' => 'Household',
1038 return $this->_contactCreate($params);
1042 * Private helper function for calling civicrm_contact_add
1047 * @internal param \parameters $array for civicrm_contact_add api function call
1049 * @return int id of Household created
1051 private function _contactCreate($params) {
1052 $result = $this->callAPISuccess('contact', 'create', $params);
1053 if (!empty($result['is_error']) ||
empty($result['id'])) {
1054 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1056 return $result['id'];
1064 function contactDelete($contactID) {
1067 'skip_undelete' => 1,
1070 $domain = new CRM_Core_BAO_Domain
;
1071 $domain->contact_id
= $contactID;
1072 if ($domain->find(TRUE)) {
1073 // we are finding tests trying to delete the domain contact in cleanup
1074 //since this is mainly for cleanup lets put a safeguard here
1077 $result = $this->callAPISuccess('contact', 'delete', $params);
1082 * @param $contactTypeId
1086 function contactTypeDelete($contactTypeId) {
1087 require_once 'CRM/Contact/BAO/ContactType.php';
1088 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1090 throw new Exception('Could not delete contact type');
1095 * @param array $params
1099 function membershipTypeCreate($params = array()) {
1100 CRM_Member_PseudoConstant
::flush('membershipType');
1101 CRM_Core_Config
::clearDBCache();
1102 $memberOfOrganization = $this->organizationCreate();
1103 $params = array_merge(array(
1104 'name' => 'General',
1105 'duration_unit' => 'year',
1106 'duration_interval' => 1,
1107 'period_type' => 'rolling',
1108 'member_of_contact_id' => $memberOfOrganization,
1110 'financial_type_id' => 1,
1113 'visibility' => 'Public',
1116 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1118 CRM_Member_PseudoConstant
::flush('membershipType');
1119 CRM_Utils_Cache
::singleton()->flush();
1121 return $result['id'];
1129 function contactMembershipCreate($params) {
1131 'join_date' => '2007-01-21',
1132 'start_date' => '2007-01-21',
1133 'end_date' => '2007-12-21',
1134 'source' => 'Payment',
1137 foreach ($pre as $key => $val) {
1138 if (!isset($params[$key])) {
1139 $params[$key] = $val;
1143 $result = $this->callAPISuccess('Membership', 'create', $params);
1144 return $result['id'];
1148 * Function to delete Membership Type
1151 * @internal param int $membershipTypeID
1153 function membershipTypeDelete($params) {
1154 $this->callAPISuccess('MembershipType', 'Delete', $params);
1158 * @param $membershipID
1160 function membershipDelete($membershipID) {
1161 $deleteParams = array('id' => $membershipID);
1162 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1167 * @param string $name
1171 function membershipStatusCreate($name = 'test member status') {
1172 $params['name'] = $name;
1173 $params['start_event'] = 'start_date';
1174 $params['end_event'] = 'end_date';
1175 $params['is_current_member'] = 1;
1176 $params['is_active'] = 1;
1178 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1179 CRM_Member_PseudoConstant
::flush('membershipStatus');
1180 return $result['id'];
1184 * @param $membershipStatusID
1186 function membershipStatusDelete($membershipStatusID) {
1187 if (!$membershipStatusID) {
1190 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1195 * @param array $params
1199 function relationshipTypeCreate($params = array()) {
1200 $params = array_merge(array(
1201 'name_a_b' => 'Relation 1 for relationship type create',
1202 'name_b_a' => 'Relation 2 for relationship type create',
1203 'contact_type_a' => 'Individual',
1204 'contact_type_b' => 'Organization',
1211 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1212 CRM_Core_PseudoConstant
::flush('relationshipType');
1214 return $result['id'];
1218 * Function to delete Relatinship Type
1220 * @param int $relationshipTypeID
1222 function relationshipTypeDelete($relationshipTypeID) {
1223 $params['id'] = $relationshipTypeID;
1224 $this->callAPISuccess('relationship_type', 'delete', $params);
1228 * @param null $params
1232 function paymentProcessorTypeCreate($params = NULL) {
1233 if (is_null($params)) {
1235 'name' => 'API_Test_PP',
1236 'title' => 'API Test Payment Processor',
1237 'class_name' => 'CRM_Core_Payment_APITest',
1238 'billing_mode' => 'form',
1244 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1246 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1248 return $result['id'];
1252 * Function to create Participant
1254 * @param array $params array of contact id and event id values
1256 * @return int $id of participant created
1258 function participantCreate($params) {
1259 if(empty($params['contact_id'])){
1260 $params['contact_id'] = $this->individualCreate();
1262 if(empty($params['event_id'])){
1263 $event = $this->eventCreate();
1264 $params['event_id'] = $event['id'];
1269 'register_date' => 20070219,
1270 'source' => 'Wimbeldon',
1271 'event_level' => 'Payment',
1275 $params = array_merge($defaults, $params);
1276 $result = $this->callAPISuccess('Participant', 'create', $params);
1277 return $result['id'];
1281 * Function to create Payment Processor
1283 * @return object of Payment Processsor
1285 function processorCreate() {
1286 $processorParams = array(
1289 'payment_processor_type_id' => 10,
1290 'financial_account_id' => 12,
1293 'url_site' => 'http://dummy.com',
1294 'url_recur' => 'http://dummy.com',
1295 'billing_mode' => 1,
1297 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1298 return $paymentProcessor;
1302 * Function to create contribution page
1305 * @return object of contribution page
1307 function contributionPageCreate($params) {
1308 $this->_pageParams
= array(
1309 'title' => 'Test Contribution Page',
1310 'financial_type_id' => 1,
1311 'currency' => 'USD',
1312 'financial_account_id' => 1,
1313 'payment_processor' => $params['processor_id'],
1315 'is_allow_other_amount' => 1,
1317 'max_amount' => 1000,
1319 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1320 return $contributionPage;
1324 * Function to create Tag
1326 * @param array $params
1327 * @return array result of created tag
1329 function tagCreate($params = array()) {
1331 'name' => 'New Tag3',
1332 'description' => 'This is description for Our New Tag ',
1335 $params = array_merge($defaults, $params);
1336 $result = $this->callAPISuccess('Tag', 'create', $params);
1337 return $result['values'][$result['id']];
1341 * Function to delete Tag
1343 * @param int $tagId id of the tag to be deleted
1345 function tagDelete($tagId) {
1346 require_once 'api/api.php';
1350 $result = $this->callAPISuccess('Tag', 'delete', $params);
1351 return $result['id'];
1355 * Add entity(s) to the tag
1357 * @param array $params
1361 function entityTagAdd($params) {
1362 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1367 * Function to create contribution
1369 * @param int $cID contact_id
1371 * @internal param int $cTypeID id of financial type
1373 * @return int id of created contribution
1375 function pledgeCreate($cID) {
1377 'contact_id' => $cID,
1378 'pledge_create_date' => date('Ymd'),
1379 'start_date' => date('Ymd'),
1380 'scheduled_date' => date('Ymd'),
1382 'pledge_status_id' => '2',
1383 'financial_type_id' => '1',
1384 'pledge_original_installment_amount' => 20,
1385 'frequency_interval' => 5,
1386 'frequency_unit' => 'year',
1387 'frequency_day' => 15,
1388 'installments' => 5,
1391 $result = $this->callAPISuccess('Pledge', 'create', $params);
1392 return $result['id'];
1396 * Function to delete contribution
1399 * @internal param int $contributionId
1401 function pledgeDelete($pledgeId) {
1403 'pledge_id' => $pledgeId,
1405 $this->callAPISuccess('Pledge', 'delete', $params);
1409 * Function to create contribution
1411 * @param int $cID contact_id
1412 * @param int $cTypeID id of financial type
1414 * @param int $invoiceID
1415 * @param int $trxnID
1416 * @param int $paymentInstrumentID
1417 * @param bool $isFee
1418 * @return int id of created contribution
1420 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1423 'contact_id' => $cID,
1424 'receive_date' => date('Ymd'),
1425 'total_amount' => 100.00,
1426 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1427 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1428 'non_deductible_amount' => 10.00,
1429 'trxn_id' => $trxnID,
1430 'invoice_id' => $invoiceID,
1432 'contribution_status_id' => 1,
1433 // 'note' => 'Donating for Nobel Cause', *Fixme
1437 $params['fee_amount'] = 5.00;
1438 $params['net_amount'] = 95.00;
1441 $result = $this->callAPISuccess('contribution', 'create', $params);
1442 return $result['id'];
1446 * Function to create online contribution
1449 * @param int $financialType id of financial type
1451 * @param int $invoiceID
1452 * @param int $trxnID
1453 * @return int id of created contribution
1455 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1456 $contribParams = array(
1457 'contact_id' => $params['contact_id'],
1458 'receive_date' => date('Ymd'),
1459 'total_amount' => 100.00,
1460 'financial_type_id' => $financialType,
1461 'contribution_page_id' => $params['contribution_page_id'],
1463 'invoice_id' => 67890,
1466 $contribParams = array_merge($contribParams, $params);
1467 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1469 return $result['id'];
1473 * Function to delete contribution
1475 * @param int $contributionId
1479 function contributionDelete($contributionId) {
1481 'contribution_id' => $contributionId,
1483 $result = $this->callAPISuccess('contribution', 'delete', $params);
1488 * Function to create an Event
1490 * @param array $params name-value pair for an event
1492 * @return array $event
1494 function eventCreate($params = array()) {
1495 // if no contact was passed, make up a dummy event creator
1496 if (!isset($params['contact_id'])) {
1497 $params['contact_id'] = $this->_contactCreate(array(
1498 'contact_type' => 'Individual',
1499 'first_name' => 'Event',
1500 'last_name' => 'Creator',
1504 // set defaults for missing params
1505 $params = array_merge(array(
1506 'title' => 'Annual CiviCRM meet',
1507 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1508 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1509 'event_type_id' => 1,
1511 'start_date' => 20081021,
1512 'end_date' => 20081023,
1513 'is_online_registration' => 1,
1514 'registration_start_date' => 20080601,
1515 'registration_end_date' => 20081015,
1516 'max_participants' => 100,
1517 'event_full_text' => 'Sorry! We are already full',
1520 'is_show_location' => 0,
1523 return $this->callAPISuccess('Event', 'create', $params);
1527 * Function to delete event
1529 * @param int $id ID of the event
1533 function eventDelete($id) {
1537 return $this->callAPISuccess('event', 'delete', $params);
1541 * Function to delete participant
1543 * @param int $participantID
1547 function participantDelete($participantID) {
1549 'id' => $participantID,
1551 return $this->callAPISuccess('Participant', 'delete', $params);
1555 * Function to create participant payment
1557 * @param $participantID
1558 * @param null $contributionID
1559 * @return int $id of created payment
1561 function participantPaymentCreate($participantID, $contributionID = NULL) {
1562 //Create Participant Payment record With Values
1564 'participant_id' => $participantID,
1565 'contribution_id' => $contributionID,
1568 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1569 return $result['id'];
1573 * Function to delete participant payment
1575 * @param int $paymentID
1577 function participantPaymentDelete($paymentID) {
1581 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1585 * Function to add a Location
1588 * @return int location id of created location
1590 function locationAdd($contactID) {
1593 'location_type' => 'New Location Type',
1595 'name' => 'Saint Helier St',
1596 'county' => 'Marin',
1597 'country' => 'United States',
1598 'state_province' => 'Michigan',
1599 'supplemental_address_1' => 'Hallmark Ct',
1600 'supplemental_address_2' => 'Jersey Village',
1605 'contact_id' => $contactID,
1606 'address' => $address,
1607 'location_format' => '2.0',
1608 'location_type' => 'New Location Type',
1611 $result = $this->callAPISuccess('Location', 'create', $params);
1616 * Function to delete Locations of contact
1618 * @params array $pamars parameters
1620 function locationDelete($params) {
1621 $result = $this->callAPISuccess('Location', 'delete', $params);
1625 * Function to add a Location Type
1627 * @param null $params
1628 * @return int location id of created location
1630 function locationTypeCreate($params = NULL) {
1631 if ($params === NULL) {
1633 'name' => 'New Location Type',
1634 'vcard_name' => 'New Location Type',
1635 'description' => 'Location Type for Delete',
1640 $locationType = new CRM_Core_DAO_LocationType();
1641 $locationType->copyValues($params);
1642 $locationType->save();
1643 // clear getfields cache
1644 CRM_Core_PseudoConstant
::flush();
1645 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1646 return $locationType;
1650 * Function to delete a Location Type
1652 * @param int location type id
1654 function locationTypeDelete($locationTypeId) {
1655 $locationType = new CRM_Core_DAO_LocationType();
1656 $locationType->id
= $locationTypeId;
1657 $locationType->delete();
1661 * Function to add a Group
1663 * @params array to add group
1665 * @param array $params
1666 * @return int groupId of created group
1668 function groupCreate($params = array()) {
1669 $params = array_merge(array(
1670 'name' => 'Test Group 1',
1672 'title' => 'New Test Group Created',
1673 'description' => 'New Test Group Created',
1675 'visibility' => 'Public Pages',
1676 'group_type' => array(
1682 $result = $this->callAPISuccess('Group', 'create', $params);
1683 return $result['id'];
1687 * Function to delete a Group
1690 * @internal param int $id
1692 function groupDelete($gid) {
1698 $this->callAPISuccess('Group', 'delete', $params);
1703 * @param array $params
1705 function uFFieldCreate($params = array()) {
1706 $params = array_merge(array(
1708 'field_name' => 'first_name',
1711 'visibility' => 'Public Pages and Listings',
1712 'is_searchable' => '1',
1713 'label' => 'first_name',
1714 'field_type' => 'Individual',
1717 $this->callAPISuccess('uf_field', 'create', $params);
1721 * Function to add a UF Join Entry
1723 * @param null $params
1724 * @return int $id of created UF Join
1726 function ufjoinCreate($params = NULL) {
1727 if ($params === NULL) {
1730 'module' => 'CiviEvent',
1731 'entity_table' => 'civicrm_event',
1737 $result = $this->callAPISuccess('uf_join', 'create', $params);
1742 * Function to delete a UF Join Entry
1744 * @param array with missing uf_group_id
1746 function ufjoinDelete($params = NULL) {
1747 if ($params === NULL) {
1750 'module' => 'CiviEvent',
1751 'entity_table' => 'civicrm_event',
1754 'uf_group_id' => '',
1758 crm_add_uf_join($params);
1762 * Function to create Group for a contact
1764 * @param int $contactId
1766 function contactGroupCreate($contactId) {
1768 'contact_id.1' => $contactId,
1772 $this->callAPISuccess('GroupContact', 'Create', $params);
1776 * Function to delete Group for a contact
1779 * @internal param array $params
1781 function contactGroupDelete($contactId) {
1783 'contact_id.1' => $contactId,
1786 $this->civicrm_api('GroupContact', 'Delete', $params);
1790 * Function to create Activity
1792 * @param null $params
1794 * @internal param int $contactId
1796 function activityCreate($params = NULL) {
1798 if ($params === NULL) {
1799 $individualSourceID = $this->individualCreate();
1801 $contactParams = array(
1802 'first_name' => 'Julia',
1803 'Last_name' => 'Anderson',
1805 'email' => 'julia_anderson@civicrm.org',
1806 'contact_type' => 'Individual',
1809 $individualTargetID = $this->individualCreate($contactParams);
1812 'source_contact_id' => $individualSourceID,
1813 'target_contact_id' => array($individualTargetID),
1814 'assignee_contact_id' => array($individualTargetID),
1815 'subject' => 'Discussion on warm beer',
1816 'activity_date_time' => date('Ymd'),
1817 'duration_hours' => 30,
1818 'duration_minutes' => 20,
1819 'location' => 'Baker Street',
1820 'details' => 'Lets schedule a meeting',
1822 'activity_name' => 'Meeting',
1826 $result = $this->callAPISuccess('Activity', 'create', $params);
1828 $result['target_contact_id'] = $individualTargetID;
1829 $result['assignee_contact_id'] = $individualTargetID;
1834 * Function to create an activity type
1836 * @params array $params parameters
1838 function activityTypeCreate($params) {
1839 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1844 * Function to delete activity type
1846 * @params Integer $activityTypeId id of the activity type
1848 function activityTypeDelete($activityTypeId) {
1849 $params['activity_type_id'] = $activityTypeId;
1850 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1855 * Function to create custom group
1857 * @param array $params
1859 * @internal param string $className
1860 * @internal param string $title name of custom group
1862 function customGroupCreate($params = array()) {
1864 'title' => 'new custom group',
1865 'extends' => 'Contact',
1867 'style' => 'Inline',
1871 $params = array_merge($defaults, $params);
1873 if (strlen($params['title']) > 13) {
1874 $params['title'] = substr($params['title'], 0, 13);
1877 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1878 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1880 return $this->callAPISuccess('custom_group', 'create', $params);
1884 * existing function doesn't allow params to be over-ridden so need a new one
1885 * this one allows you to only pass in the params you want to change
1887 function CustomGroupCreateByParams($params = array()) {
1889 'title' => "API Custom Group",
1890 'extends' => 'Contact',
1892 'style' => 'Inline',
1895 $params = array_merge($defaults, $params);
1896 return $this->callAPISuccess('custom_group', 'create', $params);
1900 * Create custom group with multi fields
1902 function CustomGroupMultipleCreateByParams($params = array()) {
1907 $params = array_merge($defaults, $params);
1908 return $this->CustomGroupCreateByParams($params);
1912 * Create custom group with multi fields
1914 function CustomGroupMultipleCreateWithFields($params = array()) {
1915 // also need to pass on $params['custom_field'] if not set but not in place yet
1917 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1918 $ids['custom_group_id'] = $customGroup['id'];
1920 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1922 $ids['custom_field_id'][] = $customField['id'];
1924 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1925 $ids['custom_field_id'][] = $customField['id'];
1927 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1928 $ids['custom_field_id'][] = $customField['id'];
1934 * Create a custom group with a single text custom field. See
1935 * participant:testCreateWithCustom for how to use this
1937 * @param string $function __FUNCTION__
1939 * @internal param string $file __FILE__
1941 * @return array $ids ids of created objects
1943 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1944 $params = array('title' => $function);
1945 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1946 $params['extends'] = $entity ?
$entity : 'Contact';
1947 $customGroup = $this->CustomGroupCreate($params);
1948 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1949 CRM_Core_PseudoConstant
::flush();
1951 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1955 * Function to delete custom group
1957 * @param int $customGroupID
1961 function customGroupDelete($customGroupID) {
1962 $params['id'] = $customGroupID;
1963 return $this->callAPISuccess('custom_group', 'delete', $params);
1967 * Function to create custom field
1969 * @param array $params (custom_group_id) is required
1971 * @internal param string $name name of custom field
1972 * @internal param int $apiversion API version to use
1974 function customFieldCreate($params) {
1975 $params = array_merge(array(
1976 'label' => 'Custom Field',
1977 'data_type' => 'String',
1978 'html_type' => 'Text',
1979 'is_searchable' => 1,
1981 'default_value' => 'defaultValue',
1984 $result = $this->callAPISuccess('custom_field', 'create', $params);
1986 if ($result['is_error'] == 0 && isset($result['id'])) {
1987 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1988 // force reset of enabled components to help grab custom fields
1989 CRM_Core_Component
::getEnabledComponents(1);
1995 * Function to delete custom field
1997 * @param int $customFieldID
2001 function customFieldDelete($customFieldID) {
2003 $params['id'] = $customFieldID;
2004 return $this->callAPISuccess('custom_field', 'delete', $params);
2008 * Function to create note
2010 * @params array $params name-value pair for an event
2013 * @return array $note
2015 function noteCreate($cId) {
2017 'entity_table' => 'civicrm_contact',
2018 'entity_id' => $cId,
2019 'note' => 'hello I am testing Note',
2020 'contact_id' => $cId,
2021 'modified_date' => date('Ymd'),
2022 'subject' => 'Test Note',
2025 return $this->callAPISuccess('Note', 'create', $params);
2029 * Enable CiviCampaign Component
2031 function enableCiviCampaign() {
2032 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2033 // force reload of config object
2034 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2035 //flush cache by calling with reset
2036 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2040 * Create test generated example in api/v3/examples.
2041 * To turn this off (e.g. on the server) set
2042 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2043 * in your settings file
2044 * @param array $params array as passed to civicrm_api function
2045 * @param array $result array as received from the civicrm_api function
2046 * @param string $function calling function - generally __FUNCTION__
2047 * @param string $filename called from file - generally __FILE__
2048 * @param string $description descriptive text for the example file
2049 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2050 * @param string $action - optional action - otherwise taken from function name
2052 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2053 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2056 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2057 //todo - this is a bit cludgey
2058 if (empty($action)) {
2059 if (strstr($function, 'Create')) {
2060 $action = empty($action) ?
'create' : $action;
2061 $entityAction = 'Create';
2063 elseif (strstr($function, 'GetSingle')) {
2064 $action = empty($action) ?
'getsingle' : $action;
2065 $entityAction = 'GetSingle';
2067 elseif (strstr($function, 'GetValue')) {
2068 $action = empty($action) ?
'getvalue' : $action;
2069 $entityAction = 'GetValue';
2071 elseif (strstr($function, 'GetCount')) {
2072 $action = empty($action) ?
'getcount' : $action;
2073 $entityAction = 'GetCount';
2075 elseif (strstr($function, 'GetFields')) {
2076 $action = empty($action) ?
'getfields' : $action;
2077 $entityAction = 'GetFields';
2079 elseif (strstr($function, 'GetList')) {
2080 $action = empty($action) ?
'getlist' : $action;
2081 $entityAction = 'GetList';
2083 elseif (strstr($function, 'Get')) {
2084 $action = empty($action) ?
'get' : $action;
2085 $entityAction = 'Get';
2087 elseif (strstr($function, 'Delete')) {
2088 $action = empty($action) ?
'delete' : $action;
2089 $entityAction = 'Delete';
2091 elseif (strstr($function, 'Update')) {
2092 $action = empty($action) ?
'update' : $action;
2093 $entityAction = 'Update';
2095 elseif (strstr($function, 'Subscribe')) {
2096 $action = empty($action) ?
'subscribe' : $action;
2097 $entityAction = 'Subscribe';
2099 elseif (strstr($function, 'Submit')) {
2100 $action = empty($action) ?
'submit' : $action;
2101 $entityAction = 'Submit';
2103 elseif (strstr($function, 'Apply')) {
2104 $action = empty($action) ?
'apply' : $action;
2105 $entityAction = 'Apply';
2107 elseif (strstr($function, 'Replace')) {
2108 $action = empty($action) ?
'replace' : $action;
2109 $entityAction = 'Replace';
2113 $entityAction = ucwords($action);
2116 $this->tidyExampleResult($result);
2117 if(isset($params['version'])) {
2118 unset($params['version']);
2120 // a cleverer person than me would do it in a single regex
2121 if (strstr($entity, 'UF')) {
2122 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2125 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2127 $smarty = CRM_Core_Smarty
::singleton();
2128 $smarty->assign('testfunction', $function);
2129 $function = $fnPrefix . "_" . strtolower($action);
2130 $smarty->assign('function', $function);
2131 $smarty->assign('fnPrefix', $fnPrefix);
2132 $smarty->assign('params', $params);
2133 $smarty->assign('entity', $entity);
2134 $smarty->assign('filename', basename($filename));
2135 $smarty->assign('description', $description);
2136 $smarty->assign('result', $result);
2138 $smarty->assign('action', $action);
2139 if (empty($subfile)) {
2140 $subfile = $entityAction;
2142 if (file_exists('../tests/templates/documentFunction.tpl')) {
2143 if (!is_dir("../api/v3/examples/$entity")) {
2144 mkdir("../api/v3/examples/$entity");
2146 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2147 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2153 * Tidy up examples array so that fields that change often ..don't
2154 * and debug related fields are unset
2158 * @internal param array $params
2160 function tidyExampleResult(&$result){
2161 if(!is_array($result)) {
2164 $fieldsToChange = array(
2165 'hash' => '67eac7789eaee00',
2166 'modified_date' => '2012-11-14 16:02:35',
2167 'created_date' => '2013-07-28 08:49:19',
2168 'create_date' => '20120130621222105',
2169 'application_received_date' => '20130728084957',
2170 'in_date' => '2013-07-28 08:50:19',
2171 'scheduled_date' => '20130728085413',
2172 'approval_date' => '20130728085413',
2173 'pledge_start_date_high' => '20130726090416',
2174 'start_date' => '2013-07-29 00:00:00',
2175 'event_start_date' => '2013-07-29 00:00:00',
2176 'end_date' => '2013-08-04 00:00:00',
2177 'event_end_date' => '2013-08-04 00:00:00',
2178 'decision_date' => '20130805000000',
2181 $keysToUnset = array('xdebug', 'undefined_fields',);
2182 foreach ($keysToUnset as $unwantedKey) {
2183 if(isset($result[$unwantedKey])) {
2184 unset($result[$unwantedKey]);
2187 if (isset($result['values'])) {
2188 if(!is_array($result['values'])) {
2191 $resultArray = &$result['values'];
2193 elseif(is_array($result)) {
2194 $resultArray = &$result;
2200 foreach ($resultArray as $index => &$values) {
2201 if(!is_array($values)) {
2204 foreach($values as $key => &$value) {
2205 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2206 if(isset($value['is_error'])) {
2207 // we have a std nested result format
2208 $this->tidyExampleResult($value);
2211 foreach ($value as &$nestedResult) {
2212 // this is an alternative syntax for nested results a keyed array of results
2213 $this->tidyExampleResult($nestedResult);
2217 if(in_array($key, $keysToUnset)) {
2218 unset($values[$key]);
2221 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2222 $value = $fieldsToChange[$key];
2224 if(is_string($value)) {
2225 $value = addslashes($value);
2232 * Function to delete note
2234 * @params int $noteID
2237 function noteDelete($params) {
2238 return $this->callAPISuccess('Note', 'delete', $params);
2242 * Function to create custom field with Option Values
2244 * @param array $customGroup
2245 * @param string $name name of custom field
2249 function customFieldOptionValueCreate($customGroup, $name) {
2250 $fieldParams = array(
2251 'custom_group_id' => $customGroup['id'],
2252 'name' => 'test_custom_group',
2253 'label' => 'Country',
2254 'html_type' => 'Select',
2255 'data_type' => 'String',
2258 'is_searchable' => 0,
2262 $optionGroup = array(
2264 'name' => 'option_group1',
2265 'label' => 'option_group_label1',
2268 $optionValue = array(
2269 'option_label' => array('Label1', 'Label2'),
2270 'option_value' => array('value1', 'value2'),
2271 'option_name' => array($name . '_1', $name . '_2'),
2272 'option_weight' => array(1, 2),
2273 'option_status' => 1,
2276 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2278 return $this->callAPISuccess('custom_field', 'create', $params);
2286 function confirmEntitiesDeleted($entities) {
2287 foreach ($entities as $entity) {
2289 $result = $this->callAPISuccess($entity, 'Get', array());
2290 if ($result['error'] == 1 ||
$result['count'] > 0) {
2291 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2298 * @param $tablesToTruncate
2299 * @param bool $dropCustomValueTables
2301 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2302 if ($dropCustomValueTables) {
2303 $tablesToTruncate[] = 'civicrm_custom_group';
2304 $tablesToTruncate[] = 'civicrm_custom_field';
2307 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2309 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2310 foreach ($tablesToTruncate as $table) {
2311 $sql = "TRUNCATE TABLE $table";
2312 CRM_Core_DAO
::executeQuery($sql);
2314 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2316 if ($dropCustomValueTables) {
2317 $dbName = self
::getDBName();
2319 SELECT TABLE_NAME as tableName
2320 FROM INFORMATION_SCHEMA.TABLES
2321 WHERE TABLE_SCHEMA = '{$dbName}'
2322 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2325 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2326 while ($tableDAO->fetch()) {
2327 $sql = "DROP TABLE {$tableDAO->tableName}";
2328 CRM_Core_DAO
::executeQuery($sql);
2334 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2336 function quickCleanUpFinancialEntities() {
2337 $tablesToTruncate = array(
2338 'civicrm_contribution',
2339 'civicrm_financial_trxn',
2340 'civicrm_contribution_recur',
2341 'civicrm_line_item',
2342 'civicrm_contribution_page',
2343 'civicrm_payment_processor',
2344 'civicrm_entity_financial_trxn',
2345 'civicrm_membership',
2346 'civicrm_membership_type',
2347 'civicrm_membership_payment',
2348 'civicrm_membership_log',
2349 'civicrm_membership_block',
2351 'civicrm_participant',
2352 'civicrm_participant_payment',
2355 $this->quickCleanup($tablesToTruncate);
2358 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2359 * Default behaviour is to also delete the entity
2360 * @param array $params params array to check agains
2361 * @param int $id id of the entity concerned
2362 * @param string $entity name of entity concerned (e.g. membership)
2363 * @param bool $delete should the entity be deleted as part of this check
2364 * @param string $errorText text to print on error
2371 * @param int $delete
2372 * @param string $errorText
2376 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2378 $result = $this->callAPISuccessGetSingle($entity, array(
2383 $this->callAPISuccess($entity, 'Delete', array(
2387 $dateFields = $keys = $dateTimeFields = array();
2388 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2389 foreach ($fields['values'] as $field => $settings) {
2390 if (array_key_exists($field, $result)) {
2391 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2394 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2396 $type = CRM_Utils_Array
::value('type', $settings);
2397 if ($type == CRM_Utils_Type
::T_DATE
) {
2398 $dateFields[] = $settings['name'];
2399 // we should identify both real names & unique names as dates
2400 if($field != $settings['name']) {
2401 $dateFields[] = $field;
2404 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2405 $dateTimeFields[] = $settings['name'];
2406 // we should identify both real names & unique names as dates
2407 if($field != $settings['name']) {
2408 $dateTimeFields[] = $field;
2413 if (strtolower($entity) == 'contribution') {
2414 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2415 // this is not returned in id format
2416 unset($params['payment_instrument_id']);
2417 $params['contribution_source'] = $params['source'];
2418 unset($params['source']);
2421 foreach ($params as $key => $value) {
2422 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2425 if (in_array($key, $dateFields)) {
2426 $value = date('Y-m-d', strtotime($value));
2427 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2429 if (in_array($key, $dateTimeFields)) {
2430 $value = date('Y-m-d H:i:s', strtotime($value));
2431 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2433 $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);
2438 * Function to get formatted values in the actual and expected result
2439 * @param array $actual actual calculated values
2440 * @param array $expected expected values
2443 function checkArrayEquals(&$actual, &$expected) {
2444 self
::unsetId($actual);
2445 self
::unsetId($expected);
2446 $this->assertEquals($actual, $expected);
2450 * Function to unset the key 'id' from the array
2451 * @param array $unformattedArray The array from which the 'id' has to be unset
2454 static function unsetId(&$unformattedArray) {
2455 $formattedArray = array();
2456 if (array_key_exists('id', $unformattedArray)) {
2457 unset($unformattedArray['id']);
2459 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2460 foreach ($unformattedArray['values'] as $key => $value) {
2461 if (is_Array($value)) {
2462 foreach ($value as $k => $v) {
2468 elseif ($key == 'id') {
2469 $unformattedArray[$key];
2471 $formattedArray = array($value);
2473 $unformattedArray['values'] = $formattedArray;
2478 * Helper to enable/disable custom directory support
2480 * @param array $customDirs with members:
2481 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2482 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2484 function customDirectories($customDirs) {
2485 require_once 'CRM/Core/Config.php';
2486 $config = CRM_Core_Config
::singleton();
2488 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2489 unset($config->customPHPPathDir
);
2491 elseif ($customDirs['php_path'] === TRUE) {
2492 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2495 $config->customPHPPathDir
= $php_path;
2498 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2499 unset($config->customTemplateDir
);
2501 elseif ($customDirs['template_path'] === TRUE) {
2502 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2505 $config->customTemplateDir
= $template_path;
2510 * Generate a temporary folder
2512 * @param string $prefix
2513 * @return string $string
2515 function createTempDir($prefix = 'test-') {
2516 $tempDir = CRM_Utils_File
::tempdir($prefix);
2517 $this->tempDirs
[] = $tempDir;
2521 function cleanTempDirs() {
2522 if (!is_array($this->tempDirs
)) {
2523 // fix test errors where this is not set
2526 foreach ($this->tempDirs
as $tempDir) {
2527 if (is_dir($tempDir)) {
2528 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2534 * Temporarily replace the singleton extension with a different one
2536 function setExtensionSystem(CRM_Extension_System
$system) {
2537 if ($this->origExtensionSystem
== NULL) {
2538 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2540 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2543 function unsetExtensionSystem() {
2544 if ($this->origExtensionSystem
!== NULL) {
2545 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2546 $this->origExtensionSystem
= NULL;
2551 * Temporarily alter the settings-metadata to add a mock setting.
2553 * WARNING: The setting metadata will disappear on the next cache-clear.
2558 function setMockSettingsMetaData($extras) {
2559 CRM_Core_BAO_Setting
::$_cache = array();
2560 $this->callAPISuccess('system','flush', array());
2561 CRM_Core_BAO_Setting
::$_cache = array();
2563 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2564 $metadata = array_merge($metadata, $extras);
2567 $fields = $this->callAPISuccess('setting', 'getfields', array());
2568 foreach ($extras as $key => $spec) {
2569 $this->assertNotEmpty($spec['title']);
2570 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2577 function financialAccountDelete($name) {
2578 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2579 $financialAccount->name
= $name;
2580 if($financialAccount->find(TRUE)) {
2581 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2582 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2583 $entityFinancialType->delete();
2584 $financialAccount->delete();
2589 * Use $ids as an instruction to do test cleanup
2591 function deleteFromIDSArray() {
2592 foreach ($this->ids
as $entity => $ids) {
2593 foreach ($ids as $id) {
2594 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2600 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2601 * (NB unclear if this is still required)
2603 function _sethtmlGlobals() {
2604 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2605 'required' => array(
2606 'html_quickform_rule_required',
2607 'HTML/QuickForm/Rule/Required.php'
2609 'maxlength' => array(
2610 'html_quickform_rule_range',
2611 'HTML/QuickForm/Rule/Range.php'
2613 'minlength' => array(
2614 'html_quickform_rule_range',
2615 'HTML/QuickForm/Rule/Range.php'
2617 'rangelength' => array(
2618 'html_quickform_rule_range',
2619 'HTML/QuickForm/Rule/Range.php'
2622 'html_quickform_rule_email',
2623 'HTML/QuickForm/Rule/Email.php'
2626 'html_quickform_rule_regex',
2627 'HTML/QuickForm/Rule/Regex.php'
2629 'lettersonly' => array(
2630 'html_quickform_rule_regex',
2631 'HTML/QuickForm/Rule/Regex.php'
2633 'alphanumeric' => array(
2634 'html_quickform_rule_regex',
2635 'HTML/QuickForm/Rule/Regex.php'
2638 'html_quickform_rule_regex',
2639 'HTML/QuickForm/Rule/Regex.php'
2641 'nopunctuation' => array(
2642 'html_quickform_rule_regex',
2643 'HTML/QuickForm/Rule/Regex.php'
2646 'html_quickform_rule_regex',
2647 'HTML/QuickForm/Rule/Regex.php'
2649 'callback' => array(
2650 'html_quickform_rule_callback',
2651 'HTML/QuickForm/Rule/Callback.php'
2654 'html_quickform_rule_compare',
2655 'HTML/QuickForm/Rule/Compare.php'
2658 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2659 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2661 'HTML/QuickForm/group.php',
2662 'HTML_QuickForm_group'
2665 'HTML/QuickForm/hidden.php',
2666 'HTML_QuickForm_hidden'
2669 'HTML/QuickForm/reset.php',
2670 'HTML_QuickForm_reset'
2672 'checkbox' => array(
2673 'HTML/QuickForm/checkbox.php',
2674 'HTML_QuickForm_checkbox'
2677 'HTML/QuickForm/file.php',
2678 'HTML_QuickForm_file'
2681 'HTML/QuickForm/image.php',
2682 'HTML_QuickForm_image'
2684 'password' => array(
2685 'HTML/QuickForm/password.php',
2686 'HTML_QuickForm_password'
2689 'HTML/QuickForm/radio.php',
2690 'HTML_QuickForm_radio'
2693 'HTML/QuickForm/button.php',
2694 'HTML_QuickForm_button'
2697 'HTML/QuickForm/submit.php',
2698 'HTML_QuickForm_submit'
2701 'HTML/QuickForm/select.php',
2702 'HTML_QuickForm_select'
2704 'hiddenselect' => array(
2705 'HTML/QuickForm/hiddenselect.php',
2706 'HTML_QuickForm_hiddenselect'
2709 'HTML/QuickForm/text.php',
2710 'HTML_QuickForm_text'
2712 'textarea' => array(
2713 'HTML/QuickForm/textarea.php',
2714 'HTML_QuickForm_textarea'
2716 'fckeditor' => array(
2717 'HTML/QuickForm/fckeditor.php',
2718 'HTML_QuickForm_FCKEditor'
2721 'HTML/QuickForm/tinymce.php',
2722 'HTML_QuickForm_TinyMCE'
2724 'dojoeditor' => array(
2725 'HTML/QuickForm/dojoeditor.php',
2726 'HTML_QuickForm_dojoeditor'
2729 'HTML/QuickForm/link.php',
2730 'HTML_QuickForm_link'
2732 'advcheckbox' => array(
2733 'HTML/QuickForm/advcheckbox.php',
2734 'HTML_QuickForm_advcheckbox'
2737 'HTML/QuickForm/date.php',
2738 'HTML_QuickForm_date'
2741 'HTML/QuickForm/static.php',
2742 'HTML_QuickForm_static'
2745 'HTML/QuickForm/header.php',
2746 'HTML_QuickForm_header'
2749 'HTML/QuickForm/html.php',
2750 'HTML_QuickForm_html'
2752 'hierselect' => array(
2753 'HTML/QuickForm/hierselect.php',
2754 'HTML_QuickForm_hierselect'
2756 'autocomplete' => array(
2757 'HTML/QuickForm/autocomplete.php',
2758 'HTML_QuickForm_autocomplete'
2761 'HTML/QuickForm/xbutton.php',
2762 'HTML_QuickForm_xbutton'
2764 'advmultiselect' => array(
2765 'HTML/QuickForm/advmultiselect.php',
2766 'HTML_QuickForm_advmultiselect'
2772 * Set up an acl allowing contact to see 2 specified groups
2773 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2775 * You need to have precreated these groups & created the user e.g
2776 * $this->createLoggedInUser();
2777 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2778 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2781 function setupACL() {
2783 $_REQUEST = $this->_params
;
2784 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2785 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2786 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2787 'label' => 'pick me',
2792 CRM_Core_DAO
::executeQuery("
2793 TRUNCATE civicrm_acl_cache
2796 CRM_Core_DAO
::executeQuery("
2797 TRUNCATE civicrm_acl_contact_cache
2801 CRM_Core_DAO
::executeQuery("
2802 INSERT INTO civicrm_acl_entity_role (
2803 `acl_role_id`, `entity_table`, `entity_id`
2804 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2807 CRM_Core_DAO
::executeQuery("
2808 INSERT INTO civicrm_acl (
2809 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2812 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2816 CRM_Core_DAO
::executeQuery("
2817 INSERT INTO civicrm_acl (
2818 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2821 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2824 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2825 $this->callAPISuccess('group_contact', 'create', array(
2826 'group_id' => $this->_permissionedGroup
,
2827 'contact_id' => $this->_loggedInUser
,
2830 CRM_ACL_BAO_Cache
::resetCache();
2831 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2832 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2836 * alter default price set so that the field numbers are not all 1 (hiding errors)
2838 function offsetDefaultPriceSet() {
2839 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2840 $firstID = $contributionPriceSet['id'];
2841 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2842 unset($contributionPriceSet['id']);
2843 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2844 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2845 unset($priceField['id']);
2846 $priceField['price_set_id'] = $newPriceSet['id'];
2847 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2848 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2850 unset($priceFieldValue['id']);
2851 //create some padding to use up ids
2852 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2853 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2854 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2859 * Create an instance of the paypal processor
2860 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2861 * this parent class & we don't have a structure for that yet
2862 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2863 * & the best protection agains that is the functions this class affords
2865 function paymentProcessorCreate($params = array()) {
2866 $params = array_merge(array(
2868 'domain_id' => CRM_Core_Config
::domainID(),
2869 'payment_processor_type_id' => 'PayPal',
2873 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2874 'password' => '1183377788',
2875 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2876 'url_site' => 'https://www.sandbox.paypal.com/',
2877 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2878 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2879 'class_name' => 'Payment_PayPalImpl',
2880 'billing_mode' => 3,
2881 'financial_type_id' => 1,
2884 if(!is_numeric($params['payment_processor_type_id'])) {
2885 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2887 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2888 'name' => $params['payment_processor_type_id'],
2892 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2893 return $result['id'];
2901 */function CiviUnitTestCase_fatalErrorHandler($message) {
2902 throw new Exception("{$message['message']}: {$message['code']}");