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
;
57 use \Civi\Test\GenericAssertionsTrait
;
58 use \Civi\Test\DbTestTrait
;
59 use \Civi\Test\ContactTestTrait
;
60 use \Civi\Test\MailingTestTrait
;
63 * Database has been initialized.
67 private static $dbInit = FALSE;
70 * Database connection.
72 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
81 static protected $_dbName;
84 * Track tables we have modified during a test.
87 protected $_tablesToTruncate = array();
90 * @var array of temporary directory names
95 * @var boolean populateOnce allows to skip db resets in setUp
97 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
98 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
101 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
103 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
105 public static $populateOnce = FALSE;
108 * @var boolean DBResetRequired allows skipping DB reset
109 * in specific test case. If you still need
110 * to reset single test (method) of such case, call
111 * $this->cleanDB() in the first line of this
114 public $DBResetRequired = TRUE;
117 * @var CRM_Core_Transaction|NULL
122 * Class used for hooks during tests.
124 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
126 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
128 * @var CRM_Utils_Hook_UnitTests hookClass
130 public $hookClass = NULL;
133 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
135 protected $_params = array();
138 * @var CRM_Extension_System
140 protected $origExtensionSystem;
143 * Array of IDs created during test setup routine.
145 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
149 public $setupIDs = array();
152 * PHPUnit Mock Method to use.
156 public $mockMethod = 'getMock';
161 * Because we are overriding the parent class constructor, we
162 * need to show the same arguments as exist in the constructor of
163 * PHPUnit_Framework_TestCase, since
164 * PHPUnit_Framework_TestSuite::createTest() creates a
165 * ReflectionClass of the Test class and checks the constructor
166 * of that class to decide how to set up the test.
168 * @param string $name
170 * @param string $dataName
172 public function __construct($name = NULL, array $data = array(), $dataName = '') {
173 parent
::__construct($name, $data, $dataName);
175 // we need full error reporting
176 error_reporting(E_ALL
& ~E_NOTICE
);
178 self
::$_dbName = self
::getDBName();
180 // also load the class loader
181 require_once 'CRM/Core/ClassLoader.php';
182 CRM_Core_ClassLoader
::singleton()->register();
183 if (function_exists('_civix_phpunit_setUp')) {
184 // FIXME: loosen coupling
185 _civix_phpunit_setUp();
187 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
188 $this->mockMethod
= 'createMock';
193 * Override to run the test and assert its state.
196 * @throws \PHPUnit_Framework_IncompleteTest
197 * @throws \PHPUnit_Framework_SkippedTest
199 protected function runTest() {
201 return parent
::runTest();
203 catch (PEAR_Exception
$e) {
204 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
205 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
212 public function requireDBReset() {
213 return $this->DBResetRequired
;
219 public static function getDBName() {
220 static $dbName = NULL;
221 if ($dbName === NULL) {
222 require_once "DB.php";
223 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
224 $dbName = $dsninfo['database'];
230 * Create database connection for this instance.
232 * Initialize the test database if it hasn't been initialized
234 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
236 protected function getConnection() {
237 $dbName = self
::$_dbName;
238 if (!self
::$dbInit) {
239 $dbName = self
::getDBName();
241 // install test database
242 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
244 static::_populateDB(FALSE, $this);
246 self
::$dbInit = TRUE;
249 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
253 * Required implementation of abstract method.
255 protected function getDataSet() {
259 * @param bool $perClass
260 * @param null $object
262 * TRUE if the populate logic runs; FALSE if it is skipped
264 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
265 if (CIVICRM_UF
!== 'UnitTests') {
266 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
269 if ($perClass ||
$object == NULL) {
273 $dbreset = $object->requireDBReset();
276 if (self
::$populateOnce ||
!$dbreset) {
279 self
::$populateOnce = NULL;
281 Civi\Test
::data()->populate();
286 public static function setUpBeforeClass() {
287 static::_populateDB(TRUE);
289 // also set this global hack
290 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
294 * Common setup functions for all unit tests.
296 protected function setUp() {
297 $session = CRM_Core_Session
::singleton();
298 $session->set('userID', NULL);
301 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
302 // Use a temporary file for STDIN
303 $GLOBALS['stdin'] = tmpfile();
304 if ($GLOBALS['stdin'] === FALSE) {
305 echo "Couldn't open temporary file\n";
309 // Get and save a connection to the database
310 $this->_dbconn
= $this->getConnection();
312 // reload database before each test
313 // $this->_populateDB();
315 // "initialize" CiviCRM to avoid problems when running single tests
316 // FIXME: look at it closer in second stage
318 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
319 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
321 // disable any left-over test extensions
322 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
324 // reset all the caches
325 CRM_Utils_System
::flushCache();
327 // initialize the object once db is loaded
330 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
332 // when running unit tests, use mockup user framework
333 $this->hookClass
= CRM_Utils_Hook
::singleton();
335 // Make sure the DB connection is setup properly
336 $config->userSystem
->setMySQLTimeZone();
337 $env = new CRM_Utils_Check_Component_Env();
338 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
340 // clear permissions stub to not check permissions
341 $config->userPermissionClass
->permissions
= NULL;
343 //flush component settings
344 CRM_Core_Component
::getEnabledComponents(TRUE);
346 $_REQUEST = $_GET = $_POST = [];
347 error_reporting(E_ALL
);
349 $this->_sethtmlGlobals();
353 * Read everything from the datasets directory and insert into the db.
355 public function loadAllFixtures() {
356 $fixturesDir = __DIR__
. '/../../fixtures';
358 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
360 $xmlFiles = glob($fixturesDir . '/*.xml');
361 foreach ($xmlFiles as $xmlFixture) {
362 $op = new PHPUnit_Extensions_Database_Operation_Insert();
363 $dataset = $this->createXMLDataSet($xmlFixture);
364 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
365 $op->execute($this->_dbconn
, $dataset);
368 $yamlFiles = glob($fixturesDir . '/*.yaml');
369 foreach ($yamlFiles as $yamlFixture) {
370 $op = new PHPUnit_Extensions_Database_Operation_Insert();
371 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
372 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
373 $op->execute($this->_dbconn
, $dataset);
376 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
380 * Create default domain contacts for the two domains added during test class.
381 * database population.
383 public function createDomainContacts() {
384 $this->organizationCreate();
385 $this->organizationCreate(array('organization_name' => 'Second Domain'));
389 * Common teardown functions for all unit tests.
391 protected function tearDown() {
392 error_reporting(E_ALL
& ~E_NOTICE
);
393 CRM_Utils_Hook
::singleton()->reset();
394 if ($this->hookClass
) {
395 $this->hookClass
->reset();
397 CRM_Core_Session
::singleton()->reset(1);
400 $this->tx
->rollback()->commit();
403 CRM_Core_Transaction
::forceRollbackIfEnabled();
404 \Civi\Core\Transaction\Manager
::singleton(TRUE);
407 CRM_Core_Transaction
::forceRollbackIfEnabled();
408 \Civi\Core\Transaction\Manager
::singleton(TRUE);
410 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
411 $this->quickCleanup($tablesToTruncate);
412 $this->createDomainContacts();
415 $this->cleanTempDirs();
416 $this->unsetExtensionSystem();
420 * Create a batch of external API calls which can
421 * be executed concurrently.
424 * $calls = $this->createExternalAPI()
425 * ->addCall('Contact', 'get', ...)
426 * ->addCall('Contact', 'get', ...)
432 * @return \Civi\API\ExternalBatch
433 * @throws PHPUnit_Framework_SkippedTestError
435 public function createExternalAPI() {
436 global $civicrm_root;
437 $defaultParams = array(
438 'version' => $this->_apiversion
,
442 $calls = new \Civi\API\
ExternalBatch($defaultParams);
444 if (!$calls->isSupported()) {
445 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
452 * Create required data based on $this->entity & $this->params
453 * This is just a way to set up the test data for delete & get functions
454 * so the distinction between set
455 * up & tested functions is clearer
460 public function createTestEntity() {
461 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
465 * @param int $contactTypeId
469 public function contactTypeDelete($contactTypeId) {
470 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
472 throw new Exception('Could not delete contact type');
477 * @param array $params
481 public function membershipTypeCreate($params = array()) {
482 CRM_Member_PseudoConstant
::flush('membershipType');
483 CRM_Core_Config
::clearDBCache();
484 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
485 $params = array_merge(array(
487 'duration_unit' => 'year',
488 'duration_interval' => 1,
489 'period_type' => 'rolling',
490 'member_of_contact_id' => $memberOfOrganization,
492 'financial_type_id' => 2,
495 'visibility' => 'Public',
498 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
500 CRM_Member_PseudoConstant
::flush('membershipType');
501 CRM_Utils_Cache
::singleton()->flush();
503 return $result['id'];
507 * @param array $params
511 public function contactMembershipCreate($params) {
512 $params = array_merge(array(
513 'join_date' => '2007-01-21',
514 'start_date' => '2007-01-21',
515 'end_date' => '2007-12-21',
516 'source' => 'Payment',
517 'membership_type_id' => 'General',
519 if (!is_numeric($params['membership_type_id'])) {
520 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
521 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
522 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
526 $result = $this->callAPISuccess('Membership', 'create', $params);
527 return $result['id'];
531 * Delete Membership Type.
533 * @param array $params
535 public function membershipTypeDelete($params) {
536 $this->callAPISuccess('MembershipType', 'Delete', $params);
540 * @param int $membershipID
542 public function membershipDelete($membershipID) {
543 $deleteParams = array('id' => $membershipID);
544 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
548 * @param string $name
552 public function membershipStatusCreate($name = 'test member status') {
553 $params['name'] = $name;
554 $params['start_event'] = 'start_date';
555 $params['end_event'] = 'end_date';
556 $params['is_current_member'] = 1;
557 $params['is_active'] = 1;
559 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
560 CRM_Member_PseudoConstant
::flush('membershipStatus');
561 return $result['id'];
565 * @param int $membershipStatusID
567 public function membershipStatusDelete($membershipStatusID) {
568 if (!$membershipStatusID) {
571 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
574 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
575 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
576 $renewedMembershipEndDate = new DateTime($membershipEndDate);
577 switch ($durationUnit) {
579 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
583 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
584 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
585 $renewedMembershipEndDate->add(new DateInterval('P1D'));
586 $renewedMembershipEndDate->add(new DateInterval('P1M'));
587 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
590 return $renewedMembershipEndDate->format('Y-m-d');
594 * @param array $params
598 public function relationshipTypeCreate($params = array()) {
599 $params = array_merge(array(
600 'name_a_b' => 'Relation 1 for relationship type create',
601 'name_b_a' => 'Relation 2 for relationship type create',
602 'contact_type_a' => 'Individual',
603 'contact_type_b' => 'Organization',
608 $result = $this->callAPISuccess('relationship_type', 'create', $params);
609 CRM_Core_PseudoConstant
::flush('relationshipType');
611 return $result['id'];
615 * Delete Relatinship Type.
617 * @param int $relationshipTypeID
619 public function relationshipTypeDelete($relationshipTypeID) {
620 $params['id'] = $relationshipTypeID;
621 $check = $this->callAPISuccess('relationship_type', 'get', $params);
622 if (!empty($check['count'])) {
623 $this->callAPISuccess('relationship_type', 'delete', $params);
628 * @param array $params
632 public function paymentProcessorTypeCreate($params = NULL) {
633 if (is_null($params)) {
635 'name' => 'API_Test_PP',
636 'title' => 'API Test Payment Processor',
637 'class_name' => 'CRM_Core_Payment_APITest',
638 'billing_mode' => 'form',
644 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
646 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
648 return $result['id'];
652 * Create test Authorize.net instance.
654 * @param array $params
658 public function paymentProcessorAuthorizeNetCreate($params = array()) {
659 $params = array_merge(array(
660 'name' => 'Authorize',
661 'domain_id' => CRM_Core_Config
::domainID(),
662 'payment_processor_type_id' => 'AuthNet',
663 'title' => 'AuthNet',
668 'user_name' => '4y5BfuW7jm',
669 'password' => '4cAmW927n8uLf5J8',
670 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
671 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
672 'class_name' => 'Payment_AuthorizeNet',
676 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
677 return $result['id'];
681 * Create Participant.
683 * @param array $params
684 * Array of contact id and event id values.
687 * $id of participant created
689 public function participantCreate($params = []) {
690 if (empty($params['contact_id'])) {
691 $params['contact_id'] = $this->individualCreate();
693 if (empty($params['event_id'])) {
694 $event = $this->eventCreate();
695 $params['event_id'] = $event['id'];
700 'register_date' => 20070219,
701 'source' => 'Wimbeldon',
702 'event_level' => 'Payment',
706 $params = array_merge($defaults, $params);
707 $result = $this->callAPISuccess('Participant', 'create', $params);
708 return $result['id'];
712 * Create Payment Processor.
715 * Id Payment Processor
717 public function processorCreate($params = array()) {
718 $processorParams = array(
721 'payment_processor_type_id' => 'Dummy',
722 'financial_account_id' => 12,
726 'url_site' => 'http://dummy.com',
727 'url_recur' => 'http://dummy.com',
730 'payment_instrument_id' => 'Debit Card',
732 $processorParams = array_merge($processorParams, $params);
733 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
734 return $processor['id'];
738 * Create Payment Processor.
740 * @param array $processorParams
742 * @return \CRM_Core_Payment_Dummy
743 * Instance of Dummy Payment Processor
745 public function dummyProcessorCreate($processorParams = array()) {
746 $paymentProcessorID = $this->processorCreate($processorParams);
747 return System
::singleton()->getById($paymentProcessorID);
751 * Create contribution page.
753 * @param array $params
755 * Array of contribution page
757 public function contributionPageCreate($params = array()) {
758 $this->_pageParams
= array_merge(array(
759 'title' => 'Test Contribution Page',
760 'financial_type_id' => 1,
762 'financial_account_id' => 1,
764 'is_allow_other_amount' => 1,
766 'max_amount' => 1000,
768 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
772 * Create a sample batch.
774 public function batchCreate() {
775 $params = $this->_params
;
776 $params['name'] = $params['title'] = 'Batch_433397';
777 $params['status_id'] = 1;
778 $result = $this->callAPISuccess('batch', 'create', $params);
779 return $result['id'];
785 * @param array $params
787 * result of created tag
789 public function tagCreate($params = array()) {
791 'name' => 'New Tag3',
792 'description' => 'This is description for Our New Tag ',
795 $params = array_merge($defaults, $params);
796 $result = $this->callAPISuccess('Tag', 'create', $params);
797 return $result['values'][$result['id']];
804 * Id of the tag to be deleted.
808 public function tagDelete($tagId) {
809 require_once 'api/api.php';
813 $result = $this->callAPISuccess('Tag', 'delete', $params);
814 return $result['id'];
818 * Add entity(s) to the tag
820 * @param array $params
824 public function entityTagAdd($params) {
825 $result = $this->callAPISuccess('entity_tag', 'create', $params);
832 * @param array $params
836 * id of created pledge
838 public function pledgeCreate($params) {
839 $params = array_merge(array(
840 'pledge_create_date' => date('Ymd'),
841 'start_date' => date('Ymd'),
842 'scheduled_date' => date('Ymd'),
844 'pledge_status_id' => '2',
845 'financial_type_id' => '1',
846 'pledge_original_installment_amount' => 20,
847 'frequency_interval' => 5,
848 'frequency_unit' => 'year',
849 'frequency_day' => 15,
854 $result = $this->callAPISuccess('Pledge', 'create', $params);
855 return $result['id'];
859 * Delete contribution.
861 * @param int $pledgeId
863 public function pledgeDelete($pledgeId) {
865 'pledge_id' => $pledgeId,
867 $this->callAPISuccess('Pledge', 'delete', $params);
871 * Create contribution.
873 * @param array $params
874 * Array of parameters.
877 * id of created contribution
879 public function contributionCreate($params) {
881 $params = array_merge(array(
883 'receive_date' => date('Ymd'),
884 'total_amount' => 100.00,
885 'fee_amount' => 5.00,
886 'financial_type_id' => 1,
887 'payment_instrument_id' => 1,
888 'non_deductible_amount' => 10.00,
890 'contribution_status_id' => 1,
893 $result = $this->callAPISuccess('contribution', 'create', $params);
894 return $result['id'];
898 * Delete contribution.
900 * @param int $contributionId
904 public function contributionDelete($contributionId) {
906 'contribution_id' => $contributionId,
908 $result = $this->callAPISuccess('contribution', 'delete', $params);
915 * @param array $params
916 * Name-value pair for an event.
920 public function eventCreate($params = array()) {
921 // if no contact was passed, make up a dummy event creator
922 if (!isset($params['contact_id'])) {
923 $params['contact_id'] = $this->_contactCreate(array(
924 'contact_type' => 'Individual',
925 'first_name' => 'Event',
926 'last_name' => 'Creator',
930 // set defaults for missing params
931 $params = array_merge(array(
932 'title' => 'Annual CiviCRM meet',
933 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
934 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
935 'event_type_id' => 1,
937 'start_date' => 20081021,
938 'end_date' => 20081023,
939 'is_online_registration' => 1,
940 'registration_start_date' => 20080601,
941 'registration_end_date' => 20081015,
942 'max_participants' => 100,
943 'event_full_text' => 'Sorry! We are already full',
946 'is_show_location' => 0,
949 return $this->callAPISuccess('Event', 'create', $params);
953 * Create a paid event.
955 * @param array $params
959 protected function eventCreatePaid($params) {
960 $event = $this->eventCreate($params);
961 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
962 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
963 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
964 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
965 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
977 public function eventDelete($id) {
981 return $this->callAPISuccess('event', 'delete', $params);
985 * Delete participant.
987 * @param int $participantID
991 public function participantDelete($participantID) {
993 'id' => $participantID,
995 $check = $this->callAPISuccess('Participant', 'get', $params);
996 if ($check['count'] > 0) {
997 return $this->callAPISuccess('Participant', 'delete', $params);
1002 * Create participant payment.
1004 * @param int $participantID
1005 * @param int $contributionID
1007 * $id of created payment
1009 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1010 //Create Participant Payment record With Values
1012 'participant_id' => $participantID,
1013 'contribution_id' => $contributionID,
1016 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1017 return $result['id'];
1021 * Delete participant payment.
1023 * @param int $paymentID
1025 public function participantPaymentDelete($paymentID) {
1029 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1035 * @param int $contactID
1037 * location id of created location
1039 public function locationAdd($contactID) {
1042 'location_type' => 'New Location Type',
1044 'name' => 'Saint Helier St',
1045 'county' => 'Marin',
1046 'country' => 'UNITED STATES',
1047 'state_province' => 'Michigan',
1048 'supplemental_address_1' => 'Hallmark Ct',
1049 'supplemental_address_2' => 'Jersey Village',
1050 'supplemental_address_3' => 'My Town',
1055 'contact_id' => $contactID,
1056 'address' => $address,
1057 'location_format' => '2.0',
1058 'location_type' => 'New Location Type',
1061 $result = $this->callAPISuccess('Location', 'create', $params);
1066 * Delete Locations of contact.
1068 * @param array $params
1071 public function locationDelete($params) {
1072 $this->callAPISuccess('Location', 'delete', $params);
1076 * Add a Location Type.
1078 * @param array $params
1079 * @return CRM_Core_DAO_LocationType
1080 * location id of created location
1082 public function locationTypeCreate($params = NULL) {
1083 if ($params === NULL) {
1085 'name' => 'New Location Type',
1086 'vcard_name' => 'New Location Type',
1087 'description' => 'Location Type for Delete',
1092 $locationType = new CRM_Core_DAO_LocationType();
1093 $locationType->copyValues($params);
1094 $locationType->save();
1095 // clear getfields cache
1096 CRM_Core_PseudoConstant
::flush();
1097 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1098 return $locationType;
1102 * Delete a Location Type.
1104 * @param int $locationTypeId
1106 public function locationTypeDelete($locationTypeId) {
1107 $locationType = new CRM_Core_DAO_LocationType();
1108 $locationType->id
= $locationTypeId;
1109 $locationType->delete();
1115 * @param array $params
1116 * @return CRM_Core_DAO_Mapping
1117 * Mapping id of created mapping
1119 public function mappingCreate($params = NULL) {
1120 if ($params === NULL) {
1122 'name' => 'Mapping name',
1123 'description' => 'Mapping description',
1124 // 'Export Contact' mapping.
1125 'mapping_type_id' => 7,
1129 $mapping = new CRM_Core_DAO_Mapping();
1130 $mapping->copyValues($params);
1132 // clear getfields cache
1133 CRM_Core_PseudoConstant
::flush();
1134 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1141 * @param int $mappingId
1143 public function mappingDelete($mappingId) {
1144 $mapping = new CRM_Core_DAO_Mapping();
1145 $mapping->id
= $mappingId;
1150 * Prepare class for ACLs.
1152 protected function prepareForACLs() {
1153 $config = CRM_Core_Config
::singleton();
1154 $config->userPermissionClass
->permissions
= array();
1160 protected function cleanUpAfterACLs() {
1161 CRM_Utils_Hook
::singleton()->reset();
1162 $tablesToTruncate = array(
1164 'civicrm_acl_cache',
1165 'civicrm_acl_entity_role',
1166 'civicrm_acl_contact_cache',
1168 $this->quickCleanup($tablesToTruncate);
1169 $config = CRM_Core_Config
::singleton();
1170 unset($config->userPermissionClass
->permissions
);
1174 * Create a smart group.
1176 * By default it will be a group of households.
1178 * @param array $smartGroupParams
1179 * @param array $groupParams
1182 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1183 $smartGroupParams = array_merge(array(
1184 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1187 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1189 $groupParams['saved_search_id'] = $savedSearch->id
;
1190 return $this->groupCreate($groupParams);
1195 * @param array $params
1197 public function uFFieldCreate($params = array()) {
1198 $params = array_merge(array(
1200 'field_name' => 'first_name',
1203 'visibility' => 'Public Pages and Listings',
1204 'is_searchable' => '1',
1205 'label' => 'first_name',
1206 'field_type' => 'Individual',
1209 $this->callAPISuccess('uf_field', 'create', $params);
1213 * Add a UF Join Entry.
1215 * @param array $params
1217 * $id of created UF Join
1219 public function ufjoinCreate($params = NULL) {
1220 if ($params === NULL) {
1223 'module' => 'CiviEvent',
1224 'entity_table' => 'civicrm_event',
1230 $result = $this->callAPISuccess('uf_join', 'create', $params);
1235 * @param array $params
1236 * Optional parameters.
1237 * @param bool $reloadConfig
1238 * While enabling CiviCampaign component, we shouldn't always forcibly
1239 * reload config as this hinder hook call in test environment
1244 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1245 $this->enableCiviCampaign($reloadConfig);
1246 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1247 'name' => 'big_campaign',
1248 'title' => 'Campaign',
1250 return $campaign['id'];
1254 * Create Group for a contact.
1256 * @param int $contactId
1258 public function contactGroupCreate($contactId) {
1260 'contact_id.1' => $contactId,
1264 $this->callAPISuccess('GroupContact', 'Create', $params);
1268 * Delete Group for a contact.
1270 * @param int $contactId
1272 public function contactGroupDelete($contactId) {
1274 'contact_id.1' => $contactId,
1277 $this->civicrm_api('GroupContact', 'Delete', $params);
1283 * @param array $params
1286 public function activityCreate($params = array()) {
1287 $params = array_merge(array(
1288 'subject' => 'Discussion on warm beer',
1289 'activity_date_time' => date('Ymd'),
1290 'duration_hours' => 30,
1291 'duration_minutes' => 20,
1292 'location' => 'Baker Street',
1293 'details' => 'Lets schedule a meeting',
1295 'activity_type_id' => 'Meeting',
1297 if (!isset($params['source_contact_id'])) {
1298 $params['source_contact_id'] = $this->individualCreate();
1300 if (!isset($params['target_contact_id'])) {
1301 $params['target_contact_id'] = $this->individualCreate(array(
1302 'first_name' => 'Julia',
1303 'Last_name' => 'Anderson',
1305 'email' => 'julia_anderson@civicrm.org',
1306 'contact_type' => 'Individual',
1309 if (!isset($params['assignee_contact_id'])) {
1310 $params['assignee_contact_id'] = $params['target_contact_id'];
1313 $result = $this->callAPISuccess('Activity', 'create', $params);
1315 $result['target_contact_id'] = $params['target_contact_id'];
1316 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1321 * Create an activity type.
1323 * @param array $params
1327 public function activityTypeCreate($params) {
1328 return $this->callAPISuccess('ActivityType', 'create', $params);
1332 * Delete activity type.
1334 * @param int $activityTypeId
1335 * Id of the activity type.
1338 public function activityTypeDelete($activityTypeId) {
1339 $params['activity_type_id'] = $activityTypeId;
1340 return $this->callAPISuccess('ActivityType', 'delete', $params);
1344 * Create custom group.
1346 * @param array $params
1349 public function customGroupCreate($params = array()) {
1351 'title' => 'new custom group',
1352 'extends' => 'Contact',
1354 'style' => 'Inline',
1358 $params = array_merge($defaults, $params);
1360 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1361 $this->callAPISuccess('custom_group', 'get', array(
1362 'title' => $params['title'],
1363 array('api.custom_group.delete' => 1),
1366 return $this->callAPISuccess('custom_group', 'create', $params);
1370 * Existing function doesn't allow params to be over-ridden so need a new one
1371 * this one allows you to only pass in the params you want to change
1372 * @param array $params
1375 public function CustomGroupCreateByParams($params = array()) {
1377 'title' => "API Custom Group",
1378 'extends' => 'Contact',
1380 'style' => 'Inline',
1383 $params = array_merge($defaults, $params);
1384 return $this->callAPISuccess('custom_group', 'create', $params);
1388 * Create custom group with multi fields.
1389 * @param array $params
1392 public function CustomGroupMultipleCreateByParams($params = array()) {
1397 $params = array_merge($defaults, $params);
1398 return $this->CustomGroupCreateByParams($params);
1402 * Create custom group with multi fields.
1403 * @param array $params
1406 public function CustomGroupMultipleCreateWithFields($params = array()) {
1407 // also need to pass on $params['custom_field'] if not set but not in place yet
1409 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1410 $ids['custom_group_id'] = $customGroup['id'];
1412 $customField = $this->customFieldCreate(array(
1413 'custom_group_id' => $ids['custom_group_id'],
1414 'label' => 'field_1' . $ids['custom_group_id'],
1418 $ids['custom_field_id'][] = $customField['id'];
1420 $customField = $this->customFieldCreate(array(
1421 'custom_group_id' => $ids['custom_group_id'],
1422 'default_value' => '',
1423 'label' => 'field_2' . $ids['custom_group_id'],
1426 $ids['custom_field_id'][] = $customField['id'];
1428 $customField = $this->customFieldCreate(array(
1429 'custom_group_id' => $ids['custom_group_id'],
1430 'default_value' => '',
1431 'label' => 'field_3' . $ids['custom_group_id'],
1434 $ids['custom_field_id'][] = $customField['id'];
1440 * Create a custom group with a single text custom field. See
1441 * participant:testCreateWithCustom for how to use this
1443 * @param string $function
1445 * @param string $filename
1449 * ids of created objects
1451 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1452 $params = array('title' => $function);
1453 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1454 $params['extends'] = $entity ?
$entity : 'Contact';
1455 $customGroup = $this->CustomGroupCreate($params);
1456 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1457 CRM_Core_PseudoConstant
::flush();
1459 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1463 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1464 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1466 * @param string $function
1468 * @param string $filename
1472 * ids of created objects
1474 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1475 $params = array('title' => $function);
1476 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1477 $params['extends'] = $entity ?
$entity : 'Contact';
1478 $customGroup = $this->CustomGroupCreate($params);
1479 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1480 CRM_Core_PseudoConstant
::flush();
1482 'defaultValue' => 'Default Value',
1483 'lowercasevalue' => 'Lowercase Value',
1484 1 => 'Integer Value',
1487 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1488 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1489 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1490 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1491 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1492 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1493 foreach ($options as $option_value => $option_label) {
1494 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1495 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1498 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id'], 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'], 'custom_field_group_options' => $options);
1502 * Delete custom group.
1504 * @param int $customGroupID
1508 public function customGroupDelete($customGroupID) {
1509 $params['id'] = $customGroupID;
1510 return $this->callAPISuccess('custom_group', 'delete', $params);
1514 * Create custom field.
1516 * @param array $params
1517 * (custom_group_id) is required.
1520 public function customFieldCreate($params) {
1521 $params = array_merge(array(
1522 'label' => 'Custom Field',
1523 'data_type' => 'String',
1524 'html_type' => 'Text',
1525 'is_searchable' => 1,
1527 'default_value' => 'defaultValue',
1530 $result = $this->callAPISuccess('custom_field', 'create', $params);
1531 // these 2 functions are called with force to flush static caches
1532 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1533 CRM_Core_Component
::getEnabledComponents(1);
1538 * Delete custom field.
1540 * @param int $customFieldID
1544 public function customFieldDelete($customFieldID) {
1546 $params['id'] = $customFieldID;
1547 return $this->callAPISuccess('custom_field', 'delete', $params);
1556 public function noteCreate($cId) {
1558 'entity_table' => 'civicrm_contact',
1559 'entity_id' => $cId,
1560 'note' => 'hello I am testing Note',
1561 'contact_id' => $cId,
1562 'modified_date' => date('Ymd'),
1563 'subject' => 'Test Note',
1566 return $this->callAPISuccess('Note', 'create', $params);
1570 * Enable CiviCampaign Component.
1572 * @param bool $reloadConfig
1573 * Force relaod config or not
1575 public function enableCiviCampaign($reloadConfig = TRUE) {
1576 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1577 if ($reloadConfig) {
1578 // force reload of config object
1579 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1581 //flush cache by calling with reset
1582 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1586 * Create custom field with Option Values.
1588 * @param array $customGroup
1589 * @param string $name
1590 * Name of custom field.
1591 * @param array $extraParams
1592 * Additional parameters to pass through.
1596 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1597 $fieldParams = array(
1598 'custom_group_id' => $customGroup['id'],
1599 'name' => 'test_custom_group',
1600 'label' => 'Country',
1601 'html_type' => 'Select',
1602 'data_type' => 'String',
1605 'is_searchable' => 0,
1609 $optionGroup = array(
1611 'name' => 'option_group1',
1612 'label' => 'option_group_label1',
1615 $optionValue = array(
1616 'option_label' => array('Label1', 'Label2'),
1617 'option_value' => array('value1', 'value2'),
1618 'option_name' => array($name . '_1', $name . '_2'),
1619 'option_weight' => array(1, 2),
1620 'option_status' => 1,
1623 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1625 return $this->callAPISuccess('custom_field', 'create', $params);
1633 public function confirmEntitiesDeleted($entities) {
1634 foreach ($entities as $entity) {
1636 $result = $this->callAPISuccess($entity, 'Get', array());
1637 if ($result['error'] == 1 ||
$result['count'] > 0) {
1638 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1646 * Quick clean by emptying tables created for the test.
1648 * @param array $tablesToTruncate
1649 * @param bool $dropCustomValueTables
1650 * @throws \Exception
1652 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1654 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1656 if ($dropCustomValueTables) {
1657 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1658 while ($optionGroupResult->fetch()) {
1659 if (!empty($optionGroupResult->option_group_id
)) {
1660 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1663 $tablesToTruncate[] = 'civicrm_custom_group';
1664 $tablesToTruncate[] = 'civicrm_custom_field';
1667 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1669 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1670 foreach ($tablesToTruncate as $table) {
1671 $sql = "TRUNCATE TABLE $table";
1672 CRM_Core_DAO
::executeQuery($sql);
1674 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1676 if ($dropCustomValueTables) {
1677 $dbName = self
::getDBName();
1679 SELECT TABLE_NAME as tableName
1680 FROM INFORMATION_SCHEMA.TABLES
1681 WHERE TABLE_SCHEMA = '{$dbName}'
1682 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1685 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1686 while ($tableDAO->fetch()) {
1687 $sql = "DROP TABLE {$tableDAO->tableName}";
1688 CRM_Core_DAO
::executeQuery($sql);
1694 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1696 public function quickCleanUpFinancialEntities() {
1697 $tablesToTruncate = array(
1699 'civicrm_activity_contact',
1700 'civicrm_contribution',
1701 'civicrm_contribution_soft',
1702 'civicrm_contribution_product',
1703 'civicrm_financial_trxn',
1704 'civicrm_financial_item',
1705 'civicrm_contribution_recur',
1706 'civicrm_line_item',
1707 'civicrm_contribution_page',
1708 'civicrm_payment_processor',
1709 'civicrm_entity_financial_trxn',
1710 'civicrm_membership',
1711 'civicrm_membership_type',
1712 'civicrm_membership_payment',
1713 'civicrm_membership_log',
1714 'civicrm_membership_block',
1716 'civicrm_participant',
1717 'civicrm_participant_payment',
1719 'civicrm_pledge_payment',
1720 'civicrm_price_set_entity',
1721 'civicrm_price_field_value',
1722 'civicrm_price_field',
1724 $this->quickCleanup($tablesToTruncate);
1725 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1726 $this->restoreDefaultPriceSetConfig();
1728 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1729 $this->disableTaxAndInvoicing();
1730 $this->setCurrencySeparators(',');
1731 CRM_Core_PseudoConstant
::flush('taxRates');
1732 System
::singleton()->flushProcessors();
1735 public function restoreDefaultPriceSetConfig() {
1736 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1737 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1738 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)");
1739 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)");
1743 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1744 * Default behaviour is to also delete the entity
1745 * @param array $params
1746 * Params array to check against.
1748 * Id of the entity concerned.
1749 * @param string $entity
1750 * Name of entity concerned (e.g. membership).
1751 * @param bool $delete
1752 * Should the entity be deleted as part of this check.
1753 * @param string $errorText
1754 * Text to print on error.
1758 * @param array $params
1761 * @param int $delete
1762 * @param string $errorText
1766 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1768 $result = $this->callAPISuccessGetSingle($entity, array(
1773 $this->callAPISuccess($entity, 'Delete', array(
1777 $dateFields = $keys = $dateTimeFields = array();
1778 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1779 foreach ($fields['values'] as $field => $settings) {
1780 if (array_key_exists($field, $result)) {
1781 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1784 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1786 $type = CRM_Utils_Array
::value('type', $settings);
1787 if ($type == CRM_Utils_Type
::T_DATE
) {
1788 $dateFields[] = $settings['name'];
1789 // we should identify both real names & unique names as dates
1790 if ($field != $settings['name']) {
1791 $dateFields[] = $field;
1794 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1795 $dateTimeFields[] = $settings['name'];
1796 // we should identify both real names & unique names as dates
1797 if ($field != $settings['name']) {
1798 $dateTimeFields[] = $field;
1803 if (strtolower($entity) == 'contribution') {
1804 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1805 // this is not returned in id format
1806 unset($params['payment_instrument_id']);
1807 $params['contribution_source'] = $params['source'];
1808 unset($params['source']);
1811 foreach ($params as $key => $value) {
1812 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1815 if (in_array($key, $dateFields)) {
1816 $value = date('Y-m-d', strtotime($value));
1817 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1819 if (in_array($key, $dateTimeFields)) {
1820 $value = date('Y-m-d H:i:s', strtotime($value));
1821 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1823 $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);
1828 * Get formatted values in the actual and expected result.
1829 * @param array $actual
1830 * Actual calculated values.
1831 * @param array $expected
1834 public function checkArrayEquals(&$actual, &$expected) {
1835 self
::unsetId($actual);
1836 self
::unsetId($expected);
1837 $this->assertEquals($actual, $expected);
1841 * Unset the key 'id' from the array
1842 * @param array $unformattedArray
1843 * The array from which the 'id' has to be unset.
1845 public static function unsetId(&$unformattedArray) {
1846 $formattedArray = array();
1847 if (array_key_exists('id', $unformattedArray)) {
1848 unset($unformattedArray['id']);
1850 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1851 foreach ($unformattedArray['values'] as $key => $value) {
1852 if (is_array($value)) {
1853 foreach ($value as $k => $v) {
1859 elseif ($key == 'id') {
1860 $unformattedArray[$key];
1862 $formattedArray = array($value);
1864 $unformattedArray['values'] = $formattedArray;
1869 * Helper to enable/disable custom directory support
1871 * @param array $customDirs
1873 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1874 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1876 public function customDirectories($customDirs) {
1877 $config = CRM_Core_Config
::singleton();
1879 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1880 unset($config->customPHPPathDir
);
1882 elseif ($customDirs['php_path'] === TRUE) {
1883 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1886 $config->customPHPPathDir
= $php_path;
1889 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1890 unset($config->customTemplateDir
);
1892 elseif ($customDirs['template_path'] === TRUE) {
1893 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1896 $config->customTemplateDir
= $template_path;
1901 * Generate a temporary folder.
1903 * @param string $prefix
1906 public function createTempDir($prefix = 'test-') {
1907 $tempDir = CRM_Utils_File
::tempdir($prefix);
1908 $this->tempDirs
[] = $tempDir;
1912 public function cleanTempDirs() {
1913 if (!is_array($this->tempDirs
)) {
1914 // fix test errors where this is not set
1917 foreach ($this->tempDirs
as $tempDir) {
1918 if (is_dir($tempDir)) {
1919 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1925 * Temporarily replace the singleton extension with a different one.
1926 * @param \CRM_Extension_System $system
1928 public function setExtensionSystem(CRM_Extension_System
$system) {
1929 if ($this->origExtensionSystem
== NULL) {
1930 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1932 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1935 public function unsetExtensionSystem() {
1936 if ($this->origExtensionSystem
!== NULL) {
1937 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1938 $this->origExtensionSystem
= NULL;
1943 * Temporarily alter the settings-metadata to add a mock setting.
1945 * WARNING: The setting metadata will disappear on the next cache-clear.
1950 public function setMockSettingsMetaData($extras) {
1951 Civi
::service('settings_manager')->flush();
1953 CRM_Utils_Hook
::singleton()
1954 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
1955 $metadata = array_merge($metadata, $extras);
1958 $fields = $this->callAPISuccess('setting', 'getfields', array());
1959 foreach ($extras as $key => $spec) {
1960 $this->assertNotEmpty($spec['title']);
1961 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
1966 * @param string $name
1968 public function financialAccountDelete($name) {
1969 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
1970 $financialAccount->name
= $name;
1971 if ($financialAccount->find(TRUE)) {
1972 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
1973 $entityFinancialType->financial_account_id
= $financialAccount->id
;
1974 $entityFinancialType->delete();
1975 $financialAccount->delete();
1980 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
1981 * (NB unclear if this is still required)
1983 public function _sethtmlGlobals() {
1984 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
1985 'required' => array(
1986 'html_quickform_rule_required',
1987 'HTML/QuickForm/Rule/Required.php',
1989 'maxlength' => array(
1990 'html_quickform_rule_range',
1991 'HTML/QuickForm/Rule/Range.php',
1993 'minlength' => array(
1994 'html_quickform_rule_range',
1995 'HTML/QuickForm/Rule/Range.php',
1997 'rangelength' => array(
1998 'html_quickform_rule_range',
1999 'HTML/QuickForm/Rule/Range.php',
2002 'html_quickform_rule_email',
2003 'HTML/QuickForm/Rule/Email.php',
2006 'html_quickform_rule_regex',
2007 'HTML/QuickForm/Rule/Regex.php',
2009 'lettersonly' => array(
2010 'html_quickform_rule_regex',
2011 'HTML/QuickForm/Rule/Regex.php',
2013 'alphanumeric' => array(
2014 'html_quickform_rule_regex',
2015 'HTML/QuickForm/Rule/Regex.php',
2018 'html_quickform_rule_regex',
2019 'HTML/QuickForm/Rule/Regex.php',
2021 'nopunctuation' => array(
2022 'html_quickform_rule_regex',
2023 'HTML/QuickForm/Rule/Regex.php',
2026 'html_quickform_rule_regex',
2027 'HTML/QuickForm/Rule/Regex.php',
2029 'callback' => array(
2030 'html_quickform_rule_callback',
2031 'HTML/QuickForm/Rule/Callback.php',
2034 'html_quickform_rule_compare',
2035 'HTML/QuickForm/Rule/Compare.php',
2038 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2039 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2041 'HTML/QuickForm/group.php',
2042 'HTML_QuickForm_group',
2045 'HTML/QuickForm/hidden.php',
2046 'HTML_QuickForm_hidden',
2049 'HTML/QuickForm/reset.php',
2050 'HTML_QuickForm_reset',
2052 'checkbox' => array(
2053 'HTML/QuickForm/checkbox.php',
2054 'HTML_QuickForm_checkbox',
2057 'HTML/QuickForm/file.php',
2058 'HTML_QuickForm_file',
2061 'HTML/QuickForm/image.php',
2062 'HTML_QuickForm_image',
2064 'password' => array(
2065 'HTML/QuickForm/password.php',
2066 'HTML_QuickForm_password',
2069 'HTML/QuickForm/radio.php',
2070 'HTML_QuickForm_radio',
2073 'HTML/QuickForm/button.php',
2074 'HTML_QuickForm_button',
2077 'HTML/QuickForm/submit.php',
2078 'HTML_QuickForm_submit',
2081 'HTML/QuickForm/select.php',
2082 'HTML_QuickForm_select',
2084 'hiddenselect' => array(
2085 'HTML/QuickForm/hiddenselect.php',
2086 'HTML_QuickForm_hiddenselect',
2089 'HTML/QuickForm/text.php',
2090 'HTML_QuickForm_text',
2092 'textarea' => array(
2093 'HTML/QuickForm/textarea.php',
2094 'HTML_QuickForm_textarea',
2096 'fckeditor' => array(
2097 'HTML/QuickForm/fckeditor.php',
2098 'HTML_QuickForm_FCKEditor',
2101 'HTML/QuickForm/tinymce.php',
2102 'HTML_QuickForm_TinyMCE',
2104 'dojoeditor' => array(
2105 'HTML/QuickForm/dojoeditor.php',
2106 'HTML_QuickForm_dojoeditor',
2109 'HTML/QuickForm/link.php',
2110 'HTML_QuickForm_link',
2112 'advcheckbox' => array(
2113 'HTML/QuickForm/advcheckbox.php',
2114 'HTML_QuickForm_advcheckbox',
2117 'HTML/QuickForm/date.php',
2118 'HTML_QuickForm_date',
2121 'HTML/QuickForm/static.php',
2122 'HTML_QuickForm_static',
2125 'HTML/QuickForm/header.php',
2126 'HTML_QuickForm_header',
2129 'HTML/QuickForm/html.php',
2130 'HTML_QuickForm_html',
2132 'hierselect' => array(
2133 'HTML/QuickForm/hierselect.php',
2134 'HTML_QuickForm_hierselect',
2136 'autocomplete' => array(
2137 'HTML/QuickForm/autocomplete.php',
2138 'HTML_QuickForm_autocomplete',
2141 'HTML/QuickForm/xbutton.php',
2142 'HTML_QuickForm_xbutton',
2144 'advmultiselect' => array(
2145 'HTML/QuickForm/advmultiselect.php',
2146 'HTML_QuickForm_advmultiselect',
2152 * Set up an acl allowing contact to see 2 specified groups
2153 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2155 * You need to have pre-created these groups & created the user e.g
2156 * $this->createLoggedInUser();
2157 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2158 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2160 * @param bool $isProfile
2162 public function setupACL($isProfile = FALSE) {
2164 $_REQUEST = $this->_params
;
2166 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2167 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2168 $ov = new CRM_Core_DAO_OptionValue();
2169 $ov->option_group_id
= $optionGroupID;
2171 if ($ov->find(TRUE)) {
2172 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2174 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2175 'option_group_id' => $optionGroupID,
2176 'label' => 'pick me',
2180 CRM_Core_DAO
::executeQuery("
2181 TRUNCATE civicrm_acl_cache
2184 CRM_Core_DAO
::executeQuery("
2185 TRUNCATE civicrm_acl_contact_cache
2188 CRM_Core_DAO
::executeQuery("
2189 INSERT INTO civicrm_acl_entity_role (
2190 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2191 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2195 CRM_Core_DAO
::executeQuery("
2196 INSERT INTO civicrm_acl (
2197 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2200 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2205 CRM_Core_DAO
::executeQuery("
2206 INSERT INTO civicrm_acl (
2207 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2210 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2214 CRM_Core_DAO
::executeQuery("
2215 INSERT INTO civicrm_acl (
2216 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2219 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2224 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2225 $this->callAPISuccess('group_contact', 'create', array(
2226 'group_id' => $this->_permissionedGroup
,
2227 'contact_id' => $this->_loggedInUser
,
2232 CRM_ACL_BAO_Cache
::resetCache();
2233 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2238 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2240 public function offsetDefaultPriceSet() {
2241 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2242 $firstID = $contributionPriceSet['id'];
2243 $this->callAPISuccess('price_set', 'create', array(
2244 'id' => $contributionPriceSet['id'],
2248 unset($contributionPriceSet['id']);
2249 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2250 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2251 'price_set_id' => $firstID,
2252 'options' => array('limit' => 1),
2254 unset($priceField['id']);
2255 $priceField['price_set_id'] = $newPriceSet['id'];
2256 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2257 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2258 'price_set_id' => $firstID,
2260 'options' => array('limit' => 1),
2263 unset($priceFieldValue['id']);
2264 //create some padding to use up ids
2265 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2266 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2267 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2271 * Create an instance of the paypal processor.
2272 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2273 * this parent class & we don't have a structure for that yet
2274 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2275 * & the best protection against that is the functions this class affords
2276 * @param array $params
2277 * @return int $result['id'] payment processor id
2279 public function paymentProcessorCreate($params = array()) {
2280 $params = array_merge(array(
2282 'domain_id' => CRM_Core_Config
::domainID(),
2283 'payment_processor_type_id' => 'PayPal',
2287 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2288 'password' => '1183377788',
2289 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2290 'url_site' => 'https://www.sandbox.paypal.com/',
2291 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2292 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2293 'class_name' => 'Payment_PayPalImpl',
2294 'billing_mode' => 3,
2295 'financial_type_id' => 1,
2296 'financial_account_id' => 12,
2297 // Credit card = 1 so can pass 'by accident'.
2298 'payment_instrument_id' => 'Debit Card',
2300 if (!is_numeric($params['payment_processor_type_id'])) {
2301 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2303 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2304 'name' => $params['payment_processor_type_id'],
2308 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2309 return $result['id'];
2313 * Set up initial recurring payment allowing subsequent IPN payments.
2315 * @param array $recurParams (Optional)
2316 * @param array $contributionParams (Optional)
2318 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2319 $contributionParams = array_merge([
2320 'total_amount' => '200',
2321 'invoice_id' => $this->_invoiceID
,
2322 'financial_type_id' => 'Donation',
2323 'contribution_status_id' => 'Pending',
2324 'contact_id' => $this->_contactID
,
2325 'contribution_page_id' => $this->_contributionPageID
,
2326 'payment_processor_id' => $this->_paymentProcessorID
,
2328 'skipCleanMoney' => TRUE,
2329 ], $contributionParams);
2330 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2331 'contact_id' => $this->_contactID
,
2334 'installments' => 5,
2335 'frequency_unit' => 'Month',
2336 'frequency_interval' => 1,
2337 'invoice_id' => $this->_invoiceID
,
2338 'contribution_status_id' => 2,
2339 'payment_processor_id' => $this->_paymentProcessorID
,
2340 // processor provided ID - use contact ID as proxy.
2341 'processor_id' => $this->_contactID
,
2342 'api.contribution.create' => $contributionParams,
2344 $this->_contributionRecurID
= $contributionRecur['id'];
2345 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2349 * 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
2351 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2353 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2354 $membershipParams = $recurParams = array();
2355 if (!empty($params['duration_unit'])) {
2356 $membershipParams['duration_unit'] = $params['duration_unit'];
2358 if (!empty($params['frequency_unit'])) {
2359 $recurParams['frequency_unit'] = $params['frequency_unit'];
2362 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2363 //create a contribution so our membership & contribution don't both have id = 1
2364 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2365 $this->contributionCreate(array(
2366 'contact_id' => $this->_contactID
,
2368 'financial_type_id' => 1,
2369 'invoice_id' => 'abcd',
2373 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2375 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2376 'contact_id' => $this->_contactID
,
2377 'membership_type_id' => $this->ids
['membership_type'],
2378 'contribution_recur_id' => $this->_contributionRecurID
,
2379 'format.only_id' => TRUE,
2381 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2382 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2384 $this->callAPISuccess('line_item', 'create', array(
2385 'entity_table' => 'civicrm_membership',
2386 'entity_id' => $this->ids
['membership'],
2387 'contribution_id' => $this->_contributionID
,
2388 'label' => 'General',
2390 'unit_price' => 200,
2391 'line_total' => 200,
2392 'financial_type_id' => 1,
2393 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2395 'label' => 'Membership Amount',
2396 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2398 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2400 'label' => 'General',
2401 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2404 $this->callAPISuccess('membership_payment', 'create', array(
2405 'contribution_id' => $this->_contributionID
,
2406 'membership_id' => $this->ids
['membership'],
2415 public function CiviUnitTestCase_fatalErrorHandler($message) {
2416 throw new Exception("{$message['message']}: {$message['code']}");
2420 * Wrap the entire test case in a transaction.
2422 * Only subsequent DB statements will be wrapped in TX -- this cannot
2423 * retroactively wrap old DB statements. Therefore, it makes sense to
2424 * call this at the beginning of setUp().
2426 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2427 * this option does not work with, e.g., custom-data.
2429 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2430 * if TRUNCATE or ALTER is called while using a transaction.
2433 * Whether to use nesting or reference-counting.
2435 public function useTransaction($nest = TRUE) {
2437 $this->tx
= new CRM_Core_Transaction($nest);
2438 $this->tx
->rollback();
2443 * Assert the attachment exists.
2445 * @param bool $exists
2446 * @param array $apiResult
2448 protected function assertAttachmentExistence($exists, $apiResult) {
2449 $fileId = $apiResult['id'];
2450 $this->assertTrue(is_numeric($fileId));
2451 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2452 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2453 1 => array($fileId, 'Int'),
2455 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2456 1 => array($fileId, 'Int'),
2461 * Create a price set for an event.
2463 * @param int $feeTotal
2464 * @param int $minAmt
2465 * @param string $type
2470 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2471 // creating price set, price field
2472 $paramsSet['title'] = 'Price Set';
2473 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2474 $paramsSet['is_active'] = FALSE;
2475 $paramsSet['extends'] = 1;
2476 $paramsSet['min_amount'] = $minAmt;
2478 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2479 $this->_ids
['price_set'] = $priceSet->id
;
2481 $paramsField = array(
2482 'label' => 'Price Field',
2483 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2484 'html_type' => $type,
2485 'price' => $feeTotal,
2486 'option_label' => array('1' => 'Price Field'),
2487 'option_value' => array('1' => $feeTotal),
2488 'option_name' => array('1' => $feeTotal),
2489 'option_weight' => array('1' => 1),
2490 'option_amount' => array('1' => 1),
2491 'is_display_amounts' => 1,
2493 'options_per_line' => 1,
2494 'is_active' => array('1' => 1),
2495 'price_set_id' => $this->_ids
['price_set'],
2496 'is_enter_qty' => 1,
2497 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2499 if ($type === 'Radio') {
2500 $paramsField['is_enter_qty'] = 0;
2501 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2502 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2504 CRM_Price_BAO_PriceField
::create($paramsField);
2505 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2506 $this->_ids
['price_field'] = array_keys($fields['values']);
2507 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2508 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2510 return $this->_ids
['price_set'];
2514 * Add a profile to a contribution page.
2516 * @param string $name
2517 * @param int $contributionPageID
2518 * @param string $module
2520 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2522 'uf_group_id' => $name,
2523 'module' => $module,
2524 'entity_table' => 'civicrm_contribution_page',
2525 'entity_id' => $contributionPageID,
2528 if ($module !== 'CiviContribute') {
2529 $params['module_data'] = [$module => []];
2531 $this->callAPISuccess('UFJoin', 'create', $params);
2535 * Add participant with contribution
2539 protected function createParticipantWithContribution() {
2540 // creating price set, price field
2541 $this->_contactId
= $this->individualCreate();
2542 $event = $this->eventCreate();
2543 $this->_eventId
= $event['id'];
2544 $eventParams = array(
2545 'id' => $this->_eventId
,
2546 'financial_type_id' => 4,
2549 $this->callAPISuccess('event', 'create', $eventParams);
2550 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2551 $participantParams = array(
2552 'financial_type_id' => 4,
2553 'event_id' => $this->_eventId
,
2556 'fee_currency' => 'USD',
2557 'contact_id' => $this->_contactId
,
2559 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2560 $contributionParams = array(
2561 'total_amount' => 150,
2562 'currency' => 'USD',
2563 'contact_id' => $this->_contactId
,
2564 'financial_type_id' => 4,
2565 'contribution_status_id' => 1,
2566 'partial_payment_total' => 300.00,
2567 'partial_amount_to_pay' => 150,
2568 'contribution_mode' => 'participant',
2569 'participant_id' => $participant['id'],
2571 foreach ($priceFields['values'] as $key => $priceField) {
2572 $lineItems[1][$key] = array(
2573 'price_field_id' => $priceField['price_field_id'],
2574 'price_field_value_id' => $priceField['id'],
2575 'label' => $priceField['label'],
2576 'field_title' => $priceField['label'],
2578 'unit_price' => $priceField['amount'],
2579 'line_total' => $priceField['amount'],
2580 'financial_type_id' => $priceField['financial_type_id'],
2583 $contributionParams['line_item'] = $lineItems;
2584 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2585 $paymentParticipant = array(
2586 'participant_id' => $participant['id'],
2587 'contribution_id' => $contribution['id'],
2589 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2590 return array($lineItems, $contribution);
2596 * @param string $component
2597 * @param int $componentId
2598 * @param array $priceFieldOptions
2602 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2603 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2604 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2605 $paramsSet['is_active'] = TRUE;
2606 $paramsSet['financial_type_id'] = 'Event Fee';
2607 $paramsSet['extends'] = 1;
2608 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2609 $priceSetId = $priceSet['id'];
2610 //Checking for priceset added in the table.
2611 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2612 'id', $paramsSet['title'], 'Check DB for created priceset'
2614 $paramsField = array_merge(array(
2615 'label' => 'Price Field',
2616 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2617 'html_type' => 'CheckBox',
2618 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2619 'option_value' => array('1' => 100, '2' => 200),
2620 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2621 'option_weight' => array('1' => 1, '2' => 2),
2622 'option_amount' => array('1' => 100, '2' => 200),
2623 'is_display_amounts' => 1,
2625 'options_per_line' => 1,
2626 'is_active' => array('1' => 1, '2' => 1),
2627 'price_set_id' => $priceSet['id'],
2628 'is_enter_qty' => 1,
2629 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2630 ), $priceFieldOptions);
2632 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2634 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2636 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2640 * Replace the template with a test-oriented template designed to show all the variables.
2642 * @param string $templateName
2644 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2645 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2646 CRM_Core_DAO
::executeQuery(
2647 "UPDATE civicrm_option_group og
2648 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2649 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2650 SET m.msg_html = '{$testTemplate}'
2651 WHERE og.name = 'msg_tpl_workflow_contribution'
2652 AND ov.name = '{$templateName}'
2653 AND m.is_default = 1"
2658 * Reinstate the default template.
2660 * @param string $templateName
2662 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2663 CRM_Core_DAO
::executeQuery(
2664 "UPDATE civicrm_option_group og
2665 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2666 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2667 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2668 SET m.msg_html = m2.msg_html
2669 WHERE og.name = 'msg_tpl_workflow_contribution'
2670 AND ov.name = '{$templateName}'
2671 AND m.is_default = 1"
2676 * Flush statics relating to financial type.
2678 protected function flushFinancialTypeStatics() {
2679 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2680 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2682 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2683 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2685 CRM_Contribute_PseudoConstant
::flush('financialType');
2686 CRM_Contribute_PseudoConstant
::flush('membershipType');
2687 // Pseudoconstants may be saved to the cache table.
2688 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2689 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2690 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2694 * Set the permissions to the supplied array.
2696 * @param array $permissions
2698 protected function setPermissions($permissions) {
2699 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2700 $this->flushFinancialTypeStatics();
2704 * @param array $params
2707 public function _checkFinancialRecords($params, $context) {
2708 $entityParams = array(
2709 'entity_id' => $params['id'],
2710 'entity_table' => 'civicrm_contribution',
2712 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2713 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2714 if ($context == 'pending') {
2715 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2716 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2719 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2720 $trxnParams = array(
2721 'id' => $trxn['financial_trxn_id'],
2723 if ($context != 'online' && $context != 'payLater') {
2724 $compareParams = array(
2725 'to_financial_account_id' => 6,
2726 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2730 if ($context == 'feeAmount') {
2731 $compareParams['fee_amount'] = 50;
2733 elseif ($context == 'online') {
2734 $compareParams = array(
2735 'to_financial_account_id' => 12,
2736 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2738 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2741 elseif ($context == 'payLater') {
2742 $compareParams = array(
2743 'to_financial_account_id' => 7,
2744 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2748 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2749 $entityParams = array(
2750 'financial_trxn_id' => $trxn['financial_trxn_id'],
2751 'entity_table' => 'civicrm_financial_item',
2753 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2754 $fitemParams = array(
2755 'id' => $entityTrxn['entity_id'],
2757 $compareParams = array(
2758 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2760 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2762 if ($context == 'payLater') {
2763 $compareParams = array(
2764 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2766 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2769 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2770 if ($context == 'feeAmount') {
2772 'entity_id' => $params['id'],
2773 'entity_table' => 'civicrm_contribution',
2775 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2776 $trxnParams = array(
2777 'id' => $maxTrxn['financial_trxn_id'],
2779 $compareParams = array(
2780 'to_financial_account_id' => 5,
2781 'from_financial_account_id' => 6,
2782 'total_amount' => 50,
2785 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2786 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2787 $fitemParams = array(
2788 'entity_id' => $trxnId['financialTrxnId'],
2789 'entity_table' => 'civicrm_financial_trxn',
2791 $compareParams = array(
2794 'financial_account_id' => 5,
2796 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2798 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2799 // line should be copied into all the functions that call this function & evaluated there
2800 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2801 // when calling completeTransaction or repeatTransaction.
2802 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2806 * Return financial type id on basis of name
2808 * @param string $name Financial type m/c name
2812 public function getFinancialTypeId($name) {
2813 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2817 * Cleanup function for contents of $this->ids.
2819 * This is a best effort cleanup to use in tear downs etc.
2821 * It will not fail if the data has already been removed (some tests may do
2822 * their own cleanup).
2824 protected function cleanUpSetUpIDs() {
2825 foreach ($this->setupIDs
as $entity => $id) {
2827 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2829 catch (CiviCRM_API3_Exception
$e) {
2830 // This is a best-effort cleanup function, ignore.
2836 * Create Financial Type.
2838 * @param array $params
2842 protected function createFinancialType($params = array()) {
2843 $params = array_merge($params,
2845 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2849 return $this->callAPISuccess('FinancialType', 'create', $params);
2853 * Create Payment Instrument.
2855 * @param array $params
2856 * @param string $financialAccountName
2860 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2861 $params = array_merge(array(
2862 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2863 'option_group_id' => 'payment_instrument',
2866 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2868 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2870 $financialAccountParams = [
2871 'entity_table' => 'civicrm_option_value',
2872 'entity_id' => $newPaymentInstrument,
2873 'account_relationship' => $relationTypeID,
2874 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2876 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2878 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2882 * Enable Tax and Invoicing
2884 protected function enableTaxAndInvoicing($params = array()) {
2885 // Enable component contribute setting
2886 $contributeSetting = array_merge($params,
2889 'invoice_prefix' => 'INV_',
2890 'credit_notes_prefix' => 'CN_',
2892 'due_date_period' => 'days',
2894 'is_email_pdf' => 1,
2895 'tax_term' => 'Sales Tax',
2896 'tax_display_settings' => 'Inclusive',
2899 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2903 * Enable Tax and Invoicing
2905 protected function disableTaxAndInvoicing($params = array()) {
2906 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2907 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2909 // Enable component contribute setting
2910 $contributeSetting = array_merge($params,
2915 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2919 * Add Sales Tax relation for financial type with financial account.
2921 * @param int $financialTypeId
2925 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2927 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2928 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2929 'is_deductible' => 1,
2934 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
2935 $entityParams = array(
2936 'entity_table' => 'civicrm_financial_type',
2937 'entity_id' => $financialTypeId,
2938 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
2941 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
2942 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
2944 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
2945 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
2946 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
2947 $dao->copyValues($entityParams);
2949 if ($dao->fetch()) {
2950 $entityParams['id'] = $dao->id
;
2952 $entityParams['financial_account_id'] = $account->id
;
2954 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
2958 * Create price set with contribution test for test setup.
2960 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
2961 * on parent class at some point (fn is not in 4.4).
2964 * @param array $params
2966 public function createPriceSetWithPage($entity = NULL, $params = array()) {
2967 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
2968 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
2969 'title' => "Test Contribution Page",
2970 'financial_type_id' => 1,
2971 'currency' => 'NZD',
2972 'goal_amount' => 50,
2973 'is_pay_later' => 1,
2974 'is_monetary' => TRUE,
2975 'is_email_receipt' => FALSE,
2977 $priceSet = $this->callAPISuccess('price_set', 'create', array(
2978 'is_quick_config' => 0,
2979 'extends' => 'CiviMember',
2980 'financial_type_id' => 1,
2981 'title' => 'my Page',
2983 $priceSetID = $priceSet['id'];
2985 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
2986 $priceField = $this->callAPISuccess('price_field', 'create', array(
2987 'price_set_id' => $priceSetID,
2988 'label' => 'Goat Breed',
2989 'html_type' => 'Radio',
2991 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
2992 'price_set_id' => $priceSetID,
2993 'price_field_id' => $priceField['id'],
2994 'label' => 'Long Haired Goat',
2996 'financial_type_id' => 'Donation',
2997 'membership_type_id' => $membershipTypeID,
2998 'membership_num_terms' => 1,
3000 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3001 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3002 'price_set_id' => $priceSetID,
3003 'price_field_id' => $priceField['id'],
3004 'label' => 'Shoe-eating Goat',
3006 'financial_type_id' => 'Donation',
3007 'membership_type_id' => $membershipTypeID,
3008 'membership_num_terms' => 2,
3010 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3012 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3013 'price_set_id' => $priceSetID,
3014 'price_field_id' => $priceField['id'],
3015 'label' => 'Shoe-eating Goat',
3017 'financial_type_id' => 'Donation',
3019 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3021 $this->_ids
['price_set'] = $priceSetID;
3022 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3023 $this->_ids
['price_field'] = array($priceField['id']);
3025 $this->_ids
['membership_type'] = $membershipTypeID;
3029 * Only specified contact returned.
3030 * @implements CRM_Utils_Hook::aclWhereClause
3033 * @param $whereTables
3037 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3038 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3042 * @implements CRM_Utils_Hook::selectWhereClause
3044 * @param string $entity
3045 * @param array $clauses
3047 public function selectWhereClauseHook($entity, &$clauses) {
3048 if ($entity == 'Event') {
3049 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3054 * An implementation of hook_civicrm_post used with all our test cases.
3057 * @param string $objectName
3058 * @param int $objectId
3061 public function onPost($op, $objectName, $objectId, &$objectRef) {
3062 if ($op == 'create' && $objectName == 'Individual') {
3063 CRM_Core_DAO
::executeQuery(
3064 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3066 1 => array($objectId, 'Integer'),
3071 if ($op == 'edit' && $objectName == 'Participant') {
3073 1 => array($objectId, 'Integer'),
3075 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3076 CRM_Core_DAO
::executeQuery($query, $params);
3081 * Instantiate form object.
3083 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3085 * @param string $class
3086 * Name of form class.
3088 * @return \CRM_Core_Form
3090 public function getFormObject($class) {
3091 $form = new $class();
3092 $_SERVER['REQUEST_METHOD'] = 'GET';
3093 $form->controller
= new CRM_Core_Controller();
3098 * Get possible thousand separators.
3102 public function getThousandSeparators() {
3103 return array(array('.'), array(','));
3107 * Set the separators for thousands and decimal points.
3109 * @param string $thousandSeparator
3111 protected function setCurrencySeparators($thousandSeparator) {
3112 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3114 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3118 * Format money as it would be input.
3120 * @param string $amount
3124 protected function formatMoneyInput($amount) {
3125 return CRM_Utils_Money
::format($amount, NULL, '%a');
3129 * Get the contribution object.
3131 * @param int $contributionID
3133 * @return \CRM_Contribute_BAO_Contribution
3135 protected function getContributionObject($contributionID) {
3136 $contributionObj = new CRM_Contribute_BAO_Contribution();
3137 $contributionObj->id
= $contributionID;
3138 $contributionObj->find(TRUE);
3139 return $contributionObj;
3143 * Enable multilingual.
3145 public function enableMultilingual() {
3146 $this->callAPISuccess('Setting', 'create', array(
3147 'lcMessages' => 'en_US',
3148 'languageLimit' => array(
3153 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3156 $dbLocale = '_en_US';