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/>.
29 use Civi\Payment\System
;
32 * Include class definitions
34 require_once 'tests/phpunit/Utils.php';
35 require_once 'api/api.php';
36 require_once 'CRM/Financial/BAO/FinancialType.php';
37 define('API_LATEST_VERSION', 3);
40 * Base class for CiviCRM unit tests
42 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
43 * may opt for one or neither:
45 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
46 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
47 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
48 * 2. useTransaction() executes the test inside a transaction. It's easier to use
49 * (because you don't need to identify specific tables), but it doesn't work for tests
50 * which manipulate schema or truncate data -- and could behave inconsistently
51 * for tests which specifically examine DB transactions.
53 * Common functions for unit tests
56 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
59 * Api version - easier to override than just a define
61 protected $_apiversion = API_LATEST_VERSION
;
63 * Database has been initialized.
67 private static $dbInit = FALSE;
70 * Database connection.
72 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
81 static protected $_dbName;
84 * Track tables we have modified during a test.
86 protected $_tablesToTruncate = array();
89 * @var array of temporary directory names
99 * @var boolean populateOnce allows to skip db resets in setUp
101 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
102 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
105 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
107 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
109 public static $populateOnce = FALSE;
112 * @var boolean DBResetRequired allows skipping DB reset
113 * in specific test case. If you still need
114 * to reset single test (method) of such case, call
115 * $this->cleanDB() in the first line of this
118 public $DBResetRequired = TRUE;
121 * @var CRM_Core_Transaction|NULL
126 * @var CRM_Utils_Hook_UnitTests hookClass
127 * example of setting a method for a hook
128 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
130 public $hookClass = NULL;
133 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
135 protected $_params = array();
138 * @var CRM_Extension_System
140 protected $origExtensionSystem;
145 * Because we are overriding the parent class constructor, we
146 * need to show the same arguments as exist in the constructor of
147 * PHPUnit_Framework_TestCase, since
148 * PHPUnit_Framework_TestSuite::createTest() creates a
149 * ReflectionClass of the Test class and checks the constructor
150 * of that class to decide how to set up the test.
152 * @param string $name
154 * @param string $dataName
156 public function __construct($name = NULL, array$data = array(), $dataName = '') {
157 parent
::__construct($name, $data, $dataName);
159 // we need full error reporting
160 error_reporting(E_ALL
& ~E_NOTICE
);
162 if (!empty($GLOBALS['mysql_db'])) {
163 self
::$_dbName = $GLOBALS['mysql_db'];
166 self
::$_dbName = 'civicrm_tests_dev';
169 // create test database
170 self
::$utils = new Utils($GLOBALS['mysql_host'],
171 $GLOBALS['mysql_port'],
172 $GLOBALS['mysql_user'],
173 $GLOBALS['mysql_pass']
176 // also load the class loader
177 require_once 'CRM/Core/ClassLoader.php';
178 CRM_Core_ClassLoader
::singleton()->register();
179 if (function_exists('_civix_phpunit_setUp')) {
180 // FIXME: loosen coupling
181 _civix_phpunit_setUp();
186 * Override to run the test and assert its state.
189 * @throws \PHPUnit_Framework_IncompleteTest
190 * @throws \PHPUnit_Framework_SkippedTest
192 protected function runTest() {
194 return parent
::runTest();
196 catch (PEAR_Exception
$e) {
197 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
198 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
205 public function requireDBReset() {
206 return $this->DBResetRequired
;
212 public static function getDBName() {
213 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
218 * Create database connection for this instance.
220 * Initialize the test database if it hasn't been initialized
222 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
224 protected function getConnection() {
225 $dbName = self
::$_dbName;
226 if (!self
::$dbInit) {
227 $dbName = self
::getDBName();
229 // install test database
230 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
232 static::_populateDB(FALSE, $this);
234 self
::$dbInit = TRUE;
236 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
240 * Required implementation of abstract method.
242 protected function getDataSet() {
246 * @param bool $perClass
247 * @param null $object
249 * TRUE if the populate logic runs; FALSE if it is skipped
251 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
253 if ($perClass ||
$object == NULL) {
257 $dbreset = $object->requireDBReset();
260 if (self
::$populateOnce ||
!$dbreset) {
263 self
::$populateOnce = NULL;
265 $dbName = self
::getDBName();
266 $pdo = self
::$utils->pdo
;
267 // only consider real tables and not views
268 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
269 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
271 $truncates = array();
273 foreach ($tables as $table) {
275 if (substr($table['table_name'], 0, 4) == 'log_') {
279 // don't change list of installed extensions
280 if ($table['table_name'] == 'civicrm_extension') {
284 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
285 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
288 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
294 "SET foreign_key_checks = 0",
295 // SQL mode needs to be strict, that's our standard
296 "SET SQL_MODE='STRICT_ALL_TABLES';",
297 "SET global innodb_flush_log_at_trx_commit = 2;",
299 $queries = array_merge($queries, $truncates);
300 $queries = array_merge($queries, $drops);
301 foreach ($queries as $query) {
302 if (self
::$utils->do_query($query) === FALSE) {
303 // failed to create test database
304 echo "failed to create test db.";
309 // initialize test database
310 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
311 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
312 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
314 $query2 = file_get_contents($sql_file2);
315 $query3 = file_get_contents($sql_file3);
316 $query4 = file_get_contents($sql_file4);
317 if (self
::$utils->do_query($query2) === FALSE) {
318 echo "Cannot load civicrm_data.mysql. Aborting.";
321 if (self
::$utils->do_query($query3) === FALSE) {
322 echo "Cannot load test_data.mysql. Aborting.";
325 if (self
::$utils->do_query($query4) === FALSE) {
326 echo "Cannot load test_data.mysql. Aborting.";
330 // done with all the loading, get transactions back
331 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
332 echo "Cannot set global? Huh?";
336 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
337 echo "Cannot get foreign keys back? Huh?";
341 unset($query, $query2, $query3);
344 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
346 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
358 public static function setUpBeforeClass() {
359 static::_populateDB(TRUE);
361 // also set this global hack
362 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
366 * Common setup functions for all unit tests.
368 protected function setUp() {
369 $session = CRM_Core_Session
::singleton();
370 $session->set('userID', NULL);
372 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
373 // Use a temporary file for STDIN
374 $GLOBALS['stdin'] = tmpfile();
375 if ($GLOBALS['stdin'] === FALSE) {
376 echo "Couldn't open temporary file\n";
380 // Get and save a connection to the database
381 $this->_dbconn
= $this->getConnection();
383 // reload database before each test
384 // $this->_populateDB();
386 // "initialize" CiviCRM to avoid problems when running single tests
387 // FIXME: look at it closer in second stage
389 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
390 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
392 // disable any left-over test extensions
393 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
395 // reset all the caches
396 CRM_Utils_System
::flushCache();
398 // initialize the object once db is loaded
400 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
402 // when running unit tests, use mockup user framework
403 $this->hookClass
= CRM_Utils_Hook
::singleton();
405 // Make sure the DB connection is setup properly
406 $config->userSystem
->setMySQLTimeZone();
407 $env = new CRM_Utils_Check_Component_Env();
408 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
410 // clear permissions stub to not check permissions
411 $config->userPermissionClass
->permissions
= NULL;
413 //flush component settings
414 CRM_Core_Component
::getEnabledComponents(TRUE);
416 error_reporting(E_ALL
);
418 $this->_sethtmlGlobals();
422 * Read everything from the datasets directory and insert into the db.
424 public function loadAllFixtures() {
425 $fixturesDir = __DIR__
. '/../../fixtures';
427 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
429 $xmlFiles = glob($fixturesDir . '/*.xml');
430 foreach ($xmlFiles as $xmlFixture) {
431 $op = new PHPUnit_Extensions_Database_Operation_Insert();
432 $dataset = $this->createXMLDataSet($xmlFixture);
433 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
434 $op->execute($this->_dbconn
, $dataset);
437 $yamlFiles = glob($fixturesDir . '/*.yaml');
438 foreach ($yamlFiles as $yamlFixture) {
439 $op = new PHPUnit_Extensions_Database_Operation_Insert();
440 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
441 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
442 $op->execute($this->_dbconn
, $dataset);
445 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
449 * Emulate a logged in user since certain functions use that.
450 * value to store a record in the DB (like activity)
454 * Contact ID of the created user.
456 public function createLoggedInUser() {
458 'first_name' => 'Logged In',
459 'last_name' => 'User ' . rand(),
460 'contact_type' => 'Individual',
462 $contactID = $this->individualCreate($params);
463 $this->callAPISuccess('UFMatch', 'create', array(
464 'contact_id' => $contactID,
465 'uf_name' => 'superman',
469 $session = CRM_Core_Session
::singleton();
470 $session->set('userID', $contactID);
474 public function cleanDB() {
475 self
::$populateOnce = NULL;
476 $this->DBResetRequired
= TRUE;
478 $this->_dbconn
= $this->getConnection();
479 static::_populateDB();
480 $this->tempDirs
= array();
484 * Create default domain contacts for the two domains added during test class.
485 * database population.
487 public function createDomainContacts() {
488 $default_domain_contact = $this->organizationCreate();
489 $second_domain_contact = $this->organizationCreate();
493 * Common teardown functions for all unit tests.
495 protected function tearDown() {
496 error_reporting(E_ALL
& ~E_NOTICE
);
497 CRM_Utils_Hook
::singleton()->reset();
498 $this->hookClass
->reset();
499 $session = CRM_Core_Session
::singleton();
500 $session->set('userID', NULL);
503 $this->tx
->rollback()->commit();
506 CRM_Core_Transaction
::forceRollbackIfEnabled();
507 \Civi\Core\Transaction\Manager
::singleton(TRUE);
510 CRM_Core_Transaction
::forceRollbackIfEnabled();
511 \Civi\Core\Transaction\Manager
::singleton(TRUE);
513 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
514 $this->quickCleanup($tablesToTruncate);
515 $this->createDomainContacts();
518 $this->cleanTempDirs();
519 $this->unsetExtensionSystem();
520 $this->clearOutputBuffer();
524 * FIXME: Maybe a better way to do it
526 public function foreignKeyChecksOff() {
527 self
::$utils = new Utils($GLOBALS['mysql_host'],
528 $GLOBALS['mysql_port'],
529 $GLOBALS['mysql_user'],
530 $GLOBALS['mysql_pass']
532 $dbName = self
::getDBName();
533 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
534 if (self
::$utils->do_query($query) === FALSE) {
536 echo 'Cannot set foreign_key_checks = 0';
542 public function foreignKeyChecksOn() {
543 // FIXME: might not be needed if previous fixme implemented
547 * Generic function to compare expected values after an api call to retrieved.
550 * @daoName string DAO Name of object we're evaluating.
551 * @id int Id of object
552 * @match array Associative array of field name => expected value. Empty if asserting
553 * that a DELETE occurred
554 * @delete boolean True if we're checking that a DELETE action occurred.
558 * @param bool $delete
559 * @throws \PHPUnit_Framework_AssertionFailedError
561 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
563 // adding this here since developers forget to check for an id
564 // and hence we get the first value in the db
565 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
568 $object = new $daoName();
572 // If we're asserting successful record deletion, make sure object is NOT found.
574 if ($object->find(TRUE)) {
575 $this->fail("Object not deleted by delete operation: $daoName, $id");
580 // Otherwise check matches of DAO field values against expected values in $match.
581 if ($object->find(TRUE)) {
582 $fields = &$object->fields();
583 foreach ($fields as $name => $value) {
584 $dbName = $value['name'];
585 if (isset($match[$name])) {
587 $this->assertEquals($object->$dbName, $match[$name]);
589 elseif (isset($match[$dbName])) {
591 $this->assertEquals($object->$dbName, $match[$dbName]);
596 $this->fail("Could not retrieve object: $daoName, $id");
599 $matchSize = count($match);
600 if ($verifiedCount != $matchSize) {
601 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
606 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
607 * @param string $daoName
608 * @param $searchValue
609 * @param $returnColumn
610 * @param $searchColumn
613 * @return null|string
614 * @throws PHPUnit_Framework_AssertionFailedError
616 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
617 if (empty($searchValue)) {
618 $this->fail("empty value passed to assertDBNotNull");
620 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
621 $this->assertNotNull($value, $message);
627 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
628 * @param string $daoName
629 * @param $searchValue
630 * @param $returnColumn
631 * @param $searchColumn
634 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
635 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
636 $this->assertNull($value, $message);
640 * Request a record from the DB by id. Success if row not found.
641 * @param string $daoName
643 * @param null $message
645 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
646 $message = $message ?
$message : "$daoName (#$id) should not exist";
647 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
648 $this->assertNull($value, $message);
652 * Request a record from the DB by id. Success if row not found.
653 * @param string $daoName
655 * @param null $message
657 public function assertDBRowExist($daoName, $id, $message = NULL) {
658 $message = $message ?
$message : "$daoName (#$id) should exist";
659 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
660 $this->assertEquals($id, $value, $message);
664 * Compare a single column value in a retrieved DB record to an expected value.
665 * @param string $daoName
666 * @param $searchValue
667 * @param $returnColumn
668 * @param $searchColumn
669 * @param $expectedValue
672 public function assertDBCompareValue(
673 $daoName, $searchValue, $returnColumn, $searchColumn,
674 $expectedValue, $message
676 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
677 $this->assertEquals($value, $expectedValue, $message);
681 * Compare all values in a single retrieved DB record to an array of expected values.
682 * @param string $daoName
683 * @param array $searchParams
684 * @param $expectedValues
686 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
687 //get the values from db
689 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
691 // compare db values with expected values
692 self
::assertAttributesEquals($expectedValues, $dbValues);
696 * Assert that a SQL query returns a given value.
698 * The first argument is an expected value. The remaining arguments are passed
699 * to CRM_Core_DAO::singleValueQuery
701 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
702 * array(1 => array("Whiz", "String")));
705 * @param array $params
706 * @param string $message
708 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
712 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
713 $this->assertEquals($expected, $actual,
714 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
715 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
721 * Assert that two array-trees are exactly equal, notwithstanding
722 * the sorting of keys
724 * @param array $expected
725 * @param array $actual
727 public function assertTreeEquals($expected, $actual) {
730 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
731 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
735 $this->assertEquals($e, $a);
739 * Assert that two numbers are approximately equal.
741 * @param int|float $expected
742 * @param int|float $actual
743 * @param int|float $tolerance
744 * @param string $message
746 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
747 if ($message === NULL) {
748 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
750 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
754 * Assert attributes are equal.
756 * @param $expectedValues
757 * @param $actualValues
758 * @param string $message
760 * @throws PHPUnit_Framework_AssertionFailedError
762 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
763 foreach ($expectedValues as $paramName => $paramValue) {
764 if (isset($actualValues[$paramName])) {
765 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
768 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
777 public function assertArrayKeyExists($key, &$list) {
778 $result = isset($list[$key]) ?
TRUE : FALSE;
779 $this->assertTrue($result, ts("%1 element exists?",
788 public function assertArrayValueNotNull($key, &$list) {
789 $this->assertArrayKeyExists($key, $list);
791 $value = isset($list[$key]) ?
$list[$key] : NULL;
792 $this->assertTrue($value,
793 ts("%1 element not null?",
800 * Check that api returned 'is_error' => 0.
802 * @param array $apiResult
804 * @param string $prefix
805 * Extra test to add to message.
807 public function assertAPISuccess($apiResult, $prefix = '') {
808 if (!empty($prefix)) {
811 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
813 if (!empty($apiResult['debug_information'])) {
814 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
816 if (!empty($apiResult['trace'])) {
817 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
819 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
823 * Check that api returned 'is_error' => 1.
825 * @param array $apiResult
827 * @param string $prefix
828 * Extra test to add to message.
829 * @param null $expectedError
831 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
832 if (!empty($prefix)) {
835 if ($expectedError && !empty($apiResult['is_error'])) {
836 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
838 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
839 $this->assertNotEmpty($apiResult['error_message']);
845 * @param string $message
847 public function assertType($expected, $actual, $message = '') {
848 return $this->assertInternalType($expected, $actual, $message);
852 * Check that a deleted item has been deleted.
857 public function assertAPIDeleted($entity, $id) {
858 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
863 * Check that api returned 'is_error' => 1
864 * else provide full message
865 * @param array $result
867 * @param array $valuesToExclude
868 * @param string $prefix
869 * Extra test to add to message.
871 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
872 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
873 foreach ($valuesToExclude as $value) {
874 if (isset($result[$value])) {
875 unset($result[$value]);
877 if (isset($expected[$value])) {
878 unset($expected[$value]);
881 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
885 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
889 * @param array $params
892 public function civicrm_api($entity, $action, $params) {
893 return civicrm_api($entity, $action, $params);
897 * Create a batch of external API calls which can
898 * be executed concurrently.
901 * $calls = $this->createExternalAPI()
902 * ->addCall('Contact', 'get', ...)
903 * ->addCall('Contact', 'get', ...)
909 * @return \Civi\API\ExternalBatch
910 * @throws PHPUnit_Framework_SkippedTestError
912 public function createExternalAPI() {
913 global $civicrm_root;
914 $defaultParams = array(
915 'version' => $this->_apiversion
,
919 $calls = new \Civi\API\
ExternalBatch($defaultParams);
920 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
922 if (!$calls->isSupported()) {
923 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
930 * wrap api functions.
931 * so we can ensure they succeed & throw exceptions without litterering the test with checks
933 * @param string $entity
934 * @param string $action
935 * @param array $params
936 * @param mixed $checkAgainst
937 * Optional value to check result against, implemented for getvalue,.
938 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
939 * for getsingle the array is compared against an array passed in - the id is not compared (for
944 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
945 $params = array_merge(array(
946 'version' => $this->_apiversion
,
951 switch (strtolower($action)) {
953 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
956 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
959 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
961 $result = $this->civicrm_api($entity, $action, $params);
962 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
967 * This function exists to wrap api getValue function & check the result
968 * so we can ensure they succeed & throw exceptions without litterering the test with checks
969 * There is a type check in this
971 * @param string $entity
972 * @param array $params
973 * @param string $type
974 * Per http://php.net/manual/en/function.gettype.php possible types.
984 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
986 'version' => $this->_apiversion
,
989 $result = $this->civicrm_api($entity, 'getvalue', $params);
991 if ($type == 'integer') {
992 // api seems to return integers as strings
993 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
996 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1003 * This function exists to wrap api getsingle function & check the result
1004 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1006 * @param string $entity
1007 * @param array $params
1008 * @param array $checkAgainst
1009 * Array to compare result against.
1020 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1022 'version' => $this->_apiversion
,
1025 $result = $this->civicrm_api($entity, 'getsingle', $params);
1026 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1027 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1029 if ($checkAgainst) {
1030 // @todo - have gone with the fn that unsets id? should we check id?
1031 $this->checkArrayEquals($result, $checkAgainst);
1037 * This function exists to wrap api getValue function & check the result
1038 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1039 * There is a type check in this
1040 * @param string $entity
1041 * @param array $params
1042 * @param null $count
1046 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1048 'version' => $this->_apiversion
,
1051 $result = $this->civicrm_api($entity, 'getcount', $params);
1052 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1053 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1055 if (is_int($count)) {
1056 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1062 * This function exists to wrap api functions.
1063 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1065 * @param string $entity
1066 * @param string $action
1067 * @param array $params
1068 * @param string $function
1069 * Pass this in to create a generated example.
1070 * @param string $file
1071 * Pass this in to create a generated example.
1072 * @param string $description
1073 * @param string|null $exampleName
1077 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1078 $params['version'] = $this->_apiversion
;
1079 $result = $this->callAPISuccess($entity, $action, $params);
1080 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1085 * This function exists to wrap api functions.
1086 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1087 * @param string $entity
1088 * @param string $action
1089 * @param array $params
1090 * @param string $expectedErrorMessage
1092 * @param null $extraOutput
1095 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1096 if (is_array($params)) {
1098 'version' => $this->_apiversion
,
1101 $result = $this->civicrm_api($entity, $action, $params);
1102 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1107 * Create required data based on $this->entity & $this->params
1108 * This is just a way to set up the test data for delete & get functions
1109 * so the distinction between set
1110 * up & tested functions is clearer
1115 public function createTestEntity() {
1116 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1120 * Generic function to create Organisation, to be used in test cases
1122 * @param array $params
1123 * parameters for civicrm_contact_add api function call
1125 * sequence number if creating multiple organizations
1128 * id of Organisation created
1130 public function organizationCreate($params = array(), $seq = 0) {
1134 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1135 return $this->_contactCreate($params);
1139 * Generic function to create Individual, to be used in test cases
1141 * @param array $params
1142 * parameters for civicrm_contact_add api function call
1144 * sequence number if creating multiple individuals
1147 * id of Individual created
1149 public function individualCreate($params = array(), $seq = 0) {
1150 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1151 return $this->_contactCreate($params);
1155 * Generic function to create Household, to be used in test cases
1157 * @param array $params
1158 * parameters for civicrm_contact_add api function call
1160 * sequence number if creating multiple households
1163 * id of Household created
1165 public function householdCreate($params = array(), $seq = 0) {
1166 $params = array_merge($this->sampleContact('Household', $seq), $params);
1167 return $this->_contactCreate($params);
1171 * Helper function for getting sample contact properties.
1173 * @param string $contact_type
1174 * enum contact type: Individual, Organization
1176 * sequence number for the values of this type
1179 * properties of sample contact (ie. $params for API call)
1181 public function sampleContact($contact_type, $seq = 0) {
1183 'Individual' => array(
1184 // The number of values in each list need to be coprime numbers to not have duplicates
1185 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1186 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1187 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1189 'Organization' => array(
1190 'organization_name' => array(
1191 'Unit Test Organization',
1198 'Household' => array(
1199 'household_name' => array('Unit Test household'),
1202 $params = array('contact_type' => $contact_type);
1203 foreach ($samples[$contact_type] as $key => $values) {
1204 $params[$key] = $values[$seq %
count($values)];
1206 if ($contact_type == 'Individual') {
1207 $params['email'] = strtolower(
1208 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1210 $params['prefix_id'] = 3;
1211 $params['suffix_id'] = 3;
1217 * Private helper function for calling civicrm_contact_add.
1219 * @param array $params
1220 * For civicrm_contact_add api function call.
1225 * id of Household created
1227 private function _contactCreate($params) {
1228 $result = $this->callAPISuccess('contact', 'create', $params);
1229 if (!empty($result['is_error']) ||
empty($result['id'])) {
1230 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1232 return $result['id'];
1236 * Delete contact, ensuring it is not the domain contact
1238 * @param int $contactID
1239 * Contact ID to delete
1241 public function contactDelete($contactID) {
1242 $domain = new CRM_Core_BAO_Domain();
1243 $domain->contact_id
= $contactID;
1244 if (!$domain->find(TRUE)) {
1245 $this->callAPISuccess('contact', 'delete', array(
1247 'skip_undelete' => 1,
1253 * @param int $contactTypeId
1257 public function contactTypeDelete($contactTypeId) {
1258 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1260 throw new Exception('Could not delete contact type');
1265 * @param array $params
1269 public function membershipTypeCreate($params = array()) {
1270 CRM_Member_PseudoConstant
::flush('membershipType');
1271 CRM_Core_Config
::clearDBCache();
1272 $memberOfOrganization = $this->organizationCreate();
1273 $params = array_merge(array(
1274 'name' => 'General',
1275 'duration_unit' => 'year',
1276 'duration_interval' => 1,
1277 'period_type' => 'rolling',
1278 'member_of_contact_id' => $memberOfOrganization,
1280 'financial_type_id' => 1,
1283 'visibility' => 'Public',
1286 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1288 CRM_Member_PseudoConstant
::flush('membershipType');
1289 CRM_Utils_Cache
::singleton()->flush();
1291 return $result['id'];
1295 * @param array $params
1299 public function contactMembershipCreate($params) {
1301 'join_date' => '2007-01-21',
1302 'start_date' => '2007-01-21',
1303 'end_date' => '2007-12-21',
1304 'source' => 'Payment',
1307 foreach ($pre as $key => $val) {
1308 if (!isset($params[$key])) {
1309 $params[$key] = $val;
1313 $result = $this->callAPISuccess('Membership', 'create', $params);
1314 return $result['id'];
1318 * Delete Membership Type.
1320 * @param array $params
1322 public function membershipTypeDelete($params) {
1323 $this->callAPISuccess('MembershipType', 'Delete', $params);
1327 * @param int $membershipID
1329 public function membershipDelete($membershipID) {
1330 $deleteParams = array('id' => $membershipID);
1331 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1335 * @param string $name
1339 public function membershipStatusCreate($name = 'test member status') {
1340 $params['name'] = $name;
1341 $params['start_event'] = 'start_date';
1342 $params['end_event'] = 'end_date';
1343 $params['is_current_member'] = 1;
1344 $params['is_active'] = 1;
1346 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1347 CRM_Member_PseudoConstant
::flush('membershipStatus');
1348 return $result['id'];
1352 * @param int $membershipStatusID
1354 public function membershipStatusDelete($membershipStatusID) {
1355 if (!$membershipStatusID) {
1358 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1362 * @param array $params
1366 public function relationshipTypeCreate($params = array()) {
1367 $params = array_merge(array(
1368 'name_a_b' => 'Relation 1 for relationship type create',
1369 'name_b_a' => 'Relation 2 for relationship type create',
1370 'contact_type_a' => 'Individual',
1371 'contact_type_b' => 'Organization',
1378 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1379 CRM_Core_PseudoConstant
::flush('relationshipType');
1381 return $result['id'];
1385 * Delete Relatinship Type.
1387 * @param int $relationshipTypeID
1389 public function relationshipTypeDelete($relationshipTypeID) {
1390 $params['id'] = $relationshipTypeID;
1391 $this->callAPISuccess('relationship_type', 'delete', $params);
1395 * @param array $params
1399 public function paymentProcessorTypeCreate($params = NULL) {
1400 if (is_null($params)) {
1402 'name' => 'API_Test_PP',
1403 'title' => 'API Test Payment Processor',
1404 'class_name' => 'CRM_Core_Payment_APITest',
1405 'billing_mode' => 'form',
1411 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1413 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1415 return $result['id'];
1419 * Create test Authorize.net instance.
1421 * @param array $params
1425 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1426 $params = array_merge(array(
1427 'name' => 'Authorize',
1428 'domain_id' => CRM_Core_Config
::domainID(),
1429 'payment_processor_type_id' => 'AuthNet',
1430 'title' => 'AuthNet',
1435 'user_name' => '4y5BfuW7jm',
1436 'password' => '4cAmW927n8uLf5J8',
1437 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1438 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1439 'class_name' => 'Payment_AuthorizeNet',
1440 'billing_mode' => 1,
1443 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1444 return $result['id'];
1448 * Create Participant.
1450 * @param array $params
1451 * Array of contact id and event id values.
1454 * $id of participant created
1456 public function participantCreate($params) {
1457 if (empty($params['contact_id'])) {
1458 $params['contact_id'] = $this->individualCreate();
1460 if (empty($params['event_id'])) {
1461 $event = $this->eventCreate();
1462 $params['event_id'] = $event['id'];
1467 'register_date' => 20070219,
1468 'source' => 'Wimbeldon',
1469 'event_level' => 'Payment',
1473 $params = array_merge($defaults, $params);
1474 $result = $this->callAPISuccess('Participant', 'create', $params);
1475 return $result['id'];
1479 * Create Payment Processor.
1482 * Id Payment Processor
1484 public function processorCreate() {
1485 $processorParams = array(
1488 'payment_processor_type_id' => 'Dummy',
1489 'financial_account_id' => 12,
1493 'url_site' => 'http://dummy.com',
1494 'url_recur' => 'http://dummy.com',
1495 'billing_mode' => 1,
1498 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1499 return $processor['id'];
1503 * Create Payment Processor.
1505 * @param array $processorParams
1507 * @return \CRM_Core_Payment_Dummy
1508 * Instance of Dummy Payment Processor
1510 public function dummyProcessorCreate($processorParams = array()) {
1511 $paymentProcessorID = $this->processorCreate($processorParams);
1512 return System
::singleton()->getById($paymentProcessorID);
1516 * Create contribution page.
1518 * @param array $params
1520 * Array of contribution page
1522 public function contributionPageCreate($params) {
1523 $this->_pageParams
= array(
1524 'title' => 'Test Contribution Page',
1525 'financial_type_id' => 1,
1526 'currency' => 'USD',
1527 'financial_account_id' => 1,
1528 'payment_processor' => $params['processor_id'],
1530 'is_allow_other_amount' => 1,
1532 'max_amount' => 1000,
1534 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1535 return $contributionPage;
1539 * Create a sample batch.
1541 public function batchCreate() {
1542 $params = $this->_params
;
1543 $params['name'] = $params['title'] = 'Batch_433397';
1544 $params['status_id'] = 1;
1545 $result = $this->callAPISuccess('batch', 'create', $params);
1546 return $result['id'];
1552 * @param array $params
1554 * result of created tag
1556 public function tagCreate($params = array()) {
1558 'name' => 'New Tag3',
1559 'description' => 'This is description for Our New Tag ',
1562 $params = array_merge($defaults, $params);
1563 $result = $this->callAPISuccess('Tag', 'create', $params);
1564 return $result['values'][$result['id']];
1571 * Id of the tag to be deleted.
1575 public function tagDelete($tagId) {
1576 require_once 'api/api.php';
1580 $result = $this->callAPISuccess('Tag', 'delete', $params);
1581 return $result['id'];
1585 * Add entity(s) to the tag
1587 * @param array $params
1591 public function entityTagAdd($params) {
1592 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1597 * Create contribution.
1603 * id of created contribution
1605 public function pledgeCreate($cID) {
1607 'contact_id' => $cID,
1608 'pledge_create_date' => date('Ymd'),
1609 'start_date' => date('Ymd'),
1610 'scheduled_date' => date('Ymd'),
1612 'pledge_status_id' => '2',
1613 'financial_type_id' => '1',
1614 'pledge_original_installment_amount' => 20,
1615 'frequency_interval' => 5,
1616 'frequency_unit' => 'year',
1617 'frequency_day' => 15,
1618 'installments' => 5,
1621 $result = $this->callAPISuccess('Pledge', 'create', $params);
1622 return $result['id'];
1626 * Delete contribution.
1628 * @param int $pledgeId
1630 public function pledgeDelete($pledgeId) {
1632 'pledge_id' => $pledgeId,
1634 $this->callAPISuccess('Pledge', 'delete', $params);
1638 * Create contribution.
1640 * @param array $params
1641 * Array of parameters.
1644 * id of created contribution
1646 public function contributionCreate($params) {
1648 $params = array_merge(array(
1650 'receive_date' => date('Ymd'),
1651 'total_amount' => 100.00,
1652 'fee_amount' => 5.00,
1653 'net_ammount' => 95.00,
1654 'financial_type_id' => 1,
1655 'payment_instrument_id' => 1,
1656 'non_deductible_amount' => 10.00,
1658 'invoice_id' => 67890,
1660 'contribution_status_id' => 1,
1663 $result = $this->callAPISuccess('contribution', 'create', $params);
1664 return $result['id'];
1668 * Delete contribution.
1670 * @param int $contributionId
1674 public function contributionDelete($contributionId) {
1676 'contribution_id' => $contributionId,
1678 $result = $this->callAPISuccess('contribution', 'delete', $params);
1685 * @param array $params
1686 * Name-value pair for an event.
1690 public function eventCreate($params = array()) {
1691 // if no contact was passed, make up a dummy event creator
1692 if (!isset($params['contact_id'])) {
1693 $params['contact_id'] = $this->_contactCreate(array(
1694 'contact_type' => 'Individual',
1695 'first_name' => 'Event',
1696 'last_name' => 'Creator',
1700 // set defaults for missing params
1701 $params = array_merge(array(
1702 'title' => 'Annual CiviCRM meet',
1703 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1704 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1705 'event_type_id' => 1,
1707 'start_date' => 20081021,
1708 'end_date' => 20081023,
1709 'is_online_registration' => 1,
1710 'registration_start_date' => 20080601,
1711 'registration_end_date' => 20081015,
1712 'max_participants' => 100,
1713 'event_full_text' => 'Sorry! We are already full',
1716 'is_show_location' => 0,
1719 return $this->callAPISuccess('Event', 'create', $params);
1730 public function eventDelete($id) {
1734 return $this->callAPISuccess('event', 'delete', $params);
1738 * Delete participant.
1740 * @param int $participantID
1744 public function participantDelete($participantID) {
1746 'id' => $participantID,
1748 return $this->callAPISuccess('Participant', 'delete', $params);
1752 * Create participant payment.
1754 * @param int $participantID
1755 * @param int $contributionID
1757 * $id of created payment
1759 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1760 //Create Participant Payment record With Values
1762 'participant_id' => $participantID,
1763 'contribution_id' => $contributionID,
1766 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1767 return $result['id'];
1771 * Delete participant payment.
1773 * @param int $paymentID
1775 public function participantPaymentDelete($paymentID) {
1779 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1785 * @param int $contactID
1787 * location id of created location
1789 public function locationAdd($contactID) {
1792 'location_type' => 'New Location Type',
1794 'name' => 'Saint Helier St',
1795 'county' => 'Marin',
1796 'country' => 'UNITED STATES',
1797 'state_province' => 'Michigan',
1798 'supplemental_address_1' => 'Hallmark Ct',
1799 'supplemental_address_2' => 'Jersey Village',
1804 'contact_id' => $contactID,
1805 'address' => $address,
1806 'location_format' => '2.0',
1807 'location_type' => 'New Location Type',
1810 $result = $this->callAPISuccess('Location', 'create', $params);
1815 * Delete Locations of contact.
1817 * @param array $params
1820 public function locationDelete($params) {
1821 $this->callAPISuccess('Location', 'delete', $params);
1825 * Add a Location Type.
1827 * @param array $params
1828 * @return CRM_Core_DAO_LocationType
1829 * location id of created location
1831 public function locationTypeCreate($params = NULL) {
1832 if ($params === NULL) {
1834 'name' => 'New Location Type',
1835 'vcard_name' => 'New Location Type',
1836 'description' => 'Location Type for Delete',
1841 $locationType = new CRM_Core_DAO_LocationType();
1842 $locationType->copyValues($params);
1843 $locationType->save();
1844 // clear getfields cache
1845 CRM_Core_PseudoConstant
::flush();
1846 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1847 return $locationType;
1851 * Delete a Location Type.
1853 * @param int $locationTypeId
1855 public function locationTypeDelete($locationTypeId) {
1856 $locationType = new CRM_Core_DAO_LocationType();
1857 $locationType->id
= $locationTypeId;
1858 $locationType->delete();
1864 * @param array $params
1865 * @return CRM_Core_DAO_Mapping
1866 * Mapping id of created mapping
1868 public function mappingCreate($params = NULL) {
1869 if ($params === NULL) {
1871 'name' => 'Mapping name',
1872 'description' => 'Mapping description',
1873 // 'Export Contact' mapping.
1874 'mapping_type_id' => 7,
1878 $mapping = new CRM_Core_DAO_Mapping();
1879 $mapping->copyValues($params);
1881 // clear getfields cache
1882 CRM_Core_PseudoConstant
::flush();
1883 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1890 * @param int $mappingId
1892 public function mappingDelete($mappingId) {
1893 $mapping = new CRM_Core_DAO_Mapping();
1894 $mapping->id
= $mappingId;
1901 * @param array $params
1903 * groupId of created group
1905 public function groupCreate($params = array()) {
1906 $params = array_merge(array(
1907 'name' => 'Test Group 1',
1909 'title' => 'New Test Group Created',
1910 'description' => 'New Test Group Created',
1912 'visibility' => 'Public Pages',
1913 'group_type' => array(
1919 $result = $this->callAPISuccess('Group', 'create', $params);
1920 return $result['id'];
1925 * Function to add a Group.
1927 * @params array to add group
1929 * @param int $groupID
1930 * @param int $totalCount
1932 * groupId of created group
1934 public function groupContactCreate($groupID, $totalCount = 10) {
1935 $params = array('group_id' => $groupID);
1936 for ($i = 1; $i <= $totalCount; $i++
) {
1937 $contactID = $this->individualCreate();
1939 $params +
= array('contact_id' => $contactID);
1942 $params +
= array("contact_id.$i" => $contactID);
1945 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1955 public function groupDelete($gid) {
1961 $this->callAPISuccess('Group', 'delete', $params);
1966 * @param array $params
1968 public function uFFieldCreate($params = array()) {
1969 $params = array_merge(array(
1971 'field_name' => 'first_name',
1974 'visibility' => 'Public Pages and Listings',
1975 'is_searchable' => '1',
1976 'label' => 'first_name',
1977 'field_type' => 'Individual',
1980 $this->callAPISuccess('uf_field', 'create', $params);
1984 * Add a UF Join Entry.
1986 * @param array $params
1988 * $id of created UF Join
1990 public function ufjoinCreate($params = NULL) {
1991 if ($params === NULL) {
1994 'module' => 'CiviEvent',
1995 'entity_table' => 'civicrm_event',
2001 $result = $this->callAPISuccess('uf_join', 'create', $params);
2006 * Delete a UF Join Entry.
2008 * @param array $params
2009 * with missing uf_group_id
2011 public function ufjoinDelete($params = NULL) {
2012 if ($params === NULL) {
2015 'module' => 'CiviEvent',
2016 'entity_table' => 'civicrm_event',
2019 'uf_group_id' => '',
2023 crm_add_uf_join($params);
2027 * @param array $params
2028 * Optional parameters.
2033 public function campaignCreate($params = array()) {
2034 $this->enableCiviCampaign();
2035 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2036 'name' => 'big_campaign',
2037 'title' => 'Campaign',
2039 return $campaign['id'];
2043 * Create Group for a contact.
2045 * @param int $contactId
2047 public function contactGroupCreate($contactId) {
2049 'contact_id.1' => $contactId,
2053 $this->callAPISuccess('GroupContact', 'Create', $params);
2057 * Delete Group for a contact.
2059 * @param int $contactId
2061 public function contactGroupDelete($contactId) {
2063 'contact_id.1' => $contactId,
2066 $this->civicrm_api('GroupContact', 'Delete', $params);
2072 * @param array $params
2075 public function activityCreate($params = NULL) {
2077 if ($params === NULL) {
2078 $individualSourceID = $this->individualCreate();
2080 $contactParams = array(
2081 'first_name' => 'Julia',
2082 'Last_name' => 'Anderson',
2084 'email' => 'julia_anderson@civicrm.org',
2085 'contact_type' => 'Individual',
2088 $individualTargetID = $this->individualCreate($contactParams);
2091 'source_contact_id' => $individualSourceID,
2092 'target_contact_id' => array($individualTargetID),
2093 'assignee_contact_id' => array($individualTargetID),
2094 'subject' => 'Discussion on warm beer',
2095 'activity_date_time' => date('Ymd'),
2096 'duration_hours' => 30,
2097 'duration_minutes' => 20,
2098 'location' => 'Baker Street',
2099 'details' => 'Lets schedule a meeting',
2101 'activity_name' => 'Meeting',
2105 $result = $this->callAPISuccess('Activity', 'create', $params);
2107 $result['target_contact_id'] = $individualTargetID;
2108 $result['assignee_contact_id'] = $individualTargetID;
2113 * Create an activity type.
2115 * @param array $params
2119 public function activityTypeCreate($params) {
2120 return $this->callAPISuccess('ActivityType', 'create', $params);
2124 * Delete activity type.
2126 * @param int $activityTypeId
2127 * Id of the activity type.
2130 public function activityTypeDelete($activityTypeId) {
2131 $params['activity_type_id'] = $activityTypeId;
2132 return $this->callAPISuccess('ActivityType', 'delete', $params);
2136 * Create custom group.
2138 * @param array $params
2141 public function customGroupCreate($params = array()) {
2143 'title' => 'new custom group',
2144 'extends' => 'Contact',
2146 'style' => 'Inline',
2150 $params = array_merge($defaults, $params);
2152 if (strlen($params['title']) > 13) {
2153 $params['title'] = substr($params['title'], 0, 13);
2156 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2157 $this->callAPISuccess('custom_group', 'get', array(
2158 'title' => $params['title'],
2159 array('api.custom_group.delete' => 1),
2162 return $this->callAPISuccess('custom_group', 'create', $params);
2166 * Existing function doesn't allow params to be over-ridden so need a new one
2167 * this one allows you to only pass in the params you want to change
2168 * @param array $params
2171 public function CustomGroupCreateByParams($params = array()) {
2173 'title' => "API Custom Group",
2174 'extends' => 'Contact',
2176 'style' => 'Inline',
2179 $params = array_merge($defaults, $params);
2180 return $this->callAPISuccess('custom_group', 'create', $params);
2184 * Create custom group with multi fields.
2185 * @param array $params
2188 public function CustomGroupMultipleCreateByParams($params = array()) {
2193 $params = array_merge($defaults, $params);
2194 return $this->CustomGroupCreateByParams($params);
2198 * Create custom group with multi fields.
2199 * @param array $params
2202 public function CustomGroupMultipleCreateWithFields($params = array()) {
2203 // also need to pass on $params['custom_field'] if not set but not in place yet
2205 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2206 $ids['custom_group_id'] = $customGroup['id'];
2208 $customField = $this->customFieldCreate(array(
2209 'custom_group_id' => $ids['custom_group_id'],
2210 'label' => 'field_1' . $ids['custom_group_id'],
2213 $ids['custom_field_id'][] = $customField['id'];
2215 $customField = $this->customFieldCreate(array(
2216 'custom_group_id' => $ids['custom_group_id'],
2217 'default_value' => '',
2218 'label' => 'field_2' . $ids['custom_group_id'],
2220 $ids['custom_field_id'][] = $customField['id'];
2222 $customField = $this->customFieldCreate(array(
2223 'custom_group_id' => $ids['custom_group_id'],
2224 'default_value' => '',
2225 'label' => 'field_3' . $ids['custom_group_id'],
2227 $ids['custom_field_id'][] = $customField['id'];
2233 * Create a custom group with a single text custom field. See
2234 * participant:testCreateWithCustom for how to use this
2236 * @param string $function
2238 * @param string $filename
2242 * ids of created objects
2244 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2245 $params = array('title' => $function);
2246 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2247 $params['extends'] = $entity ?
$entity : 'Contact';
2248 $customGroup = $this->CustomGroupCreate($params);
2249 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2250 CRM_Core_PseudoConstant
::flush();
2252 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2256 * Delete custom group.
2258 * @param int $customGroupID
2262 public function customGroupDelete($customGroupID) {
2263 $params['id'] = $customGroupID;
2264 return $this->callAPISuccess('custom_group', 'delete', $params);
2268 * Create custom field.
2270 * @param array $params
2271 * (custom_group_id) is required.
2274 public function customFieldCreate($params) {
2275 $params = array_merge(array(
2276 'label' => 'Custom Field',
2277 'data_type' => 'String',
2278 'html_type' => 'Text',
2279 'is_searchable' => 1,
2281 'default_value' => 'defaultValue',
2284 $result = $this->callAPISuccess('custom_field', 'create', $params);
2285 // these 2 functions are called with force to flush static caches
2286 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2287 CRM_Core_Component
::getEnabledComponents(1);
2292 * Delete custom field.
2294 * @param int $customFieldID
2298 public function customFieldDelete($customFieldID) {
2300 $params['id'] = $customFieldID;
2301 return $this->callAPISuccess('custom_field', 'delete', $params);
2310 public function noteCreate($cId) {
2312 'entity_table' => 'civicrm_contact',
2313 'entity_id' => $cId,
2314 'note' => 'hello I am testing Note',
2315 'contact_id' => $cId,
2316 'modified_date' => date('Ymd'),
2317 'subject' => 'Test Note',
2320 return $this->callAPISuccess('Note', 'create', $params);
2324 * Enable CiviCampaign Component.
2326 public function enableCiviCampaign() {
2327 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2328 // force reload of config object
2329 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2330 //flush cache by calling with reset
2331 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2335 * Create test generated example in api/v3/examples.
2337 * To turn this off (e.g. on the server) set
2338 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2339 * in your settings file
2341 * @param string $entity
2342 * @param string $action
2343 * @param array $params
2344 * Array as passed to civicrm_api function.
2345 * @param array $result
2346 * Array as received from the civicrm_api function.
2347 * @param string $testFunction
2348 * Calling function - generally __FUNCTION__.
2349 * @param string $testFile
2350 * Called from file - generally __FILE__.
2351 * @param string $description
2352 * Descriptive text for the example file.
2353 * @param string $exampleName
2354 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2356 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2357 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2360 $entity = _civicrm_api_get_camel_name($entity);
2361 $action = strtolower($action);
2363 if (empty($exampleName)) {
2364 // Attempt to convert lowercase action name to CamelCase.
2365 // This is clunky/imperfect due to the convention of all lowercase actions.
2366 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2367 $knownPrefixes = array(
2374 foreach ($knownPrefixes as $prefix) {
2375 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2376 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2381 $this->tidyExampleResult($result);
2382 if (isset($params['version'])) {
2383 unset($params['version']);
2385 // Format multiline description as array
2387 if (is_string($description) && strlen($description)) {
2388 foreach (explode("\n", $description) as $line) {
2389 $desc[] = trim($line);
2392 $smarty = CRM_Core_Smarty
::singleton();
2393 $smarty->assign('testFunction', $testFunction);
2394 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2395 $smarty->assign('params', $params);
2396 $smarty->assign('entity', $entity);
2397 $smarty->assign('testFile', basename($testFile));
2398 $smarty->assign('description', $desc);
2399 $smarty->assign('result', $result);
2400 $smarty->assign('action', $action);
2402 if (file_exists('../tests/templates/documentFunction.tpl')) {
2403 if (!is_dir("../api/v3/examples/$entity")) {
2404 mkdir("../api/v3/examples/$entity");
2406 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2407 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2413 * Tidy up examples array so that fields that change often ..don't
2414 * and debug related fields are unset
2416 * @param array $result
2418 public function tidyExampleResult(&$result) {
2419 if (!is_array($result)) {
2422 $fieldsToChange = array(
2423 'hash' => '67eac7789eaee00',
2424 'modified_date' => '2012-11-14 16:02:35',
2425 'created_date' => '2013-07-28 08:49:19',
2426 'create_date' => '20120130621222105',
2427 'application_received_date' => '20130728084957',
2428 'in_date' => '2013-07-28 08:50:19',
2429 'scheduled_date' => '20130728085413',
2430 'approval_date' => '20130728085413',
2431 'pledge_start_date_high' => '20130726090416',
2432 'start_date' => '2013-07-29 00:00:00',
2433 'event_start_date' => '2013-07-29 00:00:00',
2434 'end_date' => '2013-08-04 00:00:00',
2435 'event_end_date' => '2013-08-04 00:00:00',
2436 'decision_date' => '20130805000000',
2439 $keysToUnset = array('xdebug', 'undefined_fields');
2440 foreach ($keysToUnset as $unwantedKey) {
2441 if (isset($result[$unwantedKey])) {
2442 unset($result[$unwantedKey]);
2445 if (isset($result['values'])) {
2446 if (!is_array($result['values'])) {
2449 $resultArray = &$result['values'];
2451 elseif (is_array($result)) {
2452 $resultArray = &$result;
2458 foreach ($resultArray as $index => &$values) {
2459 if (!is_array($values)) {
2462 foreach ($values as $key => &$value) {
2463 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2464 if (isset($value['is_error'])) {
2465 // we have a std nested result format
2466 $this->tidyExampleResult($value);
2469 foreach ($value as &$nestedResult) {
2470 // this is an alternative syntax for nested results a keyed array of results
2471 $this->tidyExampleResult($nestedResult);
2475 if (in_array($key, $keysToUnset)) {
2476 unset($values[$key]);
2479 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2480 $value = $fieldsToChange[$key];
2482 if (is_string($value)) {
2483 $value = addslashes($value);
2492 * @param array $params
2496 public function noteDelete($params) {
2497 return $this->callAPISuccess('Note', 'delete', $params);
2501 * Create custom field with Option Values.
2503 * @param array $customGroup
2504 * @param string $name
2505 * Name of custom field.
2509 public function customFieldOptionValueCreate($customGroup, $name) {
2510 $fieldParams = array(
2511 'custom_group_id' => $customGroup['id'],
2512 'name' => 'test_custom_group',
2513 'label' => 'Country',
2514 'html_type' => 'Select',
2515 'data_type' => 'String',
2518 'is_searchable' => 0,
2522 $optionGroup = array(
2524 'name' => 'option_group1',
2525 'label' => 'option_group_label1',
2528 $optionValue = array(
2529 'option_label' => array('Label1', 'Label2'),
2530 'option_value' => array('value1', 'value2'),
2531 'option_name' => array($name . '_1', $name . '_2'),
2532 'option_weight' => array(1, 2),
2533 'option_status' => 1,
2536 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2538 return $this->callAPISuccess('custom_field', 'create', $params);
2546 public function confirmEntitiesDeleted($entities) {
2547 foreach ($entities as $entity) {
2549 $result = $this->callAPISuccess($entity, 'Get', array());
2550 if ($result['error'] == 1 ||
$result['count'] > 0) {
2551 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2559 * Quick clean by emptying tables created for the test.
2561 * @param array $tablesToTruncate
2562 * @param bool $dropCustomValueTables
2563 * @throws \Exception
2565 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2567 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2569 if ($dropCustomValueTables) {
2570 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2571 while ($optionGroupResult->fetch()) {
2572 if (!empty($optionGroupResult->option_group_id
)) {
2573 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2576 $tablesToTruncate[] = 'civicrm_custom_group';
2577 $tablesToTruncate[] = 'civicrm_custom_field';
2580 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2582 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2583 foreach ($tablesToTruncate as $table) {
2584 $sql = "TRUNCATE TABLE $table";
2585 CRM_Core_DAO
::executeQuery($sql);
2587 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2589 if ($dropCustomValueTables) {
2590 $dbName = self
::getDBName();
2592 SELECT TABLE_NAME as tableName
2593 FROM INFORMATION_SCHEMA.TABLES
2594 WHERE TABLE_SCHEMA = '{$dbName}'
2595 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2598 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2599 while ($tableDAO->fetch()) {
2600 $sql = "DROP TABLE {$tableDAO->tableName}";
2601 CRM_Core_DAO
::executeQuery($sql);
2607 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2609 public function quickCleanUpFinancialEntities() {
2610 $tablesToTruncate = array(
2612 'civicrm_activity_contact',
2613 'civicrm_contribution',
2614 'civicrm_contribution_soft',
2615 'civicrm_contribution_product',
2616 'civicrm_financial_trxn',
2617 'civicrm_financial_item',
2618 'civicrm_contribution_recur',
2619 'civicrm_line_item',
2620 'civicrm_contribution_page',
2621 'civicrm_payment_processor',
2622 'civicrm_entity_financial_trxn',
2623 'civicrm_membership',
2624 'civicrm_membership_type',
2625 'civicrm_membership_payment',
2626 'civicrm_membership_log',
2627 'civicrm_membership_block',
2629 'civicrm_participant',
2630 'civicrm_participant_payment',
2632 'civicrm_price_set_entity',
2633 'civicrm_price_field_value',
2634 'civicrm_price_field',
2636 $this->quickCleanup($tablesToTruncate);
2637 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2638 $this->restoreDefaultPriceSetConfig();
2640 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2641 System
::singleton()->flushProcessors();
2644 public function restoreDefaultPriceSetConfig() {
2645 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2646 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field` (`id`, `price_set_id`, `name`, `label`, `html_type`, `is_enter_qty`, `help_pre`, `help_post`, `weight`, `is_display_amounts`, `options_per_line`, `is_active`, `is_required`, `active_on`, `expire_on`, `javascript`, `visibility_id`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', 'Text', 0, NULL, NULL, 1, 1, 1, 1, 1, NULL, NULL, NULL, 1)");
2647 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2650 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2651 * Default behaviour is to also delete the entity
2652 * @param array $params
2653 * Params array to check against.
2655 * Id of the entity concerned.
2656 * @param string $entity
2657 * Name of entity concerned (e.g. membership).
2658 * @param bool $delete
2659 * Should the entity be deleted as part of this check.
2660 * @param string $errorText
2661 * Text to print on error.
2664 * @param array $params
2667 * @param int $delete
2668 * @param string $errorText
2672 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2674 $result = $this->callAPISuccessGetSingle($entity, array(
2679 $this->callAPISuccess($entity, 'Delete', array(
2683 $dateFields = $keys = $dateTimeFields = array();
2684 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2685 foreach ($fields['values'] as $field => $settings) {
2686 if (array_key_exists($field, $result)) {
2687 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2690 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2692 $type = CRM_Utils_Array
::value('type', $settings);
2693 if ($type == CRM_Utils_Type
::T_DATE
) {
2694 $dateFields[] = $settings['name'];
2695 // we should identify both real names & unique names as dates
2696 if ($field != $settings['name']) {
2697 $dateFields[] = $field;
2700 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2701 $dateTimeFields[] = $settings['name'];
2702 // we should identify both real names & unique names as dates
2703 if ($field != $settings['name']) {
2704 $dateTimeFields[] = $field;
2709 if (strtolower($entity) == 'contribution') {
2710 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2711 // this is not returned in id format
2712 unset($params['payment_instrument_id']);
2713 $params['contribution_source'] = $params['source'];
2714 unset($params['source']);
2717 foreach ($params as $key => $value) {
2718 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2721 if (in_array($key, $dateFields)) {
2722 $value = date('Y-m-d', strtotime($value));
2723 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2725 if (in_array($key, $dateTimeFields)) {
2726 $value = date('Y-m-d H:i:s', strtotime($value));
2727 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2729 $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);
2734 * Get formatted values in the actual and expected result.
2735 * @param array $actual
2736 * Actual calculated values.
2737 * @param array $expected
2740 public function checkArrayEquals(&$actual, &$expected) {
2741 self
::unsetId($actual);
2742 self
::unsetId($expected);
2743 $this->assertEquals($actual, $expected);
2747 * Unset the key 'id' from the array
2748 * @param array $unformattedArray
2749 * The array from which the 'id' has to be unset.
2751 public static function unsetId(&$unformattedArray) {
2752 $formattedArray = array();
2753 if (array_key_exists('id', $unformattedArray)) {
2754 unset($unformattedArray['id']);
2756 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2757 foreach ($unformattedArray['values'] as $key => $value) {
2758 if (is_array($value)) {
2759 foreach ($value as $k => $v) {
2765 elseif ($key == 'id') {
2766 $unformattedArray[$key];
2768 $formattedArray = array($value);
2770 $unformattedArray['values'] = $formattedArray;
2775 * Helper to enable/disable custom directory support
2777 * @param array $customDirs
2779 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2780 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2782 public function customDirectories($customDirs) {
2783 require_once 'CRM/Core/Config.php';
2784 $config = CRM_Core_Config
::singleton();
2786 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2787 unset($config->customPHPPathDir
);
2789 elseif ($customDirs['php_path'] === TRUE) {
2790 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2793 $config->customPHPPathDir
= $php_path;
2796 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2797 unset($config->customTemplateDir
);
2799 elseif ($customDirs['template_path'] === TRUE) {
2800 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2803 $config->customTemplateDir
= $template_path;
2808 * Generate a temporary folder.
2810 * @param string $prefix
2813 public function createTempDir($prefix = 'test-') {
2814 $tempDir = CRM_Utils_File
::tempdir($prefix);
2815 $this->tempDirs
[] = $tempDir;
2819 public function cleanTempDirs() {
2820 if (!is_array($this->tempDirs
)) {
2821 // fix test errors where this is not set
2824 foreach ($this->tempDirs
as $tempDir) {
2825 if (is_dir($tempDir)) {
2826 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2832 * Temporarily replace the singleton extension with a different one.
2833 * @param \CRM_Extension_System $system
2835 public function setExtensionSystem(CRM_Extension_System
$system) {
2836 if ($this->origExtensionSystem
== NULL) {
2837 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2839 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2842 public function unsetExtensionSystem() {
2843 if ($this->origExtensionSystem
!== NULL) {
2844 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2845 $this->origExtensionSystem
= NULL;
2850 * Temporarily alter the settings-metadata to add a mock setting.
2852 * WARNING: The setting metadata will disappear on the next cache-clear.
2857 public function setMockSettingsMetaData($extras) {
2858 Civi
::service('settings_manager')->flush();
2860 CRM_Utils_Hook
::singleton()
2861 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2862 $metadata = array_merge($metadata, $extras);
2865 $fields = $this->callAPISuccess('setting', 'getfields', array());
2866 foreach ($extras as $key => $spec) {
2867 $this->assertNotEmpty($spec['title']);
2868 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2873 * @param string $name
2875 public function financialAccountDelete($name) {
2876 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2877 $financialAccount->name
= $name;
2878 if ($financialAccount->find(TRUE)) {
2879 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2880 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2881 $entityFinancialType->delete();
2882 $financialAccount->delete();
2887 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2888 * (NB unclear if this is still required)
2890 public function _sethtmlGlobals() {
2891 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2892 'required' => array(
2893 'html_quickform_rule_required',
2894 'HTML/QuickForm/Rule/Required.php',
2896 'maxlength' => array(
2897 'html_quickform_rule_range',
2898 'HTML/QuickForm/Rule/Range.php',
2900 'minlength' => array(
2901 'html_quickform_rule_range',
2902 'HTML/QuickForm/Rule/Range.php',
2904 'rangelength' => array(
2905 'html_quickform_rule_range',
2906 'HTML/QuickForm/Rule/Range.php',
2909 'html_quickform_rule_email',
2910 'HTML/QuickForm/Rule/Email.php',
2913 'html_quickform_rule_regex',
2914 'HTML/QuickForm/Rule/Regex.php',
2916 'lettersonly' => array(
2917 'html_quickform_rule_regex',
2918 'HTML/QuickForm/Rule/Regex.php',
2920 'alphanumeric' => array(
2921 'html_quickform_rule_regex',
2922 'HTML/QuickForm/Rule/Regex.php',
2925 'html_quickform_rule_regex',
2926 'HTML/QuickForm/Rule/Regex.php',
2928 'nopunctuation' => array(
2929 'html_quickform_rule_regex',
2930 'HTML/QuickForm/Rule/Regex.php',
2933 'html_quickform_rule_regex',
2934 'HTML/QuickForm/Rule/Regex.php',
2936 'callback' => array(
2937 'html_quickform_rule_callback',
2938 'HTML/QuickForm/Rule/Callback.php',
2941 'html_quickform_rule_compare',
2942 'HTML/QuickForm/Rule/Compare.php',
2945 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2946 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2948 'HTML/QuickForm/group.php',
2949 'HTML_QuickForm_group',
2952 'HTML/QuickForm/hidden.php',
2953 'HTML_QuickForm_hidden',
2956 'HTML/QuickForm/reset.php',
2957 'HTML_QuickForm_reset',
2959 'checkbox' => array(
2960 'HTML/QuickForm/checkbox.php',
2961 'HTML_QuickForm_checkbox',
2964 'HTML/QuickForm/file.php',
2965 'HTML_QuickForm_file',
2968 'HTML/QuickForm/image.php',
2969 'HTML_QuickForm_image',
2971 'password' => array(
2972 'HTML/QuickForm/password.php',
2973 'HTML_QuickForm_password',
2976 'HTML/QuickForm/radio.php',
2977 'HTML_QuickForm_radio',
2980 'HTML/QuickForm/button.php',
2981 'HTML_QuickForm_button',
2984 'HTML/QuickForm/submit.php',
2985 'HTML_QuickForm_submit',
2988 'HTML/QuickForm/select.php',
2989 'HTML_QuickForm_select',
2991 'hiddenselect' => array(
2992 'HTML/QuickForm/hiddenselect.php',
2993 'HTML_QuickForm_hiddenselect',
2996 'HTML/QuickForm/text.php',
2997 'HTML_QuickForm_text',
2999 'textarea' => array(
3000 'HTML/QuickForm/textarea.php',
3001 'HTML_QuickForm_textarea',
3003 'fckeditor' => array(
3004 'HTML/QuickForm/fckeditor.php',
3005 'HTML_QuickForm_FCKEditor',
3008 'HTML/QuickForm/tinymce.php',
3009 'HTML_QuickForm_TinyMCE',
3011 'dojoeditor' => array(
3012 'HTML/QuickForm/dojoeditor.php',
3013 'HTML_QuickForm_dojoeditor',
3016 'HTML/QuickForm/link.php',
3017 'HTML_QuickForm_link',
3019 'advcheckbox' => array(
3020 'HTML/QuickForm/advcheckbox.php',
3021 'HTML_QuickForm_advcheckbox',
3024 'HTML/QuickForm/date.php',
3025 'HTML_QuickForm_date',
3028 'HTML/QuickForm/static.php',
3029 'HTML_QuickForm_static',
3032 'HTML/QuickForm/header.php',
3033 'HTML_QuickForm_header',
3036 'HTML/QuickForm/html.php',
3037 'HTML_QuickForm_html',
3039 'hierselect' => array(
3040 'HTML/QuickForm/hierselect.php',
3041 'HTML_QuickForm_hierselect',
3043 'autocomplete' => array(
3044 'HTML/QuickForm/autocomplete.php',
3045 'HTML_QuickForm_autocomplete',
3048 'HTML/QuickForm/xbutton.php',
3049 'HTML_QuickForm_xbutton',
3051 'advmultiselect' => array(
3052 'HTML/QuickForm/advmultiselect.php',
3053 'HTML_QuickForm_advmultiselect',
3059 * Set up an acl allowing contact to see 2 specified groups
3060 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3062 * You need to have pre-created these groups & created the user e.g
3063 * $this->createLoggedInUser();
3064 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3065 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3067 * @param bool $isProfile
3069 public function setupACL($isProfile = FALSE) {
3071 $_REQUEST = $this->_params
;
3073 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3074 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3075 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3076 'option_group_id' => $optionGroupID,
3077 'label' => 'pick me',
3081 CRM_Core_DAO
::executeQuery("
3082 TRUNCATE civicrm_acl_cache
3085 CRM_Core_DAO
::executeQuery("
3086 TRUNCATE civicrm_acl_contact_cache
3089 CRM_Core_DAO
::executeQuery("
3090 INSERT INTO civicrm_acl_entity_role (
3091 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3092 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3096 CRM_Core_DAO
::executeQuery("
3097 INSERT INTO civicrm_acl (
3098 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3101 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3106 CRM_Core_DAO
::executeQuery("
3107 INSERT INTO civicrm_acl (
3108 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3111 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3115 CRM_Core_DAO
::executeQuery("
3116 INSERT INTO civicrm_acl (
3117 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3120 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3125 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3126 $this->callAPISuccess('group_contact', 'create', array(
3127 'group_id' => $this->_permissionedGroup
,
3128 'contact_id' => $this->_loggedInUser
,
3133 CRM_ACL_BAO_Cache
::resetCache();
3134 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3135 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3140 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3142 public function offsetDefaultPriceSet() {
3143 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3144 $firstID = $contributionPriceSet['id'];
3145 $this->callAPISuccess('price_set', 'create', array(
3146 'id' => $contributionPriceSet['id'],
3150 unset($contributionPriceSet['id']);
3151 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3152 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3153 'price_set_id' => $firstID,
3154 'options' => array('limit' => 1),
3156 unset($priceField['id']);
3157 $priceField['price_set_id'] = $newPriceSet['id'];
3158 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3159 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3160 'price_set_id' => $firstID,
3162 'options' => array('limit' => 1),
3165 unset($priceFieldValue['id']);
3166 //create some padding to use up ids
3167 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3168 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3169 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3173 * Create an instance of the paypal processor.
3174 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3175 * this parent class & we don't have a structure for that yet
3176 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3177 * & the best protection against that is the functions this class affords
3178 * @param array $params
3179 * @return int $result['id'] payment processor id
3181 public function paymentProcessorCreate($params = array()) {
3182 $params = array_merge(array(
3184 'domain_id' => CRM_Core_Config
::domainID(),
3185 'payment_processor_type_id' => 'PayPal',
3189 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3190 'password' => '1183377788',
3191 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3192 'url_site' => 'https://www.sandbox.paypal.com/',
3193 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3194 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3195 'class_name' => 'Payment_PayPalImpl',
3196 'billing_mode' => 3,
3197 'financial_type_id' => 1,
3200 if (!is_numeric($params['payment_processor_type_id'])) {
3201 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3203 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3204 'name' => $params['payment_processor_type_id'],
3208 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3209 return $result['id'];
3213 * Set up initial recurring payment allowing subsequent IPN payments.
3215 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3216 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3217 'contact_id' => $this->_contactID
,
3220 'installments' => 5,
3221 'frequency_unit' => 'Month',
3222 'frequency_interval' => 1,
3223 'invoice_id' => $this->_invoiceID
,
3224 'contribution_status_id' => 2,
3225 'payment_processor_id' => $this->_paymentProcessorID
,
3226 // processor provided ID - use contact ID as proxy.
3227 'processor_id' => $this->_contactID
,
3228 'api.contribution.create' => array(
3229 'total_amount' => '200',
3230 'invoice_id' => $this->_invoiceID
,
3231 'financial_type_id' => 1,
3232 'contribution_status_id' => 'Pending',
3233 'contact_id' => $this->_contactID
,
3234 'contribution_page_id' => $this->_contributionPageID
,
3235 'payment_processor_id' => $this->_paymentProcessorID
,
3239 $this->_contributionRecurID
= $contributionRecur['id'];
3240 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3244 * We don't have a good way to set up a recurring contribution with a membership so let's just do one then alter it
3246 public function setupMembershipRecurringPaymentProcessorTransaction() {
3247 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3248 //create a contribution so our membership & contribution don't both have id = 1
3249 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3250 $this->contributionCreate(array(
3251 'contact_id' => $this->_contactID
,
3253 'financial_type_id' => 1,
3254 'invoice_id' => 'abcd',
3258 $this->setupRecurringPaymentProcessorTransaction();
3260 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3261 'contact_id' => $this->_contactID
,
3262 'membership_type_id' => $this->ids
['membership_type'],
3263 'contribution_recur_id' => $this->_contributionRecurID
,
3264 'format.only_id' => TRUE,
3266 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3267 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3269 $this->callAPISuccess('line_item', 'create', array(
3270 'entity_table' => 'civicrm_membership',
3271 'entity_id' => $this->ids
['membership'],
3272 'contribution_id' => $this->_contributionID
,
3273 'label' => 'General',
3275 'unit_price' => 200,
3276 'line_total' => 200,
3277 'financial_type_id' => 1,
3278 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3280 'label' => 'Membership Amount',
3281 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3283 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3285 'label' => 'General',
3286 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3289 $this->callAPISuccess('membership_payment', 'create', array(
3290 'contribution_id' => $this->_contributionID
,
3291 'membership_id' => $this->ids
['membership'],
3300 public function CiviUnitTestCase_fatalErrorHandler($message) {
3301 throw new Exception("{$message['message']}: {$message['code']}");
3305 * Helper function to create new mailing.
3308 public function createMailing() {
3310 'subject' => 'maild' . rand(),
3311 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3312 'name' => 'mailing name' . rand(),
3316 $result = $this->callAPISuccess('Mailing', 'create', $params);
3317 return $result['id'];
3321 * Helper function to delete mailing.
3324 public function deleteMailing($id) {
3329 $this->callAPISuccess('Mailing', 'delete', $params);
3333 * Wrap the entire test case in a transaction.
3335 * Only subsequent DB statements will be wrapped in TX -- this cannot
3336 * retroactively wrap old DB statements. Therefore, it makes sense to
3337 * call this at the beginning of setUp().
3339 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3340 * this option does not work with, e.g., custom-data.
3342 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3343 * if TRUNCATE or ALTER is called while using a transaction.
3346 * Whether to use nesting or reference-counting.
3348 public function useTransaction($nest = TRUE) {
3350 $this->tx
= new CRM_Core_Transaction($nest);
3351 $this->tx
->rollback();
3355 public function clearOutputBuffer() {
3356 while (ob_get_level() > 0) {
3362 * Assert the attachment exists.
3364 * @param bool $exists
3365 * @param array $apiResult
3367 protected function assertAttachmentExistence($exists, $apiResult) {
3368 $fileId = $apiResult['id'];
3369 $this->assertTrue(is_numeric($fileId));
3370 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3371 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3372 1 => array($fileId, 'Int'),
3374 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3375 1 => array($fileId, 'Int'),
3380 * Create a price set for an event.
3382 * @param int $feeTotal
3387 protected function eventPriceSetCreate($feeTotal) {
3388 // creating price set, price field
3389 $paramsSet['title'] = 'Price Set';
3390 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3391 $paramsSet['is_active'] = FALSE;
3392 $paramsSet['extends'] = 1;
3394 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3395 $priceSetId = $priceset->id
;
3397 //Checking for priceset added in the table.
3398 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3399 'id', $paramsSet['title'], 'Check DB for created priceset'
3401 $paramsField = array(
3402 'label' => 'Price Field',
3403 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3404 'html_type' => 'Text',
3405 'price' => $feeTotal,
3406 'option_label' => array('1' => 'Price Field'),
3407 'option_value' => array('1' => $feeTotal),
3408 'option_name' => array('1' => $feeTotal),
3409 'option_weight' => array('1' => 1),
3410 'option_amount' => array('1' => 1),
3411 'is_display_amounts' => 1,
3413 'options_per_line' => 1,
3414 'is_active' => array('1' => 1),
3415 'price_set_id' => $priceset->id
,
3416 'is_enter_qty' => 1,
3417 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3419 CRM_Price_BAO_PriceField
::create($paramsField);
3425 * Add a profile to a contribution page.
3427 * @param string $name
3428 * @param int $contributionPageID
3430 protected function addProfile($name, $contributionPageID) {
3431 $this->callAPISuccess('UFJoin', 'create', array(
3432 'uf_group_id' => $name,
3433 'module' => 'CiviContribute',
3434 'entity_table' => 'civicrm_contribution_page',
3435 'entity_id' => $contributionPageID,
3441 * Add participant with contribution
3445 protected function createParticipantWithContribution() {
3446 // creating price set, price field
3447 require_once 'CiviTest/Event.php';
3448 require_once 'CiviTest/Contact.php';
3449 $this->_contactId
= Contact
::createIndividual();
3450 $this->_eventId
= Event
::create($this->_contactId
);
3451 $eventParams = array(
3452 'id' => $this->_eventId
,
3453 'financial_type_id' => 4,
3456 $this->callAPISuccess('event', 'create', $eventParams);
3457 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3458 $participantParams = array(
3459 'financial_type_id' => 4,
3460 'event_id' => $this->_eventId
,
3463 'fee_currency' => 'USD',
3464 'contact_id' => $this->_contactId
,
3466 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3467 $contributionParams = array(
3468 'total_amount' => 150,
3469 'currency' => 'USD',
3470 'contact_id' => $this->_contactId
,
3471 'financial_type_id' => 4,
3472 'contribution_status_id' => 1,
3473 'partial_payment_total' => 300.00,
3474 'partial_amount_pay' => 150,
3475 'contribution_mode' => 'participant',
3476 'participant_id' => $participant['id'],
3478 foreach ($priceFields['values'] as $key => $priceField) {
3479 $lineItems[1][$key] = array(
3480 'price_field_id' => $priceField['price_field_id'],
3481 'price_field_value_id' => $priceField['id'],
3482 'label' => $priceField['label'],
3483 'field_title' => $priceField['label'],
3485 'unit_price' => $priceField['amount'],
3486 'line_total' => $priceField['amount'],
3487 'financial_type_id' => $priceField['financial_type_id'],
3490 $contributionParams['line_item'] = $lineItems;
3491 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3492 $paymentParticipant = array(
3493 'participant_id' => $participant['id'],
3494 'contribution_id' => $contribution['id'],
3497 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3498 return array($lineItems, $contribution);
3504 * @param string $component
3505 * @param int $componentId
3509 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3510 $paramsSet['title'] = 'Price Set';
3511 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3512 $paramsSet['is_active'] = TRUE;
3513 $paramsSet['financial_type_id'] = 4;
3514 $paramsSet['extends'] = 1;
3515 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3516 $priceSetId = $priceSet['id'];
3517 //Checking for priceset added in the table.
3518 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3519 'id', $paramsSet['title'], 'Check DB for created priceset'
3521 $paramsField = array(
3522 'label' => 'Price Field',
3523 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3524 'html_type' => 'CheckBox',
3525 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3526 'option_value' => array('1' => 100, '2' => 200),
3527 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3528 'option_weight' => array('1' => 1, '2' => 2),
3529 'option_amount' => array('1' => 100, '2' => 200),
3530 'is_display_amounts' => 1,
3532 'options_per_line' => 1,
3533 'is_active' => array('1' => 1, '2' => 1),
3534 'price_set_id' => $priceSet['id'],
3535 'is_enter_qty' => 1,
3536 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3538 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3540 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3542 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));