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 bool 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 bool 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 * Array of IDs created to support the test.
125 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
132 * Class used for hooks during tests.
134 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
136 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
138 * @var CRM_Utils_Hook_UnitTests hookClass
140 public $hookClass = NULL;
143 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
145 protected $_params = array();
148 * @var CRM_Extension_System
150 protected $origExtensionSystem;
153 * Array of IDs created during test setup routine.
155 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
159 public $setupIDs = array();
162 * PHPUnit Mock Method to use.
166 public $mockMethod = 'getMock';
171 * Because we are overriding the parent class constructor, we
172 * need to show the same arguments as exist in the constructor of
173 * PHPUnit_Framework_TestCase, since
174 * PHPUnit_Framework_TestSuite::createTest() creates a
175 * ReflectionClass of the Test class and checks the constructor
176 * of that class to decide how to set up the test.
178 * @param string $name
180 * @param string $dataName
182 public function __construct($name = NULL, array $data = array(), $dataName = '') {
183 parent
::__construct($name, $data, $dataName);
185 // we need full error reporting
186 error_reporting(E_ALL
& ~E_NOTICE
);
188 self
::$_dbName = self
::getDBName();
190 // also load the class loader
191 require_once 'CRM/Core/ClassLoader.php';
192 CRM_Core_ClassLoader
::singleton()->register();
193 if (function_exists('_civix_phpunit_setUp')) {
194 // FIXME: loosen coupling
195 _civix_phpunit_setUp();
197 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
198 $this->mockMethod
= 'createMock';
203 * Override to run the test and assert its state.
206 * @throws \PHPUnit_Framework_IncompleteTest
207 * @throws \PHPUnit_Framework_SkippedTest
209 protected function runTest() {
211 return parent
::runTest();
213 catch (PEAR_Exception
$e) {
214 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
215 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
222 public function requireDBReset() {
223 return $this->DBResetRequired
;
229 public static function getDBName() {
230 static $dbName = NULL;
231 if ($dbName === NULL) {
232 require_once "DB.php";
233 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
234 $dbName = $dsninfo['database'];
240 * Create database connection for this instance.
242 * Initialize the test database if it hasn't been initialized
244 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
246 protected function getConnection() {
247 $dbName = self
::$_dbName;
248 if (!self
::$dbInit) {
249 $dbName = self
::getDBName();
251 // install test database
252 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
254 static::_populateDB(FALSE, $this);
256 self
::$dbInit = TRUE;
259 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
263 * Required implementation of abstract method.
265 protected function getDataSet() {
269 * @param bool $perClass
270 * @param null $object
272 * TRUE if the populate logic runs; FALSE if it is skipped
274 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
275 if (CIVICRM_UF
!== 'UnitTests') {
276 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
279 if ($perClass ||
$object == NULL) {
283 $dbreset = $object->requireDBReset();
286 if (self
::$populateOnce ||
!$dbreset) {
289 self
::$populateOnce = NULL;
291 Civi\Test
::data()->populate();
296 public static function setUpBeforeClass() {
297 static::_populateDB(TRUE);
299 // also set this global hack
300 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
304 * Common setup functions for all unit tests.
306 protected function setUp() {
307 $session = CRM_Core_Session
::singleton();
308 $session->set('userID', NULL);
311 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
312 // Use a temporary file for STDIN
313 $GLOBALS['stdin'] = tmpfile();
314 if ($GLOBALS['stdin'] === FALSE) {
315 echo "Couldn't open temporary file\n";
319 // Get and save a connection to the database
320 $this->_dbconn
= $this->getConnection();
322 // reload database before each test
323 // $this->_populateDB();
325 // "initialize" CiviCRM to avoid problems when running single tests
326 // FIXME: look at it closer in second stage
328 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
329 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
331 // disable any left-over test extensions
332 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
334 $extensions = \CRM_Extension_System
::singleton()->getManager();
335 $api4Status = $extensions->getStatus('org.civicrm.api4');
336 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
337 $extensions->enable(['org.civicrm.api4']);
340 // reset all the caches
341 CRM_Utils_System
::flushCache();
343 // initialize the object once db is loaded
346 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
348 // when running unit tests, use mockup user framework
349 $this->hookClass
= CRM_Utils_Hook
::singleton();
351 // Make sure the DB connection is setup properly
352 $config->userSystem
->setMySQLTimeZone();
353 $env = new CRM_Utils_Check_Component_Env();
354 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
356 // clear permissions stub to not check permissions
357 $config->userPermissionClass
->permissions
= NULL;
359 //flush component settings
360 CRM_Core_Component
::getEnabledComponents(TRUE);
362 $_REQUEST = $_GET = $_POST = [];
363 error_reporting(E_ALL
);
365 $this->_sethtmlGlobals();
369 * Read everything from the datasets directory and insert into the db.
371 public function loadAllFixtures() {
372 $fixturesDir = __DIR__
. '/../../fixtures';
374 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
376 $yamlFiles = glob($fixturesDir . '/*.yaml');
377 foreach ($yamlFiles as $yamlFixture) {
378 $op = new PHPUnit_Extensions_Database_Operation_Insert();
379 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
380 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
381 $op->execute($this->_dbconn
, $dataset);
384 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
388 * Create default domain contacts for the two domains added during test class.
389 * database population.
391 public function createDomainContacts() {
392 $this->organizationCreate();
393 $this->organizationCreate(array('organization_name' => 'Second Domain'));
397 * Common teardown functions for all unit tests.
399 protected function tearDown() {
400 error_reporting(E_ALL
& ~E_NOTICE
);
401 CRM_Utils_Hook
::singleton()->reset();
402 if ($this->hookClass
) {
403 $this->hookClass
->reset();
405 CRM_Core_Session
::singleton()->reset(1);
408 $this->tx
->rollback()->commit();
411 CRM_Core_Transaction
::forceRollbackIfEnabled();
412 \Civi\Core\Transaction\Manager
::singleton(TRUE);
415 CRM_Core_Transaction
::forceRollbackIfEnabled();
416 \Civi\Core\Transaction\Manager
::singleton(TRUE);
418 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
419 $this->quickCleanup($tablesToTruncate);
420 $this->createDomainContacts();
423 $this->cleanTempDirs();
424 $this->unsetExtensionSystem();
428 * Create a batch of external API calls which can
429 * be executed concurrently.
432 * $calls = $this->createExternalAPI()
433 * ->addCall('Contact', 'get', ...)
434 * ->addCall('Contact', 'get', ...)
440 * @return \Civi\API\ExternalBatch
441 * @throws PHPUnit_Framework_SkippedTestError
443 public function createExternalAPI() {
444 global $civicrm_root;
445 $defaultParams = array(
446 'version' => $this->_apiversion
,
450 $calls = new \Civi\API\
ExternalBatch($defaultParams);
452 if (!$calls->isSupported()) {
453 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
460 * Create required data based on $this->entity & $this->params
461 * This is just a way to set up the test data for delete & get functions
462 * so the distinction between set
463 * up & tested functions is clearer
468 public function createTestEntity() {
469 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
473 * @param int $contactTypeId
477 public function contactTypeDelete($contactTypeId) {
478 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
480 throw new Exception('Could not delete contact type');
485 * @param array $params
489 public function membershipTypeCreate($params = array()) {
490 CRM_Member_PseudoConstant
::flush('membershipType');
491 CRM_Core_Config
::clearDBCache();
492 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
493 $params = array_merge(array(
495 'duration_unit' => 'year',
496 'duration_interval' => 1,
497 'period_type' => 'rolling',
498 'member_of_contact_id' => $memberOfOrganization,
500 'financial_type_id' => 2,
503 'visibility' => 'Public',
506 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
508 CRM_Member_PseudoConstant
::flush('membershipType');
509 CRM_Utils_Cache
::singleton()->flush();
511 return $result['id'];
515 * @param array $params
519 public function contactMembershipCreate($params) {
520 $params = array_merge(array(
521 'join_date' => '2007-01-21',
522 'start_date' => '2007-01-21',
523 'end_date' => '2007-12-21',
524 'source' => 'Payment',
525 'membership_type_id' => 'General',
527 if (!is_numeric($params['membership_type_id'])) {
528 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
529 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
530 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
534 $result = $this->callAPISuccess('Membership', 'create', $params);
535 return $result['id'];
539 * Delete Membership Type.
541 * @param array $params
543 public function membershipTypeDelete($params) {
544 $this->callAPISuccess('MembershipType', 'Delete', $params);
548 * @param int $membershipID
550 public function membershipDelete($membershipID) {
551 $deleteParams = array('id' => $membershipID);
552 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
556 * @param string $name
560 public function membershipStatusCreate($name = 'test member status') {
561 $params['name'] = $name;
562 $params['start_event'] = 'start_date';
563 $params['end_event'] = 'end_date';
564 $params['is_current_member'] = 1;
565 $params['is_active'] = 1;
567 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
568 CRM_Member_PseudoConstant
::flush('membershipStatus');
569 return $result['id'];
573 * @param int $membershipStatusID
575 public function membershipStatusDelete($membershipStatusID) {
576 if (!$membershipStatusID) {
579 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
582 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
583 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
584 $renewedMembershipEndDate = new DateTime($membershipEndDate);
585 switch ($durationUnit) {
587 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
591 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
592 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
593 $renewedMembershipEndDate->add(new DateInterval('P1D'));
594 $renewedMembershipEndDate->add(new DateInterval('P1M'));
595 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
598 return $renewedMembershipEndDate->format('Y-m-d');
602 * @param array $params
606 public function relationshipTypeCreate($params = array()) {
607 $params = array_merge(array(
608 'name_a_b' => 'Relation 1 for relationship type create',
609 'name_b_a' => 'Relation 2 for relationship type create',
610 'contact_type_a' => 'Individual',
611 'contact_type_b' => 'Organization',
616 $result = $this->callAPISuccess('relationship_type', 'create', $params);
617 CRM_Core_PseudoConstant
::flush('relationshipType');
619 return $result['id'];
623 * Delete Relatinship Type.
625 * @param int $relationshipTypeID
627 public function relationshipTypeDelete($relationshipTypeID) {
628 $params['id'] = $relationshipTypeID;
629 $check = $this->callAPISuccess('relationship_type', 'get', $params);
630 if (!empty($check['count'])) {
631 $this->callAPISuccess('relationship_type', 'delete', $params);
636 * @param array $params
640 public function paymentProcessorTypeCreate($params = NULL) {
641 if (is_null($params)) {
643 'name' => 'API_Test_PP',
644 'title' => 'API Test Payment Processor',
645 'class_name' => 'CRM_Core_Payment_APITest',
646 'billing_mode' => 'form',
652 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
654 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
656 return $result['id'];
660 * Create test Authorize.net instance.
662 * @param array $params
666 public function paymentProcessorAuthorizeNetCreate($params = array()) {
667 $params = array_merge(array(
668 'name' => 'Authorize',
669 'domain_id' => CRM_Core_Config
::domainID(),
670 'payment_processor_type_id' => 'AuthNet',
671 'title' => 'AuthNet',
676 'user_name' => '4y5BfuW7jm',
677 'password' => '4cAmW927n8uLf5J8',
678 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
679 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
680 'class_name' => 'Payment_AuthorizeNet',
684 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
685 return $result['id'];
689 * Create Participant.
691 * @param array $params
692 * Array of contact id and event id values.
695 * $id of participant created
697 public function participantCreate($params = []) {
698 if (empty($params['contact_id'])) {
699 $params['contact_id'] = $this->individualCreate();
701 if (empty($params['event_id'])) {
702 $event = $this->eventCreate();
703 $params['event_id'] = $event['id'];
708 'register_date' => 20070219,
709 'source' => 'Wimbeldon',
710 'event_level' => 'Payment',
714 $params = array_merge($defaults, $params);
715 $result = $this->callAPISuccess('Participant', 'create', $params);
716 return $result['id'];
720 * Create Payment Processor.
723 * Id Payment Processor
725 public function processorCreate($params = array()) {
726 $processorParams = array(
729 'payment_processor_type_id' => 'Dummy',
730 'financial_account_id' => 12,
734 'url_site' => 'http://dummy.com',
735 'url_recur' => 'http://dummy.com',
738 'payment_instrument_id' => 'Debit Card',
740 $processorParams = array_merge($processorParams, $params);
741 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
742 return $processor['id'];
746 * Create Payment Processor.
748 * @param array $processorParams
750 * @return \CRM_Core_Payment_Dummy
751 * Instance of Dummy Payment Processor
753 public function dummyProcessorCreate($processorParams = array()) {
754 $paymentProcessorID = $this->processorCreate($processorParams);
755 return System
::singleton()->getById($paymentProcessorID);
759 * Create contribution page.
761 * @param array $params
763 * Array of contribution page
765 public function contributionPageCreate($params = array()) {
766 $this->_pageParams
= array_merge(array(
767 'title' => 'Test Contribution Page',
768 'financial_type_id' => 1,
770 'financial_account_id' => 1,
772 'is_allow_other_amount' => 1,
774 'max_amount' => 1000,
776 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
780 * Create a sample batch.
782 public function batchCreate() {
783 $params = $this->_params
;
784 $params['name'] = $params['title'] = 'Batch_433397';
785 $params['status_id'] = 1;
786 $result = $this->callAPISuccess('batch', 'create', $params);
787 return $result['id'];
793 * @param array $params
795 * result of created tag
797 public function tagCreate($params = array()) {
799 'name' => 'New Tag3',
800 'description' => 'This is description for Our New Tag ',
803 $params = array_merge($defaults, $params);
804 $result = $this->callAPISuccess('Tag', 'create', $params);
805 return $result['values'][$result['id']];
812 * Id of the tag to be deleted.
816 public function tagDelete($tagId) {
817 require_once 'api/api.php';
821 $result = $this->callAPISuccess('Tag', 'delete', $params);
822 return $result['id'];
826 * Add entity(s) to the tag
828 * @param array $params
832 public function entityTagAdd($params) {
833 $result = $this->callAPISuccess('entity_tag', 'create', $params);
840 * @param array $params
844 * id of created pledge
846 public function pledgeCreate($params) {
847 $params = array_merge(array(
848 'pledge_create_date' => date('Ymd'),
849 'start_date' => date('Ymd'),
850 'scheduled_date' => date('Ymd'),
852 'pledge_status_id' => '2',
853 'financial_type_id' => '1',
854 'pledge_original_installment_amount' => 20,
855 'frequency_interval' => 5,
856 'frequency_unit' => 'year',
857 'frequency_day' => 15,
862 $result = $this->callAPISuccess('Pledge', 'create', $params);
863 return $result['id'];
867 * Delete contribution.
869 * @param int $pledgeId
871 public function pledgeDelete($pledgeId) {
873 'pledge_id' => $pledgeId,
875 $this->callAPISuccess('Pledge', 'delete', $params);
879 * Create contribution.
881 * @param array $params
882 * Array of parameters.
885 * id of created contribution
887 public function contributionCreate($params) {
889 $params = array_merge(array(
891 'receive_date' => date('Ymd'),
892 'total_amount' => 100.00,
893 'fee_amount' => 5.00,
894 'financial_type_id' => 1,
895 'payment_instrument_id' => 1,
896 'non_deductible_amount' => 10.00,
898 'contribution_status_id' => 1,
901 $result = $this->callAPISuccess('contribution', 'create', $params);
902 return $result['id'];
906 * Delete contribution.
908 * @param int $contributionId
912 public function contributionDelete($contributionId) {
914 'contribution_id' => $contributionId,
916 $result = $this->callAPISuccess('contribution', 'delete', $params);
923 * @param array $params
924 * Name-value pair for an event.
928 public function eventCreate($params = array()) {
929 // if no contact was passed, make up a dummy event creator
930 if (!isset($params['contact_id'])) {
931 $params['contact_id'] = $this->_contactCreate(array(
932 'contact_type' => 'Individual',
933 'first_name' => 'Event',
934 'last_name' => 'Creator',
938 // set defaults for missing params
939 $params = array_merge(array(
940 'title' => 'Annual CiviCRM meet',
941 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
942 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
943 'event_type_id' => 1,
945 'start_date' => 20081021,
946 'end_date' => 20081023,
947 'is_online_registration' => 1,
948 'registration_start_date' => 20080601,
949 'registration_end_date' => 20081015,
950 'max_participants' => 100,
951 'event_full_text' => 'Sorry! We are already full',
954 'is_show_location' => 0,
957 return $this->callAPISuccess('Event', 'create', $params);
961 * Create a paid event.
963 * @param array $params
967 protected function eventCreatePaid($params) {
968 $event = $this->eventCreate($params);
969 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
970 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
971 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
972 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
973 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
985 public function eventDelete($id) {
989 return $this->callAPISuccess('event', 'delete', $params);
993 * Delete participant.
995 * @param int $participantID
999 public function participantDelete($participantID) {
1001 'id' => $participantID,
1003 $check = $this->callAPISuccess('Participant', 'get', $params);
1004 if ($check['count'] > 0) {
1005 return $this->callAPISuccess('Participant', 'delete', $params);
1010 * Create participant payment.
1012 * @param int $participantID
1013 * @param int $contributionID
1015 * $id of created payment
1017 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1018 //Create Participant Payment record With Values
1020 'participant_id' => $participantID,
1021 'contribution_id' => $contributionID,
1024 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1025 return $result['id'];
1029 * Delete participant payment.
1031 * @param int $paymentID
1033 public function participantPaymentDelete($paymentID) {
1037 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1043 * @param int $contactID
1045 * location id of created location
1047 public function locationAdd($contactID) {
1050 'location_type' => 'New Location Type',
1052 'name' => 'Saint Helier St',
1053 'county' => 'Marin',
1054 'country' => 'UNITED STATES',
1055 'state_province' => 'Michigan',
1056 'supplemental_address_1' => 'Hallmark Ct',
1057 'supplemental_address_2' => 'Jersey Village',
1058 'supplemental_address_3' => 'My Town',
1063 'contact_id' => $contactID,
1064 'address' => $address,
1065 'location_format' => '2.0',
1066 'location_type' => 'New Location Type',
1069 $result = $this->callAPISuccess('Location', 'create', $params);
1074 * Delete Locations of contact.
1076 * @param array $params
1079 public function locationDelete($params) {
1080 $this->callAPISuccess('Location', 'delete', $params);
1084 * Add a Location Type.
1086 * @param array $params
1087 * @return CRM_Core_DAO_LocationType
1088 * location id of created location
1090 public function locationTypeCreate($params = NULL) {
1091 if ($params === NULL) {
1093 'name' => 'New Location Type',
1094 'vcard_name' => 'New Location Type',
1095 'description' => 'Location Type for Delete',
1100 $locationType = new CRM_Core_DAO_LocationType();
1101 $locationType->copyValues($params);
1102 $locationType->save();
1103 // clear getfields cache
1104 CRM_Core_PseudoConstant
::flush();
1105 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1106 return $locationType;
1110 * Delete a Location Type.
1112 * @param int $locationTypeId
1114 public function locationTypeDelete($locationTypeId) {
1115 $locationType = new CRM_Core_DAO_LocationType();
1116 $locationType->id
= $locationTypeId;
1117 $locationType->delete();
1123 * @param array $params
1124 * @return CRM_Core_DAO_Mapping
1125 * Mapping id of created mapping
1127 public function mappingCreate($params = NULL) {
1128 if ($params === NULL) {
1130 'name' => 'Mapping name',
1131 'description' => 'Mapping description',
1132 // 'Export Contact' mapping.
1133 'mapping_type_id' => 7,
1137 $mapping = new CRM_Core_DAO_Mapping();
1138 $mapping->copyValues($params);
1140 // clear getfields cache
1141 CRM_Core_PseudoConstant
::flush();
1142 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1149 * @param int $mappingId
1151 public function mappingDelete($mappingId) {
1152 $mapping = new CRM_Core_DAO_Mapping();
1153 $mapping->id
= $mappingId;
1158 * Prepare class for ACLs.
1160 protected function prepareForACLs() {
1161 $config = CRM_Core_Config
::singleton();
1162 $config->userPermissionClass
->permissions
= array();
1168 protected function cleanUpAfterACLs() {
1169 CRM_Utils_Hook
::singleton()->reset();
1170 $tablesToTruncate = array(
1172 'civicrm_acl_cache',
1173 'civicrm_acl_entity_role',
1174 'civicrm_acl_contact_cache',
1176 $this->quickCleanup($tablesToTruncate);
1177 $config = CRM_Core_Config
::singleton();
1178 unset($config->userPermissionClass
->permissions
);
1182 * Create a smart group.
1184 * By default it will be a group of households.
1186 * @param array $smartGroupParams
1187 * @param array $groupParams
1190 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1191 $smartGroupParams = array_merge(array(
1192 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1195 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1197 $groupParams['saved_search_id'] = $savedSearch->id
;
1198 return $this->groupCreate($groupParams);
1203 * @param array $params
1205 public function uFFieldCreate($params = array()) {
1206 $params = array_merge(array(
1208 'field_name' => 'first_name',
1211 'visibility' => 'Public Pages and Listings',
1212 'is_searchable' => '1',
1213 'label' => 'first_name',
1214 'field_type' => 'Individual',
1217 $this->callAPISuccess('uf_field', 'create', $params);
1221 * Add a UF Join Entry.
1223 * @param array $params
1225 * $id of created UF Join
1227 public function ufjoinCreate($params = NULL) {
1228 if ($params === NULL) {
1231 'module' => 'CiviEvent',
1232 'entity_table' => 'civicrm_event',
1238 $result = $this->callAPISuccess('uf_join', 'create', $params);
1243 * @param array $params
1244 * Optional parameters.
1245 * @param bool $reloadConfig
1246 * While enabling CiviCampaign component, we shouldn't always forcibly
1247 * reload config as this hinder hook call in test environment
1252 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1253 $this->enableCiviCampaign($reloadConfig);
1254 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1255 'name' => 'big_campaign',
1256 'title' => 'Campaign',
1258 return $campaign['id'];
1262 * Create Group for a contact.
1264 * @param int $contactId
1266 public function contactGroupCreate($contactId) {
1268 'contact_id.1' => $contactId,
1272 $this->callAPISuccess('GroupContact', 'Create', $params);
1276 * Delete Group for a contact.
1278 * @param int $contactId
1280 public function contactGroupDelete($contactId) {
1282 'contact_id.1' => $contactId,
1285 $this->civicrm_api('GroupContact', 'Delete', $params);
1291 * @param array $params
1294 public function activityCreate($params = array()) {
1295 $params = array_merge(array(
1296 'subject' => 'Discussion on warm beer',
1297 'activity_date_time' => date('Ymd'),
1298 'duration_hours' => 30,
1299 'duration_minutes' => 20,
1300 'location' => 'Baker Street',
1301 'details' => 'Lets schedule a meeting',
1303 'activity_type_id' => 'Meeting',
1305 if (!isset($params['source_contact_id'])) {
1306 $params['source_contact_id'] = $this->individualCreate();
1308 if (!isset($params['target_contact_id'])) {
1309 $params['target_contact_id'] = $this->individualCreate(array(
1310 'first_name' => 'Julia',
1311 'Last_name' => 'Anderson',
1313 'email' => 'julia_anderson@civicrm.org',
1314 'contact_type' => 'Individual',
1317 if (!isset($params['assignee_contact_id'])) {
1318 $params['assignee_contact_id'] = $params['target_contact_id'];
1321 $result = $this->callAPISuccess('Activity', 'create', $params);
1323 $result['target_contact_id'] = $params['target_contact_id'];
1324 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1329 * Create an activity type.
1331 * @param array $params
1335 public function activityTypeCreate($params) {
1336 return $this->callAPISuccess('ActivityType', 'create', $params);
1340 * Delete activity type.
1342 * @param int $activityTypeId
1343 * Id of the activity type.
1346 public function activityTypeDelete($activityTypeId) {
1347 $params['activity_type_id'] = $activityTypeId;
1348 return $this->callAPISuccess('ActivityType', 'delete', $params);
1352 * Create custom group.
1354 * @param array $params
1357 public function customGroupCreate($params = array()) {
1359 'title' => 'new custom group',
1360 'extends' => 'Contact',
1362 'style' => 'Inline',
1366 $params = array_merge($defaults, $params);
1368 return $this->callAPISuccess('custom_group', 'create', $params);
1372 * Existing function doesn't allow params to be over-ridden so need a new one
1373 * this one allows you to only pass in the params you want to change
1374 * @param array $params
1377 public function CustomGroupCreateByParams($params = array()) {
1379 'title' => "API Custom Group",
1380 'extends' => 'Contact',
1382 'style' => 'Inline',
1385 $params = array_merge($defaults, $params);
1386 return $this->callAPISuccess('custom_group', 'create', $params);
1390 * Create custom group with multi fields.
1391 * @param array $params
1394 public function CustomGroupMultipleCreateByParams($params = array()) {
1399 $params = array_merge($defaults, $params);
1400 return $this->CustomGroupCreateByParams($params);
1404 * Create custom group with multi fields.
1405 * @param array $params
1408 public function CustomGroupMultipleCreateWithFields($params = array()) {
1409 // also need to pass on $params['custom_field'] if not set but not in place yet
1411 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1412 $ids['custom_group_id'] = $customGroup['id'];
1414 $customField = $this->customFieldCreate(array(
1415 'custom_group_id' => $ids['custom_group_id'],
1416 'label' => 'field_1' . $ids['custom_group_id'],
1420 $ids['custom_field_id'][] = $customField['id'];
1422 $customField = $this->customFieldCreate(array(
1423 'custom_group_id' => $ids['custom_group_id'],
1424 'default_value' => '',
1425 'label' => 'field_2' . $ids['custom_group_id'],
1428 $ids['custom_field_id'][] = $customField['id'];
1430 $customField = $this->customFieldCreate(array(
1431 'custom_group_id' => $ids['custom_group_id'],
1432 'default_value' => '',
1433 'label' => 'field_3' . $ids['custom_group_id'],
1436 $ids['custom_field_id'][] = $customField['id'];
1442 * Create a custom group with a single text custom field. See
1443 * participant:testCreateWithCustom for how to use this
1445 * @param string $function
1447 * @param string $filename
1451 * ids of created objects
1453 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1454 $params = array('title' => $function);
1455 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1456 $params['extends'] = $entity ?
$entity : 'Contact';
1457 $customGroup = $this->CustomGroupCreate($params);
1458 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1459 CRM_Core_PseudoConstant
::flush();
1461 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1465 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1466 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1468 * @param string $function
1470 * @param string $filename
1474 * ids of created objects
1476 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1477 $params = array('title' => $function);
1478 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1479 $params['extends'] = $entity ?
$entity : 'Contact';
1480 $customGroup = $this->CustomGroupCreate($params);
1481 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1482 CRM_Core_PseudoConstant
::flush();
1484 'defaultValue' => 'Default Value',
1485 'lowercasevalue' => 'Lowercase Value',
1486 1 => 'Integer Value',
1489 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1490 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1491 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1492 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1493 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1494 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1495 foreach ($options as $option_value => $option_label) {
1496 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1497 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1500 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);
1504 * Delete custom group.
1506 * @param int $customGroupID
1510 public function customGroupDelete($customGroupID) {
1511 $params['id'] = $customGroupID;
1512 return $this->callAPISuccess('custom_group', 'delete', $params);
1516 * Create custom field.
1518 * @param array $params
1519 * (custom_group_id) is required.
1522 public function customFieldCreate($params) {
1523 $params = array_merge(array(
1524 'label' => 'Custom Field',
1525 'data_type' => 'String',
1526 'html_type' => 'Text',
1527 'is_searchable' => 1,
1529 'default_value' => 'defaultValue',
1532 $result = $this->callAPISuccess('custom_field', 'create', $params);
1533 // these 2 functions are called with force to flush static caches
1534 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1535 CRM_Core_Component
::getEnabledComponents(1);
1540 * Delete custom field.
1542 * @param int $customFieldID
1546 public function customFieldDelete($customFieldID) {
1548 $params['id'] = $customFieldID;
1549 return $this->callAPISuccess('custom_field', 'delete', $params);
1558 public function noteCreate($cId) {
1560 'entity_table' => 'civicrm_contact',
1561 'entity_id' => $cId,
1562 'note' => 'hello I am testing Note',
1563 'contact_id' => $cId,
1564 'modified_date' => date('Ymd'),
1565 'subject' => 'Test Note',
1568 return $this->callAPISuccess('Note', 'create', $params);
1572 * Enable CiviCampaign Component.
1574 * @param bool $reloadConfig
1575 * Force relaod config or not
1577 public function enableCiviCampaign($reloadConfig = TRUE) {
1578 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1579 if ($reloadConfig) {
1580 // force reload of config object
1581 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1583 //flush cache by calling with reset
1584 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1588 * Create custom field with Option Values.
1590 * @param array $customGroup
1591 * @param string $name
1592 * Name of custom field.
1593 * @param array $extraParams
1594 * Additional parameters to pass through.
1598 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1599 $fieldParams = array(
1600 'custom_group_id' => $customGroup['id'],
1601 'name' => 'test_custom_group',
1602 'label' => 'Country',
1603 'html_type' => 'Select',
1604 'data_type' => 'String',
1607 'is_searchable' => 0,
1611 $optionGroup = array(
1613 'name' => 'option_group1',
1614 'label' => 'option_group_label1',
1617 $optionValue = array(
1618 'option_label' => array('Label1', 'Label2'),
1619 'option_value' => array('value1', 'value2'),
1620 'option_name' => array($name . '_1', $name . '_2'),
1621 'option_weight' => array(1, 2),
1622 'option_status' => 1,
1625 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1627 return $this->callAPISuccess('custom_field', 'create', $params);
1635 public function confirmEntitiesDeleted($entities) {
1636 foreach ($entities as $entity) {
1638 $result = $this->callAPISuccess($entity, 'Get', array());
1639 if ($result['error'] == 1 ||
$result['count'] > 0) {
1640 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1648 * Quick clean by emptying tables created for the test.
1650 * @param array $tablesToTruncate
1651 * @param bool $dropCustomValueTables
1652 * @throws \Exception
1654 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1656 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1658 if ($dropCustomValueTables) {
1659 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1660 while ($optionGroupResult->fetch()) {
1661 if (!empty($optionGroupResult->option_group_id
)) {
1662 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1665 $tablesToTruncate[] = 'civicrm_custom_group';
1666 $tablesToTruncate[] = 'civicrm_custom_field';
1669 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1671 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1672 foreach ($tablesToTruncate as $table) {
1673 $sql = "TRUNCATE TABLE $table";
1674 CRM_Core_DAO
::executeQuery($sql);
1676 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1678 if ($dropCustomValueTables) {
1679 $dbName = self
::getDBName();
1681 SELECT TABLE_NAME as tableName
1682 FROM INFORMATION_SCHEMA.TABLES
1683 WHERE TABLE_SCHEMA = '{$dbName}'
1684 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1687 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1688 while ($tableDAO->fetch()) {
1689 $sql = "DROP TABLE {$tableDAO->tableName}";
1690 CRM_Core_DAO
::executeQuery($sql);
1696 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1698 public function quickCleanUpFinancialEntities() {
1699 $tablesToTruncate = array(
1701 'civicrm_activity_contact',
1702 'civicrm_contribution',
1703 'civicrm_contribution_soft',
1704 'civicrm_contribution_product',
1705 'civicrm_financial_trxn',
1706 'civicrm_financial_item',
1707 'civicrm_contribution_recur',
1708 'civicrm_line_item',
1709 'civicrm_contribution_page',
1710 'civicrm_payment_processor',
1711 'civicrm_entity_financial_trxn',
1712 'civicrm_membership',
1713 'civicrm_membership_type',
1714 'civicrm_membership_payment',
1715 'civicrm_membership_log',
1716 'civicrm_membership_block',
1718 'civicrm_participant',
1719 'civicrm_participant_payment',
1721 'civicrm_pledge_payment',
1722 'civicrm_price_set_entity',
1723 'civicrm_price_field_value',
1724 'civicrm_price_field',
1726 $this->quickCleanup($tablesToTruncate);
1727 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1728 $this->restoreDefaultPriceSetConfig();
1730 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1731 $this->disableTaxAndInvoicing();
1732 $this->setCurrencySeparators(',');
1733 CRM_Core_PseudoConstant
::flush('taxRates');
1734 System
::singleton()->flushProcessors();
1737 public function restoreDefaultPriceSetConfig() {
1738 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1739 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1740 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)");
1741 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)");
1745 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1746 * Default behaviour is to also delete the entity
1747 * @param array $params
1748 * Params array to check against.
1750 * Id of the entity concerned.
1751 * @param string $entity
1752 * Name of entity concerned (e.g. membership).
1753 * @param bool $delete
1754 * Should the entity be deleted as part of this check.
1755 * @param string $errorText
1756 * Text to print on error.
1760 * @param array $params
1763 * @param int $delete
1764 * @param string $errorText
1768 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1770 $result = $this->callAPISuccessGetSingle($entity, array(
1775 $this->callAPISuccess($entity, 'Delete', array(
1779 $dateFields = $keys = $dateTimeFields = array();
1780 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1781 foreach ($fields['values'] as $field => $settings) {
1782 if (array_key_exists($field, $result)) {
1783 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1786 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1788 $type = CRM_Utils_Array
::value('type', $settings);
1789 if ($type == CRM_Utils_Type
::T_DATE
) {
1790 $dateFields[] = $settings['name'];
1791 // we should identify both real names & unique names as dates
1792 if ($field != $settings['name']) {
1793 $dateFields[] = $field;
1796 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1797 $dateTimeFields[] = $settings['name'];
1798 // we should identify both real names & unique names as dates
1799 if ($field != $settings['name']) {
1800 $dateTimeFields[] = $field;
1805 if (strtolower($entity) == 'contribution') {
1806 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1807 // this is not returned in id format
1808 unset($params['payment_instrument_id']);
1809 $params['contribution_source'] = $params['source'];
1810 unset($params['source']);
1813 foreach ($params as $key => $value) {
1814 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1817 if (in_array($key, $dateFields)) {
1818 $value = date('Y-m-d', strtotime($value));
1819 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1821 if (in_array($key, $dateTimeFields)) {
1822 $value = date('Y-m-d H:i:s', strtotime($value));
1823 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1825 $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);
1830 * Get formatted values in the actual and expected result.
1831 * @param array $actual
1832 * Actual calculated values.
1833 * @param array $expected
1836 public function checkArrayEquals(&$actual, &$expected) {
1837 self
::unsetId($actual);
1838 self
::unsetId($expected);
1839 $this->assertEquals($actual, $expected);
1843 * Unset the key 'id' from the array
1844 * @param array $unformattedArray
1845 * The array from which the 'id' has to be unset.
1847 public static function unsetId(&$unformattedArray) {
1848 $formattedArray = array();
1849 if (array_key_exists('id', $unformattedArray)) {
1850 unset($unformattedArray['id']);
1852 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1853 foreach ($unformattedArray['values'] as $key => $value) {
1854 if (is_array($value)) {
1855 foreach ($value as $k => $v) {
1861 elseif ($key == 'id') {
1862 $unformattedArray[$key];
1864 $formattedArray = array($value);
1866 $unformattedArray['values'] = $formattedArray;
1871 * Helper to enable/disable custom directory support
1873 * @param array $customDirs
1875 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1876 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1878 public function customDirectories($customDirs) {
1879 $config = CRM_Core_Config
::singleton();
1881 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1882 unset($config->customPHPPathDir
);
1884 elseif ($customDirs['php_path'] === TRUE) {
1885 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1888 $config->customPHPPathDir
= $php_path;
1891 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1892 unset($config->customTemplateDir
);
1894 elseif ($customDirs['template_path'] === TRUE) {
1895 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1898 $config->customTemplateDir
= $template_path;
1903 * Generate a temporary folder.
1905 * @param string $prefix
1908 public function createTempDir($prefix = 'test-') {
1909 $tempDir = CRM_Utils_File
::tempdir($prefix);
1910 $this->tempDirs
[] = $tempDir;
1914 public function cleanTempDirs() {
1915 if (!is_array($this->tempDirs
)) {
1916 // fix test errors where this is not set
1919 foreach ($this->tempDirs
as $tempDir) {
1920 if (is_dir($tempDir)) {
1921 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1927 * Temporarily replace the singleton extension with a different one.
1928 * @param \CRM_Extension_System $system
1930 public function setExtensionSystem(CRM_Extension_System
$system) {
1931 if ($this->origExtensionSystem
== NULL) {
1932 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1934 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1937 public function unsetExtensionSystem() {
1938 if ($this->origExtensionSystem
!== NULL) {
1939 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1940 $this->origExtensionSystem
= NULL;
1945 * Temporarily alter the settings-metadata to add a mock setting.
1947 * WARNING: The setting metadata will disappear on the next cache-clear.
1952 public function setMockSettingsMetaData($extras) {
1953 CRM_Utils_Hook
::singleton()
1954 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
1955 $metadata = array_merge($metadata, $extras);
1958 Civi
::service('settings_manager')->flush();
1960 $fields = $this->callAPISuccess('setting', 'getfields', array());
1961 foreach ($extras as $key => $spec) {
1962 $this->assertNotEmpty($spec['title']);
1963 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
1968 * @param string $name
1970 public function financialAccountDelete($name) {
1971 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
1972 $financialAccount->name
= $name;
1973 if ($financialAccount->find(TRUE)) {
1974 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
1975 $entityFinancialType->financial_account_id
= $financialAccount->id
;
1976 $entityFinancialType->delete();
1977 $financialAccount->delete();
1982 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
1983 * (NB unclear if this is still required)
1985 public function _sethtmlGlobals() {
1986 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
1987 'required' => array(
1988 'html_quickform_rule_required',
1989 'HTML/QuickForm/Rule/Required.php',
1991 'maxlength' => array(
1992 'html_quickform_rule_range',
1993 'HTML/QuickForm/Rule/Range.php',
1995 'minlength' => array(
1996 'html_quickform_rule_range',
1997 'HTML/QuickForm/Rule/Range.php',
1999 'rangelength' => array(
2000 'html_quickform_rule_range',
2001 'HTML/QuickForm/Rule/Range.php',
2004 'html_quickform_rule_email',
2005 'HTML/QuickForm/Rule/Email.php',
2008 'html_quickform_rule_regex',
2009 'HTML/QuickForm/Rule/Regex.php',
2011 'lettersonly' => array(
2012 'html_quickform_rule_regex',
2013 'HTML/QuickForm/Rule/Regex.php',
2015 'alphanumeric' => array(
2016 'html_quickform_rule_regex',
2017 'HTML/QuickForm/Rule/Regex.php',
2020 'html_quickform_rule_regex',
2021 'HTML/QuickForm/Rule/Regex.php',
2023 'nopunctuation' => array(
2024 'html_quickform_rule_regex',
2025 'HTML/QuickForm/Rule/Regex.php',
2028 'html_quickform_rule_regex',
2029 'HTML/QuickForm/Rule/Regex.php',
2031 'callback' => array(
2032 'html_quickform_rule_callback',
2033 'HTML/QuickForm/Rule/Callback.php',
2036 'html_quickform_rule_compare',
2037 'HTML/QuickForm/Rule/Compare.php',
2040 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2041 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2043 'HTML/QuickForm/group.php',
2044 'HTML_QuickForm_group',
2047 'HTML/QuickForm/hidden.php',
2048 'HTML_QuickForm_hidden',
2051 'HTML/QuickForm/reset.php',
2052 'HTML_QuickForm_reset',
2054 'checkbox' => array(
2055 'HTML/QuickForm/checkbox.php',
2056 'HTML_QuickForm_checkbox',
2059 'HTML/QuickForm/file.php',
2060 'HTML_QuickForm_file',
2063 'HTML/QuickForm/image.php',
2064 'HTML_QuickForm_image',
2066 'password' => array(
2067 'HTML/QuickForm/password.php',
2068 'HTML_QuickForm_password',
2071 'HTML/QuickForm/radio.php',
2072 'HTML_QuickForm_radio',
2075 'HTML/QuickForm/button.php',
2076 'HTML_QuickForm_button',
2079 'HTML/QuickForm/submit.php',
2080 'HTML_QuickForm_submit',
2083 'HTML/QuickForm/select.php',
2084 'HTML_QuickForm_select',
2086 'hiddenselect' => array(
2087 'HTML/QuickForm/hiddenselect.php',
2088 'HTML_QuickForm_hiddenselect',
2091 'HTML/QuickForm/text.php',
2092 'HTML_QuickForm_text',
2094 'textarea' => array(
2095 'HTML/QuickForm/textarea.php',
2096 'HTML_QuickForm_textarea',
2098 'fckeditor' => array(
2099 'HTML/QuickForm/fckeditor.php',
2100 'HTML_QuickForm_FCKEditor',
2103 'HTML/QuickForm/tinymce.php',
2104 'HTML_QuickForm_TinyMCE',
2106 'dojoeditor' => array(
2107 'HTML/QuickForm/dojoeditor.php',
2108 'HTML_QuickForm_dojoeditor',
2111 'HTML/QuickForm/link.php',
2112 'HTML_QuickForm_link',
2114 'advcheckbox' => array(
2115 'HTML/QuickForm/advcheckbox.php',
2116 'HTML_QuickForm_advcheckbox',
2119 'HTML/QuickForm/date.php',
2120 'HTML_QuickForm_date',
2123 'HTML/QuickForm/static.php',
2124 'HTML_QuickForm_static',
2127 'HTML/QuickForm/header.php',
2128 'HTML_QuickForm_header',
2131 'HTML/QuickForm/html.php',
2132 'HTML_QuickForm_html',
2134 'hierselect' => array(
2135 'HTML/QuickForm/hierselect.php',
2136 'HTML_QuickForm_hierselect',
2138 'autocomplete' => array(
2139 'HTML/QuickForm/autocomplete.php',
2140 'HTML_QuickForm_autocomplete',
2143 'HTML/QuickForm/xbutton.php',
2144 'HTML_QuickForm_xbutton',
2146 'advmultiselect' => array(
2147 'HTML/QuickForm/advmultiselect.php',
2148 'HTML_QuickForm_advmultiselect',
2154 * Set up an acl allowing contact to see 2 specified groups
2155 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2157 * You need to have pre-created these groups & created the user e.g
2158 * $this->createLoggedInUser();
2159 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2160 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2162 * @param bool $isProfile
2164 public function setupACL($isProfile = FALSE) {
2166 $_REQUEST = $this->_params
;
2168 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2169 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2170 $ov = new CRM_Core_DAO_OptionValue();
2171 $ov->option_group_id
= $optionGroupID;
2173 if ($ov->find(TRUE)) {
2174 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2176 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2177 'option_group_id' => $optionGroupID,
2178 'label' => 'pick me',
2182 CRM_Core_DAO
::executeQuery("
2183 TRUNCATE civicrm_acl_cache
2186 CRM_Core_DAO
::executeQuery("
2187 TRUNCATE civicrm_acl_contact_cache
2190 CRM_Core_DAO
::executeQuery("
2191 INSERT INTO civicrm_acl_entity_role (
2192 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2193 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2197 CRM_Core_DAO
::executeQuery("
2198 INSERT INTO civicrm_acl (
2199 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2202 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2207 CRM_Core_DAO
::executeQuery("
2208 INSERT INTO civicrm_acl (
2209 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2212 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2216 CRM_Core_DAO
::executeQuery("
2217 INSERT INTO civicrm_acl (
2218 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2221 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2226 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2227 $this->callAPISuccess('group_contact', 'create', array(
2228 'group_id' => $this->_permissionedGroup
,
2229 'contact_id' => $this->_loggedInUser
,
2234 CRM_ACL_BAO_Cache
::resetCache();
2235 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2240 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2242 public function offsetDefaultPriceSet() {
2243 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2244 $firstID = $contributionPriceSet['id'];
2245 $this->callAPISuccess('price_set', 'create', array(
2246 'id' => $contributionPriceSet['id'],
2250 unset($contributionPriceSet['id']);
2251 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2252 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2253 'price_set_id' => $firstID,
2254 'options' => array('limit' => 1),
2256 unset($priceField['id']);
2257 $priceField['price_set_id'] = $newPriceSet['id'];
2258 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2259 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2260 'price_set_id' => $firstID,
2262 'options' => array('limit' => 1),
2265 unset($priceFieldValue['id']);
2266 //create some padding to use up ids
2267 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2268 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2269 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2273 * Create an instance of the paypal processor.
2274 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2275 * this parent class & we don't have a structure for that yet
2276 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2277 * & the best protection against that is the functions this class affords
2278 * @param array $params
2279 * @return int $result['id'] payment processor id
2281 public function paymentProcessorCreate($params = array()) {
2282 $params = array_merge(array(
2284 'domain_id' => CRM_Core_Config
::domainID(),
2285 'payment_processor_type_id' => 'PayPal',
2289 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2290 'password' => '1183377788',
2291 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2292 'url_site' => 'https://www.sandbox.paypal.com/',
2293 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2294 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2295 'class_name' => 'Payment_PayPalImpl',
2296 'billing_mode' => 3,
2297 'financial_type_id' => 1,
2298 'financial_account_id' => 12,
2299 // Credit card = 1 so can pass 'by accident'.
2300 'payment_instrument_id' => 'Debit Card',
2302 if (!is_numeric($params['payment_processor_type_id'])) {
2303 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2305 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2306 'name' => $params['payment_processor_type_id'],
2310 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2311 return $result['id'];
2315 * Set up initial recurring payment allowing subsequent IPN payments.
2317 * @param array $recurParams (Optional)
2318 * @param array $contributionParams (Optional)
2320 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2321 $contributionParams = array_merge([
2322 'total_amount' => '200',
2323 'invoice_id' => $this->_invoiceID
,
2324 'financial_type_id' => 'Donation',
2325 'contribution_status_id' => 'Pending',
2326 'contact_id' => $this->_contactID
,
2327 'contribution_page_id' => $this->_contributionPageID
,
2328 'payment_processor_id' => $this->_paymentProcessorID
,
2330 'skipCleanMoney' => TRUE,
2331 ], $contributionParams);
2332 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2333 'contact_id' => $this->_contactID
,
2336 'installments' => 5,
2337 'frequency_unit' => 'Month',
2338 'frequency_interval' => 1,
2339 'invoice_id' => $this->_invoiceID
,
2340 'contribution_status_id' => 2,
2341 'payment_processor_id' => $this->_paymentProcessorID
,
2342 // processor provided ID - use contact ID as proxy.
2343 'processor_id' => $this->_contactID
,
2344 'api.contribution.create' => $contributionParams,
2346 $this->_contributionRecurID
= $contributionRecur['id'];
2347 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2351 * 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
2353 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2355 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2356 $membershipParams = $recurParams = array();
2357 if (!empty($params['duration_unit'])) {
2358 $membershipParams['duration_unit'] = $params['duration_unit'];
2360 if (!empty($params['frequency_unit'])) {
2361 $recurParams['frequency_unit'] = $params['frequency_unit'];
2364 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2365 //create a contribution so our membership & contribution don't both have id = 1
2366 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2367 $this->contributionCreate(array(
2368 'contact_id' => $this->_contactID
,
2370 'financial_type_id' => 1,
2371 'invoice_id' => 'abcd',
2375 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2377 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2378 'contact_id' => $this->_contactID
,
2379 'membership_type_id' => $this->ids
['membership_type'],
2380 'contribution_recur_id' => $this->_contributionRecurID
,
2381 'format.only_id' => TRUE,
2383 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2384 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2386 $this->callAPISuccess('line_item', 'create', array(
2387 'entity_table' => 'civicrm_membership',
2388 'entity_id' => $this->ids
['membership'],
2389 'contribution_id' => $this->_contributionID
,
2390 'label' => 'General',
2392 'unit_price' => 200,
2393 'line_total' => 200,
2394 'financial_type_id' => 1,
2395 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2397 'label' => 'Membership Amount',
2398 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2400 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2402 'label' => 'General',
2403 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2406 $this->callAPISuccess('membership_payment', 'create', array(
2407 'contribution_id' => $this->_contributionID
,
2408 'membership_id' => $this->ids
['membership'],
2417 public function CiviUnitTestCase_fatalErrorHandler($message) {
2418 throw new Exception("{$message['message']}: {$message['code']}");
2422 * Wrap the entire test case in a transaction.
2424 * Only subsequent DB statements will be wrapped in TX -- this cannot
2425 * retroactively wrap old DB statements. Therefore, it makes sense to
2426 * call this at the beginning of setUp().
2428 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2429 * this option does not work with, e.g., custom-data.
2431 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2432 * if TRUNCATE or ALTER is called while using a transaction.
2435 * Whether to use nesting or reference-counting.
2437 public function useTransaction($nest = TRUE) {
2439 $this->tx
= new CRM_Core_Transaction($nest);
2440 $this->tx
->rollback();
2445 * Assert the attachment exists.
2447 * @param bool $exists
2448 * @param array $apiResult
2450 protected function assertAttachmentExistence($exists, $apiResult) {
2451 $fileId = $apiResult['id'];
2452 $this->assertTrue(is_numeric($fileId));
2453 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2454 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2455 1 => array($fileId, 'Int'),
2457 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2458 1 => array($fileId, 'Int'),
2463 * Create a price set for an event.
2465 * @param int $feeTotal
2466 * @param int $minAmt
2467 * @param string $type
2472 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2473 // creating price set, price field
2474 $paramsSet['title'] = 'Price Set';
2475 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2476 $paramsSet['is_active'] = FALSE;
2477 $paramsSet['extends'] = 1;
2478 $paramsSet['min_amount'] = $minAmt;
2480 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2481 $this->_ids
['price_set'] = $priceSet->id
;
2483 $paramsField = array(
2484 'label' => 'Price Field',
2485 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2486 'html_type' => $type,
2487 'price' => $feeTotal,
2488 'option_label' => array('1' => 'Price Field'),
2489 'option_value' => array('1' => $feeTotal),
2490 'option_name' => array('1' => $feeTotal),
2491 'option_weight' => array('1' => 1),
2492 'option_amount' => array('1' => 1),
2493 'is_display_amounts' => 1,
2495 'options_per_line' => 1,
2496 'is_active' => array('1' => 1),
2497 'price_set_id' => $this->_ids
['price_set'],
2498 'is_enter_qty' => 1,
2499 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2501 if ($type === 'Radio') {
2502 $paramsField['is_enter_qty'] = 0;
2503 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2504 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2506 CRM_Price_BAO_PriceField
::create($paramsField);
2507 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2508 $this->_ids
['price_field'] = array_keys($fields['values']);
2509 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2510 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2512 return $this->_ids
['price_set'];
2516 * Add a profile to a contribution page.
2518 * @param string $name
2519 * @param int $contributionPageID
2520 * @param string $module
2522 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2524 'uf_group_id' => $name,
2525 'module' => $module,
2526 'entity_table' => 'civicrm_contribution_page',
2527 'entity_id' => $contributionPageID,
2530 if ($module !== 'CiviContribute') {
2531 $params['module_data'] = [$module => []];
2533 $this->callAPISuccess('UFJoin', 'create', $params);
2537 * Add participant with contribution
2541 protected function createParticipantWithContribution() {
2542 // creating price set, price field
2543 $this->_contactId
= $this->individualCreate();
2544 $event = $this->eventCreate();
2545 $this->_eventId
= $event['id'];
2546 $eventParams = array(
2547 'id' => $this->_eventId
,
2548 'financial_type_id' => 4,
2551 $this->callAPISuccess('event', 'create', $eventParams);
2552 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2553 $participantParams = array(
2554 'financial_type_id' => 4,
2555 'event_id' => $this->_eventId
,
2558 'fee_currency' => 'USD',
2559 'contact_id' => $this->_contactId
,
2561 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2562 $contributionParams = array(
2563 'total_amount' => 150,
2564 'currency' => 'USD',
2565 'contact_id' => $this->_contactId
,
2566 'financial_type_id' => 4,
2567 'contribution_status_id' => 1,
2568 'partial_payment_total' => 300.00,
2569 'partial_amount_to_pay' => 150,
2570 'contribution_mode' => 'participant',
2571 'participant_id' => $participant['id'],
2573 foreach ($priceFields['values'] as $key => $priceField) {
2574 $lineItems[1][$key] = array(
2575 'price_field_id' => $priceField['price_field_id'],
2576 'price_field_value_id' => $priceField['id'],
2577 'label' => $priceField['label'],
2578 'field_title' => $priceField['label'],
2580 'unit_price' => $priceField['amount'],
2581 'line_total' => $priceField['amount'],
2582 'financial_type_id' => $priceField['financial_type_id'],
2585 $contributionParams['line_item'] = $lineItems;
2586 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2587 $paymentParticipant = array(
2588 'participant_id' => $participant['id'],
2589 'contribution_id' => $contribution['id'],
2591 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2592 return array($lineItems, $contribution);
2598 * @param string $component
2599 * @param int $componentId
2600 * @param array $priceFieldOptions
2604 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2605 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2606 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2607 $paramsSet['is_active'] = TRUE;
2608 $paramsSet['financial_type_id'] = 'Event Fee';
2609 $paramsSet['extends'] = 1;
2610 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2611 $priceSetId = $priceSet['id'];
2612 //Checking for priceset added in the table.
2613 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2614 'id', $paramsSet['title'], 'Check DB for created priceset'
2616 $paramsField = array_merge(array(
2617 'label' => 'Price Field',
2618 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2619 'html_type' => 'CheckBox',
2620 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2621 'option_value' => array('1' => 100, '2' => 200),
2622 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2623 'option_weight' => array('1' => 1, '2' => 2),
2624 'option_amount' => array('1' => 100, '2' => 200),
2625 'is_display_amounts' => 1,
2627 'options_per_line' => 1,
2628 'is_active' => array('1' => 1, '2' => 1),
2629 'price_set_id' => $priceSet['id'],
2630 'is_enter_qty' => 1,
2631 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2632 ), $priceFieldOptions);
2634 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2636 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2638 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2642 * Replace the template with a test-oriented template designed to show all the variables.
2644 * @param string $templateName
2646 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2647 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2648 CRM_Core_DAO
::executeQuery(
2649 "UPDATE civicrm_option_group og
2650 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2651 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2652 SET m.msg_html = '{$testTemplate}'
2653 WHERE og.name = 'msg_tpl_workflow_contribution'
2654 AND ov.name = '{$templateName}'
2655 AND m.is_default = 1"
2660 * Reinstate the default template.
2662 * @param string $templateName
2664 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2665 CRM_Core_DAO
::executeQuery(
2666 "UPDATE civicrm_option_group og
2667 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2668 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2669 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2670 SET m.msg_html = m2.msg_html
2671 WHERE og.name = 'msg_tpl_workflow_contribution'
2672 AND ov.name = '{$templateName}'
2673 AND m.is_default = 1"
2678 * Flush statics relating to financial type.
2680 protected function flushFinancialTypeStatics() {
2681 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2682 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2684 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2685 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2687 CRM_Contribute_PseudoConstant
::flush('financialType');
2688 CRM_Contribute_PseudoConstant
::flush('membershipType');
2689 // Pseudoconstants may be saved to the cache table.
2690 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2691 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2692 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2696 * Set the permissions to the supplied array.
2698 * @param array $permissions
2700 protected function setPermissions($permissions) {
2701 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2702 $this->flushFinancialTypeStatics();
2706 * @param array $params
2709 public function _checkFinancialRecords($params, $context) {
2710 $entityParams = array(
2711 'entity_id' => $params['id'],
2712 'entity_table' => 'civicrm_contribution',
2714 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2715 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2716 if ($context == 'pending') {
2717 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2718 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2721 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2722 $trxnParams = array(
2723 'id' => $trxn['financial_trxn_id'],
2725 if ($context != 'online' && $context != 'payLater') {
2726 $compareParams = array(
2727 'to_financial_account_id' => 6,
2728 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2732 if ($context == 'feeAmount') {
2733 $compareParams['fee_amount'] = 50;
2735 elseif ($context == 'online') {
2736 $compareParams = array(
2737 'to_financial_account_id' => 12,
2738 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2740 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2743 elseif ($context == 'payLater') {
2744 $compareParams = array(
2745 'to_financial_account_id' => 7,
2746 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2750 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2751 $entityParams = array(
2752 'financial_trxn_id' => $trxn['financial_trxn_id'],
2753 'entity_table' => 'civicrm_financial_item',
2755 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2756 $fitemParams = array(
2757 'id' => $entityTrxn['entity_id'],
2759 $compareParams = array(
2760 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2762 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2764 if ($context == 'payLater') {
2765 $compareParams = array(
2766 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2768 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2771 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2772 if ($context == 'feeAmount') {
2774 'entity_id' => $params['id'],
2775 'entity_table' => 'civicrm_contribution',
2777 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2778 $trxnParams = array(
2779 'id' => $maxTrxn['financial_trxn_id'],
2781 $compareParams = array(
2782 'to_financial_account_id' => 5,
2783 'from_financial_account_id' => 6,
2784 'total_amount' => 50,
2787 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2788 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2789 $fitemParams = array(
2790 'entity_id' => $trxnId['financialTrxnId'],
2791 'entity_table' => 'civicrm_financial_trxn',
2793 $compareParams = array(
2796 'financial_account_id' => 5,
2798 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2800 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2801 // line should be copied into all the functions that call this function & evaluated there
2802 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2803 // when calling completeTransaction or repeatTransaction.
2804 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2808 * Return financial type id on basis of name
2810 * @param string $name Financial type m/c name
2814 public function getFinancialTypeId($name) {
2815 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2819 * Cleanup function for contents of $this->ids.
2821 * This is a best effort cleanup to use in tear downs etc.
2823 * It will not fail if the data has already been removed (some tests may do
2824 * their own cleanup).
2826 protected function cleanUpSetUpIDs() {
2827 foreach ($this->setupIDs
as $entity => $id) {
2829 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2831 catch (CiviCRM_API3_Exception
$e) {
2832 // This is a best-effort cleanup function, ignore.
2838 * Create Financial Type.
2840 * @param array $params
2844 protected function createFinancialType($params = array()) {
2845 $params = array_merge($params,
2847 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2851 return $this->callAPISuccess('FinancialType', 'create', $params);
2855 * Create Payment Instrument.
2857 * @param array $params
2858 * @param string $financialAccountName
2862 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2863 $params = array_merge(array(
2864 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2865 'option_group_id' => 'payment_instrument',
2868 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2870 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2872 $financialAccountParams = [
2873 'entity_table' => 'civicrm_option_value',
2874 'entity_id' => $newPaymentInstrument,
2875 'account_relationship' => $relationTypeID,
2876 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2878 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2880 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2884 * Enable Tax and Invoicing
2886 protected function enableTaxAndInvoicing($params = array()) {
2887 // Enable component contribute setting
2888 $contributeSetting = array_merge($params,
2891 'invoice_prefix' => 'INV_',
2892 'credit_notes_prefix' => 'CN_',
2894 'due_date_period' => 'days',
2896 'is_email_pdf' => 1,
2897 'tax_term' => 'Sales Tax',
2898 'tax_display_settings' => 'Inclusive',
2901 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2905 * Enable Tax and Invoicing
2907 protected function disableTaxAndInvoicing($params = array()) {
2908 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2909 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2911 // Enable component contribute setting
2912 $contributeSetting = array_merge($params,
2917 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2921 * Add Sales Tax relation for financial type with financial account.
2923 * @param int $financialTypeId
2927 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2929 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2930 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2931 'is_deductible' => 1,
2936 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
2937 $entityParams = array(
2938 'entity_table' => 'civicrm_financial_type',
2939 'entity_id' => $financialTypeId,
2940 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
2943 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
2944 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
2946 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
2947 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
2948 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
2949 $dao->copyValues($entityParams);
2951 if ($dao->fetch()) {
2952 $entityParams['id'] = $dao->id
;
2954 $entityParams['financial_account_id'] = $account->id
;
2956 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
2960 * Create price set with contribution test for test setup.
2962 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
2963 * on parent class at some point (fn is not in 4.4).
2966 * @param array $params
2968 public function createPriceSetWithPage($entity = NULL, $params = array()) {
2969 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
2970 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
2971 'title' => "Test Contribution Page",
2972 'financial_type_id' => 1,
2973 'currency' => 'NZD',
2974 'goal_amount' => 50,
2975 'is_pay_later' => 1,
2976 'is_monetary' => TRUE,
2977 'is_email_receipt' => FALSE,
2979 $priceSet = $this->callAPISuccess('price_set', 'create', array(
2980 'is_quick_config' => 0,
2981 'extends' => 'CiviMember',
2982 'financial_type_id' => 1,
2983 'title' => 'my Page',
2985 $priceSetID = $priceSet['id'];
2987 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
2988 $priceField = $this->callAPISuccess('price_field', 'create', array(
2989 'price_set_id' => $priceSetID,
2990 'label' => 'Goat Breed',
2991 'html_type' => 'Radio',
2993 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
2994 'price_set_id' => $priceSetID,
2995 'price_field_id' => $priceField['id'],
2996 'label' => 'Long Haired Goat',
2998 'financial_type_id' => 'Donation',
2999 'membership_type_id' => $membershipTypeID,
3000 'membership_num_terms' => 1,
3002 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3003 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3004 'price_set_id' => $priceSetID,
3005 'price_field_id' => $priceField['id'],
3006 'label' => 'Shoe-eating Goat',
3008 'financial_type_id' => 'Donation',
3009 'membership_type_id' => $membershipTypeID,
3010 'membership_num_terms' => 2,
3012 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3014 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3015 'price_set_id' => $priceSetID,
3016 'price_field_id' => $priceField['id'],
3017 'label' => 'Shoe-eating Goat',
3019 'financial_type_id' => 'Donation',
3021 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3023 $this->_ids
['price_set'] = $priceSetID;
3024 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3025 $this->_ids
['price_field'] = array($priceField['id']);
3027 $this->_ids
['membership_type'] = $membershipTypeID;
3031 * Only specified contact returned.
3032 * @implements CRM_Utils_Hook::aclWhereClause
3035 * @param $whereTables
3039 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3040 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3044 * @implements CRM_Utils_Hook::selectWhereClause
3046 * @param string $entity
3047 * @param array $clauses
3049 public function selectWhereClauseHook($entity, &$clauses) {
3050 if ($entity == 'Event') {
3051 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3056 * An implementation of hook_civicrm_post used with all our test cases.
3059 * @param string $objectName
3060 * @param int $objectId
3063 public function onPost($op, $objectName, $objectId, &$objectRef) {
3064 if ($op == 'create' && $objectName == 'Individual') {
3065 CRM_Core_DAO
::executeQuery(
3066 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3068 1 => array($objectId, 'Integer'),
3073 if ($op == 'edit' && $objectName == 'Participant') {
3075 1 => array($objectId, 'Integer'),
3077 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3078 CRM_Core_DAO
::executeQuery($query, $params);
3083 * Instantiate form object.
3085 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3087 * @param string $class
3088 * Name of form class.
3090 * @return \CRM_Core_Form
3092 public function getFormObject($class) {
3093 $form = new $class();
3094 $_SERVER['REQUEST_METHOD'] = 'GET';
3095 $form->controller
= new CRM_Core_Controller();
3100 * Get possible thousand separators.
3104 public function getThousandSeparators() {
3105 return array(array('.'), array(','));
3109 * Set the separators for thousands and decimal points.
3111 * @param string $thousandSeparator
3113 protected function setCurrencySeparators($thousandSeparator) {
3114 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3116 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3120 * Format money as it would be input.
3122 * @param string $amount
3126 protected function formatMoneyInput($amount) {
3127 return CRM_Utils_Money
::format($amount, NULL, '%a');
3131 * Get the contribution object.
3133 * @param int $contributionID
3135 * @return \CRM_Contribute_BAO_Contribution
3137 protected function getContributionObject($contributionID) {
3138 $contributionObj = new CRM_Contribute_BAO_Contribution();
3139 $contributionObj->id
= $contributionID;
3140 $contributionObj->find(TRUE);
3141 return $contributionObj;
3145 * Enable multilingual.
3147 public function enableMultilingual() {
3148 $this->callAPISuccess('Setting', 'create', array(
3149 'lcMessages' => 'en_US',
3150 'languageLimit' => array(
3155 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3158 $dbLocale = '_en_US';
3162 * Setup or clean up SMS tests
3163 * @param bool $teardown
3165 * @throws \CiviCRM_API3_Exception
3167 public function setupForSmsTests($teardown = FALSE) {
3168 require_once 'CiviTest/CiviTestSMSProvider.php';
3170 // Option value params for CiviTestSMSProvider
3171 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3173 'option_group_id' => $groupID,
3174 'label' => 'unittestSMS',
3175 'value' => 'unit.test.sms',
3176 'name' => 'CiviTestSMSProvider',
3183 // Test completed, delete provider
3184 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3185 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3189 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3190 // in CRM/Sms/Provider.php even though it is not an extension.
3191 return civicrm_api3('option_value', 'create', $params);