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\Api4\Address
;
30 use Civi\Api4\Contribution
;
31 use Civi\Api4\CustomField
;
32 use Civi\Api4\CustomGroup
;
33 use Civi\Api4\FinancialType
;
34 use Civi\Api4\LineItem
;
35 use Civi\Api4\MembershipType
;
36 use Civi\Api4\OptionGroup
;
38 use Civi\Api4\RelationshipType
;
39 use Civi\Payment\System
;
40 use Civi\Api4\OptionValue
;
41 use Civi\Test\Api3DocTrait
;
42 use League\Csv\Reader
;
45 * Include class definitions
47 require_once 'api/api.php';
48 define('API_LATEST_VERSION', 3);
51 * Base class for CiviCRM unit tests
53 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
54 * may opt for one or neither:
56 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
57 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
58 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
59 * 2. useTransaction() executes the test inside a transaction. It's easier to use
60 * (because you don't need to identify specific tables), but it doesn't work for tests
61 * which manipulate schema or truncate data -- and could behave inconsistently
62 * for tests which specifically examine DB transactions.
64 * Common functions for unit tests
68 class CiviUnitTestCase
extends PHPUnit\Framework\TestCase
{
71 use \Civi\Test\GenericAssertionsTrait
;
72 use \Civi\Test\DbTestTrait
;
73 use \Civi\Test\ContactTestTrait
;
74 use \Civi\Test\MailingTestTrait
;
77 * Database has been initialized.
81 private static $dbInit = FALSE;
84 * Database connection.
86 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
95 static protected $_dbName;
102 protected $_apiversion = 3;
105 * Track tables we have modified during a test.
109 protected $_tablesToTruncate = [];
113 * Array of temporary directory names
119 * populateOnce allows to skip db resets in setUp
121 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
122 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
125 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
127 * @see http://forum.civicrm.org/index.php/topic,18065.0.html
129 public static $populateOnce = FALSE;
132 * DBResetRequired allows skipping DB reset
133 * in specific test case. If you still need
134 * to reset single test (method) of such case, call
135 * $this->cleanDB() in the first line of this
139 public $DBResetRequired = TRUE;
142 * @var CRM_Core_Transaction|null
147 * Array of IDs created to support the test.
150 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
157 * Should financials be checked after the test but before tear down.
159 * Ideally all tests (or at least all that call any financial api calls ) should do this but there
160 * are some test data issues and some real bugs currently blocking.
164 protected $isValidateFinancialsOnPostAssert = TRUE;
167 * Should location types be checked to ensure primary addresses are correctly assigned after each test.
171 protected $isLocationTypesOnPostAssert = TRUE;
174 * Has the test class been verified as 'getsafe'.
176 * If a class is getsafe it means that where
177 * callApiSuccess is called 'return' is specified or 'return' =>'id'
178 * can be added by that function. This is part of getting away
179 * from open-ended get calls.
181 * Eventually we want to not be doing these in our test classes & start
182 * to work to not do them in our main code base. Note they mainly
183 * cause issues for activity.get and contact.get as these are where the
184 * too many joins limit is most likely to be hit.
188 protected $isGetSafe = FALSE;
191 * Class used for hooks during tests.
193 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
195 * $this->hookClass->setHook('civicrm_aclWhereClause', [$this, 'aclWhereHookAllResults']);
197 * @var \CRM_Utils_Hook_UnitTests
203 * Common values to be re-used multiple times within a class - usually to create the relevant entity
205 protected $_params = [];
208 * @var CRM_Extension_System
210 protected $origExtensionSystem;
213 * Array of IDs created during test setup routine.
215 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
219 public $setupIDs = [];
224 * Because we are overriding the parent class constructor, we
225 * need to show the same arguments as exist in the constructor of
226 * PHPUnit_Framework_TestCase, since
227 * PHPUnit_Framework_TestSuite::createTest() creates a
228 * ReflectionClass of the Test class and checks the constructor
229 * of that class to decide how to set up the test.
231 * @param string $name
233 * @param string $dataName
235 public function __construct($name = NULL, array $data = [], $dataName = '') {
236 parent
::__construct($name, $data, $dataName);
238 // we need full error reporting
239 error_reporting(E_ALL
& ~E_NOTICE
);
241 self
::$_dbName = self
::getDBName();
243 // also load the class loader
244 require_once 'CRM/Core/ClassLoader.php';
245 CRM_Core_ClassLoader
::singleton()->register();
246 if (function_exists('_civix_phpunit_setUp')) {
247 // FIXME: loosen coupling
248 _civix_phpunit_setUp();
253 * Override to run the test and assert its state.
257 * @throws \PHPUnit_Framework_IncompleteTest
258 * @throws \PHPUnit_Framework_SkippedTest
260 protected function runTest() {
262 return parent
::runTest();
264 catch (PEAR_Exception
$e) {
265 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
266 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
273 public function requireDBReset() {
274 return $this->DBResetRequired
;
280 public static function getDBName() {
281 static $dbName = NULL;
282 if ($dbName === NULL) {
283 require_once "DB.php";
284 $dsn = CRM_Utils_SQL
::autoSwitchDSN(CIVICRM_DSN
);
285 $dsninfo = DB
::parseDSN($dsn);
286 $dbName = $dsninfo['database'];
292 * Create database connection for this instance.
294 * Initialize the test database if it hasn't been initialized
297 protected function getConnection() {
298 if (!self
::$dbInit) {
299 $dbName = self
::getDBName();
301 // install test database
302 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
304 static::_populateDB(FALSE, $this);
306 self
::$dbInit = TRUE;
312 * Required implementation of abstract method.
314 protected function getDataSet() {
318 * @param bool $perClass
319 * @param null $object
322 * TRUE if the populate logic runs; FALSE if it is skipped
324 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
325 if (CIVICRM_UF
!== 'UnitTests') {
326 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
329 if ($perClass ||
$object == NULL) {
333 $dbreset = $object->requireDBReset();
336 if (self
::$populateOnce ||
!$dbreset) {
339 self
::$populateOnce = NULL;
341 Civi\Test
::data()->populate();
346 public static function setUpBeforeClass(): void
{
347 static::_populateDB(TRUE);
349 // also set this global hack
350 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = [];
354 * Common setup functions for all unit tests.
356 protected function setUp(): void
{
358 $session = CRM_Core_Session
::singleton();
359 $session->set('userID', NULL);
361 $this->_apiversion
= 3;
363 // Use a temporary file for STDIN
364 $GLOBALS['stdin'] = tmpfile();
365 if ($GLOBALS['stdin'] === FALSE) {
366 echo "Couldn't open temporary file\n";
370 // Get and save a connection to the database
371 $this->_dbconn
= $this->getConnection();
373 // reload database before each test
374 // $this->_populateDB();
376 // "initialize" CiviCRM to avoid problems when running single tests
377 // FIXME: look at it closer in second stage
379 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
380 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
382 // disable any left-over test extensions
383 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
385 // reset all the caches
386 CRM_Utils_System
::flushCache();
388 // initialize the object once db is loaded
389 \Civi
::$statics = [];
391 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
393 // when running unit tests, use mockup user framework
394 $this->hookClass
= CRM_Utils_Hook
::singleton();
396 // Make sure the DB connection is setup properly
397 $config->userSystem
->setMySQLTimeZone();
398 $env = new CRM_Utils_Check_Component_Env();
399 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
401 // clear permissions stub to not check permissions
402 $config->userPermissionClass
->permissions
= NULL;
404 //flush component settings
405 CRM_Core_Component
::getEnabledComponents(TRUE);
407 $_REQUEST = $_GET = $_POST = [];
408 error_reporting(E_ALL
);
410 $this->renameLabels();
411 $this->ensureMySQLMode(['IGNORE_SPACE', 'ERROR_FOR_DIVISION_BY_ZERO', 'STRICT_TRANS_TABLES']);
412 putenv('CIVICRM_SMARTY_DEFAULT_ESCAPE=1');
416 * Read everything from the datasets directory and insert into the db.
418 public function loadAllFixtures(): void
{
419 $fixturesDir = __DIR__
. '/../../fixtures';
421 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
423 $jsonFiles = glob($fixturesDir . '/*.json');
424 foreach ($jsonFiles as $jsonFixture) {
425 $json = json_decode(file_get_contents($jsonFixture));
426 foreach ($json as $tableName => $vars) {
427 if ($tableName === 'civicrm_contact') {
428 CRM_Core_DAO
::executeQuery('DELETE c FROM civicrm_contact c LEFT JOIN civicrm_domain d ON d.contact_id = c.id WHERE d.id IS NULL');
431 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
433 foreach ($vars as $entity) {
434 $keys = $values = [];
435 foreach ($entity as $key => $value) {
437 $values[] = is_numeric($value) ?
$value : "'{$value}'";
439 CRM_Core_DAO
::executeQuery("
440 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
447 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
451 * Load the data that used to be handled by the discontinued dbunit class.
453 * This could do with further tidy up - the initial priority is simply to get rid of
454 * the dbunity package which is no longer supported.
456 * @param string $fileName
458 protected function loadXMLDataSet($fileName) {
459 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
460 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
461 foreach ($xml as $tableName => $element) {
462 if (!empty($element)) {
463 foreach ($element as $row) {
464 $keys = $values = [];
465 if (isset($row['@attributes'])) {
466 foreach ($row['@attributes'] as $key => $value) {
468 $values[] = is_numeric($value) ?
$value : "'{$value}'";
471 elseif (!empty($row)) {
472 // cos we copied it & it is inconsistent....
473 foreach ($row as $key => $value) {
475 $values[] = is_numeric($value) ?
$value : "'{$value}'";
479 if (!empty($values)) {
480 CRM_Core_DAO
::executeQuery("
481 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
487 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
491 * Create default domain contacts for the two domains added during test class.
492 * database population.
494 public function createDomainContacts(): void
{
496 $this->organizationCreate(['api.Email.create' => ['email' => 'fixme.domainemail@example.org']]);
497 $this->organizationCreate([
498 'organization_name' => 'Second Domain',
499 'api.Email.create' => ['email' => 'domainemail2@example.org'],
500 'api.Address.create' => [
501 'street_address' => '15 Main St',
502 'location_type_id' => 1,
503 'city' => 'Collinsville',
504 'country_id' => 1228,
505 'state_province_id' => 1003,
506 'postal_code' => 6022,
509 OptionValue
::replace(FALSE)->addWhere(
510 'option_group_id:name', '=', 'from_email_address'
513 'name' => '"FIXME" <info@EXAMPLE.ORG>',
514 'label' => '"FIXME" <info@EXAMPLE.ORG>',
515 ])->setRecords([['domain_id' => 1], ['domain_id' => 2]])->execute();
517 catch (API_Exception
$e) {
518 $this->fail('failed to re-instate domain contacts ' . $e->getMessage());
523 * Common teardown functions for all unit tests.
525 protected function tearDown(): void
{
526 $this->_apiversion
= 3;
527 $this->resetLabels();
529 error_reporting(E_ALL
& ~E_NOTICE
);
530 CRM_Utils_Hook
::singleton()->reset();
531 if ($this->hookClass
) {
532 $this->hookClass
->reset();
534 CRM_Core_Session
::singleton()->reset(1);
537 $this->tx
->rollback()->commit();
540 CRM_Core_Transaction
::forceRollbackIfEnabled();
541 \Civi\Core\Transaction\Manager
::singleton(TRUE);
544 CRM_Core_Transaction
::forceRollbackIfEnabled();
545 \Civi\Core\Transaction\Manager
::singleton(TRUE);
547 $tablesToTruncate = ['civicrm_contact', 'civicrm_uf_match', 'civicrm_email', 'civicrm_address'];
548 $this->quickCleanup($tablesToTruncate);
549 $this->createDomainContacts();
552 $this->cleanTempDirs();
553 $this->unsetExtensionSystem();
554 $this->assertEquals([], CRM_Core_DAO
::$_nullArray);
555 $this->assertEquals(NULL, CRM_Core_DAO
::$_nullObject);
556 // Ensure the destruct runs by unsetting it. Also, unsetting
557 // classes frees memory as they are not otherwise unset until the
564 * CHeck that all tests that have created payments have created them with the right financial entities.
566 * @throws \API_Exception
567 * @throws \CRM_Core_Exception
569 protected function assertPostConditions(): void
{
570 // Reset to version 3 as not all (e.g payments) work on v4
571 $this->_apiversion
= 3;
572 if ($this->isLocationTypesOnPostAssert
) {
573 $this->assertLocationValidity();
575 $this->assertCount(1, OptionGroup
::get(FALSE)
576 ->addWhere('name', '=', 'from_email_address')
578 if (!$this->isValidateFinancialsOnPostAssert
) {
581 $this->validateAllPayments();
582 $this->validateAllContributions();
586 * Create a batch of external API calls which can
587 * be executed concurrently.
590 * $calls = $this->createExternalAPI()
591 * ->addCall('Contact', 'get', ...)
592 * ->addCall('Contact', 'get', ...)
598 * @return \Civi\API\ExternalBatch
599 * @throws PHPUnit_Framework_SkippedTestError
601 public function createExternalAPI() {
602 global $civicrm_root;
604 'version' => $this->_apiversion
,
608 $calls = new \Civi\API\
ExternalBatch($defaultParams);
610 if (!$calls->isSupported()) {
611 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
618 * Create required data based on $this->entity & $this->params
619 * This is just a way to set up the test data for delete & get functions
620 * so the distinction between set
621 * up & tested functions is clearer
626 public function createTestEntity() {
627 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
631 * @param int $contactTypeId
635 public function contactTypeDelete($contactTypeId) {
636 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
638 throw new Exception('Could not delete contact type');
643 * @param array $params
647 public function membershipTypeCreate($params = []) {
648 CRM_Member_PseudoConstant
::flush('membershipType');
649 CRM_Core_Config
::clearDBCache();
650 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
651 $params = array_merge([
653 'duration_unit' => 'year',
654 'duration_interval' => 1,
655 'period_type' => 'rolling',
656 'member_of_contact_id' => $memberOfOrganization,
658 'financial_type_id' => 2,
661 'visibility' => 'Public',
664 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
666 CRM_Member_PseudoConstant
::flush('membershipType');
667 CRM_Utils_Cache
::singleton()->flush();
669 return (int) $result['id'];
675 * @param array $params
679 public function contactMembershipCreate(array $params): int {
680 $params = array_merge([
681 'join_date' => '2007-01-21',
682 'start_date' => '2007-01-21',
683 'end_date' => '2007-12-21',
684 'source' => 'Payment',
685 'membership_type_id' => 'General',
687 if (!is_numeric($params['membership_type_id'])) {
688 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', ['action' => 'create', 'field' => 'membership_type_id']);
689 if (!in_array($params['membership_type_id'], $membershipTypes['values'], TRUE)) {
690 $this->membershipTypeCreate(['name' => $params['membership_type_id']]);
694 $result = $this->callAPISuccess('Membership', 'create', $params);
695 return $result['id'];
699 * Delete Membership Type.
701 * @param array $params
703 public function membershipTypeDelete($params) {
704 $this->callAPISuccess('MembershipType', 'Delete', $params);
708 * @param int $membershipID
710 public function membershipDelete($membershipID) {
711 $deleteParams = ['id' => $membershipID];
712 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
716 * @param string $name
720 public function membershipStatusCreate($name = 'test member status') {
721 $params['name'] = $name;
722 $params['start_event'] = 'start_date';
723 $params['end_event'] = 'end_date';
724 $params['is_current_member'] = 1;
725 $params['is_active'] = 1;
727 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
728 CRM_Member_PseudoConstant
::flush('membershipStatus');
729 return (int) $result['id'];
733 * Delete the given membership status, deleting any memberships of the status first.
735 * @param int $membershipStatusID
737 * @throws \CRM_Core_Exception
739 public function membershipStatusDelete(int $membershipStatusID): void
{
740 $this->callAPISuccess('Membership', 'get', ['status_id' => $membershipStatusID, 'api.Membership.delete' => 1]);
741 $this->callAPISuccess('MembershipStatus', 'Delete', ['id' => $membershipStatusID]);
744 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
745 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
746 $renewedMembershipEndDate = new DateTime($membershipEndDate);
747 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
748 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
749 $renewedMembershipEndDate->add(new DateInterval('P1D'));
750 switch ($durationUnit) {
752 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
756 $renewedMembershipEndDate->add(new DateInterval('P1M'));
759 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
760 return $renewedMembershipEndDate->format('Y-m-d');
764 * Create a relationship type.
766 * @param array $params
770 * @throws \CRM_Core_Exception
772 public function relationshipTypeCreate($params = []) {
773 $params = array_merge([
774 'name_a_b' => 'Relation 1 for relationship type create',
775 'name_b_a' => 'Relation 2 for relationship type create',
776 'contact_type_a' => 'Individual',
777 'contact_type_b' => 'Organization',
782 $result = $this->callAPISuccess('relationship_type', 'create', $params);
783 CRM_Core_PseudoConstant
::flush('relationshipType');
785 return $result['id'];
789 * Delete Relatinship Type.
791 * @param int $relationshipTypeID
793 public function relationshipTypeDelete($relationshipTypeID) {
794 $params['id'] = $relationshipTypeID;
795 $check = $this->callAPISuccess('relationship_type', 'get', $params);
796 if (!empty($check['count'])) {
797 $this->callAPISuccess('relationship_type', 'delete', $params);
802 * @param array $params
805 * @throws \CRM_Core_Exception
807 public function paymentProcessorTypeCreate($params = []) {
808 $params = array_merge([
809 'name' => 'API_Test_PP',
810 'title' => 'API Test Payment Processor',
811 'class_name' => 'CRM_Core_Payment_APITest',
812 'billing_mode' => 'form',
817 $result = $this->callAPISuccess('PaymentProcessorType', 'create', $params);
819 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
821 return $result['id'];
825 * Create test Authorize.net instance.
827 * @param array $params
831 public function paymentProcessorAuthorizeNetCreate($params = []) {
832 $params = array_merge([
833 'name' => 'Authorize',
834 'domain_id' => CRM_Core_Config
::domainID(),
835 'payment_processor_type_id' => 'AuthNet',
836 'title' => 'AuthNet',
841 'user_name' => '4y5BfuW7jm',
842 'password' => '4cAmW927n8uLf5J8',
843 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
844 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
845 'class_name' => 'Payment_AuthorizeNet',
849 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
850 return (int) $result['id'];
854 * Create Participant.
856 * @param array $params
857 * Array of contact id and event id values.
860 * $id of participant created
862 public function participantCreate(array $params = []) {
863 if (empty($params['contact_id'])) {
864 $this->ids
['Contact']['participant'] = $params['contact_id'] = $this->individualCreate();
866 if (empty($params['event_id'])) {
867 $event = $this->eventCreate(['end_date' => 20081023, 'registration_end_date' => 20081015]);
868 $params['event_id'] = $event['id'];
873 'register_date' => 20070219,
874 'source' => 'Wimbeldon',
875 'event_level' => 'Payment',
879 $params = array_merge($defaults, $params);
880 $result = $this->callAPISuccess('Participant', 'create', $params);
881 return $result['id'];
885 * Create Payment Processor.
888 * Id Payment Processor
890 public function processorCreate($params = []) {
895 'payment_processor_type_id' => 'Dummy',
896 'financial_account_id' => 12,
900 'url_site' => 'http://dummy.com',
901 'url_recur' => 'http://dummy.com',
904 'payment_instrument_id' => 'Debit Card',
906 $processorParams = array_merge($processorParams, $params);
907 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
908 return $processor['id'];
912 * Create Payment Processor.
914 * @param array $processorParams
916 * @return \CRM_Core_Payment_Dummy
917 * Instance of Dummy Payment Processor
919 * @throws \CiviCRM_API3_Exception
921 public function dummyProcessorCreate($processorParams = []) {
922 $paymentProcessorID = $this->processorCreate($processorParams);
923 // For the tests we don't need a live processor, but as core ALWAYS creates a processor in live mode and one in test mode we do need to create both
924 // Otherwise we are testing a scenario that only exists in tests (and some tests fail because the live processor has not been defined).
925 $processorParams['is_test'] = FALSE;
926 $this->processorCreate($processorParams);
927 return System
::singleton()->getById($paymentProcessorID);
931 * Create contribution page.
933 * @param array $params
936 * Array of contribution page
938 public function contributionPageCreate($params = []) {
939 $this->_pageParams
= array_merge([
940 'title' => 'Test Contribution Page',
941 'financial_type_id' => 1,
943 'financial_account_id' => 1,
945 'is_allow_other_amount' => 1,
947 'max_amount' => 1000,
949 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
953 * Create a sample batch.
955 public function batchCreate() {
956 $params = $this->_params
;
957 $params['name'] = $params['title'] = 'Batch_433397';
958 $params['status_id'] = 1;
959 $result = $this->callAPISuccess('batch', 'create', $params);
960 return $result['id'];
966 * @param array $params
969 * result of created tag
971 public function tagCreate($params = []) {
973 'name' => 'New Tag3',
974 'description' => 'This is description for Our New Tag ',
977 $params = array_merge($defaults, $params);
978 $result = $this->callAPISuccess('Tag', 'create', $params);
979 return $result['values'][$result['id']];
986 * Id of the tag to be deleted.
990 public function tagDelete($tagId) {
991 require_once 'api/api.php';
995 $result = $this->callAPISuccess('Tag', 'delete', $params);
996 return $result['id'];
1000 * Add entity(s) to the tag
1002 * @param array $params
1006 public function entityTagAdd($params) {
1007 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1014 * @param array $params
1018 * id of created pledge
1020 public function pledgeCreate($params): int {
1021 $params = array_merge([
1022 'pledge_create_date' => date('Ymd'),
1023 'start_date' => date('Ymd'),
1024 'scheduled_date' => date('Ymd'),
1026 'pledge_status_id' => '2',
1027 'financial_type_id' => '1',
1028 'pledge_original_installment_amount' => 20,
1029 'frequency_interval' => 5,
1030 'frequency_unit' => 'year',
1031 'frequency_day' => 15,
1032 'installments' => 5,
1036 $result = $this->callAPISuccess('Pledge', 'create', $params);
1037 return $result['id'];
1041 * Delete contribution.
1043 * @param int $pledgeId
1045 * @throws \CRM_Core_Exception
1047 public function pledgeDelete($pledgeId) {
1049 'pledge_id' => $pledgeId,
1051 $this->callAPISuccess('Pledge', 'delete', $params);
1055 * Create contribution.
1057 * @param array $params
1058 * Array of parameters.
1061 * id of created contribution
1063 public function contributionCreate(array $params): int {
1064 $params = array_merge([
1066 'receive_date' => date('Ymd'),
1067 'total_amount' => 100.00,
1068 'fee_amount' => 5.00,
1069 'financial_type_id' => 1,
1070 'payment_instrument_id' => 1,
1071 'non_deductible_amount' => 10.00,
1073 'contribution_status_id' => 1,
1076 $result = $this->callAPISuccess('contribution', 'create', $params);
1077 return $result['id'];
1081 * Delete contribution.
1083 * @param int $contributionId
1086 * @throws \CRM_Core_Exception
1088 public function contributionDelete($contributionId) {
1090 'contribution_id' => $contributionId,
1092 $result = $this->callAPISuccess('contribution', 'delete', $params);
1099 * @param array $params
1100 * Name-value pair for an event.
1104 public function eventCreate(array $params = []): array {
1105 // if no contact was passed, make up a dummy event creator
1106 if (!isset($params['contact_id'])) {
1107 $params['contact_id'] = $this->_contactCreate([
1108 'contact_type' => 'Individual',
1109 'first_name' => 'Event',
1110 'last_name' => 'Creator',
1114 // set defaults for missing params
1115 $params = array_merge([
1116 'title' => 'Annual CiviCRM meet',
1117 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1118 'description' => 'This event is intended to give brief idea about progress of CiviCRM and giving solutions to common user issues',
1119 'event_type_id' => 1,
1121 'start_date' => 20081021,
1122 'end_date' => '+ 1 month',
1123 'is_online_registration' => 1,
1124 'registration_start_date' => 20080601,
1125 'registration_end_date' => '+ 1 month',
1126 'max_participants' => 100,
1127 'event_full_text' => 'Sorry! We are already full',
1130 'is_show_location' => 0,
1131 'is_email_confirm' => 1,
1134 $event = $this->callAPISuccess('Event', 'create', $params);
1135 $this->ids
['event'][] = $event['id'];
1140 * Create a paid event.
1142 * @param array $params
1144 * @param array $options
1146 * @param string $key
1147 * Index for storing event ID in ids array.
1151 * @throws \CRM_Core_Exception
1153 protected function eventCreatePaid($params, $options = [['name' => 'hundy', 'amount' => 100]], $key = 'event') {
1154 $params['is_monetary'] = TRUE;
1155 $event = $this->eventCreate($params);
1156 $this->ids
['Event'][$key] = (int) $event['id'];
1157 $this->ids
['PriceSet'][$key] = $this->eventPriceSetCreate(55, 0, 'Radio', $options);
1158 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->ids
['PriceSet'][$key]);
1159 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->ids
['PriceSet'][$key], TRUE, FALSE);
1160 $priceSet = $priceSet[$this->ids
['PriceSet'][$key]] ??
NULL;
1161 $this->eventFeeBlock
= $priceSet['fields'] ??
NULL;
1173 public function eventDelete($id) {
1177 return $this->callAPISuccess('event', 'delete', $params);
1181 * Delete participant.
1183 * @param int $participantID
1187 public function participantDelete($participantID) {
1189 'id' => $participantID,
1191 $check = $this->callAPISuccess('Participant', 'get', $params);
1192 if ($check['count'] > 0) {
1193 return $this->callAPISuccess('Participant', 'delete', $params);
1198 * Create participant payment.
1200 * @param int $participantID
1201 * @param int $contributionID
1204 * $id of created payment
1206 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1207 //Create Participant Payment record With Values
1209 'participant_id' => $participantID,
1210 'contribution_id' => $contributionID,
1213 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1214 return $result['id'];
1218 * Delete participant payment.
1220 * @param int $paymentID
1222 public function participantPaymentDelete($paymentID) {
1226 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1232 * @param int $contactID
1235 * location id of created location
1237 public function locationAdd($contactID) {
1240 'location_type' => 'New Location Type',
1242 'name' => 'Saint Helier St',
1243 'county' => 'Marin',
1244 'country' => 'UNITED STATES',
1245 'state_province' => 'Michigan',
1246 'supplemental_address_1' => 'Hallmark Ct',
1247 'supplemental_address_2' => 'Jersey Village',
1248 'supplemental_address_3' => 'My Town',
1253 'contact_id' => $contactID,
1254 'address' => $address,
1255 'location_format' => '2.0',
1256 'location_type' => 'New Location Type',
1259 $result = $this->callAPISuccess('Location', 'create', $params);
1264 * Delete Locations of contact.
1266 * @param array $params
1269 public function locationDelete($params) {
1270 $this->callAPISuccess('Location', 'delete', $params);
1274 * Add a Location Type.
1276 * @param array $params
1278 * @return CRM_Core_DAO_LocationType
1279 * location id of created location
1281 public function locationTypeCreate($params = NULL) {
1282 if ($params === NULL) {
1284 'name' => 'New Location Type',
1285 'vcard_name' => 'New Location Type',
1286 'description' => 'Location Type for Delete',
1291 $locationType = new CRM_Core_DAO_LocationType();
1292 $locationType->copyValues($params);
1293 $locationType->save();
1294 // clear getfields cache
1295 CRM_Core_PseudoConstant
::flush();
1296 $this->callAPISuccess('phone', 'getfields', ['version' => 3, 'cache_clear' => 1]);
1297 return $locationType->id
;
1301 * Delete a Location Type.
1303 * @param int $locationTypeId
1305 public function locationTypeDelete($locationTypeId) {
1306 $locationType = new CRM_Core_DAO_LocationType();
1307 $locationType->id
= $locationTypeId;
1308 $locationType->delete();
1314 * @param array $params
1316 * @return CRM_Core_DAO_Mapping
1317 * Mapping id of created mapping
1319 public function mappingCreate($params = NULL) {
1320 if ($params === NULL) {
1322 'name' => 'Mapping name',
1323 'description' => 'Mapping description',
1324 // 'Export Contact' mapping.
1325 'mapping_type_id' => 7,
1329 $mapping = new CRM_Core_DAO_Mapping();
1330 $mapping->copyValues($params);
1332 // clear getfields cache
1333 CRM_Core_PseudoConstant
::flush();
1334 $this->callAPISuccess('mapping', 'getfields', ['version' => 3, 'cache_clear' => 1]);
1341 * @param int $mappingId
1343 public function mappingDelete($mappingId) {
1344 $mapping = new CRM_Core_DAO_Mapping();
1345 $mapping->id
= $mappingId;
1350 * Prepare class for ACLs.
1352 protected function prepareForACLs() {
1353 $config = CRM_Core_Config
::singleton();
1354 $config->userPermissionClass
->permissions
= [];
1360 protected function cleanUpAfterACLs() {
1361 CRM_Utils_Hook
::singleton()->reset();
1362 $tablesToTruncate = [
1364 'civicrm_acl_cache',
1365 'civicrm_acl_entity_role',
1366 'civicrm_acl_contact_cache',
1368 $this->quickCleanup($tablesToTruncate);
1369 $config = CRM_Core_Config
::singleton();
1370 unset($config->userPermissionClass
->permissions
);
1374 * Create a smart group.
1376 * By default it will be a group of households.
1378 * @param array $smartGroupParams
1379 * @param array $groupParams
1380 * @param string $contactType
1384 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1385 $smartGroupParams = array_merge(['form_values' => ['contact_type' => ['IN' => [$contactType]]]], $smartGroupParams);
1386 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1388 $groupParams['saved_search_id'] = $savedSearch->id
;
1389 return $this->groupCreate($groupParams);
1395 * @param array $params
1397 public function uFFieldCreate($params = []) {
1398 $params = array_merge([
1400 'field_name' => 'first_name',
1403 'visibility' => 'Public Pages and Listings',
1404 'is_searchable' => '1',
1405 'label' => 'first_name',
1406 'field_type' => 'Individual',
1409 $this->callAPISuccess('uf_field', 'create', $params);
1413 * Add a UF Join Entry.
1415 * @param array $params
1418 * $id of created UF Join
1420 public function ufjoinCreate($params = NULL) {
1421 if ($params === NULL) {
1424 'module' => 'CiviEvent',
1425 'entity_table' => 'civicrm_event',
1431 $result = $this->callAPISuccess('uf_join', 'create', $params);
1436 * @param array $params
1437 * Optional parameters.
1438 * @param bool $reloadConfig
1439 * While enabling CiviCampaign component, we shouldn't always forcibly
1440 * reload config as this hinder hook call in test environment
1445 public function campaignCreate($params = [], $reloadConfig = TRUE) {
1446 $this->enableCiviCampaign($reloadConfig);
1447 $campaign = $this->callAPISuccess('campaign', 'create', array_merge([
1448 'name' => 'big_campaign',
1449 'title' => 'Campaign',
1451 return $campaign['id'];
1455 * Create Group for a contact.
1457 * @param int $contactId
1459 public function contactGroupCreate($contactId) {
1461 'contact_id.1' => $contactId,
1465 $this->callAPISuccess('GroupContact', 'Create', $params);
1469 * Delete Group for a contact.
1471 * @param int $contactId
1473 public function contactGroupDelete($contactId) {
1475 'contact_id.1' => $contactId,
1478 $this->civicrm_api('GroupContact', 'Delete', $params);
1484 * @param array $params
1488 * @throws \CRM_Core_Exception
1489 * @throws \CiviCRM_API3_Exception
1491 public function activityCreate($params = []) {
1492 $params = array_merge([
1493 'subject' => 'Discussion on warm beer',
1494 'activity_date_time' => date('Ymd'),
1496 'location' => 'Baker Street',
1497 'details' => 'Lets schedule a meeting',
1499 'activity_type_id' => 'Meeting',
1501 if (!isset($params['source_contact_id'])) {
1502 $params['source_contact_id'] = $this->individualCreate();
1504 if (!isset($params['target_contact_id'])) {
1505 $params['target_contact_id'] = $this->individualCreate([
1506 'first_name' => 'Julia',
1507 'last_name' => 'Anderson',
1509 'email' => 'julia_anderson@civicrm.org',
1510 'contact_type' => 'Individual',
1513 if (!isset($params['assignee_contact_id'])) {
1514 $params['assignee_contact_id'] = $params['target_contact_id'];
1517 $result = civicrm_api3('Activity', 'create', $params);
1519 $result['target_contact_id'] = $params['target_contact_id'];
1520 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1525 * Create an activity type.
1527 * @param array $params
1532 public function activityTypeCreate($params) {
1533 return $this->callAPISuccess('ActivityType', 'create', $params);
1537 * Delete activity type.
1539 * @param int $activityTypeId
1540 * Id of the activity type.
1544 public function activityTypeDelete($activityTypeId) {
1545 $params['activity_type_id'] = $activityTypeId;
1546 return $this->callAPISuccess('ActivityType', 'delete', $params);
1550 * Create custom group.
1552 * @param array $params
1556 public function customGroupCreate($params = []) {
1558 'title' => 'new custom group',
1559 'extends' => 'Contact',
1561 'style' => 'Inline',
1565 $params = array_merge($defaults, $params);
1567 return $this->callAPISuccess('custom_group', 'create', $params);
1571 * Existing function doesn't allow params to be over-ridden so need a new one
1572 * this one allows you to only pass in the params you want to change
1574 * @param array $params
1578 public function CustomGroupCreateByParams($params = []) {
1580 'title' => "API Custom Group",
1581 'extends' => 'Contact',
1583 'style' => 'Inline',
1586 $params = array_merge($defaults, $params);
1587 return $this->callAPISuccess('custom_group', 'create', $params);
1591 * Create custom group with multi fields.
1593 * @param array $params
1597 public function CustomGroupMultipleCreateByParams($params = []) {
1602 $params = array_merge($defaults, $params);
1603 return $this->CustomGroupCreateByParams($params);
1607 * Create custom group with multi fields.
1609 * @param array $params
1613 public function CustomGroupMultipleCreateWithFields($params = []) {
1614 // also need to pass on $params['custom_field'] if not set but not in place yet
1616 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1617 $ids['custom_group_id'] = $customGroup['id'];
1619 $customField = $this->customFieldCreate([
1620 'custom_group_id' => $ids['custom_group_id'],
1621 'label' => 'field_1' . $ids['custom_group_id'],
1625 $ids['custom_field_id'][] = $customField['id'];
1627 $customField = $this->customFieldCreate([
1628 'custom_group_id' => $ids['custom_group_id'],
1629 'default_value' => '',
1630 'label' => 'field_2' . $ids['custom_group_id'],
1633 $ids['custom_field_id'][] = $customField['id'];
1635 $customField = $this->customFieldCreate([
1636 'custom_group_id' => $ids['custom_group_id'],
1637 'default_value' => '',
1638 'label' => 'field_3' . $ids['custom_group_id'],
1641 $ids['custom_field_id'][] = $customField['id'];
1647 * Create a custom group with a single text custom field. See
1648 * participant:testCreateWithCustom for how to use this
1650 * @param string $function
1652 * @param string $filename
1656 * ids of created objects
1658 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1659 $params = ['title' => $function];
1660 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1661 $params['extends'] = $entity ?
$entity : 'Contact';
1662 $customGroup = $this->customGroupCreate($params);
1663 $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id'], 'label' => $function]);
1664 CRM_Core_PseudoConstant
::flush();
1666 return ['custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']];
1670 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1671 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1673 * @param string $function
1675 * @param string $filename
1679 * ids of created objects
1681 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1682 $params = ['title' => $function];
1683 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1684 $params['extends'] = $entity ?
$entity : 'Contact';
1685 $customGroup = $this->customGroupCreate($params);
1686 $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1]);
1687 CRM_Core_PseudoConstant
::flush();
1689 'defaultValue' => 'Default Value',
1690 'lowercasevalue' => 'Lowercase Value',
1691 1 => 'Integer Value',
1694 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1695 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1696 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1697 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1698 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1699 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1700 foreach ($options as $option_value => $option_label) {
1701 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1702 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1706 'custom_group_id' => $customGroup['id'],
1707 'custom_field_id' => $customField['id'],
1708 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'],
1709 'custom_field_group_options' => $options,
1714 * Delete custom group.
1716 * @param int $customGroupID
1720 public function customGroupDelete($customGroupID) {
1721 $params['id'] = $customGroupID;
1722 return $this->callAPISuccess('custom_group', 'delete', $params);
1726 * Create custom field.
1728 * @param array $params
1729 * (custom_group_id) is required.
1733 public function customFieldCreate($params) {
1734 $params = array_merge([
1735 'label' => 'Custom Field',
1736 'data_type' => 'String',
1737 'html_type' => 'Text',
1738 'is_searchable' => 1,
1740 'default_value' => 'defaultValue',
1743 $result = $this->callAPISuccess('custom_field', 'create', $params);
1744 // these 2 functions are called with force to flush static caches
1745 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1746 CRM_Core_Component
::getEnabledComponents(1);
1751 * Delete custom field.
1753 * @param int $customFieldID
1757 public function customFieldDelete($customFieldID) {
1759 $params['id'] = $customFieldID;
1760 return $this->callAPISuccess('custom_field', 'delete', $params);
1770 public function noteCreate($cId) {
1772 'entity_table' => 'civicrm_contact',
1773 'entity_id' => $cId,
1774 'note' => 'hello I am testing Note',
1775 'contact_id' => $cId,
1776 'modified_date' => date('Ymd'),
1777 'subject' => 'Test Note',
1780 return $this->callAPISuccess('Note', 'create', $params);
1784 * Enable CiviCampaign Component.
1786 public function enableCiviCampaign(): void
{
1787 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1791 * Create custom field with Option Values.
1793 * @param array $customGroup
1794 * @param string $name
1795 * Name of custom field.
1796 * @param array $extraParams
1797 * Additional parameters to pass through.
1801 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = []) {
1803 'custom_group_id' => $customGroup['id'],
1804 'name' => 'test_custom_group',
1805 'label' => 'Country',
1806 'html_type' => 'Select',
1807 'data_type' => 'String',
1810 'is_searchable' => 0,
1816 'name' => 'option_group1',
1817 'label' => 'option_group_label1',
1821 'option_label' => ['Label1', 'Label2'],
1822 'option_value' => ['value1', 'value2'],
1823 'option_name' => [$name . '_1', $name . '_2'],
1824 'option_weight' => [1, 2],
1825 'option_status' => [1, 1],
1828 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1830 return $this->callAPISuccess('custom_field', 'create', $params);
1838 public function confirmEntitiesDeleted($entities) {
1839 foreach ($entities as $entity) {
1841 $result = $this->callAPISuccess($entity, 'Get', []);
1842 if ($result['error'] == 1 ||
$result['count'] > 0) {
1843 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1851 * Quick clean by emptying tables created for the test.
1853 * @param array $tablesToTruncate
1854 * @param bool $dropCustomValueTables
1856 public function quickCleanup(array $tablesToTruncate, $dropCustomValueTables = FALSE): void
{
1858 $this->fail('CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()');
1860 if ($dropCustomValueTables) {
1861 $this->cleanupCustomGroups();
1862 // Reset autoincrement too.
1863 $tablesToTruncate[] = 'civicrm_custom_group';
1864 $tablesToTruncate[] = 'civicrm_custom_field';
1867 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1869 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0;');
1870 foreach ($tablesToTruncate as $table) {
1871 $sql = "TRUNCATE TABLE $table";
1872 CRM_Core_DAO
::executeQuery($sql);
1874 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1;');
1878 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1880 public function quickCleanUpFinancialEntities(): void
{
1881 $tablesToTruncate = [
1883 'civicrm_activity_contact',
1884 'civicrm_contribution',
1885 'civicrm_contribution_soft',
1886 'civicrm_contribution_product',
1887 'civicrm_financial_trxn',
1888 'civicrm_financial_item',
1889 'civicrm_contribution_recur',
1890 'civicrm_line_item',
1891 'civicrm_contribution_page',
1892 'civicrm_payment_processor',
1893 'civicrm_entity_financial_trxn',
1894 'civicrm_membership',
1895 'civicrm_membership_type',
1896 'civicrm_membership_payment',
1897 'civicrm_membership_log',
1898 'civicrm_membership_block',
1900 'civicrm_participant',
1901 'civicrm_participant_payment',
1903 'civicrm_pcp_block',
1905 'civicrm_pledge_block',
1906 'civicrm_pledge_payment',
1907 'civicrm_price_set_entity',
1908 'civicrm_price_field_value',
1909 'civicrm_price_field',
1911 $this->quickCleanup($tablesToTruncate);
1912 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1913 $this->restoreDefaultPriceSetConfig();
1914 $this->disableTaxAndInvoicing();
1915 $this->setCurrencySeparators(',');
1917 FinancialType
::delete(FALSE)->addWhere(
1921 'Campaign Contribution',
1926 catch (API_Exception
$e) {
1927 $this->fail('failed to cleanup financial types ' . $e->getMessage());
1929 CRM_Core_PseudoConstant
::flush('taxRates');
1930 System
::singleton()->flushProcessors();
1931 // @fixme this parameter is leaking - it should not be defined as a class static
1932 // but for now we just handle in tear down.
1933 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1937 * Reset the price set config so results exist.
1939 public function restoreDefaultPriceSetConfig(): void
{
1940 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1941 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1942 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)");
1943 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)");
1947 * Recreate default membership types.
1949 * @throws \API_Exception
1951 public function restoreMembershipTypes(): void
{
1952 MembershipType
::delete(FALSE)->addWhere('id', '>', 0)->execute();
1953 $this->quickCleanup(['civicrm_membership_type']);
1954 $this->ensureMembershipPriceSetExists();
1956 MembershipType
::save(FALSE)
1960 'name' => 'General',
1961 'description' => 'Regular annual membership.',
1962 'minimum_fee' => 100,
1963 'duration_unit' => 'year',
1964 'duration_interval' => 2,
1965 'period_type' => 'rolling',
1966 'relationship_type_id' => 7,
1967 'relationship_direction' => 'b_a',
1968 'visibility' => 'Public',
1973 'name' => 'Student',
1974 'description' => 'Discount membership for full-time students.',
1975 'minimum_fee' => 50,
1976 'duration_unit' => 1,
1977 'duration_interval' => 'year',
1978 'period_type' => 'rolling',
1979 'visibility' => 'Public',
1982 'name' => 'Lifetime',
1983 'description' => 'Lifetime membership.',
1984 'minimum_fee' => 1200.00,
1985 'duration_unit' => 1,
1986 'duration_interval' => 'lifetime',
1987 'period_type' => 'rolling',
1988 'relationship_type_id' => 7,
1989 'relationship_direction' => 'b_a',
1990 'visibility' => 'Admin',
1996 'member_of_contact_id' => 1,
1997 'financial_type_id' => 2,
2003 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2004 * Default behaviour is to also delete the entity
2005 * @param array $params
2006 * Params array to check against.
2008 * Id of the entity concerned.
2009 * @param string $entity
2010 * Name of entity concerned (e.g. membership).
2011 * @param bool $delete
2012 * Should the entity be deleted as part of this check.
2013 * @param string $errorText
2014 * Text to print on error.
2018 * @param array $params
2021 * @param int $delete
2022 * @param string $errorText
2024 public function getAndCheck(array $params, int $id, $entity, int $delete = 1, string $errorText = ''): void
{
2026 $result = $this->callAPISuccessGetSingle($entity, [
2028 'return' => array_keys($params),
2032 $this->callAPISuccess($entity, 'Delete', [
2036 $dateFields = $keys = $dateTimeFields = [];
2037 $fields = $this->callAPISuccess($entity, 'getfields', ['version' => 3, 'action' => 'get']);
2038 foreach ($fields['values'] as $field => $settings) {
2039 if (array_key_exists($field, $result)) {
2040 $keys[CRM_Utils_Array
::value('name', $settings, $field)] = $field;
2043 $keys[CRM_Utils_Array
::value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2045 $type = $settings['type'] ??
NULL;
2046 if ($type === CRM_Utils_Type
::T_DATE
) {
2047 $dateFields[] = $settings['name'];
2048 // we should identify both real names & unique names as dates
2049 if ($field !== $settings['name']) {
2050 $dateFields[] = $field;
2053 if ($type === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2054 $dateTimeFields[] = $settings['name'];
2055 // we should identify both real names & unique names as dates
2056 if ($field !== $settings['name']) {
2057 $dateTimeFields[] = $field;
2062 if (strtolower($entity) === 'contribution') {
2063 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2064 // this is not returned in id format
2065 unset($params['payment_instrument_id']);
2066 $params['contribution_source'] = $params['source'];
2067 unset($params['source']);
2070 foreach ($params as $key => $value) {
2071 if ($key === 'version' ||
strpos($key, 'api') === 0 ||
(!array_key_exists($key, $keys) ||
!array_key_exists($keys[$key], $result))) {
2074 if (in_array($key, $dateFields, TRUE)) {
2075 $value = date('Y-m-d', strtotime($value));
2076 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2078 if (in_array($key, $dateTimeFields, TRUE)) {
2079 $value = date('Y-m-d H:i:s', strtotime($value));
2080 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2082 $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);
2087 * Get formatted values in the actual and expected result.
2089 * @param array $actual
2090 * Actual calculated values.
2091 * @param array $expected
2094 public function checkArrayEquals(&$actual, &$expected) {
2095 self
::unsetId($actual);
2096 self
::unsetId($expected);
2097 $this->assertEquals($expected, $actual);
2101 * Unset the key 'id' from the array
2103 * @param array $unformattedArray
2104 * The array from which the 'id' has to be unset.
2106 public static function unsetId(&$unformattedArray) {
2107 $formattedArray = [];
2108 if (array_key_exists('id', $unformattedArray)) {
2109 unset($unformattedArray['id']);
2111 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2112 foreach ($unformattedArray['values'] as $key => $value) {
2113 if (is_array($value)) {
2114 foreach ($value as $k => $v) {
2120 elseif ($key == 'id') {
2121 $unformattedArray[$key];
2123 $formattedArray = [$value];
2125 $unformattedArray['values'] = $formattedArray;
2130 * Helper to enable/disable custom directory support
2132 * @param array $customDirs
2134 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2135 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2137 public function customDirectories($customDirs) {
2138 $config = CRM_Core_Config
::singleton();
2140 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2141 unset($config->customPHPPathDir
);
2143 elseif ($customDirs['php_path'] === TRUE) {
2144 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2147 $config->customPHPPathDir
= $php_path;
2150 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2151 unset($config->customTemplateDir
);
2153 elseif ($customDirs['template_path'] === TRUE) {
2154 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2157 $config->customTemplateDir
= $template_path;
2162 * Generate a temporary folder.
2164 * @param string $prefix
2168 public function createTempDir($prefix = 'test-') {
2169 $tempDir = CRM_Utils_File
::tempdir($prefix);
2170 $this->tempDirs
[] = $tempDir;
2174 public function cleanTempDirs() {
2175 if (!is_array($this->tempDirs
)) {
2176 // fix test errors where this is not set
2179 foreach ($this->tempDirs
as $tempDir) {
2180 if (is_dir($tempDir)) {
2181 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2187 * Temporarily replace the singleton extension with a different one.
2189 * @param \CRM_Extension_System $system
2191 public function setExtensionSystem(CRM_Extension_System
$system) {
2192 if ($this->origExtensionSystem
== NULL) {
2193 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2195 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2198 public function unsetExtensionSystem() {
2199 if ($this->origExtensionSystem
!== NULL) {
2200 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2201 $this->origExtensionSystem
= NULL;
2206 * Temporarily alter the settings-metadata to add a mock setting.
2208 * WARNING: The setting metadata will disappear on the next cache-clear.
2214 public function setMockSettingsMetaData($extras) {
2215 CRM_Utils_Hook
::singleton()
2216 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2217 $metadata = array_merge($metadata, $extras);
2220 Civi
::service('settings_manager')->flush();
2222 $fields = $this->callAPISuccess('setting', 'getfields', []);
2223 foreach ($extras as $key => $spec) {
2224 $this->assertNotEmpty($spec['title']);
2225 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2230 * @param string $name
2232 public function financialAccountDelete($name) {
2233 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2234 $financialAccount->name
= $name;
2235 if ($financialAccount->find(TRUE)) {
2236 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2237 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2238 $entityFinancialType->delete();
2239 $financialAccount->delete();
2244 * Set up an acl allowing contact to see 2 specified groups
2245 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2247 * You need to have pre-created these groups & created the user e.g
2248 * $this->createLoggedInUser();
2249 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2250 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2252 * @param bool $isProfile
2254 public function setupACL($isProfile = FALSE) {
2256 $_REQUEST = $this->_params
;
2258 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['access CiviCRM'];
2259 $optionGroupID = $this->callAPISuccessGetValue('option_group', ['return' => 'id', 'name' => 'acl_role']);
2260 $ov = new CRM_Core_DAO_OptionValue();
2261 $ov->option_group_id
= $optionGroupID;
2263 if ($ov->find(TRUE)) {
2264 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2266 $optionValue = $this->callAPISuccess('option_value', 'create', [
2267 'option_group_id' => $optionGroupID,
2268 'label' => 'pick me',
2272 CRM_Core_DAO
::executeQuery("
2273 TRUNCATE civicrm_acl_cache
2276 CRM_Core_DAO
::executeQuery("
2277 TRUNCATE civicrm_acl_contact_cache
2280 CRM_Core_DAO
::executeQuery("
2281 INSERT INTO civicrm_acl_entity_role (
2282 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2283 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2287 CRM_Core_DAO
::executeQuery("
2288 INSERT INTO civicrm_acl (
2289 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2292 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2297 CRM_Core_DAO
::executeQuery("
2298 INSERT INTO civicrm_acl (
2299 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2302 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2306 CRM_Core_DAO
::executeQuery("
2307 INSERT INTO civicrm_acl (
2308 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2311 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2316 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2317 $this->callAPISuccess('group_contact', 'create', [
2318 'group_id' => $this->_permissionedGroup
,
2319 'contact_id' => $this->_loggedInUser
,
2323 CRM_ACL_BAO_Cache
::resetCache();
2328 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2330 public function offsetDefaultPriceSet() {
2331 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', ['name' => 'default_contribution_amount']);
2332 $firstID = $contributionPriceSet['id'];
2333 $this->callAPISuccess('price_set', 'create', [
2334 'id' => $contributionPriceSet['id'],
2338 unset($contributionPriceSet['id']);
2339 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2340 $priceField = $this->callAPISuccess('price_field', 'getsingle', [
2341 'price_set_id' => $firstID,
2342 'options' => ['limit' => 1],
2344 unset($priceField['id']);
2345 $priceField['price_set_id'] = $newPriceSet['id'];
2346 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2347 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', [
2348 'price_set_id' => $firstID,
2350 'options' => ['limit' => 1],
2353 unset($priceFieldValue['id']);
2354 //create some padding to use up ids
2355 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2356 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2357 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, ['price_field_id' => $newPriceField['id']]));
2361 * Create an instance of the paypal processor.
2363 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2364 * this parent class & we don't have a structure for that yet
2365 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2366 * & the best protection against that is the functions this class affords
2368 * @param array $params
2370 * @return int $result['id'] payment processor id
2372 public function paymentProcessorCreate($params = []) {
2373 $params = array_merge([
2375 'domain_id' => CRM_Core_Config
::domainID(),
2376 'payment_processor_type_id' => 'PayPal',
2380 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2381 'password' => '1183377788',
2382 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2383 'url_site' => 'https://www.sandbox.paypal.com/',
2384 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2385 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2386 'class_name' => 'Payment_PayPalImpl',
2387 'billing_mode' => 3,
2388 'financial_type_id' => 1,
2389 'financial_account_id' => 12,
2390 // Credit card = 1 so can pass 'by accident'.
2391 'payment_instrument_id' => 'Debit Card',
2393 if (!is_numeric($params['payment_processor_type_id'])) {
2394 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2396 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', [
2397 'name' => $params['payment_processor_type_id'],
2401 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2402 return $result['id'];
2406 * Get the rendered contents from a form.
2408 * @param string $formName
2410 * @return false|string
2412 protected function getRenderedFormContents(string $formName) {
2413 $form = $this->getFormObject($formName);
2416 $form->controller
->_actions
['display']->perform($form, 'display');
2417 return ob_get_clean();
2421 * Set up initial recurring payment allowing subsequent IPN payments.
2423 * @param array $recurParams (Optional)
2424 * @param array $contributionParams (Optional)
2426 public function setupRecurringPaymentProcessorTransaction(array $recurParams = [], array $contributionParams = []): void
{
2427 $this->ids
['campaign'][0] = $this->callAPISuccess('Campaign', 'create', ['title' => 'get the money'])['id'];
2428 $contributionParams = array_merge([
2429 'total_amount' => '200',
2430 'invoice_id' => $this->_invoiceID
,
2431 'financial_type_id' => 'Donation',
2432 'contact_id' => $this->_contactID
,
2433 'contribution_page_id' => $this->_contributionPageID
,
2434 'payment_processor_id' => $this->_paymentProcessorID
,
2435 'receive_date' => '2019-07-25 07:34:23',
2436 'skipCleanMoney' => TRUE,
2437 'amount_level' => 'expensive',
2438 'campaign_id' => $this->ids
['campaign'][0],
2439 'source' => 'Online Contribution: Page name',
2440 ], $contributionParams);
2441 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
2442 'contact_id' => $this->_contactID
,
2445 'installments' => 5,
2446 'frequency_unit' => 'Month',
2447 'frequency_interval' => 1,
2448 'invoice_id' => $this->_invoiceID
,
2449 'contribution_status_id' => 2,
2450 'payment_processor_id' => $this->_paymentProcessorID
,
2451 // processor provided ID - use contact ID as proxy.
2452 'processor_id' => $this->_contactID
,
2453 'api.Order.create' => $contributionParams,
2454 ], $recurParams))['values'][0];
2455 $this->_contributionRecurID
= $contributionRecur['id'];
2456 $this->_contributionID
= $contributionRecur['api.Order.create']['id'];
2457 $this->ids
['Contribution'][0] = $this->_contributionID
;
2461 * 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
2463 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2465 * @throws \API_Exception
2467 public function setupMembershipRecurringPaymentProcessorTransaction($params = []): void
{
2468 $membershipParams = $recurParams = [];
2469 if (!empty($params['duration_unit'])) {
2470 $membershipParams['duration_unit'] = $params['duration_unit'];
2472 if (!empty($params['frequency_unit'])) {
2473 $recurParams['frequency_unit'] = $params['frequency_unit'];
2476 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2477 //create a contribution so our membership & contribution don't both have id = 1
2478 if ($this->callAPISuccess('Contribution', 'getcount', []) === 0) {
2479 $this->contributionCreate([
2480 'contact_id' => $this->_contactID
,
2482 'financial_type_id' => 1,
2483 'invoice_id' => 'abcd',
2485 'receive_date' => '2019-07-25 07:34:23',
2489 $this->setupRecurringPaymentProcessorTransaction($recurParams, [
2494 'label' => 'General',
2496 'unit_price' => 200,
2497 'line_total' => 200,
2498 'financial_type_id' => 1,
2499 'membership_type_id' => $this->ids
['membership_type'],
2503 'contact_id' => $this->_contactID
,
2504 'membership_type_id' => $this->ids
['membership_type'],
2505 'source' => 'Payment',
2510 $this->ids
['membership'] = LineItem
::get()
2511 ->addWhere('contribution_id', '=', $this->ids
['Contribution'][0])
2512 ->addWhere('entity_table', '=', 'civicrm_membership')
2513 ->addSelect('entity_id')
2514 ->execute()->first()['entity_id'];
2522 public function CiviUnitTestCase_fatalErrorHandler($message) {
2523 throw new Exception("{$message['message']}: {$message['code']}");
2527 * Wrap the entire test case in a transaction.
2529 * Only subsequent DB statements will be wrapped in TX -- this cannot
2530 * retroactively wrap old DB statements. Therefore, it makes sense to
2531 * call this at the beginning of setUp().
2533 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2534 * this option does not work with, e.g., custom-data.
2536 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2537 * if TRUNCATE or ALTER is called while using a transaction.
2540 * Whether to use nesting or reference-counting.
2542 public function useTransaction($nest = TRUE) {
2544 $this->tx
= new CRM_Core_Transaction($nest);
2545 $this->tx
->rollback();
2550 * Assert the attachment exists.
2552 * @param bool $exists
2553 * @param array $apiResult
2555 protected function assertAttachmentExistence($exists, $apiResult) {
2556 $fileId = $apiResult['id'];
2557 $this->assertTrue(is_numeric($fileId));
2558 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2559 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', [
2560 1 => [$fileId, 'Int'],
2562 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', [
2563 1 => [$fileId, 'Int'],
2568 * Assert 2 sql strings are the same, ignoring double spaces.
2570 * @param string $expectedSQL
2571 * @param string $actualSQL
2572 * @param string $message
2574 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2575 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2576 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2577 $this->assertEquals($expected, $actual, $message);
2581 * Create a price set for an event.
2583 * @param int $feeTotal
2584 * @param int $minAmt
2585 * @param string $type
2587 * @param array $options
2591 * @throws \CRM_Core_Exception
2593 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text', $options = [['name' => 'hundy', 'amount' => 100]]) {
2594 // creating price set, price field
2595 $paramsSet['title'] = 'Price Set';
2596 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2597 $paramsSet['is_active'] = FALSE;
2598 $paramsSet['extends'] = 1;
2599 $paramsSet['min_amount'] = $minAmt;
2601 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2602 $this->_ids
['price_set'] = $priceSet->id
;
2605 'label' => 'Price Field',
2606 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2607 'html_type' => $type,
2608 'price' => $feeTotal,
2609 'option_label' => ['1' => 'Price Field'],
2610 'option_value' => ['1' => $feeTotal],
2611 'option_name' => ['1' => $feeTotal],
2612 'option_weight' => ['1' => 1],
2613 'option_amount' => ['1' => 1],
2614 'is_display_amounts' => 1,
2616 'options_per_line' => 1,
2617 'is_active' => ['1' => 1],
2618 'price_set_id' => $this->_ids
['price_set'],
2619 'is_enter_qty' => 1,
2620 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2622 if ($type === 'Radio') {
2623 foreach ($options as $index => $option) {
2624 $paramsField['is_enter_qty'] = 0;
2625 $optionID = $index +
2;
2626 $paramsField['option_value'][$optionID] = $paramsField['option_weight'][$optionID] = $paramsField['option_amount'][$optionID] = $option['amount'];
2627 $paramsField['option_label'][$optionID] = $paramsField['option_name'][$optionID] = $option['name'];
2631 $this->callAPISuccess('PriceField', 'create', $paramsField);
2632 $fields = $this->callAPISuccess('PriceField', 'get', ['price_set_id' => $this->_ids
['price_set']]);
2633 $this->_ids
['price_field'] = array_keys($fields['values']);
2634 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $this->_ids
['price_field'][0]]);
2635 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2637 return $this->_ids
['price_set'];
2641 * Add a profile to a contribution page.
2643 * @param string $name
2644 * @param int $contributionPageID
2645 * @param string $module
2647 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2649 'uf_group_id' => $name,
2650 'module' => $module,
2651 'entity_table' => 'civicrm_contribution_page',
2652 'entity_id' => $contributionPageID,
2655 if ($module !== 'CiviContribute') {
2656 $params['module_data'] = [$module => []];
2658 $this->callAPISuccess('UFJoin', 'create', $params);
2662 * Add participant with contribution
2666 * @throws \CRM_Core_Exception
2668 protected function createPartiallyPaidParticipantOrder() {
2669 $orderParams = $this->getParticipantOrderParams();
2670 $orderParams['api.Payment.create'] = ['total_amount' => 150];
2671 return $this->callAPISuccess('Order', 'create', $orderParams);
2675 * Create price set that includes one price field with two option values.
2677 * @param string $component
2678 * @param int $componentId
2679 * @param array $priceFieldOptions
2681 * @return array - the result of API3 PriceFieldValue.get for the new PriceField
2683 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = []) {
2684 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2685 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2686 $paramsSet['is_active'] = TRUE;
2687 $paramsSet['financial_type_id'] = 'Event Fee';
2688 $paramsSet['extends'] = 1;
2689 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2691 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSet['id']);
2693 $paramsField = array_merge([
2694 'label' => 'Price Field',
2695 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2696 'html_type' => 'CheckBox',
2697 'option_label' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
2698 'option_value' => ['1' => 100, '2' => 200],
2699 'option_name' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
2700 'option_weight' => ['1' => 1, '2' => 2],
2701 'option_amount' => ['1' => 100, '2' => 200],
2702 'is_display_amounts' => 1,
2704 'options_per_line' => 1,
2705 'is_active' => ['1' => 1, '2' => 1],
2706 'price_set_id' => $priceSet['id'],
2707 'is_enter_qty' => 1,
2708 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2709 ], $priceFieldOptions);
2711 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2712 return $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $priceField->id
]);
2716 * Replace the template with a test-oriented template designed to show all the variables.
2718 * @param string $templateName
2719 * @param string $input
2720 * @param string $type
2722 protected function swapMessageTemplateForInput(string $templateName, string $input, string $type = 'html'): void
{
2723 CRM_Core_DAO
::executeQuery(
2724 "UPDATE civicrm_msg_template
2725 SET msg_{$type} = %1
2726 WHERE workflow_name = '{$templateName}'
2727 AND is_default = 1", [1 => [$input, 'String']]
2732 * Replace the template with a test-oriented template designed to show all the variables.
2734 * @param string $templateName
2735 * @param string $type
2737 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt', $type = 'html'): void
{
2738 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_' . $type . '.tpl');
2739 CRM_Core_DAO
::executeQuery(
2740 "UPDATE civicrm_msg_template
2741 SET msg_{$type} = %1
2742 WHERE workflow_name = '{$templateName}'
2743 AND is_default = 1", [1 => [$testTemplate, 'String']]
2748 * Reinstate the default template.
2750 * @param string $templateName
2751 * @param string $type
2753 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt', $type = 'html') {
2754 CRM_Core_DAO
::executeQuery(
2755 "UPDATE civicrm_option_group og
2756 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2757 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2758 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2759 SET m.msg_{$type} = m2.msg_{$type}
2760 WHERE og.name = 'msg_tpl_workflow_contribution'
2761 AND ov.name = '{$templateName}'
2762 AND m.is_default = 1"
2767 * Flush statics relating to financial type.
2769 protected function flushFinancialTypeStatics() {
2770 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2771 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2773 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2774 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2776 CRM_Contribute_PseudoConstant
::flush('financialType');
2777 CRM_Contribute_PseudoConstant
::flush('membershipType');
2778 // Pseudoconstants may be saved to the cache table.
2779 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2780 CRM_Financial_BAO_FinancialType
::$_statusACLFt = [];
2781 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2785 * Set the permissions to the supplied array.
2787 * @param array $permissions
2789 protected function setPermissions($permissions) {
2790 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2791 $this->flushFinancialTypeStatics();
2795 * @param array $params
2798 public function _checkFinancialRecords($params, $context) {
2800 'entity_id' => $params['id'],
2801 'entity_table' => 'civicrm_contribution',
2803 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
2804 'id' => $params['id'],
2805 'return' => ['total_amount', 'fee_amount', 'net_amount'],
2807 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2808 if ($context === 'pending') {
2809 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2810 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2813 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2815 'id' => $trxn['financial_trxn_id'],
2817 if ($context !== 'online' && $context !== 'payLater') {
2819 'to_financial_account_id' => 6,
2820 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2824 if ($context === 'feeAmount') {
2825 $compareParams['fee_amount'] = 50;
2827 elseif ($context === 'online') {
2829 'to_financial_account_id' => 12,
2830 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2832 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2835 elseif ($context == 'payLater') {
2837 'to_financial_account_id' => 7,
2838 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2842 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2844 'financial_trxn_id' => $trxn['financial_trxn_id'],
2845 'entity_table' => 'civicrm_financial_item',
2847 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2849 'id' => $entityTrxn['entity_id'],
2852 'amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2854 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2856 if ($context === 'payLater') {
2858 'amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2860 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2863 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2864 if ($context == 'feeAmount') {
2866 'entity_id' => $params['id'],
2867 'entity_table' => 'civicrm_contribution',
2869 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2871 'id' => $maxTrxn['financial_trxn_id'],
2874 'to_financial_account_id' => 5,
2875 'from_financial_account_id' => 6,
2876 'total_amount' => 50,
2879 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2880 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2882 'entity_id' => $trxnId['financialTrxnId'],
2883 'entity_table' => 'civicrm_financial_trxn',
2888 'financial_account_id' => 5,
2890 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2892 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2893 // line should be copied into all the functions that call this function & evaluated there
2894 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2895 // when calling completeTransaction or repeatTransaction.
2896 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2900 * Return financial type id on basis of name
2902 * @param string $name Financial type m/c name
2906 public function getFinancialTypeId($name) {
2907 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2911 * Cleanup function for contents of $this->ids.
2913 * This is a best effort cleanup to use in tear downs etc.
2915 * It will not fail if the data has already been removed (some tests may do
2916 * their own cleanup).
2918 protected function cleanUpSetUpIDs() {
2919 foreach ($this->setupIDs
as $entity => $id) {
2921 civicrm_api3($entity, 'delete', ['id' => $id, 'skip_undelete' => 1]);
2923 catch (CiviCRM_API3_Exception
$e) {
2924 // This is a best-effort cleanup function, ignore.
2930 * Create Financial Type.
2932 * @param array $params
2936 protected function createFinancialType($params = []) {
2937 $params = array_merge($params,
2939 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2943 return $this->callAPISuccess('FinancialType', 'create', $params);
2947 * Create Payment Instrument.
2949 * @param array $params
2950 * @param string $financialAccountName
2954 protected function createPaymentInstrument($params = [], $financialAccountName = 'Donation') {
2955 $params = array_merge([
2956 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2957 'option_group_id' => 'payment_instrument',
2960 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2962 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2964 $financialAccountParams = [
2965 'entity_table' => 'civicrm_option_value',
2966 'entity_id' => $newPaymentInstrument,
2967 'account_relationship' => $relationTypeID,
2968 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2970 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2972 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2976 * Enable Tax and Invoicing
2978 * @param array $params
2980 protected function enableTaxAndInvoicing(array $params = []): void
{
2981 // Enable component contribute setting
2982 $contributeSetting = array_merge($params,
2985 'invoice_prefix' => 'INV_',
2986 'invoice_due_date' => 10,
2987 'invoice_due_date_period' => 'days',
2988 'invoice_notes' => '',
2989 'invoice_is_email_pdf' => 1,
2990 'tax_term' => 'Sales Tax',
2991 'tax_display_settings' => 'Inclusive',
2994 foreach ($contributeSetting as $setting => $value) {
2995 Civi
::settings()->set($setting, $value);
3000 * Enable Tax and Invoicing
3002 protected function disableTaxAndInvoicing(): void
{
3003 $accounts = $this->callAPISuccess('EntityFinancialAccount', 'get', ['account_relationship' => 'Sales Tax Account is'])['values'];
3004 foreach ($accounts as $account) {
3005 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $account['id']]);
3006 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $account['financial_account_id']]);
3009 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3010 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3012 Civi
::settings()->set('invoice_is_email_pdf', FALSE);
3013 Civi
::settings()->set('invoicing', FALSE);
3017 * Add Sales Tax Account for the financial type.
3019 * @param int $financialTypeId
3021 * @param array $accountParams
3023 * @return CRM_Financial_DAO_EntityFinancialAccount
3024 * @throws \CRM_Core_Exception
3026 protected function addTaxAccountToFinancialType(int $financialTypeId, $accountParams = []) {
3027 $params = array_merge([
3028 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3029 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3030 'is_deductible' => 1,
3035 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3037 'entity_table' => 'civicrm_financial_type',
3038 'entity_id' => $financialTypeId,
3039 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3042 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3043 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = $params['tax_rate'];
3045 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3046 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3047 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3048 $dao->copyValues($entityParams);
3050 if ($dao->fetch()) {
3051 $entityParams['id'] = $dao->id
;
3053 $entityParams['financial_account_id'] = $account->id
;
3055 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3059 * Create price set with contribution test for test setup.
3061 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3062 * on parent class at some point (fn is not in 4.4).
3065 * @param array $params
3067 public function createPriceSetWithPage($entity = NULL, $params = []) {
3068 $membershipTypeID = $this->membershipTypeCreate(['name' => 'Special']);
3069 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', [
3070 'title' => 'Test Contribution Page',
3071 'financial_type_id' => 1,
3072 'currency' => 'NZD',
3073 'goal_amount' => 50,
3074 'is_pay_later' => 1,
3075 'is_monetary' => TRUE,
3076 'is_email_receipt' => FALSE,
3078 $priceSet = $this->callAPISuccess('price_set', 'create', [
3079 'is_quick_config' => 0,
3080 'extends' => 'CiviMember',
3081 'financial_type_id' => 1,
3082 'title' => 'my Page',
3084 $priceSetID = $priceSet['id'];
3086 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3087 $priceField = $this->callAPISuccess('price_field', 'create', [
3088 'price_set_id' => $priceSetID,
3089 'label' => 'Goat Breed',
3090 'html_type' => 'Radio',
3092 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3093 'price_set_id' => $priceSetID,
3094 'price_field_id' => $priceField['id'],
3095 'label' => 'Long Haired Goat',
3097 'financial_type_id' => 'Donation',
3098 'membership_type_id' => $membershipTypeID,
3099 'membership_num_terms' => 1,
3101 $this->_ids
['price_field_value'] = [$priceFieldValue['id']];
3102 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3103 'price_set_id' => $priceSetID,
3104 'price_field_id' => $priceField['id'],
3105 'label' => 'Shoe-eating Goat',
3107 'financial_type_id' => 'Donation',
3108 'membership_type_id' => $membershipTypeID,
3109 'membership_num_terms' => 2,
3111 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3113 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3114 'price_set_id' => $priceSetID,
3115 'price_field_id' => $priceField['id'],
3116 'label' => 'Shoe-eating Goat',
3118 'financial_type_id' => 'Donation',
3120 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3122 $this->_ids
['price_set'] = $priceSetID;
3123 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3124 $this->_ids
['price_field'] = [$priceField['id']];
3126 $this->_ids
['membership_type'] = $membershipTypeID;
3130 * Only specified contact returned.
3132 * @implements CRM_Utils_Hook::aclWhereClause
3136 * @param $whereTables
3140 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3141 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3145 * @implements CRM_Utils_Hook::selectWhereClause
3147 * @param string $entity
3148 * @param array $clauses
3150 public function selectWhereClauseHook($entity, &$clauses) {
3151 if ($entity == 'Event') {
3152 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3157 * An implementation of hook_civicrm_post used with all our test cases.
3160 * @param string $objectName
3161 * @param int $objectId
3164 public function onPost($op, $objectName, $objectId, &$objectRef) {
3165 if ($op == 'create' && $objectName == 'Individual') {
3166 CRM_Core_DAO
::executeQuery(
3167 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3169 1 => [$objectId, 'Integer'],
3174 if ($op == 'edit' && $objectName == 'Participant') {
3176 1 => [$objectId, 'Integer'],
3178 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3179 CRM_Core_DAO
::executeQuery($query, $params);
3184 * Instantiate form object.
3186 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3188 * @param string $class
3189 * Name of form class.
3191 * @param array $formValues
3193 * @param string $pageName
3195 * @param array $searchFormValues
3196 * Values for the search form if the form is a task eg.
3197 * for selected ids 6 & 8:
3199 * 'radio_ts' => 'ts_sel',
3200 * 'task' => CRM_Member_Task::PDF_LETTER,
3205 * @return \CRM_Core_Form
3207 public function getFormObject($class, $formValues = [], $pageName = '', $searchFormValues = []) {
3208 $_POST = $formValues;
3209 /* @var CRM_Core_Form $form */
3210 $form = new $class();
3211 $_SERVER['REQUEST_METHOD'] = 'GET';
3213 case 'CRM_Event_Cart_Form_Checkout_Payment':
3214 case 'CRM_Event_Cart_Form_Checkout_ParticipantsAndPrices':
3215 $form->controller
= new CRM_Event_Cart_Controller_Checkout();
3218 case strpos($class, '_Form_') !== FALSE:
3219 $form->controller
= new CRM_Core_Controller_Simple($class, $pageName);
3223 $form->controller
= new CRM_Core_Controller();
3226 $pageName = $form->getName();
3228 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3229 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3230 if ($searchFormValues) {
3231 $_SESSION['_' . $form->controller
->_name
. '_container']['values']['Search'] = $searchFormValues;
3233 if (isset($formValues['_qf_button_name'])) {
3234 $_SESSION['_' . $form->controller
->_name
. '_container']['_qf_button_name'] = $formValues['_qf_button_name'];
3240 * Get possible thousand separators.
3244 public function getThousandSeparators() {
3245 return [['.'], [',']];
3249 * Get the boolean options as a provider.
3253 public function getBooleanDataProvider() {
3254 return [[TRUE], [FALSE]];
3258 * Set the separators for thousands and decimal points.
3260 * Note that this only covers some common scenarios.
3262 * It does not cater for a situation where the thousand separator is a [space]
3263 * Latter is the Norwegian localization. At least some tests need to
3264 * use setMonetaryDecimalPoint and setMonetaryThousandSeparator directly
3265 * to provide broader coverage.
3267 * @param string $thousandSeparator
3269 protected function setCurrencySeparators($thousandSeparator) {
3270 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3271 Civi
::settings()->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3275 * Sets the thousand separator.
3277 * If you use this function also set the decimal separator: setMonetaryDecimalSeparator
3279 * @param $thousandSeparator
3281 protected function setMonetaryThousandSeparator($thousandSeparator) {
3282 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3286 * Sets the decimal separator.
3288 * If you use this function also set the thousand separator setMonetaryDecimalPoint
3290 * @param $decimalPoint
3292 protected function setMonetaryDecimalPoint($decimalPoint) {
3293 Civi
::settings()->set('monetaryDecimalPoint', $decimalPoint);
3297 * Sets the default currency.
3301 protected function setDefaultCurrency($currency) {
3302 Civi
::settings()->set('defaultCurrency', $currency);
3306 * Format money as it would be input.
3308 * @param string $amount
3312 protected function formatMoneyInput($amount) {
3313 return CRM_Utils_Money
::format($amount, NULL, '%a');
3317 * Get the contribution object.
3319 * @param int $contributionID
3321 * @return \CRM_Contribute_BAO_Contribution
3323 protected function getContributionObject($contributionID) {
3324 $contributionObj = new CRM_Contribute_BAO_Contribution();
3325 $contributionObj->id
= $contributionID;
3326 $contributionObj->find(TRUE);
3327 return $contributionObj;
3331 * Enable multilingual.
3333 public function enableMultilingual() {
3334 $this->callAPISuccess('Setting', 'create', [
3335 'lcMessages' => 'en_US',
3336 'languageLimit' => [
3341 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3344 $dbLocale = '_en_US';
3348 * Setup or clean up SMS tests
3350 * @param bool $teardown
3352 * @throws \CiviCRM_API3_Exception
3354 public function setupForSmsTests($teardown = FALSE) {
3355 require_once 'CiviTest/CiviTestSMSProvider.php';
3357 // Option value params for CiviTestSMSProvider
3358 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3360 'option_group_id' => $groupID,
3361 'label' => 'unittestSMS',
3362 'value' => 'unit.test.sms',
3363 'name' => 'CiviTestSMSProvider',
3370 // Test completed, delete provider
3371 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3372 civicrm_api3('option_value', 'delete', ['id' => $providerOptionValueResult['id']]);
3376 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3377 // in CRM/Sms/Provider.php even though it is not an extension.
3378 return civicrm_api3('option_value', 'create', $params);
3382 * Start capturing browser output.
3384 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3386 protected function startCapturingOutput() {
3388 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3392 * Stop capturing browser output and return as a csv.
3394 * @param bool $isFirstRowHeaders
3396 * @return \League\Csv\Reader
3398 * @throws \League\Csv\Exception
3400 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3401 $output = ob_get_flush();
3402 $stream = fopen('php://memory', 'r+');
3403 fwrite($stream, $output);
3405 $this->assertEquals("\xEF\xBB\xBF", substr($output, 0, 3));
3406 $csv = Reader
::createFromString($output);
3407 if ($isFirstRowHeaders) {
3408 $csv->setHeaderOffset(0);
3415 * Rename various labels to not match the names.
3417 * Doing these mimics the fact the name != the label in international installs & triggers failures in
3418 * code that expects it to.
3420 protected function renameLabels() {
3421 $replacements = ['Pending', 'Refunded'];
3422 foreach ($replacements as $name) {
3423 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = '{$name} Label**' where label = '{$name}' AND name = '{$name}'");
3428 * Undo any label renaming.
3430 protected function resetLabels() {
3431 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = REPLACE(name, ' Label**', '') WHERE label LIKE '% Label**'");
3435 * Get parameters to set up a multi-line participant order.
3438 * @throws \CRM_Core_Exception
3440 protected function getParticipantOrderParams(): array {
3441 $event = $this->eventCreate();
3442 $this->_eventId
= $event['id'];
3444 'id' => $this->_eventId
,
3445 'financial_type_id' => 4,
3448 $this->callAPISuccess('event', 'create', $eventParams);
3449 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3451 'total_amount' => 300,
3452 'currency' => 'USD',
3453 'contact_id' => $this->individualCreate(),
3454 'financial_type_id' => 4,
3455 'contribution_status_id' => 'Pending',
3457 foreach ($priceFields['values'] as $key => $priceField) {
3458 $orderParams['line_items'][] = [
3461 'price_field_id' => $priceField['price_field_id'],
3462 'price_field_value_id' => $priceField['id'],
3463 'label' => $priceField['label'],
3464 'field_title' => $priceField['label'],
3466 'unit_price' => $priceField['amount'],
3467 'line_total' => $priceField['amount'],
3468 'financial_type_id' => $priceField['financial_type_id'],
3469 'entity_table' => 'civicrm_participant',
3473 'financial_type_id' => 4,
3474 'event_id' => $this->_eventId
,
3477 'fee_currency' => 'USD',
3478 'contact_id' => $this->individualCreate(),
3482 return $orderParams;
3488 * @throws \CRM_Core_Exception
3490 protected function validatePayments($payments): void
{
3491 foreach ($payments as $payment) {
3492 $balance = CRM_Contribute_BAO_Contribution
::getContributionBalance($payment['contribution_id']);
3493 if ($balance < 0 && $balance +
$payment['total_amount'] === 0.0) {
3494 // This is an overpayment situation. there are no financial items to allocate the overpayment.
3495 // This is a pretty rough way at guessing which payment is the overpayment - but
3496 // for the test suite it should be enough.
3499 $items = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
3500 'financial_trxn_id' => $payment['id'],
3501 'entity_table' => 'civicrm_financial_item',
3502 'return' => ['amount'],
3505 foreach ($items as $item) {
3506 $itemTotal +
= $item['amount'];
3508 $this->assertEquals($payment['total_amount'], $itemTotal);
3513 * Validate all created payments.
3515 * @throws \CRM_Core_Exception
3517 protected function validateAllPayments(): void
{
3518 $payments = $this->callAPISuccess('Payment', 'get', [
3519 'return' => ['total_amount', 'tax_amount'],
3520 'options' => ['limit' => 0],
3522 $this->validatePayments($payments);
3526 * Validate all created contributions.
3528 * @throws \API_Exception
3530 protected function validateAllContributions(): void
{
3531 $contributions = Contribution
::get(FALSE)->setSelect(['total_amount', 'tax_amount'])->execute();
3532 foreach ($contributions as $contribution) {
3533 $lineItems = $this->callAPISuccess('LineItem', 'get', [
3534 'contribution_id' => $contribution['id'],
3535 'return' => ['tax_amount', 'line_total', 'entity_table', 'entity_id', 'qty'],
3541 foreach ($lineItems as $lineItem) {
3542 $total +
= $lineItem['line_total'];
3543 $taxTotal +
= (float) ($lineItem['tax_amount'] ??
0);
3544 if ($lineItem['entity_table'] === 'civicrm_membership') {
3545 $memberships[] = $lineItem['entity_id'];
3547 if ($lineItem['entity_table'] === 'civicrm_participant' && $lineItem['qty'] > 0) {
3548 $participants[$lineItem['entity_id']] = $lineItem['entity_id'];
3551 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', ['contribution_id' => $contribution['id'], 'return' => 'membership_id'])['values'];
3552 $participantPayments = $this->callAPISuccess('ParticipantPayment', 'get', ['contribution_id' => $contribution['id'], 'return' => 'participant_id'])['values'];
3553 $this->assertCount(count($memberships), $membershipPayments);
3554 $this->assertCount(count($participants), $participantPayments);
3555 foreach ($membershipPayments as $payment) {
3556 $this->assertContains($payment['membership_id'], $memberships);
3558 foreach ($participantPayments as $payment) {
3559 $this->assertContains($payment['participant_id'], $participants);
3561 $this->assertEquals($taxTotal, (float) ($contribution['tax_amount'] ??
0));
3562 $this->assertEquals($total +
$taxTotal, $contribution['total_amount']);
3569 protected function createRuleGroup() {
3570 return $this->callAPISuccess('RuleGroup', 'create', [
3571 'contact_type' => 'Individual',
3573 'used' => 'General',
3574 'name' => 'TestRule',
3575 'title' => 'TestRule',
3581 * Generic create test.
3583 * @param int $version
3585 * @throws \CRM_Core_Exception
3587 protected function basicCreateTest(int $version): void
{
3588 $this->_apiversion
= $version;
3589 $result = $this->callAPIAndDocument($this->_entity
, 'create', $this->params
, __FUNCTION__
, __FILE__
);
3590 $this->assertEquals(1, $result['count']);
3591 $this->assertNotNull($result['values'][$result['id']]['id']);
3592 $this->getAndCheck($this->params
, $result['id'], $this->_entity
);
3596 * Generic delete test.
3598 * @param int $version
3600 * @throws \CRM_Core_Exception
3602 protected function basicDeleteTest(int $version): void
{
3603 $this->_apiversion
= $version;
3604 $result = $this->callAPISuccess($this->_entity
, 'create', $this->params
);
3605 $deleteParams = ['id' => $result['id']];
3606 $this->callAPIAndDocument($this->_entity
, 'delete', $deleteParams, __FUNCTION__
, __FILE__
);
3607 $checkDeleted = $this->callAPISuccess($this->_entity
, 'get', []);
3608 $this->assertEquals(0, $checkDeleted['count']);
3612 * Create and return a case object for the given Client ID.
3614 * @param int $clientId
3615 * @param int $loggedInUser
3616 * Omit or pass NULL to use the same as clientId
3617 * @param array $extra
3618 * Optional specific parameters such as start_date
3620 * @return CRM_Case_BAO_Case
3622 public function createCase($clientId, $loggedInUser = NULL, $extra = []) {
3623 if (empty($loggedInUser)) {
3624 // backwards compatibility - but it's more typical that the creator is a different person than the client
3625 $loggedInUser = $clientId;
3627 $caseParams = array_merge([
3628 'activity_subject' => 'Case Subject',
3629 'client_id' => $clientId,
3630 'case_type_id' => 1,
3632 'case_type' => 'housing_support',
3633 'subject' => 'Case Subject',
3634 'start_date' => date('Y-m-d'),
3635 'start_date_time' => date('YmdHis'),
3637 'activity_details' => '',
3639 $form = new CRM_Case_Form_Case();
3640 return $form->testSubmit($caseParams, 'OpenCase', $loggedInUser, 'standalone');
3644 * Validate that all location entities have exactly one primary.
3646 * This query takes about 2 minutes on a DB with 10s of millions of contacts.
3648 public function assertLocationValidity(): void
{
3649 $this->assertEquals(0, CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM
3651 (SELECT a1.contact_id
3652 FROM civicrm_address a1
3653 LEFT JOIN civicrm_address a2 ON a1.id <> a2.id AND a2.is_primary = 1
3654 AND a1.contact_id = a2.contact_id
3657 AND a2.id IS NOT NULL
3658 AND a1.contact_id IS NOT NULL
3660 SELECT a1.contact_id
3661 FROM civicrm_address a1
3662 LEFT JOIN civicrm_address a2 ON a1.id <> a2.id AND a2.is_primary = 1
3663 AND a1.contact_id = a2.contact_id
3664 WHERE a1.is_primary = 0
3666 AND a1.contact_id IS NOT NULL
3670 SELECT a1.contact_id
3671 FROM civicrm_email a1
3672 LEFT JOIN civicrm_email a2 ON a1.id <> a2.id AND a2.is_primary = 1
3673 AND a1.contact_id = a2.contact_id
3676 AND a2.id IS NOT NULL
3677 AND a1.contact_id IS NOT NULL
3679 SELECT a1.contact_id
3680 FROM civicrm_email a1
3681 LEFT JOIN civicrm_email a2 ON a1.id <> a2.id AND a2.is_primary = 1
3682 AND a1.contact_id = a2.contact_id
3683 WHERE a1.is_primary = 0
3685 AND a1.contact_id IS NOT NULL
3689 SELECT a1.contact_id
3690 FROM civicrm_phone a1
3691 LEFT JOIN civicrm_phone a2 ON a1.id <> a2.id AND a2.is_primary = 1
3692 AND a1.contact_id = a2.contact_id
3695 AND a2.id IS NOT NULL
3696 AND a1.contact_id IS NOT NULL
3698 SELECT a1.contact_id
3699 FROM civicrm_phone a1
3700 LEFT JOIN civicrm_phone a2 ON a1.id <> a2.id AND a2.is_primary = 1
3701 AND a1.contact_id = a2.contact_id
3702 WHERE a1.is_primary = 0
3704 AND a1.contact_id IS NOT NULL
3708 SELECT a1.contact_id
3710 LEFT JOIN civicrm_im a2 ON a1.id <> a2.id AND a2.is_primary = 1
3711 AND a1.contact_id = a2.contact_id
3714 AND a2.id IS NOT NULL
3715 AND a1.contact_id IS NOT NULL
3717 SELECT a1.contact_id
3719 LEFT JOIN civicrm_im a2 ON a1.id <> a2.id AND a2.is_primary = 1
3720 AND a1.contact_id = a2.contact_id
3721 WHERE a1.is_primary = 0
3723 AND a1.contact_id IS NOT NULL
3727 SELECT a1.contact_id
3728 FROM civicrm_openid a1
3729 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3730 AND a1.contact_id = a2.contact_id
3731 WHERE (a1.is_primary = 1 AND a2.id IS NOT NULL)
3734 SELECT a1.contact_id
3735 FROM civicrm_openid a1
3736 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3737 AND a1.contact_id = a2.contact_id
3740 AND a2.id IS NOT NULL
3741 AND a1.contact_id IS NOT NULL
3743 SELECT a1.contact_id
3744 FROM civicrm_openid a1
3745 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3746 AND a1.contact_id = a2.contact_id
3747 WHERE a1.is_primary = 0
3749 AND a1.contact_id IS NOT NULL) as primary_descrepancies
3754 * Ensure the specified mysql mode/s are activated.
3756 * @param array $modes
3758 protected function ensureMySQLMode(array $modes): void
{
3759 $currentModes = array_fill_keys(CRM_Utils_SQL
::getSqlModes(), 1);
3760 $currentModes = array_merge($currentModes, array_fill_keys($modes, 1));
3761 CRM_Core_DAO
::executeQuery("SET GLOBAL sql_mode = '" . implode(',', array_keys($currentModes)) . "'");
3762 CRM_Core_DAO
::executeQuery("SET sql_mode = '" . implode(',', array_keys($currentModes)) . "'");
3766 * Delete any extraneous relationship types.
3768 * @throws \API_Exception
3769 * @throws \Civi\API\Exception\UnauthorizedException
3771 protected function deleteNonDefaultRelationshipTypes(): void
{
3772 RelationshipType
::delete(FALSE)->addWhere('name_a_b', 'NOT IN', [
3779 'Head of Household for',
3780 'Household Member of',
3781 'Case Coordinator is',
3787 * Delete any existing custom data groups.
3789 protected function cleanupCustomGroups(): void
{
3791 CustomField
::get(FALSE)->setSelect(['option_group_id', 'custom_group_id'])
3792 ->addChain('delete_options', OptionGroup
::delete()
3793 ->addWhere('id', '=', '$option_group_id')
3795 ->addChain('delete_fields', CustomField
::delete()
3796 ->addWhere('id', '=', '$id')
3799 CustomGroup
::delete(FALSE)->addWhere('id', '>', 0)->execute();
3801 catch (API_Exception
$e) {
3802 $this->fail('failed to cleanup custom groups ' . $e->getMessage());
3807 * Ensure the default price set & field exist for memberships.
3809 protected function ensureMembershipPriceSetExists(): void
{
3810 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_price_set (`id`, `name`, `title`, `extends`)
3811 VALUES (2, 'default_membership_type_amount', 'Membership Amount', 3)
3812 ON DUPLICATE KEY UPDATE `name` = 'default_membership_type_amount', title = 'Membership Amount';
3814 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_price_field
3815 (`id`, `name`, `price_set_id`, `label`, `html_type`)
3816 VALUES (2, 1, 2, 'Membership Amount', 'Radio')
3817 ON DUPLICATE KEY UPDATE `name` = '1', price_set_id = 1, label = 'Membership Amount', html_type = 'Radio'
3822 * Add an address block to the current domain.
3824 * @noinspection PhpUnhandledExceptionInspection
3826 protected function addLocationBlockToDomain(): void
{
3827 $contactID = CRM_Core_BAO_Domain
::getDomain()->contact_id
;
3829 ->setValues(['phone' => 123, 'contact_id' => $contactID])
3832 Address
::create()->setValues([
3833 'street_address' => '10 Downing Street',
3835 'contact_id' => $contactID,
3836 ])->execute()->first();