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 return $this->callAPISuccess('custom_group', 'create', $params);
1364 * Existing function doesn't allow params to be over-ridden so need a new one
1365 * this one allows you to only pass in the params you want to change
1366 * @param array $params
1369 public function CustomGroupCreateByParams($params = array()) {
1371 'title' => "API Custom Group",
1372 'extends' => 'Contact',
1374 'style' => 'Inline',
1377 $params = array_merge($defaults, $params);
1378 return $this->callAPISuccess('custom_group', 'create', $params);
1382 * Create custom group with multi fields.
1383 * @param array $params
1386 public function CustomGroupMultipleCreateByParams($params = array()) {
1391 $params = array_merge($defaults, $params);
1392 return $this->CustomGroupCreateByParams($params);
1396 * Create custom group with multi fields.
1397 * @param array $params
1400 public function CustomGroupMultipleCreateWithFields($params = array()) {
1401 // also need to pass on $params['custom_field'] if not set but not in place yet
1403 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1404 $ids['custom_group_id'] = $customGroup['id'];
1406 $customField = $this->customFieldCreate(array(
1407 'custom_group_id' => $ids['custom_group_id'],
1408 'label' => 'field_1' . $ids['custom_group_id'],
1412 $ids['custom_field_id'][] = $customField['id'];
1414 $customField = $this->customFieldCreate(array(
1415 'custom_group_id' => $ids['custom_group_id'],
1416 'default_value' => '',
1417 'label' => 'field_2' . $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_3' . $ids['custom_group_id'],
1428 $ids['custom_field_id'][] = $customField['id'];
1434 * Create a custom group with a single text custom field. See
1435 * participant:testCreateWithCustom for how to use this
1437 * @param string $function
1439 * @param string $filename
1443 * ids of created objects
1445 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1446 $params = array('title' => $function);
1447 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1448 $params['extends'] = $entity ?
$entity : 'Contact';
1449 $customGroup = $this->CustomGroupCreate($params);
1450 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1451 CRM_Core_PseudoConstant
::flush();
1453 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1457 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1458 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1460 * @param string $function
1462 * @param string $filename
1466 * ids of created objects
1468 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1469 $params = array('title' => $function);
1470 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1471 $params['extends'] = $entity ?
$entity : 'Contact';
1472 $customGroup = $this->CustomGroupCreate($params);
1473 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1474 CRM_Core_PseudoConstant
::flush();
1476 'defaultValue' => 'Default Value',
1477 'lowercasevalue' => 'Lowercase Value',
1478 1 => 'Integer Value',
1481 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1482 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1483 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1484 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1485 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1486 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1487 foreach ($options as $option_value => $option_label) {
1488 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1489 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1492 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);
1496 * Delete custom group.
1498 * @param int $customGroupID
1502 public function customGroupDelete($customGroupID) {
1503 $params['id'] = $customGroupID;
1504 return $this->callAPISuccess('custom_group', 'delete', $params);
1508 * Create custom field.
1510 * @param array $params
1511 * (custom_group_id) is required.
1514 public function customFieldCreate($params) {
1515 $params = array_merge(array(
1516 'label' => 'Custom Field',
1517 'data_type' => 'String',
1518 'html_type' => 'Text',
1519 'is_searchable' => 1,
1521 'default_value' => 'defaultValue',
1524 $result = $this->callAPISuccess('custom_field', 'create', $params);
1525 // these 2 functions are called with force to flush static caches
1526 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1527 CRM_Core_Component
::getEnabledComponents(1);
1532 * Delete custom field.
1534 * @param int $customFieldID
1538 public function customFieldDelete($customFieldID) {
1540 $params['id'] = $customFieldID;
1541 return $this->callAPISuccess('custom_field', 'delete', $params);
1550 public function noteCreate($cId) {
1552 'entity_table' => 'civicrm_contact',
1553 'entity_id' => $cId,
1554 'note' => 'hello I am testing Note',
1555 'contact_id' => $cId,
1556 'modified_date' => date('Ymd'),
1557 'subject' => 'Test Note',
1560 return $this->callAPISuccess('Note', 'create', $params);
1564 * Enable CiviCampaign Component.
1566 * @param bool $reloadConfig
1567 * Force relaod config or not
1569 public function enableCiviCampaign($reloadConfig = TRUE) {
1570 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1571 if ($reloadConfig) {
1572 // force reload of config object
1573 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1575 //flush cache by calling with reset
1576 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1580 * Create custom field with Option Values.
1582 * @param array $customGroup
1583 * @param string $name
1584 * Name of custom field.
1585 * @param array $extraParams
1586 * Additional parameters to pass through.
1590 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1591 $fieldParams = array(
1592 'custom_group_id' => $customGroup['id'],
1593 'name' => 'test_custom_group',
1594 'label' => 'Country',
1595 'html_type' => 'Select',
1596 'data_type' => 'String',
1599 'is_searchable' => 0,
1603 $optionGroup = array(
1605 'name' => 'option_group1',
1606 'label' => 'option_group_label1',
1609 $optionValue = array(
1610 'option_label' => array('Label1', 'Label2'),
1611 'option_value' => array('value1', 'value2'),
1612 'option_name' => array($name . '_1', $name . '_2'),
1613 'option_weight' => array(1, 2),
1614 'option_status' => 1,
1617 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1619 return $this->callAPISuccess('custom_field', 'create', $params);
1627 public function confirmEntitiesDeleted($entities) {
1628 foreach ($entities as $entity) {
1630 $result = $this->callAPISuccess($entity, 'Get', array());
1631 if ($result['error'] == 1 ||
$result['count'] > 0) {
1632 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1640 * Quick clean by emptying tables created for the test.
1642 * @param array $tablesToTruncate
1643 * @param bool $dropCustomValueTables
1644 * @throws \Exception
1646 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1648 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1650 if ($dropCustomValueTables) {
1651 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1652 while ($optionGroupResult->fetch()) {
1653 if (!empty($optionGroupResult->option_group_id
)) {
1654 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1657 $tablesToTruncate[] = 'civicrm_custom_group';
1658 $tablesToTruncate[] = 'civicrm_custom_field';
1661 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1663 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1664 foreach ($tablesToTruncate as $table) {
1665 $sql = "TRUNCATE TABLE $table";
1666 CRM_Core_DAO
::executeQuery($sql);
1668 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1670 if ($dropCustomValueTables) {
1671 $dbName = self
::getDBName();
1673 SELECT TABLE_NAME as tableName
1674 FROM INFORMATION_SCHEMA.TABLES
1675 WHERE TABLE_SCHEMA = '{$dbName}'
1676 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1679 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1680 while ($tableDAO->fetch()) {
1681 $sql = "DROP TABLE {$tableDAO->tableName}";
1682 CRM_Core_DAO
::executeQuery($sql);
1688 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1690 public function quickCleanUpFinancialEntities() {
1691 $tablesToTruncate = array(
1693 'civicrm_activity_contact',
1694 'civicrm_contribution',
1695 'civicrm_contribution_soft',
1696 'civicrm_contribution_product',
1697 'civicrm_financial_trxn',
1698 'civicrm_financial_item',
1699 'civicrm_contribution_recur',
1700 'civicrm_line_item',
1701 'civicrm_contribution_page',
1702 'civicrm_payment_processor',
1703 'civicrm_entity_financial_trxn',
1704 'civicrm_membership',
1705 'civicrm_membership_type',
1706 'civicrm_membership_payment',
1707 'civicrm_membership_log',
1708 'civicrm_membership_block',
1710 'civicrm_participant',
1711 'civicrm_participant_payment',
1713 'civicrm_pledge_payment',
1714 'civicrm_price_set_entity',
1715 'civicrm_price_field_value',
1716 'civicrm_price_field',
1718 $this->quickCleanup($tablesToTruncate);
1719 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1720 $this->restoreDefaultPriceSetConfig();
1722 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1723 $this->disableTaxAndInvoicing();
1724 $this->setCurrencySeparators(',');
1725 CRM_Core_PseudoConstant
::flush('taxRates');
1726 System
::singleton()->flushProcessors();
1729 public function restoreDefaultPriceSetConfig() {
1730 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1731 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1732 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)");
1733 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)");
1737 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1738 * Default behaviour is to also delete the entity
1739 * @param array $params
1740 * Params array to check against.
1742 * Id of the entity concerned.
1743 * @param string $entity
1744 * Name of entity concerned (e.g. membership).
1745 * @param bool $delete
1746 * Should the entity be deleted as part of this check.
1747 * @param string $errorText
1748 * Text to print on error.
1752 * @param array $params
1755 * @param int $delete
1756 * @param string $errorText
1760 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1762 $result = $this->callAPISuccessGetSingle($entity, array(
1767 $this->callAPISuccess($entity, 'Delete', array(
1771 $dateFields = $keys = $dateTimeFields = array();
1772 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1773 foreach ($fields['values'] as $field => $settings) {
1774 if (array_key_exists($field, $result)) {
1775 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1778 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1780 $type = CRM_Utils_Array
::value('type', $settings);
1781 if ($type == CRM_Utils_Type
::T_DATE
) {
1782 $dateFields[] = $settings['name'];
1783 // we should identify both real names & unique names as dates
1784 if ($field != $settings['name']) {
1785 $dateFields[] = $field;
1788 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1789 $dateTimeFields[] = $settings['name'];
1790 // we should identify both real names & unique names as dates
1791 if ($field != $settings['name']) {
1792 $dateTimeFields[] = $field;
1797 if (strtolower($entity) == 'contribution') {
1798 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1799 // this is not returned in id format
1800 unset($params['payment_instrument_id']);
1801 $params['contribution_source'] = $params['source'];
1802 unset($params['source']);
1805 foreach ($params as $key => $value) {
1806 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1809 if (in_array($key, $dateFields)) {
1810 $value = date('Y-m-d', strtotime($value));
1811 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1813 if (in_array($key, $dateTimeFields)) {
1814 $value = date('Y-m-d H:i:s', strtotime($value));
1815 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1817 $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);
1822 * Get formatted values in the actual and expected result.
1823 * @param array $actual
1824 * Actual calculated values.
1825 * @param array $expected
1828 public function checkArrayEquals(&$actual, &$expected) {
1829 self
::unsetId($actual);
1830 self
::unsetId($expected);
1831 $this->assertEquals($actual, $expected);
1835 * Unset the key 'id' from the array
1836 * @param array $unformattedArray
1837 * The array from which the 'id' has to be unset.
1839 public static function unsetId(&$unformattedArray) {
1840 $formattedArray = array();
1841 if (array_key_exists('id', $unformattedArray)) {
1842 unset($unformattedArray['id']);
1844 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1845 foreach ($unformattedArray['values'] as $key => $value) {
1846 if (is_array($value)) {
1847 foreach ($value as $k => $v) {
1853 elseif ($key == 'id') {
1854 $unformattedArray[$key];
1856 $formattedArray = array($value);
1858 $unformattedArray['values'] = $formattedArray;
1863 * Helper to enable/disable custom directory support
1865 * @param array $customDirs
1867 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1868 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1870 public function customDirectories($customDirs) {
1871 $config = CRM_Core_Config
::singleton();
1873 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1874 unset($config->customPHPPathDir
);
1876 elseif ($customDirs['php_path'] === TRUE) {
1877 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1880 $config->customPHPPathDir
= $php_path;
1883 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1884 unset($config->customTemplateDir
);
1886 elseif ($customDirs['template_path'] === TRUE) {
1887 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1890 $config->customTemplateDir
= $template_path;
1895 * Generate a temporary folder.
1897 * @param string $prefix
1900 public function createTempDir($prefix = 'test-') {
1901 $tempDir = CRM_Utils_File
::tempdir($prefix);
1902 $this->tempDirs
[] = $tempDir;
1906 public function cleanTempDirs() {
1907 if (!is_array($this->tempDirs
)) {
1908 // fix test errors where this is not set
1911 foreach ($this->tempDirs
as $tempDir) {
1912 if (is_dir($tempDir)) {
1913 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1919 * Temporarily replace the singleton extension with a different one.
1920 * @param \CRM_Extension_System $system
1922 public function setExtensionSystem(CRM_Extension_System
$system) {
1923 if ($this->origExtensionSystem
== NULL) {
1924 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1926 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1929 public function unsetExtensionSystem() {
1930 if ($this->origExtensionSystem
!== NULL) {
1931 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1932 $this->origExtensionSystem
= NULL;
1937 * Temporarily alter the settings-metadata to add a mock setting.
1939 * WARNING: The setting metadata will disappear on the next cache-clear.
1944 public function setMockSettingsMetaData($extras) {
1945 Civi
::service('settings_manager')->flush();
1947 CRM_Utils_Hook
::singleton()
1948 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
1949 $metadata = array_merge($metadata, $extras);
1952 $fields = $this->callAPISuccess('setting', 'getfields', array());
1953 foreach ($extras as $key => $spec) {
1954 $this->assertNotEmpty($spec['title']);
1955 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
1960 * @param string $name
1962 public function financialAccountDelete($name) {
1963 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
1964 $financialAccount->name
= $name;
1965 if ($financialAccount->find(TRUE)) {
1966 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
1967 $entityFinancialType->financial_account_id
= $financialAccount->id
;
1968 $entityFinancialType->delete();
1969 $financialAccount->delete();
1974 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
1975 * (NB unclear if this is still required)
1977 public function _sethtmlGlobals() {
1978 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
1979 'required' => array(
1980 'html_quickform_rule_required',
1981 'HTML/QuickForm/Rule/Required.php',
1983 'maxlength' => array(
1984 'html_quickform_rule_range',
1985 'HTML/QuickForm/Rule/Range.php',
1987 'minlength' => array(
1988 'html_quickform_rule_range',
1989 'HTML/QuickForm/Rule/Range.php',
1991 'rangelength' => array(
1992 'html_quickform_rule_range',
1993 'HTML/QuickForm/Rule/Range.php',
1996 'html_quickform_rule_email',
1997 'HTML/QuickForm/Rule/Email.php',
2000 'html_quickform_rule_regex',
2001 'HTML/QuickForm/Rule/Regex.php',
2003 'lettersonly' => array(
2004 'html_quickform_rule_regex',
2005 'HTML/QuickForm/Rule/Regex.php',
2007 'alphanumeric' => array(
2008 'html_quickform_rule_regex',
2009 'HTML/QuickForm/Rule/Regex.php',
2012 'html_quickform_rule_regex',
2013 'HTML/QuickForm/Rule/Regex.php',
2015 'nopunctuation' => array(
2016 'html_quickform_rule_regex',
2017 'HTML/QuickForm/Rule/Regex.php',
2020 'html_quickform_rule_regex',
2021 'HTML/QuickForm/Rule/Regex.php',
2023 'callback' => array(
2024 'html_quickform_rule_callback',
2025 'HTML/QuickForm/Rule/Callback.php',
2028 'html_quickform_rule_compare',
2029 'HTML/QuickForm/Rule/Compare.php',
2032 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2033 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2035 'HTML/QuickForm/group.php',
2036 'HTML_QuickForm_group',
2039 'HTML/QuickForm/hidden.php',
2040 'HTML_QuickForm_hidden',
2043 'HTML/QuickForm/reset.php',
2044 'HTML_QuickForm_reset',
2046 'checkbox' => array(
2047 'HTML/QuickForm/checkbox.php',
2048 'HTML_QuickForm_checkbox',
2051 'HTML/QuickForm/file.php',
2052 'HTML_QuickForm_file',
2055 'HTML/QuickForm/image.php',
2056 'HTML_QuickForm_image',
2058 'password' => array(
2059 'HTML/QuickForm/password.php',
2060 'HTML_QuickForm_password',
2063 'HTML/QuickForm/radio.php',
2064 'HTML_QuickForm_radio',
2067 'HTML/QuickForm/button.php',
2068 'HTML_QuickForm_button',
2071 'HTML/QuickForm/submit.php',
2072 'HTML_QuickForm_submit',
2075 'HTML/QuickForm/select.php',
2076 'HTML_QuickForm_select',
2078 'hiddenselect' => array(
2079 'HTML/QuickForm/hiddenselect.php',
2080 'HTML_QuickForm_hiddenselect',
2083 'HTML/QuickForm/text.php',
2084 'HTML_QuickForm_text',
2086 'textarea' => array(
2087 'HTML/QuickForm/textarea.php',
2088 'HTML_QuickForm_textarea',
2090 'fckeditor' => array(
2091 'HTML/QuickForm/fckeditor.php',
2092 'HTML_QuickForm_FCKEditor',
2095 'HTML/QuickForm/tinymce.php',
2096 'HTML_QuickForm_TinyMCE',
2098 'dojoeditor' => array(
2099 'HTML/QuickForm/dojoeditor.php',
2100 'HTML_QuickForm_dojoeditor',
2103 'HTML/QuickForm/link.php',
2104 'HTML_QuickForm_link',
2106 'advcheckbox' => array(
2107 'HTML/QuickForm/advcheckbox.php',
2108 'HTML_QuickForm_advcheckbox',
2111 'HTML/QuickForm/date.php',
2112 'HTML_QuickForm_date',
2115 'HTML/QuickForm/static.php',
2116 'HTML_QuickForm_static',
2119 'HTML/QuickForm/header.php',
2120 'HTML_QuickForm_header',
2123 'HTML/QuickForm/html.php',
2124 'HTML_QuickForm_html',
2126 'hierselect' => array(
2127 'HTML/QuickForm/hierselect.php',
2128 'HTML_QuickForm_hierselect',
2130 'autocomplete' => array(
2131 'HTML/QuickForm/autocomplete.php',
2132 'HTML_QuickForm_autocomplete',
2135 'HTML/QuickForm/xbutton.php',
2136 'HTML_QuickForm_xbutton',
2138 'advmultiselect' => array(
2139 'HTML/QuickForm/advmultiselect.php',
2140 'HTML_QuickForm_advmultiselect',
2146 * Set up an acl allowing contact to see 2 specified groups
2147 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2149 * You need to have pre-created these groups & created the user e.g
2150 * $this->createLoggedInUser();
2151 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2152 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2154 * @param bool $isProfile
2156 public function setupACL($isProfile = FALSE) {
2158 $_REQUEST = $this->_params
;
2160 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2161 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2162 $ov = new CRM_Core_DAO_OptionValue();
2163 $ov->option_group_id
= $optionGroupID;
2165 if ($ov->find(TRUE)) {
2166 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2168 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2169 'option_group_id' => $optionGroupID,
2170 'label' => 'pick me',
2174 CRM_Core_DAO
::executeQuery("
2175 TRUNCATE civicrm_acl_cache
2178 CRM_Core_DAO
::executeQuery("
2179 TRUNCATE civicrm_acl_contact_cache
2182 CRM_Core_DAO
::executeQuery("
2183 INSERT INTO civicrm_acl_entity_role (
2184 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2185 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2189 CRM_Core_DAO
::executeQuery("
2190 INSERT INTO civicrm_acl (
2191 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2194 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2199 CRM_Core_DAO
::executeQuery("
2200 INSERT INTO civicrm_acl (
2201 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2204 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2208 CRM_Core_DAO
::executeQuery("
2209 INSERT INTO civicrm_acl (
2210 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2213 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2218 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2219 $this->callAPISuccess('group_contact', 'create', array(
2220 'group_id' => $this->_permissionedGroup
,
2221 'contact_id' => $this->_loggedInUser
,
2226 CRM_ACL_BAO_Cache
::resetCache();
2227 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2232 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2234 public function offsetDefaultPriceSet() {
2235 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2236 $firstID = $contributionPriceSet['id'];
2237 $this->callAPISuccess('price_set', 'create', array(
2238 'id' => $contributionPriceSet['id'],
2242 unset($contributionPriceSet['id']);
2243 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2244 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2245 'price_set_id' => $firstID,
2246 'options' => array('limit' => 1),
2248 unset($priceField['id']);
2249 $priceField['price_set_id'] = $newPriceSet['id'];
2250 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2251 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2252 'price_set_id' => $firstID,
2254 'options' => array('limit' => 1),
2257 unset($priceFieldValue['id']);
2258 //create some padding to use up ids
2259 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2260 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2261 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2265 * Create an instance of the paypal processor.
2266 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2267 * this parent class & we don't have a structure for that yet
2268 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2269 * & the best protection against that is the functions this class affords
2270 * @param array $params
2271 * @return int $result['id'] payment processor id
2273 public function paymentProcessorCreate($params = array()) {
2274 $params = array_merge(array(
2276 'domain_id' => CRM_Core_Config
::domainID(),
2277 'payment_processor_type_id' => 'PayPal',
2281 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2282 'password' => '1183377788',
2283 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2284 'url_site' => 'https://www.sandbox.paypal.com/',
2285 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2286 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2287 'class_name' => 'Payment_PayPalImpl',
2288 'billing_mode' => 3,
2289 'financial_type_id' => 1,
2290 'financial_account_id' => 12,
2291 // Credit card = 1 so can pass 'by accident'.
2292 'payment_instrument_id' => 'Debit Card',
2294 if (!is_numeric($params['payment_processor_type_id'])) {
2295 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2297 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2298 'name' => $params['payment_processor_type_id'],
2302 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2303 return $result['id'];
2307 * Set up initial recurring payment allowing subsequent IPN payments.
2309 * @param array $recurParams (Optional)
2310 * @param array $contributionParams (Optional)
2312 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2313 $contributionParams = array_merge([
2314 'total_amount' => '200',
2315 'invoice_id' => $this->_invoiceID
,
2316 'financial_type_id' => 'Donation',
2317 'contribution_status_id' => 'Pending',
2318 'contact_id' => $this->_contactID
,
2319 'contribution_page_id' => $this->_contributionPageID
,
2320 'payment_processor_id' => $this->_paymentProcessorID
,
2322 'skipCleanMoney' => TRUE,
2323 ], $contributionParams);
2324 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2325 'contact_id' => $this->_contactID
,
2328 'installments' => 5,
2329 'frequency_unit' => 'Month',
2330 'frequency_interval' => 1,
2331 'invoice_id' => $this->_invoiceID
,
2332 'contribution_status_id' => 2,
2333 'payment_processor_id' => $this->_paymentProcessorID
,
2334 // processor provided ID - use contact ID as proxy.
2335 'processor_id' => $this->_contactID
,
2336 'api.contribution.create' => $contributionParams,
2338 $this->_contributionRecurID
= $contributionRecur['id'];
2339 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2343 * 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
2345 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2347 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2348 $membershipParams = $recurParams = array();
2349 if (!empty($params['duration_unit'])) {
2350 $membershipParams['duration_unit'] = $params['duration_unit'];
2352 if (!empty($params['frequency_unit'])) {
2353 $recurParams['frequency_unit'] = $params['frequency_unit'];
2356 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2357 //create a contribution so our membership & contribution don't both have id = 1
2358 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2359 $this->contributionCreate(array(
2360 'contact_id' => $this->_contactID
,
2362 'financial_type_id' => 1,
2363 'invoice_id' => 'abcd',
2367 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2369 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2370 'contact_id' => $this->_contactID
,
2371 'membership_type_id' => $this->ids
['membership_type'],
2372 'contribution_recur_id' => $this->_contributionRecurID
,
2373 'format.only_id' => TRUE,
2375 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2376 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2378 $this->callAPISuccess('line_item', 'create', array(
2379 'entity_table' => 'civicrm_membership',
2380 'entity_id' => $this->ids
['membership'],
2381 'contribution_id' => $this->_contributionID
,
2382 'label' => 'General',
2384 'unit_price' => 200,
2385 'line_total' => 200,
2386 'financial_type_id' => 1,
2387 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2389 'label' => 'Membership Amount',
2390 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2392 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2394 'label' => 'General',
2395 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2398 $this->callAPISuccess('membership_payment', 'create', array(
2399 'contribution_id' => $this->_contributionID
,
2400 'membership_id' => $this->ids
['membership'],
2409 public function CiviUnitTestCase_fatalErrorHandler($message) {
2410 throw new Exception("{$message['message']}: {$message['code']}");
2414 * Wrap the entire test case in a transaction.
2416 * Only subsequent DB statements will be wrapped in TX -- this cannot
2417 * retroactively wrap old DB statements. Therefore, it makes sense to
2418 * call this at the beginning of setUp().
2420 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2421 * this option does not work with, e.g., custom-data.
2423 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2424 * if TRUNCATE or ALTER is called while using a transaction.
2427 * Whether to use nesting or reference-counting.
2429 public function useTransaction($nest = TRUE) {
2431 $this->tx
= new CRM_Core_Transaction($nest);
2432 $this->tx
->rollback();
2437 * Assert the attachment exists.
2439 * @param bool $exists
2440 * @param array $apiResult
2442 protected function assertAttachmentExistence($exists, $apiResult) {
2443 $fileId = $apiResult['id'];
2444 $this->assertTrue(is_numeric($fileId));
2445 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2446 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2447 1 => array($fileId, 'Int'),
2449 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2450 1 => array($fileId, 'Int'),
2455 * Create a price set for an event.
2457 * @param int $feeTotal
2458 * @param int $minAmt
2459 * @param string $type
2464 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2465 // creating price set, price field
2466 $paramsSet['title'] = 'Price Set';
2467 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2468 $paramsSet['is_active'] = FALSE;
2469 $paramsSet['extends'] = 1;
2470 $paramsSet['min_amount'] = $minAmt;
2472 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2473 $this->_ids
['price_set'] = $priceSet->id
;
2475 $paramsField = array(
2476 'label' => 'Price Field',
2477 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2478 'html_type' => $type,
2479 'price' => $feeTotal,
2480 'option_label' => array('1' => 'Price Field'),
2481 'option_value' => array('1' => $feeTotal),
2482 'option_name' => array('1' => $feeTotal),
2483 'option_weight' => array('1' => 1),
2484 'option_amount' => array('1' => 1),
2485 'is_display_amounts' => 1,
2487 'options_per_line' => 1,
2488 'is_active' => array('1' => 1),
2489 'price_set_id' => $this->_ids
['price_set'],
2490 'is_enter_qty' => 1,
2491 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2493 if ($type === 'Radio') {
2494 $paramsField['is_enter_qty'] = 0;
2495 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2496 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2498 CRM_Price_BAO_PriceField
::create($paramsField);
2499 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2500 $this->_ids
['price_field'] = array_keys($fields['values']);
2501 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2502 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2504 return $this->_ids
['price_set'];
2508 * Add a profile to a contribution page.
2510 * @param string $name
2511 * @param int $contributionPageID
2512 * @param string $module
2514 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2516 'uf_group_id' => $name,
2517 'module' => $module,
2518 'entity_table' => 'civicrm_contribution_page',
2519 'entity_id' => $contributionPageID,
2522 if ($module !== 'CiviContribute') {
2523 $params['module_data'] = [$module => []];
2525 $this->callAPISuccess('UFJoin', 'create', $params);
2529 * Add participant with contribution
2533 protected function createParticipantWithContribution() {
2534 // creating price set, price field
2535 $this->_contactId
= $this->individualCreate();
2536 $event = $this->eventCreate();
2537 $this->_eventId
= $event['id'];
2538 $eventParams = array(
2539 'id' => $this->_eventId
,
2540 'financial_type_id' => 4,
2543 $this->callAPISuccess('event', 'create', $eventParams);
2544 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2545 $participantParams = array(
2546 'financial_type_id' => 4,
2547 'event_id' => $this->_eventId
,
2550 'fee_currency' => 'USD',
2551 'contact_id' => $this->_contactId
,
2553 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2554 $contributionParams = array(
2555 'total_amount' => 150,
2556 'currency' => 'USD',
2557 'contact_id' => $this->_contactId
,
2558 'financial_type_id' => 4,
2559 'contribution_status_id' => 1,
2560 'partial_payment_total' => 300.00,
2561 'partial_amount_to_pay' => 150,
2562 'contribution_mode' => 'participant',
2563 'participant_id' => $participant['id'],
2565 foreach ($priceFields['values'] as $key => $priceField) {
2566 $lineItems[1][$key] = array(
2567 'price_field_id' => $priceField['price_field_id'],
2568 'price_field_value_id' => $priceField['id'],
2569 'label' => $priceField['label'],
2570 'field_title' => $priceField['label'],
2572 'unit_price' => $priceField['amount'],
2573 'line_total' => $priceField['amount'],
2574 'financial_type_id' => $priceField['financial_type_id'],
2577 $contributionParams['line_item'] = $lineItems;
2578 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2579 $paymentParticipant = array(
2580 'participant_id' => $participant['id'],
2581 'contribution_id' => $contribution['id'],
2583 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2584 return array($lineItems, $contribution);
2590 * @param string $component
2591 * @param int $componentId
2592 * @param array $priceFieldOptions
2596 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2597 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2598 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2599 $paramsSet['is_active'] = TRUE;
2600 $paramsSet['financial_type_id'] = 'Event Fee';
2601 $paramsSet['extends'] = 1;
2602 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2603 $priceSetId = $priceSet['id'];
2604 //Checking for priceset added in the table.
2605 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2606 'id', $paramsSet['title'], 'Check DB for created priceset'
2608 $paramsField = array_merge(array(
2609 'label' => 'Price Field',
2610 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2611 'html_type' => 'CheckBox',
2612 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2613 'option_value' => array('1' => 100, '2' => 200),
2614 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2615 'option_weight' => array('1' => 1, '2' => 2),
2616 'option_amount' => array('1' => 100, '2' => 200),
2617 'is_display_amounts' => 1,
2619 'options_per_line' => 1,
2620 'is_active' => array('1' => 1, '2' => 1),
2621 'price_set_id' => $priceSet['id'],
2622 'is_enter_qty' => 1,
2623 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2624 ), $priceFieldOptions);
2626 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2628 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2630 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2634 * Replace the template with a test-oriented template designed to show all the variables.
2636 * @param string $templateName
2638 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2639 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2640 CRM_Core_DAO
::executeQuery(
2641 "UPDATE civicrm_option_group og
2642 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2643 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2644 SET m.msg_html = '{$testTemplate}'
2645 WHERE og.name = 'msg_tpl_workflow_contribution'
2646 AND ov.name = '{$templateName}'
2647 AND m.is_default = 1"
2652 * Reinstate the default template.
2654 * @param string $templateName
2656 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2657 CRM_Core_DAO
::executeQuery(
2658 "UPDATE civicrm_option_group og
2659 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2660 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2661 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2662 SET m.msg_html = m2.msg_html
2663 WHERE og.name = 'msg_tpl_workflow_contribution'
2664 AND ov.name = '{$templateName}'
2665 AND m.is_default = 1"
2670 * Flush statics relating to financial type.
2672 protected function flushFinancialTypeStatics() {
2673 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2674 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2676 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2677 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2679 CRM_Contribute_PseudoConstant
::flush('financialType');
2680 CRM_Contribute_PseudoConstant
::flush('membershipType');
2681 // Pseudoconstants may be saved to the cache table.
2682 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2683 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2684 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2688 * Set the permissions to the supplied array.
2690 * @param array $permissions
2692 protected function setPermissions($permissions) {
2693 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2694 $this->flushFinancialTypeStatics();
2698 * @param array $params
2701 public function _checkFinancialRecords($params, $context) {
2702 $entityParams = array(
2703 'entity_id' => $params['id'],
2704 'entity_table' => 'civicrm_contribution',
2706 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2707 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2708 if ($context == 'pending') {
2709 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2710 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2713 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2714 $trxnParams = array(
2715 'id' => $trxn['financial_trxn_id'],
2717 if ($context != 'online' && $context != 'payLater') {
2718 $compareParams = array(
2719 'to_financial_account_id' => 6,
2720 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2724 if ($context == 'feeAmount') {
2725 $compareParams['fee_amount'] = 50;
2727 elseif ($context == 'online') {
2728 $compareParams = array(
2729 'to_financial_account_id' => 12,
2730 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2732 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2735 elseif ($context == 'payLater') {
2736 $compareParams = array(
2737 'to_financial_account_id' => 7,
2738 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2742 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2743 $entityParams = array(
2744 'financial_trxn_id' => $trxn['financial_trxn_id'],
2745 'entity_table' => 'civicrm_financial_item',
2747 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2748 $fitemParams = array(
2749 'id' => $entityTrxn['entity_id'],
2751 $compareParams = array(
2752 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2754 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2756 if ($context == 'payLater') {
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),
2763 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2764 if ($context == 'feeAmount') {
2766 'entity_id' => $params['id'],
2767 'entity_table' => 'civicrm_contribution',
2769 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2770 $trxnParams = array(
2771 'id' => $maxTrxn['financial_trxn_id'],
2773 $compareParams = array(
2774 'to_financial_account_id' => 5,
2775 'from_financial_account_id' => 6,
2776 'total_amount' => 50,
2779 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2780 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2781 $fitemParams = array(
2782 'entity_id' => $trxnId['financialTrxnId'],
2783 'entity_table' => 'civicrm_financial_trxn',
2785 $compareParams = array(
2788 'financial_account_id' => 5,
2790 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2792 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2793 // line should be copied into all the functions that call this function & evaluated there
2794 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2795 // when calling completeTransaction or repeatTransaction.
2796 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2800 * Return financial type id on basis of name
2802 * @param string $name Financial type m/c name
2806 public function getFinancialTypeId($name) {
2807 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2811 * Cleanup function for contents of $this->ids.
2813 * This is a best effort cleanup to use in tear downs etc.
2815 * It will not fail if the data has already been removed (some tests may do
2816 * their own cleanup).
2818 protected function cleanUpSetUpIDs() {
2819 foreach ($this->setupIDs
as $entity => $id) {
2821 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2823 catch (CiviCRM_API3_Exception
$e) {
2824 // This is a best-effort cleanup function, ignore.
2830 * Create Financial Type.
2832 * @param array $params
2836 protected function createFinancialType($params = array()) {
2837 $params = array_merge($params,
2839 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2843 return $this->callAPISuccess('FinancialType', 'create', $params);
2847 * Create Payment Instrument.
2849 * @param array $params
2850 * @param string $financialAccountName
2854 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2855 $params = array_merge(array(
2856 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2857 'option_group_id' => 'payment_instrument',
2860 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2862 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2864 $financialAccountParams = [
2865 'entity_table' => 'civicrm_option_value',
2866 'entity_id' => $newPaymentInstrument,
2867 'account_relationship' => $relationTypeID,
2868 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2870 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2872 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2876 * Enable Tax and Invoicing
2878 protected function enableTaxAndInvoicing($params = array()) {
2879 // Enable component contribute setting
2880 $contributeSetting = array_merge($params,
2883 'invoice_prefix' => 'INV_',
2884 'credit_notes_prefix' => 'CN_',
2886 'due_date_period' => 'days',
2888 'is_email_pdf' => 1,
2889 'tax_term' => 'Sales Tax',
2890 'tax_display_settings' => 'Inclusive',
2893 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2897 * Enable Tax and Invoicing
2899 protected function disableTaxAndInvoicing($params = array()) {
2900 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2901 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2903 // Enable component contribute setting
2904 $contributeSetting = array_merge($params,
2909 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2913 * Add Sales Tax relation for financial type with financial account.
2915 * @param int $financialTypeId
2919 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2921 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2922 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2923 'is_deductible' => 1,
2928 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
2929 $entityParams = array(
2930 'entity_table' => 'civicrm_financial_type',
2931 'entity_id' => $financialTypeId,
2932 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
2935 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
2936 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
2938 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
2939 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
2940 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
2941 $dao->copyValues($entityParams);
2943 if ($dao->fetch()) {
2944 $entityParams['id'] = $dao->id
;
2946 $entityParams['financial_account_id'] = $account->id
;
2948 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
2952 * Create price set with contribution test for test setup.
2954 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
2955 * on parent class at some point (fn is not in 4.4).
2958 * @param array $params
2960 public function createPriceSetWithPage($entity = NULL, $params = array()) {
2961 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
2962 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
2963 'title' => "Test Contribution Page",
2964 'financial_type_id' => 1,
2965 'currency' => 'NZD',
2966 'goal_amount' => 50,
2967 'is_pay_later' => 1,
2968 'is_monetary' => TRUE,
2969 'is_email_receipt' => FALSE,
2971 $priceSet = $this->callAPISuccess('price_set', 'create', array(
2972 'is_quick_config' => 0,
2973 'extends' => 'CiviMember',
2974 'financial_type_id' => 1,
2975 'title' => 'my Page',
2977 $priceSetID = $priceSet['id'];
2979 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
2980 $priceField = $this->callAPISuccess('price_field', 'create', array(
2981 'price_set_id' => $priceSetID,
2982 'label' => 'Goat Breed',
2983 'html_type' => 'Radio',
2985 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
2986 'price_set_id' => $priceSetID,
2987 'price_field_id' => $priceField['id'],
2988 'label' => 'Long Haired Goat',
2990 'financial_type_id' => 'Donation',
2991 'membership_type_id' => $membershipTypeID,
2992 'membership_num_terms' => 1,
2994 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
2995 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
2996 'price_set_id' => $priceSetID,
2997 'price_field_id' => $priceField['id'],
2998 'label' => 'Shoe-eating Goat',
3000 'financial_type_id' => 'Donation',
3001 'membership_type_id' => $membershipTypeID,
3002 'membership_num_terms' => 2,
3004 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3006 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3007 'price_set_id' => $priceSetID,
3008 'price_field_id' => $priceField['id'],
3009 'label' => 'Shoe-eating Goat',
3011 'financial_type_id' => 'Donation',
3013 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3015 $this->_ids
['price_set'] = $priceSetID;
3016 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3017 $this->_ids
['price_field'] = array($priceField['id']);
3019 $this->_ids
['membership_type'] = $membershipTypeID;
3023 * Only specified contact returned.
3024 * @implements CRM_Utils_Hook::aclWhereClause
3027 * @param $whereTables
3031 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3032 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3036 * @implements CRM_Utils_Hook::selectWhereClause
3038 * @param string $entity
3039 * @param array $clauses
3041 public function selectWhereClauseHook($entity, &$clauses) {
3042 if ($entity == 'Event') {
3043 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3048 * An implementation of hook_civicrm_post used with all our test cases.
3051 * @param string $objectName
3052 * @param int $objectId
3055 public function onPost($op, $objectName, $objectId, &$objectRef) {
3056 if ($op == 'create' && $objectName == 'Individual') {
3057 CRM_Core_DAO
::executeQuery(
3058 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3060 1 => array($objectId, 'Integer'),
3065 if ($op == 'edit' && $objectName == 'Participant') {
3067 1 => array($objectId, 'Integer'),
3069 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3070 CRM_Core_DAO
::executeQuery($query, $params);
3075 * Instantiate form object.
3077 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3079 * @param string $class
3080 * Name of form class.
3082 * @return \CRM_Core_Form
3084 public function getFormObject($class) {
3085 $form = new $class();
3086 $_SERVER['REQUEST_METHOD'] = 'GET';
3087 $form->controller
= new CRM_Core_Controller();
3092 * Get possible thousand separators.
3096 public function getThousandSeparators() {
3097 return array(array('.'), array(','));
3101 * Set the separators for thousands and decimal points.
3103 * @param string $thousandSeparator
3105 protected function setCurrencySeparators($thousandSeparator) {
3106 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3108 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3112 * Format money as it would be input.
3114 * @param string $amount
3118 protected function formatMoneyInput($amount) {
3119 return CRM_Utils_Money
::format($amount, NULL, '%a');
3123 * Get the contribution object.
3125 * @param int $contributionID
3127 * @return \CRM_Contribute_BAO_Contribution
3129 protected function getContributionObject($contributionID) {
3130 $contributionObj = new CRM_Contribute_BAO_Contribution();
3131 $contributionObj->id
= $contributionID;
3132 $contributionObj->find(TRUE);
3133 return $contributionObj;
3137 * Enable multilingual.
3139 public function enableMultilingual() {
3140 $this->callAPISuccess('Setting', 'create', array(
3141 'lcMessages' => 'en_US',
3142 'languageLimit' => array(
3147 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3150 $dbLocale = '_en_US';