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 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
56 use \Civi\Test\Api3DocTrait
;
59 * Database has been initialized.
63 private static $dbInit = FALSE;
66 * Database connection.
68 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
77 static protected $_dbName;
80 * Track tables we have modified during a test.
82 protected $_tablesToTruncate = array();
85 * @var array of temporary directory names
90 * @var boolean populateOnce allows to skip db resets in setUp
92 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
93 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
96 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
98 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
100 public static $populateOnce = FALSE;
103 * @var boolean DBResetRequired allows skipping DB reset
104 * in specific test case. If you still need
105 * to reset single test (method) of such case, call
106 * $this->cleanDB() in the first line of this
109 public $DBResetRequired = TRUE;
112 * @var CRM_Core_Transaction|NULL
117 * @var CRM_Utils_Hook_UnitTests hookClass
118 * example of setting a method for a hook
119 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
121 public $hookClass = NULL;
124 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
126 protected $_params = array();
129 * @var CRM_Extension_System
131 protected $origExtensionSystem;
134 * Array of IDs created during test setup routine.
136 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
140 public $setupIDs = array();
143 * PHPUnit Mock Mecthod to use.
147 public $mockMethod = 'getMock';
152 * Because we are overriding the parent class constructor, we
153 * need to show the same arguments as exist in the constructor of
154 * PHPUnit_Framework_TestCase, since
155 * PHPUnit_Framework_TestSuite::createTest() creates a
156 * ReflectionClass of the Test class and checks the constructor
157 * of that class to decide how to set up the test.
159 * @param string $name
161 * @param string $dataName
163 public function __construct($name = NULL, array$data = array(), $dataName = '') {
164 parent
::__construct($name, $data, $dataName);
166 // we need full error reporting
167 error_reporting(E_ALL
& ~E_NOTICE
);
169 self
::$_dbName = self
::getDBName();
171 // also load the class loader
172 require_once 'CRM/Core/ClassLoader.php';
173 CRM_Core_ClassLoader
::singleton()->register();
174 if (function_exists('_civix_phpunit_setUp')) {
175 // FIXME: loosen coupling
176 _civix_phpunit_setUp();
178 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
179 $this->mockMethod
= 'createMock';
184 * Override to run the test and assert its state.
187 * @throws \PHPUnit_Framework_IncompleteTest
188 * @throws \PHPUnit_Framework_SkippedTest
190 protected function runTest() {
192 return parent
::runTest();
194 catch (PEAR_Exception
$e) {
195 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
196 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
203 public function requireDBReset() {
204 return $this->DBResetRequired
;
210 public static function getDBName() {
211 static $dbName = NULL;
212 if ($dbName === NULL) {
213 require_once "DB.php";
214 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
215 $dbName = $dsninfo['database'];
221 * Create database connection for this instance.
223 * Initialize the test database if it hasn't been initialized
225 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
227 protected function getConnection() {
228 $dbName = self
::$_dbName;
229 if (!self
::$dbInit) {
230 $dbName = self
::getDBName();
232 // install test database
233 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
235 static::_populateDB(FALSE, $this);
237 self
::$dbInit = TRUE;
240 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
244 * Required implementation of abstract method.
246 protected function getDataSet() {
250 * @param bool $perClass
251 * @param null $object
253 * TRUE if the populate logic runs; FALSE if it is skipped
255 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
256 if (CIVICRM_UF
!== 'UnitTests') {
257 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
260 if ($perClass ||
$object == NULL) {
264 $dbreset = $object->requireDBReset();
267 if (self
::$populateOnce ||
!$dbreset) {
270 self
::$populateOnce = NULL;
272 Civi\Test
::data()->populate();
277 public static function setUpBeforeClass() {
278 static::_populateDB(TRUE);
280 // also set this global hack
281 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
285 * Common setup functions for all unit tests.
287 protected function setUp() {
288 $session = CRM_Core_Session
::singleton();
289 $session->set('userID', NULL);
291 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
292 // Use a temporary file for STDIN
293 $GLOBALS['stdin'] = tmpfile();
294 if ($GLOBALS['stdin'] === FALSE) {
295 echo "Couldn't open temporary file\n";
299 // Get and save a connection to the database
300 $this->_dbconn
= $this->getConnection();
302 // reload database before each test
303 // $this->_populateDB();
305 // "initialize" CiviCRM to avoid problems when running single tests
306 // FIXME: look at it closer in second stage
308 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
309 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
311 // disable any left-over test extensions
312 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
314 // reset all the caches
315 CRM_Utils_System
::flushCache();
317 // initialize the object once db is loaded
319 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
321 // when running unit tests, use mockup user framework
322 $this->hookClass
= CRM_Utils_Hook
::singleton();
324 // Make sure the DB connection is setup properly
325 $config->userSystem
->setMySQLTimeZone();
326 $env = new CRM_Utils_Check_Component_Env();
327 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
329 // clear permissions stub to not check permissions
330 $config->userPermissionClass
->permissions
= NULL;
332 //flush component settings
333 CRM_Core_Component
::getEnabledComponents(TRUE);
335 error_reporting(E_ALL
);
337 $this->_sethtmlGlobals();
341 * Read everything from the datasets directory and insert into the db.
343 public function loadAllFixtures() {
344 $fixturesDir = __DIR__
. '/../../fixtures';
346 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
348 $xmlFiles = glob($fixturesDir . '/*.xml');
349 foreach ($xmlFiles as $xmlFixture) {
350 $op = new PHPUnit_Extensions_Database_Operation_Insert();
351 $dataset = $this->createXMLDataSet($xmlFixture);
352 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
353 $op->execute($this->_dbconn
, $dataset);
356 $yamlFiles = glob($fixturesDir . '/*.yaml');
357 foreach ($yamlFiles as $yamlFixture) {
358 $op = new PHPUnit_Extensions_Database_Operation_Insert();
359 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
360 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
361 $op->execute($this->_dbconn
, $dataset);
364 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
368 * Emulate a logged in user since certain functions use that.
369 * value to store a record in the DB (like activity)
373 * Contact ID of the created user.
375 public function createLoggedInUser() {
377 'first_name' => 'Logged In',
378 'last_name' => 'User ' . rand(),
379 'contact_type' => 'Individual',
381 $contactID = $this->individualCreate($params);
382 $this->callAPISuccess('UFMatch', 'create', array(
383 'contact_id' => $contactID,
384 'uf_name' => 'superman',
388 $session = CRM_Core_Session
::singleton();
389 $session->set('userID', $contactID);
394 * Create default domain contacts for the two domains added during test class.
395 * database population.
397 public function createDomainContacts() {
398 $this->organizationCreate();
399 $this->organizationCreate(array('organization_name' => 'Second Domain'));
403 * Common teardown functions for all unit tests.
405 protected function tearDown() {
406 error_reporting(E_ALL
& ~E_NOTICE
);
407 CRM_Utils_Hook
::singleton()->reset();
408 $this->hookClass
->reset();
409 $session = CRM_Core_Session
::singleton();
410 $session->set('userID', NULL);
413 $this->tx
->rollback()->commit();
416 CRM_Core_Transaction
::forceRollbackIfEnabled();
417 \Civi\Core\Transaction\Manager
::singleton(TRUE);
420 CRM_Core_Transaction
::forceRollbackIfEnabled();
421 \Civi\Core\Transaction\Manager
::singleton(TRUE);
423 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
424 $this->quickCleanup($tablesToTruncate);
425 $this->createDomainContacts();
428 $this->cleanTempDirs();
429 $this->unsetExtensionSystem();
433 * Generic function to compare expected values after an api call to retrieved.
436 * @daoName string DAO Name of object we're evaluating.
437 * @id int Id of object
438 * @match array Associative array of field name => expected value. Empty if asserting
439 * that a DELETE occurred
440 * @delete boolean True if we're checking that a DELETE action occurred.
444 * @param bool $delete
445 * @throws \PHPUnit_Framework_AssertionFailedError
447 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
449 // adding this here since developers forget to check for an id
450 // and hence we get the first value in the db
451 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
454 $object = new $daoName();
458 // If we're asserting successful record deletion, make sure object is NOT found.
460 if ($object->find(TRUE)) {
461 $this->fail("Object not deleted by delete operation: $daoName, $id");
466 // Otherwise check matches of DAO field values against expected values in $match.
467 if ($object->find(TRUE)) {
468 $fields = &$object->fields();
469 foreach ($fields as $name => $value) {
470 $dbName = $value['name'];
471 if (isset($match[$name])) {
473 $this->assertEquals($object->$dbName, $match[$name]);
475 elseif (isset($match[$dbName])) {
477 $this->assertEquals($object->$dbName, $match[$dbName]);
482 $this->fail("Could not retrieve object: $daoName, $id");
485 $matchSize = count($match);
486 if ($verifiedCount != $matchSize) {
487 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
492 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
493 * @param string $daoName
494 * @param $searchValue
495 * @param $returnColumn
496 * @param $searchColumn
499 * @return null|string
500 * @throws PHPUnit_Framework_AssertionFailedError
502 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
503 if (empty($searchValue)) {
504 $this->fail("empty value passed to assertDBNotNull");
506 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
507 $this->assertNotNull($value, $message);
513 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
514 * @param string $daoName
515 * @param $searchValue
516 * @param $returnColumn
517 * @param $searchColumn
520 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
521 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
522 $this->assertNull($value, $message);
526 * Request a record from the DB by id. Success if row not found.
527 * @param string $daoName
529 * @param null $message
531 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
532 $message = $message ?
$message : "$daoName (#$id) should not exist";
533 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
534 $this->assertNull($value, $message);
538 * Request a record from the DB by id. Success if row not found.
539 * @param string $daoName
541 * @param null $message
543 public function assertDBRowExist($daoName, $id, $message = NULL) {
544 $message = $message ?
$message : "$daoName (#$id) should exist";
545 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
546 $this->assertEquals($id, $value, $message);
550 * Compare a single column value in a retrieved DB record to an expected value.
551 * @param string $daoName
552 * @param $searchValue
553 * @param $returnColumn
554 * @param $searchColumn
555 * @param $expectedValue
558 public function assertDBCompareValue(
559 $daoName, $searchValue, $returnColumn, $searchColumn,
560 $expectedValue, $message
562 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
563 $this->assertEquals($expectedValue, $value, $message);
567 * Compare all values in a single retrieved DB record to an array of expected values.
568 * @param string $daoName
569 * @param array $searchParams
570 * @param $expectedValues
572 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
573 //get the values from db
575 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
577 // compare db values with expected values
578 self
::assertAttributesEquals($expectedValues, $dbValues);
582 * Assert that a SQL query returns a given value.
584 * The first argument is an expected value. The remaining arguments are passed
585 * to CRM_Core_DAO::singleValueQuery
587 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
588 * array(1 => array("Whiz", "String")));
591 * @param array $params
592 * @param string $message
594 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
598 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
599 $this->assertEquals($expected, $actual,
600 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
601 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
607 * Assert that two array-trees are exactly equal, notwithstanding
608 * the sorting of keys
610 * @param array $expected
611 * @param array $actual
613 public function assertTreeEquals($expected, $actual) {
616 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
617 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
621 $this->assertEquals($e, $a);
625 * Assert that two numbers are approximately equal.
627 * @param int|float $expected
628 * @param int|float $actual
629 * @param int|float $tolerance
630 * @param string $message
632 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
633 if ($message === NULL) {
634 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
636 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
640 * Assert attributes are equal.
642 * @param $expectedValues
643 * @param $actualValues
644 * @param string $message
646 * @throws PHPUnit_Framework_AssertionFailedError
648 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
649 foreach ($expectedValues as $paramName => $paramValue) {
650 if (isset($actualValues[$paramName])) {
651 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
654 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
663 public function assertArrayKeyExists($key, &$list) {
664 $result = isset($list[$key]) ?
TRUE : FALSE;
665 $this->assertTrue($result, ts("%1 element exists?",
674 public function assertArrayValueNotNull($key, &$list) {
675 $this->assertArrayKeyExists($key, $list);
677 $value = isset($list[$key]) ?
$list[$key] : NULL;
678 $this->assertTrue($value,
679 ts("%1 element not null?",
688 * @param string $message
690 public function assertType($expected, $actual, $message = '') {
691 return $this->assertInternalType($expected, $actual, $message);
695 * Create a batch of external API calls which can
696 * be executed concurrently.
699 * $calls = $this->createExternalAPI()
700 * ->addCall('Contact', 'get', ...)
701 * ->addCall('Contact', 'get', ...)
707 * @return \Civi\API\ExternalBatch
708 * @throws PHPUnit_Framework_SkippedTestError
710 public function createExternalAPI() {
711 global $civicrm_root;
712 $defaultParams = array(
713 'version' => $this->_apiversion
,
717 $calls = new \Civi\API\
ExternalBatch($defaultParams);
719 if (!$calls->isSupported()) {
720 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
727 * Create required data based on $this->entity & $this->params
728 * This is just a way to set up the test data for delete & get functions
729 * so the distinction between set
730 * up & tested functions is clearer
735 public function createTestEntity() {
736 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
740 * Generic function to create Organisation, to be used in test cases
742 * @param array $params
743 * parameters for civicrm_contact_add api function call
745 * sequence number if creating multiple organizations
748 * id of Organisation created
750 public function organizationCreate($params = array(), $seq = 0) {
754 $params = array_merge($this->sampleContact('Organization', $seq), $params);
755 return $this->_contactCreate($params);
759 * Generic function to create Individual, to be used in test cases
761 * @param array $params
762 * parameters for civicrm_contact_add api function call
764 * sequence number if creating multiple individuals
765 * @param bool $random
768 * id of Individual created
770 public function individualCreate($params = array(), $seq = 0, $random = FALSE) {
771 $params = array_merge($this->sampleContact('Individual', $seq, $random), $params);
772 return $this->_contactCreate($params);
776 * Generic function to create Household, to be used in test cases
778 * @param array $params
779 * parameters for civicrm_contact_add api function call
781 * sequence number if creating multiple households
784 * id of Household created
786 public function householdCreate($params = array(), $seq = 0) {
787 $params = array_merge($this->sampleContact('Household', $seq), $params);
788 return $this->_contactCreate($params);
792 * Helper function for getting sample contact properties.
794 * @param string $contact_type
795 * enum contact type: Individual, Organization
797 * sequence number for the values of this type
800 * properties of sample contact (ie. $params for API call)
802 public function sampleContact($contact_type, $seq = 0, $random = FALSE) {
804 'Individual' => array(
805 // The number of values in each list need to be coprime numbers to not have duplicates
806 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
807 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
808 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
810 'Organization' => array(
811 'organization_name' => array(
812 'Unit Test Organization',
819 'Household' => array(
820 'household_name' => array('Unit Test household'),
823 $params = array('contact_type' => $contact_type);
824 foreach ($samples[$contact_type] as $key => $values) {
825 $params[$key] = $values[$seq %
count($values)];
827 $params[$key] .= substr(sha1(rand()), 0, 5);
830 if ($contact_type == 'Individual') {
831 $params['email'] = strtolower(
832 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
834 $params['prefix_id'] = 3;
835 $params['suffix_id'] = 3;
841 * Private helper function for calling civicrm_contact_add.
843 * @param array $params
844 * For civicrm_contact_add api function call.
849 * id of Household created
851 private function _contactCreate($params) {
852 $result = $this->callAPISuccess('contact', 'create', $params);
853 if (!empty($result['is_error']) ||
empty($result['id'])) {
854 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
856 return $result['id'];
860 * Delete contact, ensuring it is not the domain contact
862 * @param int $contactID
863 * Contact ID to delete
865 public function contactDelete($contactID) {
866 $domain = new CRM_Core_BAO_Domain();
867 $domain->contact_id
= $contactID;
868 if (!$domain->find(TRUE)) {
869 $this->callAPISuccess('contact', 'delete', array(
871 'skip_undelete' => 1,
877 * @param int $contactTypeId
881 public function contactTypeDelete($contactTypeId) {
882 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
884 throw new Exception('Could not delete contact type');
889 * @param array $params
893 public function membershipTypeCreate($params = array()) {
894 CRM_Member_PseudoConstant
::flush('membershipType');
895 CRM_Core_Config
::clearDBCache();
896 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
897 $params = array_merge(array(
899 'duration_unit' => 'year',
900 'duration_interval' => 1,
901 'period_type' => 'rolling',
902 'member_of_contact_id' => $memberOfOrganization,
904 'financial_type_id' => 2,
907 'visibility' => 'Public',
910 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
912 CRM_Member_PseudoConstant
::flush('membershipType');
913 CRM_Utils_Cache
::singleton()->flush();
915 return $result['id'];
919 * @param array $params
923 public function contactMembershipCreate($params) {
924 $params = array_merge(array(
925 'join_date' => '2007-01-21',
926 'start_date' => '2007-01-21',
927 'end_date' => '2007-12-21',
928 'source' => 'Payment',
929 'membership_type_id' => 'General',
931 if (!is_numeric($params['membership_type_id'])) {
932 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
933 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
934 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
938 $result = $this->callAPISuccess('Membership', 'create', $params);
939 return $result['id'];
943 * Delete Membership Type.
945 * @param array $params
947 public function membershipTypeDelete($params) {
948 $this->callAPISuccess('MembershipType', 'Delete', $params);
952 * @param int $membershipID
954 public function membershipDelete($membershipID) {
955 $deleteParams = array('id' => $membershipID);
956 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
960 * @param string $name
964 public function membershipStatusCreate($name = 'test member status') {
965 $params['name'] = $name;
966 $params['start_event'] = 'start_date';
967 $params['end_event'] = 'end_date';
968 $params['is_current_member'] = 1;
969 $params['is_active'] = 1;
971 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
972 CRM_Member_PseudoConstant
::flush('membershipStatus');
973 return $result['id'];
977 * @param int $membershipStatusID
979 public function membershipStatusDelete($membershipStatusID) {
980 if (!$membershipStatusID) {
983 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
986 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
987 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
988 $renewedMembershipEndDate = new DateTime($membershipEndDate);
989 switch ($durationUnit) {
991 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
995 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
996 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
997 $renewedMembershipEndDate->add(new DateInterval('P1D'));
998 $renewedMembershipEndDate->add(new DateInterval('P1M'));
999 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
1002 return $renewedMembershipEndDate->format('Y-m-d');
1006 * @param array $params
1010 public function relationshipTypeCreate($params = array()) {
1011 $params = array_merge(array(
1012 'name_a_b' => 'Relation 1 for relationship type create',
1013 'name_b_a' => 'Relation 2 for relationship type create',
1014 'contact_type_a' => 'Individual',
1015 'contact_type_b' => 'Organization',
1022 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1023 CRM_Core_PseudoConstant
::flush('relationshipType');
1025 return $result['id'];
1029 * Delete Relatinship Type.
1031 * @param int $relationshipTypeID
1033 public function relationshipTypeDelete($relationshipTypeID) {
1034 $params['id'] = $relationshipTypeID;
1035 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1036 if (!empty($check['count'])) {
1037 $this->callAPISuccess('relationship_type', 'delete', $params);
1042 * @param array $params
1046 public function paymentProcessorTypeCreate($params = NULL) {
1047 if (is_null($params)) {
1049 'name' => 'API_Test_PP',
1050 'title' => 'API Test Payment Processor',
1051 'class_name' => 'CRM_Core_Payment_APITest',
1052 'billing_mode' => 'form',
1058 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1060 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1062 return $result['id'];
1066 * Create test Authorize.net instance.
1068 * @param array $params
1072 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1073 $params = array_merge(array(
1074 'name' => 'Authorize',
1075 'domain_id' => CRM_Core_Config
::domainID(),
1076 'payment_processor_type_id' => 'AuthNet',
1077 'title' => 'AuthNet',
1082 'user_name' => '4y5BfuW7jm',
1083 'password' => '4cAmW927n8uLf5J8',
1084 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1085 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1086 'class_name' => 'Payment_AuthorizeNet',
1087 'billing_mode' => 1,
1090 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1091 return $result['id'];
1095 * Create Participant.
1097 * @param array $params
1098 * Array of contact id and event id values.
1101 * $id of participant created
1103 public function participantCreate($params = []) {
1104 if (empty($params['contact_id'])) {
1105 $params['contact_id'] = $this->individualCreate();
1107 if (empty($params['event_id'])) {
1108 $event = $this->eventCreate();
1109 $params['event_id'] = $event['id'];
1114 'register_date' => 20070219,
1115 'source' => 'Wimbeldon',
1116 'event_level' => 'Payment',
1120 $params = array_merge($defaults, $params);
1121 $result = $this->callAPISuccess('Participant', 'create', $params);
1122 return $result['id'];
1126 * Create Payment Processor.
1129 * Id Payment Processor
1131 public function processorCreate($params = array()) {
1132 $processorParams = array(
1135 'payment_processor_type_id' => 'Dummy',
1136 'financial_account_id' => 12,
1140 'url_site' => 'http://dummy.com',
1141 'url_recur' => 'http://dummy.com',
1142 'billing_mode' => 1,
1144 'payment_instrument_id' => 'Debit Card',
1146 $processorParams = array_merge($processorParams, $params);
1147 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1148 return $processor['id'];
1152 * Create Payment Processor.
1154 * @param array $processorParams
1156 * @return \CRM_Core_Payment_Dummy
1157 * Instance of Dummy Payment Processor
1159 public function dummyProcessorCreate($processorParams = array()) {
1160 $paymentProcessorID = $this->processorCreate($processorParams);
1161 return System
::singleton()->getById($paymentProcessorID);
1165 * Create contribution page.
1167 * @param array $params
1169 * Array of contribution page
1171 public function contributionPageCreate($params = array()) {
1172 $this->_pageParams
= array_merge(array(
1173 'title' => 'Test Contribution Page',
1174 'financial_type_id' => 1,
1175 'currency' => 'USD',
1176 'financial_account_id' => 1,
1178 'is_allow_other_amount' => 1,
1180 'max_amount' => 1000,
1182 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1186 * Create a sample batch.
1188 public function batchCreate() {
1189 $params = $this->_params
;
1190 $params['name'] = $params['title'] = 'Batch_433397';
1191 $params['status_id'] = 1;
1192 $result = $this->callAPISuccess('batch', 'create', $params);
1193 return $result['id'];
1199 * @param array $params
1201 * result of created tag
1203 public function tagCreate($params = array()) {
1205 'name' => 'New Tag3',
1206 'description' => 'This is description for Our New Tag ',
1209 $params = array_merge($defaults, $params);
1210 $result = $this->callAPISuccess('Tag', 'create', $params);
1211 return $result['values'][$result['id']];
1218 * Id of the tag to be deleted.
1222 public function tagDelete($tagId) {
1223 require_once 'api/api.php';
1227 $result = $this->callAPISuccess('Tag', 'delete', $params);
1228 return $result['id'];
1232 * Add entity(s) to the tag
1234 * @param array $params
1238 public function entityTagAdd($params) {
1239 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1246 * @param array $params
1250 * id of created pledge
1252 public function pledgeCreate($params) {
1253 $params = array_merge(array(
1254 'pledge_create_date' => date('Ymd'),
1255 'start_date' => date('Ymd'),
1256 'scheduled_date' => date('Ymd'),
1258 'pledge_status_id' => '2',
1259 'financial_type_id' => '1',
1260 'pledge_original_installment_amount' => 20,
1261 'frequency_interval' => 5,
1262 'frequency_unit' => 'year',
1263 'frequency_day' => 15,
1264 'installments' => 5,
1268 $result = $this->callAPISuccess('Pledge', 'create', $params);
1269 return $result['id'];
1273 * Delete contribution.
1275 * @param int $pledgeId
1277 public function pledgeDelete($pledgeId) {
1279 'pledge_id' => $pledgeId,
1281 $this->callAPISuccess('Pledge', 'delete', $params);
1285 * Create contribution.
1287 * @param array $params
1288 * Array of parameters.
1291 * id of created contribution
1293 public function contributionCreate($params) {
1295 $params = array_merge(array(
1297 'receive_date' => date('Ymd'),
1298 'total_amount' => 100.00,
1299 'fee_amount' => 5.00,
1300 'financial_type_id' => 1,
1301 'payment_instrument_id' => 1,
1302 'non_deductible_amount' => 10.00,
1304 'invoice_id' => 67890,
1306 'contribution_status_id' => 1,
1309 $result = $this->callAPISuccess('contribution', 'create', $params);
1310 return $result['id'];
1314 * Delete contribution.
1316 * @param int $contributionId
1320 public function contributionDelete($contributionId) {
1322 'contribution_id' => $contributionId,
1324 $result = $this->callAPISuccess('contribution', 'delete', $params);
1331 * @param array $params
1332 * Name-value pair for an event.
1336 public function eventCreate($params = array()) {
1337 // if no contact was passed, make up a dummy event creator
1338 if (!isset($params['contact_id'])) {
1339 $params['contact_id'] = $this->_contactCreate(array(
1340 'contact_type' => 'Individual',
1341 'first_name' => 'Event',
1342 'last_name' => 'Creator',
1346 // set defaults for missing params
1347 $params = array_merge(array(
1348 'title' => 'Annual CiviCRM meet',
1349 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1350 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1351 'event_type_id' => 1,
1353 'start_date' => 20081021,
1354 'end_date' => 20081023,
1355 'is_online_registration' => 1,
1356 'registration_start_date' => 20080601,
1357 'registration_end_date' => 20081015,
1358 'max_participants' => 100,
1359 'event_full_text' => 'Sorry! We are already full',
1362 'is_show_location' => 0,
1365 return $this->callAPISuccess('Event', 'create', $params);
1369 * Create a paid event.
1371 * @param array $params
1375 protected function eventCreatePaid($params) {
1376 $event = $this->eventCreate($params);
1377 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1378 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1379 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1380 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1381 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1393 public function eventDelete($id) {
1397 return $this->callAPISuccess('event', 'delete', $params);
1401 * Delete participant.
1403 * @param int $participantID
1407 public function participantDelete($participantID) {
1409 'id' => $participantID,
1411 $check = $this->callAPISuccess('Participant', 'get', $params);
1412 if ($check['count'] > 0) {
1413 return $this->callAPISuccess('Participant', 'delete', $params);
1418 * Create participant payment.
1420 * @param int $participantID
1421 * @param int $contributionID
1423 * $id of created payment
1425 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1426 //Create Participant Payment record With Values
1428 'participant_id' => $participantID,
1429 'contribution_id' => $contributionID,
1432 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1433 return $result['id'];
1437 * Delete participant payment.
1439 * @param int $paymentID
1441 public function participantPaymentDelete($paymentID) {
1445 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1451 * @param int $contactID
1453 * location id of created location
1455 public function locationAdd($contactID) {
1458 'location_type' => 'New Location Type',
1460 'name' => 'Saint Helier St',
1461 'county' => 'Marin',
1462 'country' => 'UNITED STATES',
1463 'state_province' => 'Michigan',
1464 'supplemental_address_1' => 'Hallmark Ct',
1465 'supplemental_address_2' => 'Jersey Village',
1466 'supplemental_address_3' => 'My Town',
1471 'contact_id' => $contactID,
1472 'address' => $address,
1473 'location_format' => '2.0',
1474 'location_type' => 'New Location Type',
1477 $result = $this->callAPISuccess('Location', 'create', $params);
1482 * Delete Locations of contact.
1484 * @param array $params
1487 public function locationDelete($params) {
1488 $this->callAPISuccess('Location', 'delete', $params);
1492 * Add a Location Type.
1494 * @param array $params
1495 * @return CRM_Core_DAO_LocationType
1496 * location id of created location
1498 public function locationTypeCreate($params = NULL) {
1499 if ($params === NULL) {
1501 'name' => 'New Location Type',
1502 'vcard_name' => 'New Location Type',
1503 'description' => 'Location Type for Delete',
1508 $locationType = new CRM_Core_DAO_LocationType();
1509 $locationType->copyValues($params);
1510 $locationType->save();
1511 // clear getfields cache
1512 CRM_Core_PseudoConstant
::flush();
1513 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1514 return $locationType;
1518 * Delete a Location Type.
1520 * @param int $locationTypeId
1522 public function locationTypeDelete($locationTypeId) {
1523 $locationType = new CRM_Core_DAO_LocationType();
1524 $locationType->id
= $locationTypeId;
1525 $locationType->delete();
1531 * @param array $params
1532 * @return CRM_Core_DAO_Mapping
1533 * Mapping id of created mapping
1535 public function mappingCreate($params = NULL) {
1536 if ($params === NULL) {
1538 'name' => 'Mapping name',
1539 'description' => 'Mapping description',
1540 // 'Export Contact' mapping.
1541 'mapping_type_id' => 7,
1545 $mapping = new CRM_Core_DAO_Mapping();
1546 $mapping->copyValues($params);
1548 // clear getfields cache
1549 CRM_Core_PseudoConstant
::flush();
1550 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1557 * @param int $mappingId
1559 public function mappingDelete($mappingId) {
1560 $mapping = new CRM_Core_DAO_Mapping();
1561 $mapping->id
= $mappingId;
1568 * @param array $params
1570 * groupId of created group
1572 public function groupCreate($params = array()) {
1573 $params = array_merge(array(
1574 'name' => 'Test Group 1',
1576 'title' => 'New Test Group Created',
1577 'description' => 'New Test Group Created',
1579 'visibility' => 'Public Pages',
1580 'group_type' => array(
1586 $result = $this->callAPISuccess('Group', 'create', $params);
1587 return $result['id'];
1591 * Prepare class for ACLs.
1593 protected function prepareForACLs() {
1594 $config = CRM_Core_Config
::singleton();
1595 $config->userPermissionClass
->permissions
= array();
1601 protected function cleanUpAfterACLs() {
1602 CRM_Utils_Hook
::singleton()->reset();
1603 $tablesToTruncate = array(
1605 'civicrm_acl_cache',
1606 'civicrm_acl_entity_role',
1607 'civicrm_acl_contact_cache',
1609 $this->quickCleanup($tablesToTruncate);
1610 $config = CRM_Core_Config
::singleton();
1611 unset($config->userPermissionClass
->permissions
);
1614 * Create a smart group.
1616 * By default it will be a group of households.
1618 * @param array $smartGroupParams
1619 * @param array $groupParams
1622 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1623 $smartGroupParams = array_merge(array(
1624 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1627 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1629 $groupParams['saved_search_id'] = $savedSearch->id
;
1630 return $this->groupCreate($groupParams);
1634 * Function to add a Group.
1636 * @params array to add group
1638 * @param int $groupID
1639 * @param int $totalCount
1640 * @param bool $random
1642 * groupId of created group
1644 public function groupContactCreate($groupID, $totalCount = 10, $random = FALSE) {
1645 $params = array('group_id' => $groupID);
1646 for ($i = 1; $i <= $totalCount; $i++
) {
1647 $contactID = $this->individualCreate(array(), 0, $random);
1649 $params +
= array('contact_id' => $contactID);
1652 $params +
= array("contact_id.$i" => $contactID);
1655 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1665 public function groupDelete($gid) {
1671 $this->callAPISuccess('Group', 'delete', $params);
1676 * @param array $params
1678 public function uFFieldCreate($params = array()) {
1679 $params = array_merge(array(
1681 'field_name' => 'first_name',
1684 'visibility' => 'Public Pages and Listings',
1685 'is_searchable' => '1',
1686 'label' => 'first_name',
1687 'field_type' => 'Individual',
1690 $this->callAPISuccess('uf_field', 'create', $params);
1694 * Add a UF Join Entry.
1696 * @param array $params
1698 * $id of created UF Join
1700 public function ufjoinCreate($params = NULL) {
1701 if ($params === NULL) {
1704 'module' => 'CiviEvent',
1705 'entity_table' => 'civicrm_event',
1711 $result = $this->callAPISuccess('uf_join', 'create', $params);
1716 * Delete a UF Join Entry.
1718 * @param array $params
1719 * with missing uf_group_id
1721 public function ufjoinDelete($params = NULL) {
1722 if ($params === NULL) {
1725 'module' => 'CiviEvent',
1726 'entity_table' => 'civicrm_event',
1729 'uf_group_id' => '',
1733 crm_add_uf_join($params);
1737 * @param array $params
1738 * Optional parameters.
1739 * @param bool $reloadConfig
1740 * While enabling CiviCampaign component, we shouldn't always forcibly
1741 * reload config as this hinder hook call in test environment
1746 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1747 $this->enableCiviCampaign($reloadConfig);
1748 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1749 'name' => 'big_campaign',
1750 'title' => 'Campaign',
1752 return $campaign['id'];
1756 * Create Group for a contact.
1758 * @param int $contactId
1760 public function contactGroupCreate($contactId) {
1762 'contact_id.1' => $contactId,
1766 $this->callAPISuccess('GroupContact', 'Create', $params);
1770 * Delete Group for a contact.
1772 * @param int $contactId
1774 public function contactGroupDelete($contactId) {
1776 'contact_id.1' => $contactId,
1779 $this->civicrm_api('GroupContact', 'Delete', $params);
1785 * @param array $params
1788 public function activityCreate($params = array()) {
1789 $params = array_merge(array(
1790 'subject' => 'Discussion on warm beer',
1791 'activity_date_time' => date('Ymd'),
1792 'duration_hours' => 30,
1793 'duration_minutes' => 20,
1794 'location' => 'Baker Street',
1795 'details' => 'Lets schedule a meeting',
1797 'activity_name' => 'Meeting',
1799 if (!isset($params['source_contact_id'])) {
1800 $params['source_contact_id'] = $this->individualCreate();
1802 if (!isset($params['target_contact_id'])) {
1803 $params['target_contact_id'] = $this->individualCreate(array(
1804 'first_name' => 'Julia',
1805 'Last_name' => 'Anderson',
1807 'email' => 'julia_anderson@civicrm.org',
1808 'contact_type' => 'Individual',
1811 if (!isset($params['assignee_contact_id'])) {
1812 $params['assignee_contact_id'] = $params['target_contact_id'];
1815 $result = $this->callAPISuccess('Activity', 'create', $params);
1817 $result['target_contact_id'] = $params['target_contact_id'];
1818 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1823 * Create an activity type.
1825 * @param array $params
1829 public function activityTypeCreate($params) {
1830 return $this->callAPISuccess('ActivityType', 'create', $params);
1834 * Delete activity type.
1836 * @param int $activityTypeId
1837 * Id of the activity type.
1840 public function activityTypeDelete($activityTypeId) {
1841 $params['activity_type_id'] = $activityTypeId;
1842 return $this->callAPISuccess('ActivityType', 'delete', $params);
1846 * Create custom group.
1848 * @param array $params
1851 public function customGroupCreate($params = array()) {
1853 'title' => 'new custom group',
1854 'extends' => 'Contact',
1856 'style' => 'Inline',
1860 $params = array_merge($defaults, $params);
1862 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1863 $this->callAPISuccess('custom_group', 'get', array(
1864 'title' => $params['title'],
1865 array('api.custom_group.delete' => 1),
1868 return $this->callAPISuccess('custom_group', 'create', $params);
1872 * Existing function doesn't allow params to be over-ridden so need a new one
1873 * this one allows you to only pass in the params you want to change
1874 * @param array $params
1877 public function CustomGroupCreateByParams($params = array()) {
1879 'title' => "API Custom Group",
1880 'extends' => 'Contact',
1882 'style' => 'Inline',
1885 $params = array_merge($defaults, $params);
1886 return $this->callAPISuccess('custom_group', 'create', $params);
1890 * Create custom group with multi fields.
1891 * @param array $params
1894 public function CustomGroupMultipleCreateByParams($params = array()) {
1899 $params = array_merge($defaults, $params);
1900 return $this->CustomGroupCreateByParams($params);
1904 * Create custom group with multi fields.
1905 * @param array $params
1908 public function CustomGroupMultipleCreateWithFields($params = array()) {
1909 // also need to pass on $params['custom_field'] if not set but not in place yet
1911 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1912 $ids['custom_group_id'] = $customGroup['id'];
1914 $customField = $this->customFieldCreate(array(
1915 'custom_group_id' => $ids['custom_group_id'],
1916 'label' => 'field_1' . $ids['custom_group_id'],
1920 $ids['custom_field_id'][] = $customField['id'];
1922 $customField = $this->customFieldCreate(array(
1923 'custom_group_id' => $ids['custom_group_id'],
1924 'default_value' => '',
1925 'label' => 'field_2' . $ids['custom_group_id'],
1928 $ids['custom_field_id'][] = $customField['id'];
1930 $customField = $this->customFieldCreate(array(
1931 'custom_group_id' => $ids['custom_group_id'],
1932 'default_value' => '',
1933 'label' => 'field_3' . $ids['custom_group_id'],
1936 $ids['custom_field_id'][] = $customField['id'];
1942 * Create a custom group with a single text custom field. See
1943 * participant:testCreateWithCustom for how to use this
1945 * @param string $function
1947 * @param string $filename
1951 * ids of created objects
1953 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1954 $params = array('title' => $function);
1955 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1956 $params['extends'] = $entity ?
$entity : 'Contact';
1957 $customGroup = $this->CustomGroupCreate($params);
1958 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1959 CRM_Core_PseudoConstant
::flush();
1961 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1965 * Delete custom group.
1967 * @param int $customGroupID
1971 public function customGroupDelete($customGroupID) {
1972 $params['id'] = $customGroupID;
1973 return $this->callAPISuccess('custom_group', 'delete', $params);
1977 * Create custom field.
1979 * @param array $params
1980 * (custom_group_id) is required.
1983 public function customFieldCreate($params) {
1984 $params = array_merge(array(
1985 'label' => 'Custom Field',
1986 'data_type' => 'String',
1987 'html_type' => 'Text',
1988 'is_searchable' => 1,
1990 'default_value' => 'defaultValue',
1993 $result = $this->callAPISuccess('custom_field', 'create', $params);
1994 // these 2 functions are called with force to flush static caches
1995 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1996 CRM_Core_Component
::getEnabledComponents(1);
2001 * Delete custom field.
2003 * @param int $customFieldID
2007 public function customFieldDelete($customFieldID) {
2009 $params['id'] = $customFieldID;
2010 return $this->callAPISuccess('custom_field', 'delete', $params);
2019 public function noteCreate($cId) {
2021 'entity_table' => 'civicrm_contact',
2022 'entity_id' => $cId,
2023 'note' => 'hello I am testing Note',
2024 'contact_id' => $cId,
2025 'modified_date' => date('Ymd'),
2026 'subject' => 'Test Note',
2029 return $this->callAPISuccess('Note', 'create', $params);
2033 * Enable CiviCampaign Component.
2035 * @param bool $reloadConfig
2036 * Force relaod config or not
2038 public function enableCiviCampaign($reloadConfig = TRUE) {
2039 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2040 if ($reloadConfig) {
2041 // force reload of config object
2042 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2044 //flush cache by calling with reset
2045 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2049 * Create custom field with Option Values.
2051 * @param array $customGroup
2052 * @param string $name
2053 * Name of custom field.
2054 * @param array $extraParams
2055 * Additional parameters to pass through.
2059 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2060 $fieldParams = array(
2061 'custom_group_id' => $customGroup['id'],
2062 'name' => 'test_custom_group',
2063 'label' => 'Country',
2064 'html_type' => 'Select',
2065 'data_type' => 'String',
2068 'is_searchable' => 0,
2072 $optionGroup = array(
2074 'name' => 'option_group1',
2075 'label' => 'option_group_label1',
2078 $optionValue = array(
2079 'option_label' => array('Label1', 'Label2'),
2080 'option_value' => array('value1', 'value2'),
2081 'option_name' => array($name . '_1', $name . '_2'),
2082 'option_weight' => array(1, 2),
2083 'option_status' => 1,
2086 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2088 return $this->callAPISuccess('custom_field', 'create', $params);
2096 public function confirmEntitiesDeleted($entities) {
2097 foreach ($entities as $entity) {
2099 $result = $this->callAPISuccess($entity, 'Get', array());
2100 if ($result['error'] == 1 ||
$result['count'] > 0) {
2101 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2109 * Quick clean by emptying tables created for the test.
2111 * @param array $tablesToTruncate
2112 * @param bool $dropCustomValueTables
2113 * @throws \Exception
2115 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2117 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2119 if ($dropCustomValueTables) {
2120 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2121 while ($optionGroupResult->fetch()) {
2122 if (!empty($optionGroupResult->option_group_id
)) {
2123 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2126 $tablesToTruncate[] = 'civicrm_custom_group';
2127 $tablesToTruncate[] = 'civicrm_custom_field';
2130 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2132 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2133 foreach ($tablesToTruncate as $table) {
2134 $sql = "TRUNCATE TABLE $table";
2135 CRM_Core_DAO
::executeQuery($sql);
2137 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2139 if ($dropCustomValueTables) {
2140 $dbName = self
::getDBName();
2142 SELECT TABLE_NAME as tableName
2143 FROM INFORMATION_SCHEMA.TABLES
2144 WHERE TABLE_SCHEMA = '{$dbName}'
2145 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2148 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2149 while ($tableDAO->fetch()) {
2150 $sql = "DROP TABLE {$tableDAO->tableName}";
2151 CRM_Core_DAO
::executeQuery($sql);
2157 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2159 public function quickCleanUpFinancialEntities() {
2160 $tablesToTruncate = array(
2162 'civicrm_activity_contact',
2163 'civicrm_contribution',
2164 'civicrm_contribution_soft',
2165 'civicrm_contribution_product',
2166 'civicrm_financial_trxn',
2167 'civicrm_financial_item',
2168 'civicrm_contribution_recur',
2169 'civicrm_line_item',
2170 'civicrm_contribution_page',
2171 'civicrm_payment_processor',
2172 'civicrm_entity_financial_trxn',
2173 'civicrm_membership',
2174 'civicrm_membership_type',
2175 'civicrm_membership_payment',
2176 'civicrm_membership_log',
2177 'civicrm_membership_block',
2179 'civicrm_participant',
2180 'civicrm_participant_payment',
2182 'civicrm_pledge_payment',
2183 'civicrm_price_set_entity',
2184 'civicrm_price_field_value',
2185 'civicrm_price_field',
2187 $this->quickCleanup($tablesToTruncate);
2188 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2189 $this->restoreDefaultPriceSetConfig();
2191 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2192 $this->disableTaxAndInvoicing();
2193 $this->setCurrencySeparators(',');
2194 CRM_Core_PseudoConstant
::flush('taxRates');
2195 System
::singleton()->flushProcessors();
2198 public function restoreDefaultPriceSetConfig() {
2199 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2200 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2201 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)");
2202 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`, `non_deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2205 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2206 * Default behaviour is to also delete the entity
2207 * @param array $params
2208 * Params array to check against.
2210 * Id of the entity concerned.
2211 * @param string $entity
2212 * Name of entity concerned (e.g. membership).
2213 * @param bool $delete
2214 * Should the entity be deleted as part of this check.
2215 * @param string $errorText
2216 * Text to print on error.
2219 * @param array $params
2222 * @param int $delete
2223 * @param string $errorText
2227 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2229 $result = $this->callAPISuccessGetSingle($entity, array(
2234 $this->callAPISuccess($entity, 'Delete', array(
2238 $dateFields = $keys = $dateTimeFields = array();
2239 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2240 foreach ($fields['values'] as $field => $settings) {
2241 if (array_key_exists($field, $result)) {
2242 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2245 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2247 $type = CRM_Utils_Array
::value('type', $settings);
2248 if ($type == CRM_Utils_Type
::T_DATE
) {
2249 $dateFields[] = $settings['name'];
2250 // we should identify both real names & unique names as dates
2251 if ($field != $settings['name']) {
2252 $dateFields[] = $field;
2255 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2256 $dateTimeFields[] = $settings['name'];
2257 // we should identify both real names & unique names as dates
2258 if ($field != $settings['name']) {
2259 $dateTimeFields[] = $field;
2264 if (strtolower($entity) == 'contribution') {
2265 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2266 // this is not returned in id format
2267 unset($params['payment_instrument_id']);
2268 $params['contribution_source'] = $params['source'];
2269 unset($params['source']);
2272 foreach ($params as $key => $value) {
2273 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2276 if (in_array($key, $dateFields)) {
2277 $value = date('Y-m-d', strtotime($value));
2278 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2280 if (in_array($key, $dateTimeFields)) {
2281 $value = date('Y-m-d H:i:s', strtotime($value));
2282 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2284 $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);
2289 * Get formatted values in the actual and expected result.
2290 * @param array $actual
2291 * Actual calculated values.
2292 * @param array $expected
2295 public function checkArrayEquals(&$actual, &$expected) {
2296 self
::unsetId($actual);
2297 self
::unsetId($expected);
2298 $this->assertEquals($actual, $expected);
2302 * Unset the key 'id' from the array
2303 * @param array $unformattedArray
2304 * The array from which the 'id' has to be unset.
2306 public static function unsetId(&$unformattedArray) {
2307 $formattedArray = array();
2308 if (array_key_exists('id', $unformattedArray)) {
2309 unset($unformattedArray['id']);
2311 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2312 foreach ($unformattedArray['values'] as $key => $value) {
2313 if (is_array($value)) {
2314 foreach ($value as $k => $v) {
2320 elseif ($key == 'id') {
2321 $unformattedArray[$key];
2323 $formattedArray = array($value);
2325 $unformattedArray['values'] = $formattedArray;
2330 * Helper to enable/disable custom directory support
2332 * @param array $customDirs
2334 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2335 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2337 public function customDirectories($customDirs) {
2338 $config = CRM_Core_Config
::singleton();
2340 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2341 unset($config->customPHPPathDir
);
2343 elseif ($customDirs['php_path'] === TRUE) {
2344 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2347 $config->customPHPPathDir
= $php_path;
2350 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2351 unset($config->customTemplateDir
);
2353 elseif ($customDirs['template_path'] === TRUE) {
2354 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2357 $config->customTemplateDir
= $template_path;
2362 * Generate a temporary folder.
2364 * @param string $prefix
2367 public function createTempDir($prefix = 'test-') {
2368 $tempDir = CRM_Utils_File
::tempdir($prefix);
2369 $this->tempDirs
[] = $tempDir;
2373 public function cleanTempDirs() {
2374 if (!is_array($this->tempDirs
)) {
2375 // fix test errors where this is not set
2378 foreach ($this->tempDirs
as $tempDir) {
2379 if (is_dir($tempDir)) {
2380 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2386 * Temporarily replace the singleton extension with a different one.
2387 * @param \CRM_Extension_System $system
2389 public function setExtensionSystem(CRM_Extension_System
$system) {
2390 if ($this->origExtensionSystem
== NULL) {
2391 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2393 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2396 public function unsetExtensionSystem() {
2397 if ($this->origExtensionSystem
!== NULL) {
2398 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2399 $this->origExtensionSystem
= NULL;
2404 * Temporarily alter the settings-metadata to add a mock setting.
2406 * WARNING: The setting metadata will disappear on the next cache-clear.
2411 public function setMockSettingsMetaData($extras) {
2412 Civi
::service('settings_manager')->flush();
2414 CRM_Utils_Hook
::singleton()
2415 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2416 $metadata = array_merge($metadata, $extras);
2419 $fields = $this->callAPISuccess('setting', 'getfields', array());
2420 foreach ($extras as $key => $spec) {
2421 $this->assertNotEmpty($spec['title']);
2422 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2427 * @param string $name
2429 public function financialAccountDelete($name) {
2430 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2431 $financialAccount->name
= $name;
2432 if ($financialAccount->find(TRUE)) {
2433 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2434 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2435 $entityFinancialType->delete();
2436 $financialAccount->delete();
2441 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2442 * (NB unclear if this is still required)
2444 public function _sethtmlGlobals() {
2445 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2446 'required' => array(
2447 'html_quickform_rule_required',
2448 'HTML/QuickForm/Rule/Required.php',
2450 'maxlength' => array(
2451 'html_quickform_rule_range',
2452 'HTML/QuickForm/Rule/Range.php',
2454 'minlength' => array(
2455 'html_quickform_rule_range',
2456 'HTML/QuickForm/Rule/Range.php',
2458 'rangelength' => array(
2459 'html_quickform_rule_range',
2460 'HTML/QuickForm/Rule/Range.php',
2463 'html_quickform_rule_email',
2464 'HTML/QuickForm/Rule/Email.php',
2467 'html_quickform_rule_regex',
2468 'HTML/QuickForm/Rule/Regex.php',
2470 'lettersonly' => array(
2471 'html_quickform_rule_regex',
2472 'HTML/QuickForm/Rule/Regex.php',
2474 'alphanumeric' => array(
2475 'html_quickform_rule_regex',
2476 'HTML/QuickForm/Rule/Regex.php',
2479 'html_quickform_rule_regex',
2480 'HTML/QuickForm/Rule/Regex.php',
2482 'nopunctuation' => array(
2483 'html_quickform_rule_regex',
2484 'HTML/QuickForm/Rule/Regex.php',
2487 'html_quickform_rule_regex',
2488 'HTML/QuickForm/Rule/Regex.php',
2490 'callback' => array(
2491 'html_quickform_rule_callback',
2492 'HTML/QuickForm/Rule/Callback.php',
2495 'html_quickform_rule_compare',
2496 'HTML/QuickForm/Rule/Compare.php',
2499 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2500 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2502 'HTML/QuickForm/group.php',
2503 'HTML_QuickForm_group',
2506 'HTML/QuickForm/hidden.php',
2507 'HTML_QuickForm_hidden',
2510 'HTML/QuickForm/reset.php',
2511 'HTML_QuickForm_reset',
2513 'checkbox' => array(
2514 'HTML/QuickForm/checkbox.php',
2515 'HTML_QuickForm_checkbox',
2518 'HTML/QuickForm/file.php',
2519 'HTML_QuickForm_file',
2522 'HTML/QuickForm/image.php',
2523 'HTML_QuickForm_image',
2525 'password' => array(
2526 'HTML/QuickForm/password.php',
2527 'HTML_QuickForm_password',
2530 'HTML/QuickForm/radio.php',
2531 'HTML_QuickForm_radio',
2534 'HTML/QuickForm/button.php',
2535 'HTML_QuickForm_button',
2538 'HTML/QuickForm/submit.php',
2539 'HTML_QuickForm_submit',
2542 'HTML/QuickForm/select.php',
2543 'HTML_QuickForm_select',
2545 'hiddenselect' => array(
2546 'HTML/QuickForm/hiddenselect.php',
2547 'HTML_QuickForm_hiddenselect',
2550 'HTML/QuickForm/text.php',
2551 'HTML_QuickForm_text',
2553 'textarea' => array(
2554 'HTML/QuickForm/textarea.php',
2555 'HTML_QuickForm_textarea',
2557 'fckeditor' => array(
2558 'HTML/QuickForm/fckeditor.php',
2559 'HTML_QuickForm_FCKEditor',
2562 'HTML/QuickForm/tinymce.php',
2563 'HTML_QuickForm_TinyMCE',
2565 'dojoeditor' => array(
2566 'HTML/QuickForm/dojoeditor.php',
2567 'HTML_QuickForm_dojoeditor',
2570 'HTML/QuickForm/link.php',
2571 'HTML_QuickForm_link',
2573 'advcheckbox' => array(
2574 'HTML/QuickForm/advcheckbox.php',
2575 'HTML_QuickForm_advcheckbox',
2578 'HTML/QuickForm/date.php',
2579 'HTML_QuickForm_date',
2582 'HTML/QuickForm/static.php',
2583 'HTML_QuickForm_static',
2586 'HTML/QuickForm/header.php',
2587 'HTML_QuickForm_header',
2590 'HTML/QuickForm/html.php',
2591 'HTML_QuickForm_html',
2593 'hierselect' => array(
2594 'HTML/QuickForm/hierselect.php',
2595 'HTML_QuickForm_hierselect',
2597 'autocomplete' => array(
2598 'HTML/QuickForm/autocomplete.php',
2599 'HTML_QuickForm_autocomplete',
2602 'HTML/QuickForm/xbutton.php',
2603 'HTML_QuickForm_xbutton',
2605 'advmultiselect' => array(
2606 'HTML/QuickForm/advmultiselect.php',
2607 'HTML_QuickForm_advmultiselect',
2613 * Set up an acl allowing contact to see 2 specified groups
2614 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2616 * You need to have pre-created these groups & created the user e.g
2617 * $this->createLoggedInUser();
2618 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2619 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2621 * @param bool $isProfile
2623 public function setupACL($isProfile = FALSE) {
2625 $_REQUEST = $this->_params
;
2627 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2628 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2629 $ov = new CRM_Core_DAO_OptionValue();
2630 $ov->option_group_id
= $optionGroupID;
2632 if ($ov->find(TRUE)) {
2633 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2635 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2636 'option_group_id' => $optionGroupID,
2637 'label' => 'pick me',
2641 CRM_Core_DAO
::executeQuery("
2642 TRUNCATE civicrm_acl_cache
2645 CRM_Core_DAO
::executeQuery("
2646 TRUNCATE civicrm_acl_contact_cache
2649 CRM_Core_DAO
::executeQuery("
2650 INSERT INTO civicrm_acl_entity_role (
2651 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2652 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2656 CRM_Core_DAO
::executeQuery("
2657 INSERT INTO civicrm_acl (
2658 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2661 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2666 CRM_Core_DAO
::executeQuery("
2667 INSERT INTO civicrm_acl (
2668 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2671 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2675 CRM_Core_DAO
::executeQuery("
2676 INSERT INTO civicrm_acl (
2677 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2680 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2685 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2686 $this->callAPISuccess('group_contact', 'create', array(
2687 'group_id' => $this->_permissionedGroup
,
2688 'contact_id' => $this->_loggedInUser
,
2693 CRM_ACL_BAO_Cache
::resetCache();
2694 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2699 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2701 public function offsetDefaultPriceSet() {
2702 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2703 $firstID = $contributionPriceSet['id'];
2704 $this->callAPISuccess('price_set', 'create', array(
2705 'id' => $contributionPriceSet['id'],
2709 unset($contributionPriceSet['id']);
2710 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2711 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2712 'price_set_id' => $firstID,
2713 'options' => array('limit' => 1),
2715 unset($priceField['id']);
2716 $priceField['price_set_id'] = $newPriceSet['id'];
2717 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2718 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2719 'price_set_id' => $firstID,
2721 'options' => array('limit' => 1),
2724 unset($priceFieldValue['id']);
2725 //create some padding to use up ids
2726 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2727 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2728 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2732 * Create an instance of the paypal processor.
2733 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2734 * this parent class & we don't have a structure for that yet
2735 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2736 * & the best protection against that is the functions this class affords
2737 * @param array $params
2738 * @return int $result['id'] payment processor id
2740 public function paymentProcessorCreate($params = array()) {
2741 $params = array_merge(array(
2743 'domain_id' => CRM_Core_Config
::domainID(),
2744 'payment_processor_type_id' => 'PayPal',
2748 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2749 'password' => '1183377788',
2750 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2751 'url_site' => 'https://www.sandbox.paypal.com/',
2752 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2753 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2754 'class_name' => 'Payment_PayPalImpl',
2755 'billing_mode' => 3,
2756 'financial_type_id' => 1,
2757 'financial_account_id' => 12,
2758 // Credit card = 1 so can pass 'by accident'.
2759 'payment_instrument_id' => 'Debit Card',
2762 if (!is_numeric($params['payment_processor_type_id'])) {
2763 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2765 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2766 'name' => $params['payment_processor_type_id'],
2770 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2771 return $result['id'];
2775 * Set up initial recurring payment allowing subsequent IPN payments.
2777 public function setupRecurringPaymentProcessorTransaction($params = array()) {
2778 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2779 'contact_id' => $this->_contactID
,
2782 'installments' => 5,
2783 'frequency_unit' => 'Month',
2784 'frequency_interval' => 1,
2785 'invoice_id' => $this->_invoiceID
,
2786 'contribution_status_id' => 2,
2787 'payment_processor_id' => $this->_paymentProcessorID
,
2788 // processor provided ID - use contact ID as proxy.
2789 'processor_id' => $this->_contactID
,
2790 'api.contribution.create' => array(
2791 'total_amount' => '200',
2792 'invoice_id' => $this->_invoiceID
,
2793 'financial_type_id' => 1,
2794 'contribution_status_id' => 'Pending',
2795 'contact_id' => $this->_contactID
,
2796 'contribution_page_id' => $this->_contributionPageID
,
2797 'payment_processor_id' => $this->_paymentProcessorID
,
2799 'skipCleanMoney' => TRUE,
2802 $this->_contributionRecurID
= $contributionRecur['id'];
2803 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2807 * 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
2809 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2811 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2812 $membershipParams = $recurParams = array();
2813 if (!empty($params['duration_unit'])) {
2814 $membershipParams['duration_unit'] = $params['duration_unit'];
2816 if (!empty($params['frequency_unit'])) {
2817 $recurParams['frequency_unit'] = $params['frequency_unit'];
2820 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2821 //create a contribution so our membership & contribution don't both have id = 1
2822 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2823 $this->contributionCreate(array(
2824 'contact_id' => $this->_contactID
,
2826 'financial_type_id' => 1,
2827 'invoice_id' => 'abcd',
2831 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2833 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2834 'contact_id' => $this->_contactID
,
2835 'membership_type_id' => $this->ids
['membership_type'],
2836 'contribution_recur_id' => $this->_contributionRecurID
,
2837 'format.only_id' => TRUE,
2839 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2840 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2842 $this->callAPISuccess('line_item', 'create', array(
2843 'entity_table' => 'civicrm_membership',
2844 'entity_id' => $this->ids
['membership'],
2845 'contribution_id' => $this->_contributionID
,
2846 'label' => 'General',
2848 'unit_price' => 200,
2849 'line_total' => 200,
2850 'financial_type_id' => 1,
2851 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2853 'label' => 'Membership Amount',
2854 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2856 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2858 'label' => 'General',
2859 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2862 $this->callAPISuccess('membership_payment', 'create', array(
2863 'contribution_id' => $this->_contributionID
,
2864 'membership_id' => $this->ids
['membership'],
2873 public function CiviUnitTestCase_fatalErrorHandler($message) {
2874 throw new Exception("{$message['message']}: {$message['code']}");
2878 * Helper function to create new mailing.
2880 * @param array $params
2884 public function createMailing($params = array()) {
2885 $params = array_merge(array(
2886 'subject' => 'maild' . rand(),
2887 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2888 'name' => 'mailing name' . rand(),
2892 $result = $this->callAPISuccess('Mailing', 'create', $params);
2893 return $result['id'];
2897 * Helper function to delete mailing.
2900 public function deleteMailing($id) {
2905 $this->callAPISuccess('Mailing', 'delete', $params);
2909 * Wrap the entire test case in a transaction.
2911 * Only subsequent DB statements will be wrapped in TX -- this cannot
2912 * retroactively wrap old DB statements. Therefore, it makes sense to
2913 * call this at the beginning of setUp().
2915 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2916 * this option does not work with, e.g., custom-data.
2918 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2919 * if TRUNCATE or ALTER is called while using a transaction.
2922 * Whether to use nesting or reference-counting.
2924 public function useTransaction($nest = TRUE) {
2926 $this->tx
= new CRM_Core_Transaction($nest);
2927 $this->tx
->rollback();
2932 * Assert the attachment exists.
2934 * @param bool $exists
2935 * @param array $apiResult
2937 protected function assertAttachmentExistence($exists, $apiResult) {
2938 $fileId = $apiResult['id'];
2939 $this->assertTrue(is_numeric($fileId));
2940 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2941 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2942 1 => array($fileId, 'Int'),
2944 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2945 1 => array($fileId, 'Int'),
2950 * Create a price set for an event.
2952 * @param int $feeTotal
2953 * @param int $minAmt
2954 * @param string $type
2959 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2960 // creating price set, price field
2961 $paramsSet['title'] = 'Price Set';
2962 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2963 $paramsSet['is_active'] = FALSE;
2964 $paramsSet['extends'] = 1;
2965 $paramsSet['min_amount'] = $minAmt;
2967 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2968 $this->_ids
['price_set'] = $priceSet->id
;
2970 $paramsField = array(
2971 'label' => 'Price Field',
2972 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2973 'html_type' => $type,
2974 'price' => $feeTotal,
2975 'option_label' => array('1' => 'Price Field'),
2976 'option_value' => array('1' => $feeTotal),
2977 'option_name' => array('1' => $feeTotal),
2978 'option_weight' => array('1' => 1),
2979 'option_amount' => array('1' => 1),
2980 'is_display_amounts' => 1,
2982 'options_per_line' => 1,
2983 'is_active' => array('1' => 1),
2984 'price_set_id' => $this->_ids
['price_set'],
2985 'is_enter_qty' => 1,
2986 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2988 if ($type === 'Radio') {
2989 $paramsField['is_enter_qty'] = 0;
2990 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2991 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2993 CRM_Price_BAO_PriceField
::create($paramsField);
2994 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2995 $this->_ids
['price_field'] = array_keys($fields['values']);
2996 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2997 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2999 return $this->_ids
['price_set'];
3003 * Add a profile to a contribution page.
3005 * @param string $name
3006 * @param int $contributionPageID
3007 * @param string $module
3009 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
3011 'uf_group_id' => $name,
3012 'module' => $module,
3013 'entity_table' => 'civicrm_contribution_page',
3014 'entity_id' => $contributionPageID,
3017 if ($module !== 'CiviContribute') {
3018 $params['module_data'] = [$module => []];
3020 $this->callAPISuccess('UFJoin', 'create', $params);
3024 * Add participant with contribution
3028 protected function createParticipantWithContribution() {
3029 // creating price set, price field
3030 $this->_contactId
= $this->individualCreate();
3031 $event = $this->eventCreate();
3032 $this->_eventId
= $event['id'];
3033 $eventParams = array(
3034 'id' => $this->_eventId
,
3035 'financial_type_id' => 4,
3038 $this->callAPISuccess('event', 'create', $eventParams);
3039 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3040 $participantParams = array(
3041 'financial_type_id' => 4,
3042 'event_id' => $this->_eventId
,
3045 'fee_currency' => 'USD',
3046 'contact_id' => $this->_contactId
,
3048 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3049 $contributionParams = array(
3050 'total_amount' => 150,
3051 'currency' => 'USD',
3052 'contact_id' => $this->_contactId
,
3053 'financial_type_id' => 4,
3054 'contribution_status_id' => 1,
3055 'partial_payment_total' => 300.00,
3056 'partial_amount_to_pay' => 150,
3057 'contribution_mode' => 'participant',
3058 'participant_id' => $participant['id'],
3060 foreach ($priceFields['values'] as $key => $priceField) {
3061 $lineItems[1][$key] = array(
3062 'price_field_id' => $priceField['price_field_id'],
3063 'price_field_value_id' => $priceField['id'],
3064 'label' => $priceField['label'],
3065 'field_title' => $priceField['label'],
3067 'unit_price' => $priceField['amount'],
3068 'line_total' => $priceField['amount'],
3069 'financial_type_id' => $priceField['financial_type_id'],
3072 $contributionParams['line_item'] = $lineItems;
3073 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3074 $paymentParticipant = array(
3075 'participant_id' => $participant['id'],
3076 'contribution_id' => $contribution['id'],
3078 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3079 return array($lineItems, $contribution);
3085 * @param string $component
3086 * @param int $componentId
3090 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3091 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3092 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3093 $paramsSet['is_active'] = TRUE;
3094 $paramsSet['financial_type_id'] = 4;
3095 $paramsSet['extends'] = 1;
3096 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3097 $priceSetId = $priceSet['id'];
3098 //Checking for priceset added in the table.
3099 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3100 'id', $paramsSet['title'], 'Check DB for created priceset'
3102 $paramsField = array_merge(array(
3103 'label' => 'Price Field',
3104 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3105 'html_type' => 'CheckBox',
3106 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3107 'option_value' => array('1' => 100, '2' => 200),
3108 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3109 'option_weight' => array('1' => 1, '2' => 2),
3110 'option_amount' => array('1' => 100, '2' => 200),
3111 'is_display_amounts' => 1,
3113 'options_per_line' => 1,
3114 'is_active' => array('1' => 1, '2' => 1),
3115 'price_set_id' => $priceSet['id'],
3116 'is_enter_qty' => 1,
3117 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3118 ), $priceFieldOptions);
3120 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3122 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3124 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3128 * Replace the template with a test-oriented template designed to show all the variables.
3130 * @param string $templateName
3132 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3133 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3134 CRM_Core_DAO
::executeQuery(
3135 "UPDATE civicrm_option_group og
3136 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3137 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3138 SET m.msg_html = '{$testTemplate}'
3139 WHERE og.name = 'msg_tpl_workflow_contribution'
3140 AND ov.name = '{$templateName}'
3141 AND m.is_default = 1"
3146 * Reinstate the default template.
3148 * @param string $templateName
3150 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3151 CRM_Core_DAO
::executeQuery(
3152 "UPDATE civicrm_option_group og
3153 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3154 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3155 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3156 SET m.msg_html = m2.msg_html
3157 WHERE og.name = 'msg_tpl_workflow_contribution'
3158 AND ov.name = '{$templateName}'
3159 AND m.is_default = 1"
3164 * Flush statics relating to financial type.
3166 protected function flushFinancialTypeStatics() {
3167 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3168 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3170 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3171 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3173 CRM_Contribute_PseudoConstant
::flush('financialType');
3174 CRM_Contribute_PseudoConstant
::flush('membershipType');
3175 // Pseudoconstants may be saved to the cache table.
3176 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3177 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3178 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3182 * Set the permissions to the supplied array.
3184 * @param array $permissions
3186 protected function setPermissions($permissions) {
3187 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3188 $this->flushFinancialTypeStatics();
3192 * @param array $params
3195 public function _checkFinancialRecords($params, $context) {
3196 $entityParams = array(
3197 'entity_id' => $params['id'],
3198 'entity_table' => 'civicrm_contribution',
3200 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3201 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3202 if ($context == 'pending') {
3203 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3204 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3207 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3208 $trxnParams = array(
3209 'id' => $trxn['financial_trxn_id'],
3211 if ($context != 'online' && $context != 'payLater') {
3212 $compareParams = array(
3213 'to_financial_account_id' => 6,
3214 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3218 if ($context == 'feeAmount') {
3219 $compareParams['fee_amount'] = 50;
3221 elseif ($context == 'online') {
3222 $compareParams = array(
3223 'to_financial_account_id' => 12,
3224 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3226 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3229 elseif ($context == 'payLater') {
3230 $compareParams = array(
3231 'to_financial_account_id' => 7,
3232 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3236 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3237 $entityParams = array(
3238 'financial_trxn_id' => $trxn['financial_trxn_id'],
3239 'entity_table' => 'civicrm_financial_item',
3241 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3242 $fitemParams = array(
3243 'id' => $entityTrxn['entity_id'],
3245 $compareParams = array(
3246 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3248 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3250 if ($context == 'payLater') {
3251 $compareParams = array(
3252 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3254 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3257 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3258 if ($context == 'feeAmount') {
3260 'entity_id' => $params['id'],
3261 'entity_table' => 'civicrm_contribution',
3263 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3264 $trxnParams = array(
3265 'id' => $maxTrxn['financial_trxn_id'],
3267 $compareParams = array(
3268 'to_financial_account_id' => 5,
3269 'from_financial_account_id' => 6,
3270 'total_amount' => 50,
3273 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3274 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3275 $fitemParams = array(
3276 'entity_id' => $trxnId['financialTrxnId'],
3277 'entity_table' => 'civicrm_financial_trxn',
3279 $compareParams = array(
3282 'financial_account_id' => 5,
3284 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3286 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3287 // line should be copied into all the functions that call this function & evaluated there
3288 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3289 // when calling completeTransaction or repeatTransaction.
3290 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3294 * Return financial type id on basis of name
3296 * @param string $name Financial type m/c name
3300 public function getFinancialTypeId($name) {
3301 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3305 * Cleanup function for contents of $this->ids.
3307 * This is a best effort cleanup to use in tear downs etc.
3309 * It will not fail if the data has already been removed (some tests may do
3310 * their own cleanup).
3312 protected function cleanUpSetUpIDs() {
3313 foreach ($this->setupIDs
as $entity => $id) {
3315 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3317 catch (CiviCRM_API3_Exception
$e) {
3318 // This is a best-effort cleanup function, ignore.
3324 * Create Financial Type.
3326 * @param array $params
3330 protected function createFinancialType($params = array()) {
3331 $params = array_merge($params,
3333 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3337 return $this->callAPISuccess('FinancialType', 'create', $params);
3341 * Enable Tax and Invoicing
3343 protected function enableTaxAndInvoicing($params = array()) {
3344 // Enable component contribute setting
3345 $contributeSetting = array_merge($params,
3348 'invoice_prefix' => 'INV_',
3349 'credit_notes_prefix' => 'CN_',
3351 'due_date_period' => 'days',
3353 'is_email_pdf' => 1,
3354 'tax_term' => 'Sales Tax',
3355 'tax_display_settings' => 'Inclusive',
3358 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3362 * Enable Tax and Invoicing
3364 protected function disableTaxAndInvoicing($params = array()) {
3365 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3366 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3368 // Enable component contribute setting
3369 $contributeSetting = array_merge($params,
3374 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3378 * Add Sales Tax relation for financial type with financial account.
3380 * @param int $financialTypeId
3384 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3386 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3387 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3388 'is_deductible' => 1,
3393 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3394 $entityParams = array(
3395 'entity_table' => 'civicrm_financial_type',
3396 'entity_id' => $financialTypeId,
3397 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3400 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3401 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3403 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3404 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3405 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3406 $dao->copyValues($entityParams);
3408 if ($dao->fetch()) {
3409 $entityParams['id'] = $dao->id
;
3411 $entityParams['financial_account_id'] = $account->id
;
3413 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3417 * Create price set with contribution test for test setup.
3419 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3420 * on parent class at some point (fn is not in 4.4).
3423 * @param array $params
3425 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3426 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3427 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3428 'title' => "Test Contribution Page",
3429 'financial_type_id' => 1,
3430 'currency' => 'NZD',
3431 'goal_amount' => 50,
3432 'is_pay_later' => 1,
3433 'is_monetary' => TRUE,
3434 'is_email_receipt' => FALSE,
3436 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3437 'is_quick_config' => 0,
3438 'extends' => 'CiviMember',
3439 'financial_type_id' => 1,
3440 'title' => 'my Page',
3442 $priceSetID = $priceSet['id'];
3444 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3445 $priceField = $this->callAPISuccess('price_field', 'create', array(
3446 'price_set_id' => $priceSetID,
3447 'label' => 'Goat Breed',
3448 'html_type' => 'Radio',
3450 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3451 'price_set_id' => $priceSetID,
3452 'price_field_id' => $priceField['id'],
3453 'label' => 'Long Haired Goat',
3455 'financial_type_id' => 'Donation',
3456 'membership_type_id' => $membershipTypeID,
3457 'membership_num_terms' => 1,
3460 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3461 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3462 'price_set_id' => $priceSetID,
3463 'price_field_id' => $priceField['id'],
3464 'label' => 'Shoe-eating Goat',
3466 'financial_type_id' => 'Donation',
3467 'membership_type_id' => $membershipTypeID,
3468 'membership_num_terms' => 2,
3471 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3473 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3474 'price_set_id' => $priceSetID,
3475 'price_field_id' => $priceField['id'],
3476 'label' => 'Shoe-eating Goat',
3478 'financial_type_id' => 'Donation',
3481 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3483 $this->_ids
['price_set'] = $priceSetID;
3484 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3485 $this->_ids
['price_field'] = array($priceField['id']);
3487 $this->_ids
['membership_type'] = $membershipTypeID;
3491 * No results returned.
3493 * @implements CRM_Utils_Hook::aclWhereClause
3495 * @param string $type
3496 * @param array $tables
3497 * @param array $whereTables
3498 * @param int $contactID
3499 * @param string $where
3501 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3505 * Only specified contact returned.
3506 * @implements CRM_Utils_Hook::aclWhereClause
3509 * @param $whereTables
3513 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3514 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3518 * @implements CRM_Utils_Hook::selectWhereClause
3520 * @param string $entity
3521 * @param array $clauses
3523 public function selectWhereClauseHook($entity, &$clauses) {
3524 if ($entity == 'Event') {
3525 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3530 * An implementation of hook_civicrm_post used with all our test cases.
3533 * @param string $objectName
3534 * @param int $objectId
3537 public function onPost($op, $objectName, $objectId, &$objectRef) {
3538 if ($op == 'create' && $objectName == 'Individual') {
3539 CRM_Core_DAO
::executeQuery(
3540 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3542 1 => array($objectId, 'Integer'),
3547 if ($op == 'edit' && $objectName == 'Participant') {
3549 1 => array($objectId, 'Integer'),
3551 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3552 CRM_Core_DAO
::executeQuery($query, $params);
3558 * Instantiate form object.
3560 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3562 * @param string $class
3563 * Name of form class.
3565 * @return \CRM_Core_Form
3567 public function getFormObject($class) {
3568 $form = new $class();
3569 $_SERVER['REQUEST_METHOD'] = 'GET';
3570 $form->controller
= new CRM_Core_Controller();
3575 * Get possible thousand separators.
3579 public function getThousandSeparators() {
3580 return array(array('.'), array(','));
3584 * Set the separators for thousands and decimal points.
3586 * @param string $thousandSeparator
3588 protected function setCurrencySeparators($thousandSeparator) {
3589 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3591 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3595 * Format money as it would be input.
3597 * @param string $amount
3601 protected function formatMoneyInput($amount) {
3602 return CRM_Utils_Money
::format($amount, NULL, '%a');
3607 * Get the contribution object.
3609 * @param int $contributionID
3611 * @return \CRM_Contribute_BAO_Contribution
3613 protected function getContributionObject($contributionID) {
3614 $contributionObj = new CRM_Contribute_BAO_Contribution();
3615 $contributionObj->id
= $contributionID;
3616 $contributionObj->find(TRUE);
3617 return $contributionObj;
3621 * Enable multilingual.
3623 public function enableMultilingual() {
3624 $this->callAPISuccess('Setting', 'create', array(
3625 'lcMessages' => 'en_US',
3626 'languageLimit' => array(
3631 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3634 $dbLocale = '_en_US';