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 switch ($durationUnit) {
749 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
753 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
754 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
755 $renewedMembershipEndDate->add(new DateInterval('P1D'));
756 $renewedMembershipEndDate->add(new DateInterval('P1M'));
757 $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();
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 = []) {
894 'payment_processor_type_id' => 'Dummy',
895 'financial_account_id' => 12,
899 'url_site' => 'http://dummy.com',
900 'url_recur' => 'http://dummy.com',
903 'payment_instrument_id' => 'Debit Card',
905 $processorParams = array_merge($processorParams, $params);
906 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
907 return $processor['id'];
911 * Create Payment Processor.
913 * @param array $processorParams
915 * @return \CRM_Core_Payment_Dummy
916 * Instance of Dummy Payment Processor
918 * @throws \CiviCRM_API3_Exception
920 public function dummyProcessorCreate($processorParams = []) {
921 $paymentProcessorID = $this->processorCreate($processorParams);
922 // 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
923 // Otherwise we are testing a scenario that only exists in tests (and some tests fail because the live processor has not been defined).
924 $processorParams['is_test'] = FALSE;
925 $this->processorCreate($processorParams);
926 return System
::singleton()->getById($paymentProcessorID);
930 * Create contribution page.
932 * @param array $params
935 * Array of contribution page
937 public function contributionPageCreate($params = []) {
938 $this->_pageParams
= array_merge([
939 'title' => 'Test Contribution Page',
940 'financial_type_id' => 1,
942 'financial_account_id' => 1,
944 'is_allow_other_amount' => 1,
946 'max_amount' => 1000,
948 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
952 * Create a sample batch.
954 public function batchCreate() {
955 $params = $this->_params
;
956 $params['name'] = $params['title'] = 'Batch_433397';
957 $params['status_id'] = 1;
958 $result = $this->callAPISuccess('batch', 'create', $params);
959 return $result['id'];
965 * @param array $params
968 * result of created tag
970 public function tagCreate($params = []) {
972 'name' => 'New Tag3',
973 'description' => 'This is description for Our New Tag ',
976 $params = array_merge($defaults, $params);
977 $result = $this->callAPISuccess('Tag', 'create', $params);
978 return $result['values'][$result['id']];
985 * Id of the tag to be deleted.
989 public function tagDelete($tagId) {
990 require_once 'api/api.php';
994 $result = $this->callAPISuccess('Tag', 'delete', $params);
995 return $result['id'];
999 * Add entity(s) to the tag
1001 * @param array $params
1005 public function entityTagAdd($params) {
1006 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1013 * @param array $params
1017 * id of created pledge
1019 public function pledgeCreate($params): int {
1020 $params = array_merge([
1021 'pledge_create_date' => date('Ymd'),
1022 'start_date' => date('Ymd'),
1023 'scheduled_date' => date('Ymd'),
1025 'pledge_status_id' => '2',
1026 'financial_type_id' => '1',
1027 'pledge_original_installment_amount' => 20,
1028 'frequency_interval' => 5,
1029 'frequency_unit' => 'year',
1030 'frequency_day' => 15,
1031 'installments' => 5,
1035 $result = $this->callAPISuccess('Pledge', 'create', $params);
1036 return $result['id'];
1040 * Delete contribution.
1042 * @param int $pledgeId
1044 * @throws \CRM_Core_Exception
1046 public function pledgeDelete($pledgeId) {
1048 'pledge_id' => $pledgeId,
1050 $this->callAPISuccess('Pledge', 'delete', $params);
1054 * Create contribution.
1056 * @param array $params
1057 * Array of parameters.
1060 * id of created contribution
1062 public function contributionCreate(array $params): int {
1063 $params = array_merge([
1065 'receive_date' => date('Ymd'),
1066 'total_amount' => 100.00,
1067 'fee_amount' => 5.00,
1068 'financial_type_id' => 1,
1069 'payment_instrument_id' => 1,
1070 'non_deductible_amount' => 10.00,
1072 'contribution_status_id' => 1,
1075 $result = $this->callAPISuccess('contribution', 'create', $params);
1076 return $result['id'];
1080 * Delete contribution.
1082 * @param int $contributionId
1085 * @throws \CRM_Core_Exception
1087 public function contributionDelete($contributionId) {
1089 'contribution_id' => $contributionId,
1091 $result = $this->callAPISuccess('contribution', 'delete', $params);
1098 * @param array $params
1099 * Name-value pair for an event.
1103 public function eventCreate(array $params = []): array {
1104 // if no contact was passed, make up a dummy event creator
1105 if (!isset($params['contact_id'])) {
1106 $params['contact_id'] = $this->_contactCreate([
1107 'contact_type' => 'Individual',
1108 'first_name' => 'Event',
1109 'last_name' => 'Creator',
1113 // set defaults for missing params
1114 $params = array_merge([
1115 'title' => 'Annual CiviCRM meet',
1116 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1117 'description' => 'This event is intended to give brief idea about progress of CiviCRM and giving solutions to common user issues',
1118 'event_type_id' => 1,
1120 'start_date' => 20081021,
1121 'end_date' => 20081023,
1122 'is_online_registration' => 1,
1123 'registration_start_date' => 20080601,
1124 'registration_end_date' => 20081015,
1125 'max_participants' => 100,
1126 'event_full_text' => 'Sorry! We are already full',
1129 'is_show_location' => 0,
1130 'is_email_confirm' => 1,
1133 $event = $this->callAPISuccess('Event', 'create', $params);
1134 $this->ids
['event'][] = $event['id'];
1139 * Create a paid event.
1141 * @param array $params
1143 * @param array $options
1145 * @param string $key
1146 * Index for storing event ID in ids array.
1150 * @throws \CRM_Core_Exception
1152 protected function eventCreatePaid($params, $options = [['name' => 'hundy', 'amount' => 100]], $key = 'event') {
1153 $params['is_monetary'] = TRUE;
1154 $event = $this->eventCreate($params);
1155 $this->ids
['Event'][$key] = (int) $event['id'];
1156 $this->ids
['PriceSet'][$key] = $this->eventPriceSetCreate(55, 0, 'Radio', $options);
1157 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->ids
['PriceSet'][$key]);
1158 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->ids
['PriceSet'][$key], TRUE, FALSE);
1159 $priceSet = $priceSet[$this->ids
['PriceSet'][$key]] ??
NULL;
1160 $this->eventFeeBlock
= $priceSet['fields'] ??
NULL;
1172 public function eventDelete($id) {
1176 return $this->callAPISuccess('event', 'delete', $params);
1180 * Delete participant.
1182 * @param int $participantID
1186 public function participantDelete($participantID) {
1188 'id' => $participantID,
1190 $check = $this->callAPISuccess('Participant', 'get', $params);
1191 if ($check['count'] > 0) {
1192 return $this->callAPISuccess('Participant', 'delete', $params);
1197 * Create participant payment.
1199 * @param int $participantID
1200 * @param int $contributionID
1203 * $id of created payment
1205 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1206 //Create Participant Payment record With Values
1208 'participant_id' => $participantID,
1209 'contribution_id' => $contributionID,
1212 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1213 return $result['id'];
1217 * Delete participant payment.
1219 * @param int $paymentID
1221 public function participantPaymentDelete($paymentID) {
1225 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1231 * @param int $contactID
1234 * location id of created location
1236 public function locationAdd($contactID) {
1239 'location_type' => 'New Location Type',
1241 'name' => 'Saint Helier St',
1242 'county' => 'Marin',
1243 'country' => 'UNITED STATES',
1244 'state_province' => 'Michigan',
1245 'supplemental_address_1' => 'Hallmark Ct',
1246 'supplemental_address_2' => 'Jersey Village',
1247 'supplemental_address_3' => 'My Town',
1252 'contact_id' => $contactID,
1253 'address' => $address,
1254 'location_format' => '2.0',
1255 'location_type' => 'New Location Type',
1258 $result = $this->callAPISuccess('Location', 'create', $params);
1263 * Delete Locations of contact.
1265 * @param array $params
1268 public function locationDelete($params) {
1269 $this->callAPISuccess('Location', 'delete', $params);
1273 * Add a Location Type.
1275 * @param array $params
1277 * @return CRM_Core_DAO_LocationType
1278 * location id of created location
1280 public function locationTypeCreate($params = NULL) {
1281 if ($params === NULL) {
1283 'name' => 'New Location Type',
1284 'vcard_name' => 'New Location Type',
1285 'description' => 'Location Type for Delete',
1290 $locationType = new CRM_Core_DAO_LocationType();
1291 $locationType->copyValues($params);
1292 $locationType->save();
1293 // clear getfields cache
1294 CRM_Core_PseudoConstant
::flush();
1295 $this->callAPISuccess('phone', 'getfields', ['version' => 3, 'cache_clear' => 1]);
1296 return $locationType->id
;
1300 * Delete a Location Type.
1302 * @param int $locationTypeId
1304 public function locationTypeDelete($locationTypeId) {
1305 $locationType = new CRM_Core_DAO_LocationType();
1306 $locationType->id
= $locationTypeId;
1307 $locationType->delete();
1313 * @param array $params
1315 * @return CRM_Core_DAO_Mapping
1316 * Mapping id of created mapping
1318 public function mappingCreate($params = NULL) {
1319 if ($params === NULL) {
1321 'name' => 'Mapping name',
1322 'description' => 'Mapping description',
1323 // 'Export Contact' mapping.
1324 'mapping_type_id' => 7,
1328 $mapping = new CRM_Core_DAO_Mapping();
1329 $mapping->copyValues($params);
1331 // clear getfields cache
1332 CRM_Core_PseudoConstant
::flush();
1333 $this->callAPISuccess('mapping', 'getfields', ['version' => 3, 'cache_clear' => 1]);
1340 * @param int $mappingId
1342 public function mappingDelete($mappingId) {
1343 $mapping = new CRM_Core_DAO_Mapping();
1344 $mapping->id
= $mappingId;
1349 * Prepare class for ACLs.
1351 protected function prepareForACLs() {
1352 $config = CRM_Core_Config
::singleton();
1353 $config->userPermissionClass
->permissions
= [];
1359 protected function cleanUpAfterACLs() {
1360 CRM_Utils_Hook
::singleton()->reset();
1361 $tablesToTruncate = [
1363 'civicrm_acl_cache',
1364 'civicrm_acl_entity_role',
1365 'civicrm_acl_contact_cache',
1367 $this->quickCleanup($tablesToTruncate);
1368 $config = CRM_Core_Config
::singleton();
1369 unset($config->userPermissionClass
->permissions
);
1373 * Create a smart group.
1375 * By default it will be a group of households.
1377 * @param array $smartGroupParams
1378 * @param array $groupParams
1379 * @param string $contactType
1383 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1384 $smartGroupParams = array_merge(['form_values' => ['contact_type' => ['IN' => [$contactType]]]], $smartGroupParams);
1385 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1387 $groupParams['saved_search_id'] = $savedSearch->id
;
1388 return $this->groupCreate($groupParams);
1394 * @param array $params
1396 public function uFFieldCreate($params = []) {
1397 $params = array_merge([
1399 'field_name' => 'first_name',
1402 'visibility' => 'Public Pages and Listings',
1403 'is_searchable' => '1',
1404 'label' => 'first_name',
1405 'field_type' => 'Individual',
1408 $this->callAPISuccess('uf_field', 'create', $params);
1412 * Add a UF Join Entry.
1414 * @param array $params
1417 * $id of created UF Join
1419 public function ufjoinCreate($params = NULL) {
1420 if ($params === NULL) {
1423 'module' => 'CiviEvent',
1424 'entity_table' => 'civicrm_event',
1430 $result = $this->callAPISuccess('uf_join', 'create', $params);
1435 * @param array $params
1436 * Optional parameters.
1437 * @param bool $reloadConfig
1438 * While enabling CiviCampaign component, we shouldn't always forcibly
1439 * reload config as this hinder hook call in test environment
1444 public function campaignCreate($params = [], $reloadConfig = TRUE) {
1445 $this->enableCiviCampaign($reloadConfig);
1446 $campaign = $this->callAPISuccess('campaign', 'create', array_merge([
1447 'name' => 'big_campaign',
1448 'title' => 'Campaign',
1450 return $campaign['id'];
1454 * Create Group for a contact.
1456 * @param int $contactId
1458 public function contactGroupCreate($contactId) {
1460 'contact_id.1' => $contactId,
1464 $this->callAPISuccess('GroupContact', 'Create', $params);
1468 * Delete Group for a contact.
1470 * @param int $contactId
1472 public function contactGroupDelete($contactId) {
1474 'contact_id.1' => $contactId,
1477 $this->civicrm_api('GroupContact', 'Delete', $params);
1483 * @param array $params
1487 * @throws \CRM_Core_Exception
1488 * @throws \CiviCRM_API3_Exception
1490 public function activityCreate($params = []) {
1491 $params = array_merge([
1492 'subject' => 'Discussion on warm beer',
1493 'activity_date_time' => date('Ymd'),
1495 'location' => 'Baker Street',
1496 'details' => 'Lets schedule a meeting',
1498 'activity_type_id' => 'Meeting',
1500 if (!isset($params['source_contact_id'])) {
1501 $params['source_contact_id'] = $this->individualCreate();
1503 if (!isset($params['target_contact_id'])) {
1504 $params['target_contact_id'] = $this->individualCreate([
1505 'first_name' => 'Julia',
1506 'last_name' => 'Anderson',
1508 'email' => 'julia_anderson@civicrm.org',
1509 'contact_type' => 'Individual',
1512 if (!isset($params['assignee_contact_id'])) {
1513 $params['assignee_contact_id'] = $params['target_contact_id'];
1516 $result = civicrm_api3('Activity', 'create', $params);
1518 $result['target_contact_id'] = $params['target_contact_id'];
1519 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1524 * Create an activity type.
1526 * @param array $params
1531 public function activityTypeCreate($params) {
1532 return $this->callAPISuccess('ActivityType', 'create', $params);
1536 * Delete activity type.
1538 * @param int $activityTypeId
1539 * Id of the activity type.
1543 public function activityTypeDelete($activityTypeId) {
1544 $params['activity_type_id'] = $activityTypeId;
1545 return $this->callAPISuccess('ActivityType', 'delete', $params);
1549 * Create custom group.
1551 * @param array $params
1555 public function customGroupCreate($params = []) {
1557 'title' => 'new custom group',
1558 'extends' => 'Contact',
1560 'style' => 'Inline',
1564 $params = array_merge($defaults, $params);
1566 return $this->callAPISuccess('custom_group', 'create', $params);
1570 * Existing function doesn't allow params to be over-ridden so need a new one
1571 * this one allows you to only pass in the params you want to change
1573 * @param array $params
1577 public function CustomGroupCreateByParams($params = []) {
1579 'title' => "API Custom Group",
1580 'extends' => 'Contact',
1582 'style' => 'Inline',
1585 $params = array_merge($defaults, $params);
1586 return $this->callAPISuccess('custom_group', 'create', $params);
1590 * Create custom group with multi fields.
1592 * @param array $params
1596 public function CustomGroupMultipleCreateByParams($params = []) {
1601 $params = array_merge($defaults, $params);
1602 return $this->CustomGroupCreateByParams($params);
1606 * Create custom group with multi fields.
1608 * @param array $params
1612 public function CustomGroupMultipleCreateWithFields($params = []) {
1613 // also need to pass on $params['custom_field'] if not set but not in place yet
1615 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1616 $ids['custom_group_id'] = $customGroup['id'];
1618 $customField = $this->customFieldCreate([
1619 'custom_group_id' => $ids['custom_group_id'],
1620 'label' => 'field_1' . $ids['custom_group_id'],
1624 $ids['custom_field_id'][] = $customField['id'];
1626 $customField = $this->customFieldCreate([
1627 'custom_group_id' => $ids['custom_group_id'],
1628 'default_value' => '',
1629 'label' => 'field_2' . $ids['custom_group_id'],
1632 $ids['custom_field_id'][] = $customField['id'];
1634 $customField = $this->customFieldCreate([
1635 'custom_group_id' => $ids['custom_group_id'],
1636 'default_value' => '',
1637 'label' => 'field_3' . $ids['custom_group_id'],
1640 $ids['custom_field_id'][] = $customField['id'];
1646 * Create a custom group with a single text custom field. See
1647 * participant:testCreateWithCustom for how to use this
1649 * @param string $function
1651 * @param string $filename
1655 * ids of created objects
1657 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1658 $params = ['title' => $function];
1659 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1660 $params['extends'] = $entity ?
$entity : 'Contact';
1661 $customGroup = $this->customGroupCreate($params);
1662 $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id'], 'label' => $function]);
1663 CRM_Core_PseudoConstant
::flush();
1665 return ['custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']];
1669 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1670 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1672 * @param string $function
1674 * @param string $filename
1678 * ids of created objects
1680 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1681 $params = ['title' => $function];
1682 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1683 $params['extends'] = $entity ?
$entity : 'Contact';
1684 $customGroup = $this->customGroupCreate($params);
1685 $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1]);
1686 CRM_Core_PseudoConstant
::flush();
1688 'defaultValue' => 'Default Value',
1689 'lowercasevalue' => 'Lowercase Value',
1690 1 => 'Integer Value',
1693 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1694 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1695 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1696 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1697 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1698 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1699 foreach ($options as $option_value => $option_label) {
1700 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1701 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1705 'custom_group_id' => $customGroup['id'],
1706 'custom_field_id' => $customField['id'],
1707 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'],
1708 'custom_field_group_options' => $options,
1713 * Delete custom group.
1715 * @param int $customGroupID
1719 public function customGroupDelete($customGroupID) {
1720 $params['id'] = $customGroupID;
1721 return $this->callAPISuccess('custom_group', 'delete', $params);
1725 * Create custom field.
1727 * @param array $params
1728 * (custom_group_id) is required.
1732 public function customFieldCreate($params) {
1733 $params = array_merge([
1734 'label' => 'Custom Field',
1735 'data_type' => 'String',
1736 'html_type' => 'Text',
1737 'is_searchable' => 1,
1739 'default_value' => 'defaultValue',
1742 $result = $this->callAPISuccess('custom_field', 'create', $params);
1743 // these 2 functions are called with force to flush static caches
1744 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1745 CRM_Core_Component
::getEnabledComponents(1);
1750 * Delete custom field.
1752 * @param int $customFieldID
1756 public function customFieldDelete($customFieldID) {
1758 $params['id'] = $customFieldID;
1759 return $this->callAPISuccess('custom_field', 'delete', $params);
1769 public function noteCreate($cId) {
1771 'entity_table' => 'civicrm_contact',
1772 'entity_id' => $cId,
1773 'note' => 'hello I am testing Note',
1774 'contact_id' => $cId,
1775 'modified_date' => date('Ymd'),
1776 'subject' => 'Test Note',
1779 return $this->callAPISuccess('Note', 'create', $params);
1783 * Enable CiviCampaign Component.
1785 public function enableCiviCampaign(): void
{
1786 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1790 * Create custom field with Option Values.
1792 * @param array $customGroup
1793 * @param string $name
1794 * Name of custom field.
1795 * @param array $extraParams
1796 * Additional parameters to pass through.
1800 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = []) {
1802 'custom_group_id' => $customGroup['id'],
1803 'name' => 'test_custom_group',
1804 'label' => 'Country',
1805 'html_type' => 'Select',
1806 'data_type' => 'String',
1809 'is_searchable' => 0,
1815 'name' => 'option_group1',
1816 'label' => 'option_group_label1',
1820 'option_label' => ['Label1', 'Label2'],
1821 'option_value' => ['value1', 'value2'],
1822 'option_name' => [$name . '_1', $name . '_2'],
1823 'option_weight' => [1, 2],
1824 'option_status' => [1, 1],
1827 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1829 return $this->callAPISuccess('custom_field', 'create', $params);
1837 public function confirmEntitiesDeleted($entities) {
1838 foreach ($entities as $entity) {
1840 $result = $this->callAPISuccess($entity, 'Get', []);
1841 if ($result['error'] == 1 ||
$result['count'] > 0) {
1842 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1850 * Quick clean by emptying tables created for the test.
1852 * @param array $tablesToTruncate
1853 * @param bool $dropCustomValueTables
1855 public function quickCleanup(array $tablesToTruncate, $dropCustomValueTables = FALSE): void
{
1857 $this->fail('CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()');
1859 if ($dropCustomValueTables) {
1860 $this->cleanupCustomGroups();
1861 // Reset autoincrement too.
1862 $tablesToTruncate[] = 'civicrm_custom_group';
1863 $tablesToTruncate[] = 'civicrm_custom_field';
1866 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1868 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0;');
1869 foreach ($tablesToTruncate as $table) {
1870 $sql = "TRUNCATE TABLE $table";
1871 CRM_Core_DAO
::executeQuery($sql);
1873 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1;');
1877 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1879 public function quickCleanUpFinancialEntities(): void
{
1880 $tablesToTruncate = [
1882 'civicrm_activity_contact',
1883 'civicrm_contribution',
1884 'civicrm_contribution_soft',
1885 'civicrm_contribution_product',
1886 'civicrm_financial_trxn',
1887 'civicrm_financial_item',
1888 'civicrm_contribution_recur',
1889 'civicrm_line_item',
1890 'civicrm_contribution_page',
1891 'civicrm_payment_processor',
1892 'civicrm_entity_financial_trxn',
1893 'civicrm_membership',
1894 'civicrm_membership_type',
1895 'civicrm_membership_payment',
1896 'civicrm_membership_log',
1897 'civicrm_membership_block',
1899 'civicrm_participant',
1900 'civicrm_participant_payment',
1902 'civicrm_pcp_block',
1904 'civicrm_pledge_block',
1905 'civicrm_pledge_payment',
1906 'civicrm_price_set_entity',
1907 'civicrm_price_field_value',
1908 'civicrm_price_field',
1910 $this->quickCleanup($tablesToTruncate);
1911 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1912 $this->restoreDefaultPriceSetConfig();
1913 $this->disableTaxAndInvoicing();
1914 $this->setCurrencySeparators(',');
1916 FinancialType
::delete(FALSE)->addWhere(
1920 'Campaign Contribution',
1925 catch (API_Exception
$e) {
1926 $this->fail('failed to cleanup financial types ' . $e->getMessage());
1928 CRM_Core_PseudoConstant
::flush('taxRates');
1929 System
::singleton()->flushProcessors();
1930 // @fixme this parameter is leaking - it should not be defined as a class static
1931 // but for now we just handle in tear down.
1932 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1936 * Reset the price set config so results exist.
1938 public function restoreDefaultPriceSetConfig(): void
{
1939 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1940 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1941 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)");
1942 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)");
1946 * Recreate default membership types.
1948 * @throws \API_Exception
1950 public function restoreMembershipTypes(): void
{
1951 MembershipType
::delete(FALSE)->addWhere('id', '>', 0)->execute();
1952 $this->quickCleanup(['civicrm_membership_type']);
1953 $this->ensureMembershipPriceSetExists();
1955 MembershipType
::save(FALSE)
1959 'name' => 'General',
1960 'description' => 'Regular annual membership.',
1961 'minimum_fee' => 100,
1962 'duration_unit' => 'year',
1963 'duration_interval' => 2,
1964 'period_type' => 'rolling',
1965 'relationship_type_id' => 7,
1966 'relationship_direction' => 'b_a',
1967 'visibility' => 'Public',
1972 'name' => 'Student',
1973 'description' => 'Discount membership for full-time students.',
1974 'minimum_fee' => 50,
1975 'duration_unit' => 1,
1976 'duration_interval' => 'year',
1977 'period_type' => 'rolling',
1978 'visibility' => 'Public',
1981 'name' => 'Lifetime',
1982 'description' => 'Lifetime membership.',
1983 'minimum_fee' => 1200.00,
1984 'duration_unit' => 1,
1985 'duration_interval' => 'lifetime',
1986 'period_type' => 'rolling',
1987 'relationship_type_id' => 7,
1988 'relationship_direction' => 'b_a',
1989 'visibility' => 'Admin',
1995 'member_of_contact_id' => 1,
1996 'financial_type_id' => 2,
2002 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2003 * Default behaviour is to also delete the entity
2004 * @param array $params
2005 * Params array to check against.
2007 * Id of the entity concerned.
2008 * @param string $entity
2009 * Name of entity concerned (e.g. membership).
2010 * @param bool $delete
2011 * Should the entity be deleted as part of this check.
2012 * @param string $errorText
2013 * Text to print on error.
2017 * @param array $params
2020 * @param int $delete
2021 * @param string $errorText
2023 public function getAndCheck(array $params, int $id, $entity, int $delete = 1, string $errorText = ''): void
{
2025 $result = $this->callAPISuccessGetSingle($entity, [
2027 'return' => array_keys($params),
2031 $this->callAPISuccess($entity, 'Delete', [
2035 $dateFields = $keys = $dateTimeFields = [];
2036 $fields = $this->callAPISuccess($entity, 'getfields', ['version' => 3, 'action' => 'get']);
2037 foreach ($fields['values'] as $field => $settings) {
2038 if (array_key_exists($field, $result)) {
2039 $keys[CRM_Utils_Array
::value('name', $settings, $field)] = $field;
2042 $keys[CRM_Utils_Array
::value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2044 $type = $settings['type'] ??
NULL;
2045 if ($type === CRM_Utils_Type
::T_DATE
) {
2046 $dateFields[] = $settings['name'];
2047 // we should identify both real names & unique names as dates
2048 if ($field !== $settings['name']) {
2049 $dateFields[] = $field;
2052 if ($type === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2053 $dateTimeFields[] = $settings['name'];
2054 // we should identify both real names & unique names as dates
2055 if ($field !== $settings['name']) {
2056 $dateTimeFields[] = $field;
2061 if (strtolower($entity) === 'contribution') {
2062 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2063 // this is not returned in id format
2064 unset($params['payment_instrument_id']);
2065 $params['contribution_source'] = $params['source'];
2066 unset($params['source']);
2069 foreach ($params as $key => $value) {
2070 if ($key === 'version' ||
strpos($key, 'api') === 0 ||
(!array_key_exists($key, $keys) ||
!array_key_exists($keys[$key], $result))) {
2073 if (in_array($key, $dateFields, TRUE)) {
2074 $value = date('Y-m-d', strtotime($value));
2075 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2077 if (in_array($key, $dateTimeFields, TRUE)) {
2078 $value = date('Y-m-d H:i:s', strtotime($value));
2079 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2081 $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);
2086 * Get formatted values in the actual and expected result.
2088 * @param array $actual
2089 * Actual calculated values.
2090 * @param array $expected
2093 public function checkArrayEquals(&$actual, &$expected) {
2094 self
::unsetId($actual);
2095 self
::unsetId($expected);
2096 $this->assertEquals($expected, $actual);
2100 * Unset the key 'id' from the array
2102 * @param array $unformattedArray
2103 * The array from which the 'id' has to be unset.
2105 public static function unsetId(&$unformattedArray) {
2106 $formattedArray = [];
2107 if (array_key_exists('id', $unformattedArray)) {
2108 unset($unformattedArray['id']);
2110 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2111 foreach ($unformattedArray['values'] as $key => $value) {
2112 if (is_array($value)) {
2113 foreach ($value as $k => $v) {
2119 elseif ($key == 'id') {
2120 $unformattedArray[$key];
2122 $formattedArray = [$value];
2124 $unformattedArray['values'] = $formattedArray;
2129 * Helper to enable/disable custom directory support
2131 * @param array $customDirs
2133 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2134 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2136 public function customDirectories($customDirs) {
2137 $config = CRM_Core_Config
::singleton();
2139 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2140 unset($config->customPHPPathDir
);
2142 elseif ($customDirs['php_path'] === TRUE) {
2143 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2146 $config->customPHPPathDir
= $php_path;
2149 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2150 unset($config->customTemplateDir
);
2152 elseif ($customDirs['template_path'] === TRUE) {
2153 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2156 $config->customTemplateDir
= $template_path;
2161 * Generate a temporary folder.
2163 * @param string $prefix
2167 public function createTempDir($prefix = 'test-') {
2168 $tempDir = CRM_Utils_File
::tempdir($prefix);
2169 $this->tempDirs
[] = $tempDir;
2173 public function cleanTempDirs() {
2174 if (!is_array($this->tempDirs
)) {
2175 // fix test errors where this is not set
2178 foreach ($this->tempDirs
as $tempDir) {
2179 if (is_dir($tempDir)) {
2180 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2186 * Temporarily replace the singleton extension with a different one.
2188 * @param \CRM_Extension_System $system
2190 public function setExtensionSystem(CRM_Extension_System
$system) {
2191 if ($this->origExtensionSystem
== NULL) {
2192 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2194 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2197 public function unsetExtensionSystem() {
2198 if ($this->origExtensionSystem
!== NULL) {
2199 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2200 $this->origExtensionSystem
= NULL;
2205 * Temporarily alter the settings-metadata to add a mock setting.
2207 * WARNING: The setting metadata will disappear on the next cache-clear.
2213 public function setMockSettingsMetaData($extras) {
2214 CRM_Utils_Hook
::singleton()
2215 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2216 $metadata = array_merge($metadata, $extras);
2219 Civi
::service('settings_manager')->flush();
2221 $fields = $this->callAPISuccess('setting', 'getfields', []);
2222 foreach ($extras as $key => $spec) {
2223 $this->assertNotEmpty($spec['title']);
2224 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2229 * @param string $name
2231 public function financialAccountDelete($name) {
2232 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2233 $financialAccount->name
= $name;
2234 if ($financialAccount->find(TRUE)) {
2235 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2236 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2237 $entityFinancialType->delete();
2238 $financialAccount->delete();
2243 * Set up an acl allowing contact to see 2 specified groups
2244 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2246 * You need to have pre-created these groups & created the user e.g
2247 * $this->createLoggedInUser();
2248 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2249 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2251 * @param bool $isProfile
2253 public function setupACL($isProfile = FALSE) {
2255 $_REQUEST = $this->_params
;
2257 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['access CiviCRM'];
2258 $optionGroupID = $this->callAPISuccessGetValue('option_group', ['return' => 'id', 'name' => 'acl_role']);
2259 $ov = new CRM_Core_DAO_OptionValue();
2260 $ov->option_group_id
= $optionGroupID;
2262 if ($ov->find(TRUE)) {
2263 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2265 $optionValue = $this->callAPISuccess('option_value', 'create', [
2266 'option_group_id' => $optionGroupID,
2267 'label' => 'pick me',
2271 CRM_Core_DAO
::executeQuery("
2272 TRUNCATE civicrm_acl_cache
2275 CRM_Core_DAO
::executeQuery("
2276 TRUNCATE civicrm_acl_contact_cache
2279 CRM_Core_DAO
::executeQuery("
2280 INSERT INTO civicrm_acl_entity_role (
2281 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2282 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2286 CRM_Core_DAO
::executeQuery("
2287 INSERT INTO civicrm_acl (
2288 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2291 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2296 CRM_Core_DAO
::executeQuery("
2297 INSERT INTO civicrm_acl (
2298 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2301 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2305 CRM_Core_DAO
::executeQuery("
2306 INSERT INTO civicrm_acl (
2307 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2310 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2315 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2316 $this->callAPISuccess('group_contact', 'create', [
2317 'group_id' => $this->_permissionedGroup
,
2318 'contact_id' => $this->_loggedInUser
,
2322 CRM_ACL_BAO_Cache
::resetCache();
2327 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2329 public function offsetDefaultPriceSet() {
2330 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', ['name' => 'default_contribution_amount']);
2331 $firstID = $contributionPriceSet['id'];
2332 $this->callAPISuccess('price_set', 'create', [
2333 'id' => $contributionPriceSet['id'],
2337 unset($contributionPriceSet['id']);
2338 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2339 $priceField = $this->callAPISuccess('price_field', 'getsingle', [
2340 'price_set_id' => $firstID,
2341 'options' => ['limit' => 1],
2343 unset($priceField['id']);
2344 $priceField['price_set_id'] = $newPriceSet['id'];
2345 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2346 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', [
2347 'price_set_id' => $firstID,
2349 'options' => ['limit' => 1],
2352 unset($priceFieldValue['id']);
2353 //create some padding to use up ids
2354 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2355 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2356 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, ['price_field_id' => $newPriceField['id']]));
2360 * Create an instance of the paypal processor.
2362 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2363 * this parent class & we don't have a structure for that yet
2364 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2365 * & the best protection against that is the functions this class affords
2367 * @param array $params
2369 * @return int $result['id'] payment processor id
2371 public function paymentProcessorCreate($params = []) {
2372 $params = array_merge([
2374 'domain_id' => CRM_Core_Config
::domainID(),
2375 'payment_processor_type_id' => 'PayPal',
2379 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2380 'password' => '1183377788',
2381 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2382 'url_site' => 'https://www.sandbox.paypal.com/',
2383 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2384 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2385 'class_name' => 'Payment_PayPalImpl',
2386 'billing_mode' => 3,
2387 'financial_type_id' => 1,
2388 'financial_account_id' => 12,
2389 // Credit card = 1 so can pass 'by accident'.
2390 'payment_instrument_id' => 'Debit Card',
2392 if (!is_numeric($params['payment_processor_type_id'])) {
2393 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2395 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', [
2396 'name' => $params['payment_processor_type_id'],
2400 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2401 return $result['id'];
2405 * Get the rendered contents from a form.
2407 * @param string $formName
2409 * @return false|string
2411 protected function getRenderedFormContents(string $formName) {
2412 $form = $this->getFormObject($formName);
2415 $form->controller
->_actions
['display']->perform($form, 'display');
2416 return ob_get_clean();
2420 * Set up initial recurring payment allowing subsequent IPN payments.
2422 * @param array $recurParams (Optional)
2423 * @param array $contributionParams (Optional)
2425 public function setupRecurringPaymentProcessorTransaction(array $recurParams = [], array $contributionParams = []): void
{
2426 $this->ids
['campaign'][0] = $this->callAPISuccess('Campaign', 'create', ['title' => 'get the money'])['id'];
2427 $contributionParams = array_merge([
2428 'total_amount' => '200',
2429 'invoice_id' => $this->_invoiceID
,
2430 'financial_type_id' => 'Donation',
2431 'contact_id' => $this->_contactID
,
2432 'contribution_page_id' => $this->_contributionPageID
,
2433 'payment_processor_id' => $this->_paymentProcessorID
,
2434 'receive_date' => '2019-07-25 07:34:23',
2435 'skipCleanMoney' => TRUE,
2436 'amount_level' => 'expensive',
2437 'campaign_id' => $this->ids
['campaign'][0],
2438 'source' => 'Online Contribution: Page name',
2439 ], $contributionParams);
2440 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
2441 'contact_id' => $this->_contactID
,
2444 'installments' => 5,
2445 'frequency_unit' => 'Month',
2446 'frequency_interval' => 1,
2447 'invoice_id' => $this->_invoiceID
,
2448 'contribution_status_id' => 2,
2449 'payment_processor_id' => $this->_paymentProcessorID
,
2450 // processor provided ID - use contact ID as proxy.
2451 'processor_id' => $this->_contactID
,
2452 'api.Order.create' => $contributionParams,
2453 ], $recurParams))['values'][0];
2454 $this->_contributionRecurID
= $contributionRecur['id'];
2455 $this->_contributionID
= $contributionRecur['api.Order.create']['id'];
2456 $this->ids
['Contribution'][0] = $this->_contributionID
;
2460 * 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
2462 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2464 * @throws \API_Exception
2466 public function setupMembershipRecurringPaymentProcessorTransaction($params = []): void
{
2467 $membershipParams = $recurParams = [];
2468 if (!empty($params['duration_unit'])) {
2469 $membershipParams['duration_unit'] = $params['duration_unit'];
2471 if (!empty($params['frequency_unit'])) {
2472 $recurParams['frequency_unit'] = $params['frequency_unit'];
2475 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2476 //create a contribution so our membership & contribution don't both have id = 1
2477 if ($this->callAPISuccess('Contribution', 'getcount', []) === 0) {
2478 $this->contributionCreate([
2479 'contact_id' => $this->_contactID
,
2481 'financial_type_id' => 1,
2482 'invoice_id' => 'abcd',
2484 'receive_date' => '2019-07-25 07:34:23',
2488 $this->setupRecurringPaymentProcessorTransaction($recurParams, [
2493 'label' => 'General',
2495 'unit_price' => 200,
2496 'line_total' => 200,
2497 'financial_type_id' => 1,
2498 'membership_type_id' => $this->ids
['membership_type'],
2502 'contact_id' => $this->_contactID
,
2503 'membership_type_id' => $this->ids
['membership_type'],
2504 'source' => 'Payment',
2509 $this->ids
['membership'] = LineItem
::get()
2510 ->addWhere('contribution_id', '=', $this->ids
['Contribution'][0])
2511 ->addWhere('entity_table', '=', 'civicrm_membership')
2512 ->addSelect('entity_id')
2513 ->execute()->first()['entity_id'];
2521 public function CiviUnitTestCase_fatalErrorHandler($message) {
2522 throw new Exception("{$message['message']}: {$message['code']}");
2526 * Wrap the entire test case in a transaction.
2528 * Only subsequent DB statements will be wrapped in TX -- this cannot
2529 * retroactively wrap old DB statements. Therefore, it makes sense to
2530 * call this at the beginning of setUp().
2532 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2533 * this option does not work with, e.g., custom-data.
2535 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2536 * if TRUNCATE or ALTER is called while using a transaction.
2539 * Whether to use nesting or reference-counting.
2541 public function useTransaction($nest = TRUE) {
2543 $this->tx
= new CRM_Core_Transaction($nest);
2544 $this->tx
->rollback();
2549 * Assert the attachment exists.
2551 * @param bool $exists
2552 * @param array $apiResult
2554 protected function assertAttachmentExistence($exists, $apiResult) {
2555 $fileId = $apiResult['id'];
2556 $this->assertTrue(is_numeric($fileId));
2557 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2558 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', [
2559 1 => [$fileId, 'Int'],
2561 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', [
2562 1 => [$fileId, 'Int'],
2567 * Assert 2 sql strings are the same, ignoring double spaces.
2569 * @param string $expectedSQL
2570 * @param string $actualSQL
2571 * @param string $message
2573 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2574 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2575 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2576 $this->assertEquals($expected, $actual, $message);
2580 * Create a price set for an event.
2582 * @param int $feeTotal
2583 * @param int $minAmt
2584 * @param string $type
2586 * @param array $options
2590 * @throws \CRM_Core_Exception
2592 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text', $options = [['name' => 'hundy', 'amount' => 100]]) {
2593 // creating price set, price field
2594 $paramsSet['title'] = 'Price Set';
2595 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2596 $paramsSet['is_active'] = FALSE;
2597 $paramsSet['extends'] = 1;
2598 $paramsSet['min_amount'] = $minAmt;
2600 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2601 $this->_ids
['price_set'] = $priceSet->id
;
2604 'label' => 'Price Field',
2605 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2606 'html_type' => $type,
2607 'price' => $feeTotal,
2608 'option_label' => ['1' => 'Price Field'],
2609 'option_value' => ['1' => $feeTotal],
2610 'option_name' => ['1' => $feeTotal],
2611 'option_weight' => ['1' => 1],
2612 'option_amount' => ['1' => 1],
2613 'is_display_amounts' => 1,
2615 'options_per_line' => 1,
2616 'is_active' => ['1' => 1],
2617 'price_set_id' => $this->_ids
['price_set'],
2618 'is_enter_qty' => 1,
2619 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2621 if ($type === 'Radio') {
2622 foreach ($options as $index => $option) {
2623 $paramsField['is_enter_qty'] = 0;
2624 $optionID = $index +
2;
2625 $paramsField['option_value'][$optionID] = $paramsField['option_weight'][$optionID] = $paramsField['option_amount'][$optionID] = $option['amount'];
2626 $paramsField['option_label'][$optionID] = $paramsField['option_name'][$optionID] = $option['name'];
2630 $this->callAPISuccess('PriceField', 'create', $paramsField);
2631 $fields = $this->callAPISuccess('PriceField', 'get', ['price_set_id' => $this->_ids
['price_set']]);
2632 $this->_ids
['price_field'] = array_keys($fields['values']);
2633 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $this->_ids
['price_field'][0]]);
2634 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2636 return $this->_ids
['price_set'];
2640 * Add a profile to a contribution page.
2642 * @param string $name
2643 * @param int $contributionPageID
2644 * @param string $module
2646 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2648 'uf_group_id' => $name,
2649 'module' => $module,
2650 'entity_table' => 'civicrm_contribution_page',
2651 'entity_id' => $contributionPageID,
2654 if ($module !== 'CiviContribute') {
2655 $params['module_data'] = [$module => []];
2657 $this->callAPISuccess('UFJoin', 'create', $params);
2661 * Add participant with contribution
2665 * @throws \CRM_Core_Exception
2667 protected function createPartiallyPaidParticipantOrder() {
2668 $orderParams = $this->getParticipantOrderParams();
2669 $orderParams['api.Payment.create'] = ['total_amount' => 150];
2670 return $this->callAPISuccess('Order', 'create', $orderParams);
2674 * Create price set that includes one price field with two option values.
2676 * @param string $component
2677 * @param int $componentId
2678 * @param array $priceFieldOptions
2680 * @return array - the result of API3 PriceFieldValue.get for the new PriceField
2682 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = []) {
2683 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2684 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2685 $paramsSet['is_active'] = TRUE;
2686 $paramsSet['financial_type_id'] = 'Event Fee';
2687 $paramsSet['extends'] = 1;
2688 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2690 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSet['id']);
2692 $paramsField = array_merge([
2693 'label' => 'Price Field',
2694 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2695 'html_type' => 'CheckBox',
2696 'option_label' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
2697 'option_value' => ['1' => 100, '2' => 200],
2698 'option_name' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
2699 'option_weight' => ['1' => 1, '2' => 2],
2700 'option_amount' => ['1' => 100, '2' => 200],
2701 'is_display_amounts' => 1,
2703 'options_per_line' => 1,
2704 'is_active' => ['1' => 1, '2' => 1],
2705 'price_set_id' => $priceSet['id'],
2706 'is_enter_qty' => 1,
2707 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2708 ], $priceFieldOptions);
2710 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2711 return $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $priceField->id
]);
2715 * Replace the template with a test-oriented template designed to show all the variables.
2717 * @param string $templateName
2718 * @param string $input
2719 * @param string $type
2721 protected function swapMessageTemplateForInput(string $templateName, string $input, string $type = 'html'): void
{
2722 CRM_Core_DAO
::executeQuery(
2723 "UPDATE civicrm_msg_template
2724 SET msg_{$type} = %1
2725 WHERE workflow_name = '{$templateName}'
2726 AND is_default = 1", [1 => [$input, 'String']]
2731 * Replace the template with a test-oriented template designed to show all the variables.
2733 * @param string $templateName
2734 * @param string $type
2736 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt', $type = 'html'): void
{
2737 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_' . $type . '.tpl');
2738 CRM_Core_DAO
::executeQuery(
2739 "UPDATE civicrm_msg_template
2740 SET msg_{$type} = %1
2741 WHERE workflow_name = '{$templateName}'
2742 AND is_default = 1", [1 => [$testTemplate, 'String']]
2747 * Reinstate the default template.
2749 * @param string $templateName
2750 * @param string $type
2752 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt', $type = 'html') {
2753 CRM_Core_DAO
::executeQuery(
2754 "UPDATE civicrm_option_group og
2755 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2756 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2757 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2758 SET m.msg_{$type} = m2.msg_{$type}
2759 WHERE og.name = 'msg_tpl_workflow_contribution'
2760 AND ov.name = '{$templateName}'
2761 AND m.is_default = 1"
2766 * Flush statics relating to financial type.
2768 protected function flushFinancialTypeStatics() {
2769 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2770 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2772 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2773 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2775 CRM_Contribute_PseudoConstant
::flush('financialType');
2776 CRM_Contribute_PseudoConstant
::flush('membershipType');
2777 // Pseudoconstants may be saved to the cache table.
2778 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2779 CRM_Financial_BAO_FinancialType
::$_statusACLFt = [];
2780 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2784 * Set the permissions to the supplied array.
2786 * @param array $permissions
2788 protected function setPermissions($permissions) {
2789 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2790 $this->flushFinancialTypeStatics();
2794 * @param array $params
2797 public function _checkFinancialRecords($params, $context) {
2799 'entity_id' => $params['id'],
2800 'entity_table' => 'civicrm_contribution',
2802 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
2803 'id' => $params['id'],
2804 'return' => ['total_amount', 'fee_amount', 'net_amount'],
2806 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2807 if ($context === 'pending') {
2808 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2809 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2812 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2814 'id' => $trxn['financial_trxn_id'],
2816 if ($context !== 'online' && $context !== 'payLater') {
2818 'to_financial_account_id' => 6,
2819 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2823 if ($context === 'feeAmount') {
2824 $compareParams['fee_amount'] = 50;
2826 elseif ($context === 'online') {
2828 'to_financial_account_id' => 12,
2829 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2831 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2834 elseif ($context == 'payLater') {
2836 'to_financial_account_id' => 7,
2837 'total_amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2841 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2843 'financial_trxn_id' => $trxn['financial_trxn_id'],
2844 'entity_table' => 'civicrm_financial_item',
2846 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2848 'id' => $entityTrxn['entity_id'],
2851 'amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2853 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2855 if ($context === 'payLater') {
2857 'amount' => (float) CRM_Utils_Array
::value('total_amount', $params, 100.00),
2859 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2862 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2863 if ($context == 'feeAmount') {
2865 'entity_id' => $params['id'],
2866 'entity_table' => 'civicrm_contribution',
2868 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2870 'id' => $maxTrxn['financial_trxn_id'],
2873 'to_financial_account_id' => 5,
2874 'from_financial_account_id' => 6,
2875 'total_amount' => 50,
2878 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2879 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2881 'entity_id' => $trxnId['financialTrxnId'],
2882 'entity_table' => 'civicrm_financial_trxn',
2887 'financial_account_id' => 5,
2889 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2891 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2892 // line should be copied into all the functions that call this function & evaluated there
2893 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2894 // when calling completeTransaction or repeatTransaction.
2895 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2899 * Return financial type id on basis of name
2901 * @param string $name Financial type m/c name
2905 public function getFinancialTypeId($name) {
2906 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2910 * Cleanup function for contents of $this->ids.
2912 * This is a best effort cleanup to use in tear downs etc.
2914 * It will not fail if the data has already been removed (some tests may do
2915 * their own cleanup).
2917 protected function cleanUpSetUpIDs() {
2918 foreach ($this->setupIDs
as $entity => $id) {
2920 civicrm_api3($entity, 'delete', ['id' => $id, 'skip_undelete' => 1]);
2922 catch (CiviCRM_API3_Exception
$e) {
2923 // This is a best-effort cleanup function, ignore.
2929 * Create Financial Type.
2931 * @param array $params
2935 protected function createFinancialType($params = []) {
2936 $params = array_merge($params,
2938 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2942 return $this->callAPISuccess('FinancialType', 'create', $params);
2946 * Create Payment Instrument.
2948 * @param array $params
2949 * @param string $financialAccountName
2953 protected function createPaymentInstrument($params = [], $financialAccountName = 'Donation') {
2954 $params = array_merge([
2955 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2956 'option_group_id' => 'payment_instrument',
2959 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2961 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2963 $financialAccountParams = [
2964 'entity_table' => 'civicrm_option_value',
2965 'entity_id' => $newPaymentInstrument,
2966 'account_relationship' => $relationTypeID,
2967 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2969 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2971 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2975 * Enable Tax and Invoicing
2977 * @param array $params
2979 protected function enableTaxAndInvoicing(array $params = []): void
{
2980 // Enable component contribute setting
2981 $contributeSetting = array_merge($params,
2984 'invoice_prefix' => 'INV_',
2985 'invoice_due_date' => 10,
2986 'invoice_due_date_period' => 'days',
2987 'invoice_notes' => '',
2988 'invoice_is_email_pdf' => 1,
2989 'tax_term' => 'Sales Tax',
2990 'tax_display_settings' => 'Inclusive',
2993 foreach ($contributeSetting as $setting => $value) {
2994 Civi
::settings()->set($setting, $value);
2999 * Enable Tax and Invoicing
3001 protected function disableTaxAndInvoicing(): void
{
3002 $accounts = $this->callAPISuccess('EntityFinancialAccount', 'get', ['account_relationship' => 'Sales Tax Account is'])['values'];
3003 foreach ($accounts as $account) {
3004 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $account['id']]);
3005 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $account['financial_account_id']]);
3008 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3009 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3011 Civi
::settings()->set('invoice_is_email_pdf', FALSE);
3012 Civi
::settings()->set('invoicing', FALSE);
3016 * Add Sales Tax Account for the financial type.
3018 * @param int $financialTypeId
3020 * @param array $accountParams
3022 * @return CRM_Financial_DAO_EntityFinancialAccount
3023 * @throws \CRM_Core_Exception
3025 protected function addTaxAccountToFinancialType(int $financialTypeId, $accountParams = []) {
3026 $params = array_merge([
3027 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3028 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3029 'is_deductible' => 1,
3034 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3036 'entity_table' => 'civicrm_financial_type',
3037 'entity_id' => $financialTypeId,
3038 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3041 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3042 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = $params['tax_rate'];
3044 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3045 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3046 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3047 $dao->copyValues($entityParams);
3049 if ($dao->fetch()) {
3050 $entityParams['id'] = $dao->id
;
3052 $entityParams['financial_account_id'] = $account->id
;
3054 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3058 * Create price set with contribution test for test setup.
3060 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3061 * on parent class at some point (fn is not in 4.4).
3064 * @param array $params
3066 public function createPriceSetWithPage($entity = NULL, $params = []) {
3067 $membershipTypeID = $this->membershipTypeCreate(['name' => 'Special']);
3068 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', [
3069 'title' => 'Test Contribution Page',
3070 'financial_type_id' => 1,
3071 'currency' => 'NZD',
3072 'goal_amount' => 50,
3073 'is_pay_later' => 1,
3074 'is_monetary' => TRUE,
3075 'is_email_receipt' => FALSE,
3077 $priceSet = $this->callAPISuccess('price_set', 'create', [
3078 'is_quick_config' => 0,
3079 'extends' => 'CiviMember',
3080 'financial_type_id' => 1,
3081 'title' => 'my Page',
3083 $priceSetID = $priceSet['id'];
3085 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3086 $priceField = $this->callAPISuccess('price_field', 'create', [
3087 'price_set_id' => $priceSetID,
3088 'label' => 'Goat Breed',
3089 'html_type' => 'Radio',
3091 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3092 'price_set_id' => $priceSetID,
3093 'price_field_id' => $priceField['id'],
3094 'label' => 'Long Haired Goat',
3096 'financial_type_id' => 'Donation',
3097 'membership_type_id' => $membershipTypeID,
3098 'membership_num_terms' => 1,
3100 $this->_ids
['price_field_value'] = [$priceFieldValue['id']];
3101 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3102 'price_set_id' => $priceSetID,
3103 'price_field_id' => $priceField['id'],
3104 'label' => 'Shoe-eating Goat',
3106 'financial_type_id' => 'Donation',
3107 'membership_type_id' => $membershipTypeID,
3108 'membership_num_terms' => 2,
3110 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3112 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
3113 'price_set_id' => $priceSetID,
3114 'price_field_id' => $priceField['id'],
3115 'label' => 'Shoe-eating Goat',
3117 'financial_type_id' => 'Donation',
3119 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3121 $this->_ids
['price_set'] = $priceSetID;
3122 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3123 $this->_ids
['price_field'] = [$priceField['id']];
3125 $this->_ids
['membership_type'] = $membershipTypeID;
3129 * Only specified contact returned.
3131 * @implements CRM_Utils_Hook::aclWhereClause
3135 * @param $whereTables
3139 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3140 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3144 * @implements CRM_Utils_Hook::selectWhereClause
3146 * @param string $entity
3147 * @param array $clauses
3149 public function selectWhereClauseHook($entity, &$clauses) {
3150 if ($entity == 'Event') {
3151 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3156 * An implementation of hook_civicrm_post used with all our test cases.
3159 * @param string $objectName
3160 * @param int $objectId
3163 public function onPost($op, $objectName, $objectId, &$objectRef) {
3164 if ($op == 'create' && $objectName == 'Individual') {
3165 CRM_Core_DAO
::executeQuery(
3166 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3168 1 => [$objectId, 'Integer'],
3173 if ($op == 'edit' && $objectName == 'Participant') {
3175 1 => [$objectId, 'Integer'],
3177 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3178 CRM_Core_DAO
::executeQuery($query, $params);
3183 * Instantiate form object.
3185 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3187 * @param string $class
3188 * Name of form class.
3190 * @param array $formValues
3192 * @param string $pageName
3194 * @param array $searchFormValues
3195 * Values for the search form if the form is a task eg.
3196 * for selected ids 6 & 8:
3198 * 'radio_ts' => 'ts_sel',
3199 * 'task' => CRM_Member_Task::PDF_LETTER,
3204 * @return \CRM_Core_Form
3206 public function getFormObject($class, $formValues = [], $pageName = '', $searchFormValues = []) {
3207 $_POST = $formValues;
3208 /* @var CRM_Core_Form $form */
3209 $form = new $class();
3210 $_SERVER['REQUEST_METHOD'] = 'GET';
3212 case 'CRM_Event_Cart_Form_Checkout_Payment':
3213 case 'CRM_Event_Cart_Form_Checkout_ParticipantsAndPrices':
3214 $form->controller
= new CRM_Event_Cart_Controller_Checkout();
3217 case strpos($class, '_Form_') !== FALSE:
3218 $form->controller
= new CRM_Core_Controller_Simple($class, $pageName);
3222 $form->controller
= new CRM_Core_Controller();
3225 $pageName = $form->getName();
3227 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3228 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3229 if ($searchFormValues) {
3230 $_SESSION['_' . $form->controller
->_name
. '_container']['values']['Search'] = $searchFormValues;
3232 if (isset($formValues['_qf_button_name'])) {
3233 $_SESSION['_' . $form->controller
->_name
. '_container']['_qf_button_name'] = $formValues['_qf_button_name'];
3239 * Get possible thousand separators.
3243 public function getThousandSeparators() {
3244 return [['.'], [',']];
3248 * Get the boolean options as a provider.
3252 public function getBooleanDataProvider() {
3253 return [[TRUE], [FALSE]];
3257 * Set the separators for thousands and decimal points.
3259 * Note that this only covers some common scenarios.
3261 * It does not cater for a situation where the thousand separator is a [space]
3262 * Latter is the Norwegian localization. At least some tests need to
3263 * use setMonetaryDecimalPoint and setMonetaryThousandSeparator directly
3264 * to provide broader coverage.
3266 * @param string $thousandSeparator
3268 protected function setCurrencySeparators($thousandSeparator) {
3269 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3270 Civi
::settings()->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3274 * Sets the thousand separator.
3276 * If you use this function also set the decimal separator: setMonetaryDecimalSeparator
3278 * @param $thousandSeparator
3280 protected function setMonetaryThousandSeparator($thousandSeparator) {
3281 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3285 * Sets the decimal separator.
3287 * If you use this function also set the thousand separator setMonetaryDecimalPoint
3289 * @param $decimalPoint
3291 protected function setMonetaryDecimalPoint($decimalPoint) {
3292 Civi
::settings()->set('monetaryDecimalPoint', $decimalPoint);
3296 * Sets the default currency.
3300 protected function setDefaultCurrency($currency) {
3301 Civi
::settings()->set('defaultCurrency', $currency);
3305 * Format money as it would be input.
3307 * @param string $amount
3311 protected function formatMoneyInput($amount) {
3312 return CRM_Utils_Money
::format($amount, NULL, '%a');
3316 * Get the contribution object.
3318 * @param int $contributionID
3320 * @return \CRM_Contribute_BAO_Contribution
3322 protected function getContributionObject($contributionID) {
3323 $contributionObj = new CRM_Contribute_BAO_Contribution();
3324 $contributionObj->id
= $contributionID;
3325 $contributionObj->find(TRUE);
3326 return $contributionObj;
3330 * Enable multilingual.
3332 public function enableMultilingual() {
3333 $this->callAPISuccess('Setting', 'create', [
3334 'lcMessages' => 'en_US',
3335 'languageLimit' => [
3340 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3343 $dbLocale = '_en_US';
3347 * Setup or clean up SMS tests
3349 * @param bool $teardown
3351 * @throws \CiviCRM_API3_Exception
3353 public function setupForSmsTests($teardown = FALSE) {
3354 require_once 'CiviTest/CiviTestSMSProvider.php';
3356 // Option value params for CiviTestSMSProvider
3357 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3359 'option_group_id' => $groupID,
3360 'label' => 'unittestSMS',
3361 'value' => 'unit.test.sms',
3362 'name' => 'CiviTestSMSProvider',
3369 // Test completed, delete provider
3370 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3371 civicrm_api3('option_value', 'delete', ['id' => $providerOptionValueResult['id']]);
3375 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3376 // in CRM/Sms/Provider.php even though it is not an extension.
3377 return civicrm_api3('option_value', 'create', $params);
3381 * Start capturing browser output.
3383 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3385 protected function startCapturingOutput() {
3387 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3391 * Stop capturing browser output and return as a csv.
3393 * @param bool $isFirstRowHeaders
3395 * @return \League\Csv\Reader
3397 * @throws \League\Csv\Exception
3399 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3400 $output = ob_get_flush();
3401 $stream = fopen('php://memory', 'r+');
3402 fwrite($stream, $output);
3404 $this->assertEquals("\xEF\xBB\xBF", substr($output, 0, 3));
3405 $csv = Reader
::createFromString($output);
3406 if ($isFirstRowHeaders) {
3407 $csv->setHeaderOffset(0);
3414 * Rename various labels to not match the names.
3416 * Doing these mimics the fact the name != the label in international installs & triggers failures in
3417 * code that expects it to.
3419 protected function renameLabels() {
3420 $replacements = ['Pending', 'Refunded'];
3421 foreach ($replacements as $name) {
3422 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = '{$name} Label**' where label = '{$name}' AND name = '{$name}'");
3427 * Undo any label renaming.
3429 protected function resetLabels() {
3430 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = REPLACE(name, ' Label**', '') WHERE label LIKE '% Label**'");
3434 * Get parameters to set up a multi-line participant order.
3437 * @throws \CRM_Core_Exception
3439 protected function getParticipantOrderParams(): array {
3440 $event = $this->eventCreate();
3441 $this->_eventId
= $event['id'];
3443 'id' => $this->_eventId
,
3444 'financial_type_id' => 4,
3447 $this->callAPISuccess('event', 'create', $eventParams);
3448 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3450 'total_amount' => 300,
3451 'currency' => 'USD',
3452 'contact_id' => $this->individualCreate(),
3453 'financial_type_id' => 4,
3454 'contribution_status_id' => 'Pending',
3456 foreach ($priceFields['values'] as $key => $priceField) {
3457 $orderParams['line_items'][] = [
3460 'price_field_id' => $priceField['price_field_id'],
3461 'price_field_value_id' => $priceField['id'],
3462 'label' => $priceField['label'],
3463 'field_title' => $priceField['label'],
3465 'unit_price' => $priceField['amount'],
3466 'line_total' => $priceField['amount'],
3467 'financial_type_id' => $priceField['financial_type_id'],
3468 'entity_table' => 'civicrm_participant',
3472 'financial_type_id' => 4,
3473 'event_id' => $this->_eventId
,
3476 'fee_currency' => 'USD',
3477 'contact_id' => $this->individualCreate(),
3481 return $orderParams;
3487 * @throws \CRM_Core_Exception
3489 protected function validatePayments($payments): void
{
3490 foreach ($payments as $payment) {
3491 $balance = CRM_Contribute_BAO_Contribution
::getContributionBalance($payment['contribution_id']);
3492 if ($balance < 0 && $balance +
$payment['total_amount'] === 0.0) {
3493 // This is an overpayment situation. there are no financial items to allocate the overpayment.
3494 // This is a pretty rough way at guessing which payment is the overpayment - but
3495 // for the test suite it should be enough.
3498 $items = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
3499 'financial_trxn_id' => $payment['id'],
3500 'entity_table' => 'civicrm_financial_item',
3501 'return' => ['amount'],
3504 foreach ($items as $item) {
3505 $itemTotal +
= $item['amount'];
3507 $this->assertEquals($payment['total_amount'], $itemTotal);
3512 * Validate all created payments.
3514 * @throws \CRM_Core_Exception
3516 protected function validateAllPayments(): void
{
3517 $payments = $this->callAPISuccess('Payment', 'get', [
3518 'return' => ['total_amount', 'tax_amount'],
3519 'options' => ['limit' => 0],
3521 $this->validatePayments($payments);
3525 * Validate all created contributions.
3527 * @throws \API_Exception
3529 protected function validateAllContributions(): void
{
3530 $contributions = Contribution
::get(FALSE)->setSelect(['total_amount', 'tax_amount'])->execute();
3531 foreach ($contributions as $contribution) {
3532 $lineItems = $this->callAPISuccess('LineItem', 'get', [
3533 'contribution_id' => $contribution['id'],
3534 'return' => ['tax_amount', 'line_total', 'entity_table', 'entity_id', 'qty'],
3540 foreach ($lineItems as $lineItem) {
3541 $total +
= $lineItem['line_total'];
3542 $taxTotal +
= (float) ($lineItem['tax_amount'] ??
0);
3543 if ($lineItem['entity_table'] === 'civicrm_membership') {
3544 $memberships[] = $lineItem['entity_id'];
3546 if ($lineItem['entity_table'] === 'civicrm_participant' && $lineItem['qty'] > 0) {
3547 $participants[$lineItem['entity_id']] = $lineItem['entity_id'];
3550 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', ['contribution_id' => $contribution['id'], 'return' => 'membership_id'])['values'];
3551 $participantPayments = $this->callAPISuccess('ParticipantPayment', 'get', ['contribution_id' => $contribution['id'], 'return' => 'participant_id'])['values'];
3552 $this->assertCount(count($memberships), $membershipPayments);
3553 $this->assertCount(count($participants), $participantPayments);
3554 foreach ($membershipPayments as $payment) {
3555 $this->assertContains($payment['membership_id'], $memberships);
3557 foreach ($participantPayments as $payment) {
3558 $this->assertContains($payment['participant_id'], $participants);
3560 $this->assertEquals($taxTotal, (float) ($contribution['tax_amount'] ??
0));
3561 $this->assertEquals($total +
$taxTotal, $contribution['total_amount']);
3568 protected function createRuleGroup() {
3569 return $this->callAPISuccess('RuleGroup', 'create', [
3570 'contact_type' => 'Individual',
3572 'used' => 'General',
3573 'name' => 'TestRule',
3574 'title' => 'TestRule',
3580 * Generic create test.
3582 * @param int $version
3584 * @throws \CRM_Core_Exception
3586 protected function basicCreateTest(int $version): void
{
3587 $this->_apiversion
= $version;
3588 $result = $this->callAPIAndDocument($this->_entity
, 'create', $this->params
, __FUNCTION__
, __FILE__
);
3589 $this->assertEquals(1, $result['count']);
3590 $this->assertNotNull($result['values'][$result['id']]['id']);
3591 $this->getAndCheck($this->params
, $result['id'], $this->_entity
);
3595 * Generic delete test.
3597 * @param int $version
3599 * @throws \CRM_Core_Exception
3601 protected function basicDeleteTest(int $version): void
{
3602 $this->_apiversion
= $version;
3603 $result = $this->callAPISuccess($this->_entity
, 'create', $this->params
);
3604 $deleteParams = ['id' => $result['id']];
3605 $this->callAPIAndDocument($this->_entity
, 'delete', $deleteParams, __FUNCTION__
, __FILE__
);
3606 $checkDeleted = $this->callAPISuccess($this->_entity
, 'get', []);
3607 $this->assertEquals(0, $checkDeleted['count']);
3611 * Create and return a case object for the given Client ID.
3613 * @param int $clientId
3614 * @param int $loggedInUser
3615 * Omit or pass NULL to use the same as clientId
3616 * @param array $extra
3617 * Optional specific parameters such as start_date
3619 * @return CRM_Case_BAO_Case
3621 public function createCase($clientId, $loggedInUser = NULL, $extra = []) {
3622 if (empty($loggedInUser)) {
3623 // backwards compatibility - but it's more typical that the creator is a different person than the client
3624 $loggedInUser = $clientId;
3626 $caseParams = array_merge([
3627 'activity_subject' => 'Case Subject',
3628 'client_id' => $clientId,
3629 'case_type_id' => 1,
3631 'case_type' => 'housing_support',
3632 'subject' => 'Case Subject',
3633 'start_date' => date('Y-m-d'),
3634 'start_date_time' => date('YmdHis'),
3636 'activity_details' => '',
3638 $form = new CRM_Case_Form_Case();
3639 return $form->testSubmit($caseParams, 'OpenCase', $loggedInUser, 'standalone');
3643 * Validate that all location entities have exactly one primary.
3645 * This query takes about 2 minutes on a DB with 10s of millions of contacts.
3647 public function assertLocationValidity(): void
{
3648 $this->assertEquals(0, CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM
3650 (SELECT a1.contact_id
3651 FROM civicrm_address a1
3652 LEFT JOIN civicrm_address a2 ON a1.id <> a2.id AND a2.is_primary = 1
3653 AND a1.contact_id = a2.contact_id
3656 AND a2.id IS NOT NULL
3657 AND a1.contact_id IS NOT NULL
3659 SELECT a1.contact_id
3660 FROM civicrm_address a1
3661 LEFT JOIN civicrm_address a2 ON a1.id <> a2.id AND a2.is_primary = 1
3662 AND a1.contact_id = a2.contact_id
3663 WHERE a1.is_primary = 0
3665 AND a1.contact_id IS NOT NULL
3669 SELECT a1.contact_id
3670 FROM civicrm_email a1
3671 LEFT JOIN civicrm_email a2 ON a1.id <> a2.id AND a2.is_primary = 1
3672 AND a1.contact_id = a2.contact_id
3675 AND a2.id IS NOT NULL
3676 AND a1.contact_id IS NOT NULL
3678 SELECT a1.contact_id
3679 FROM civicrm_email a1
3680 LEFT JOIN civicrm_email a2 ON a1.id <> a2.id AND a2.is_primary = 1
3681 AND a1.contact_id = a2.contact_id
3682 WHERE a1.is_primary = 0
3684 AND a1.contact_id IS NOT NULL
3688 SELECT a1.contact_id
3689 FROM civicrm_phone a1
3690 LEFT JOIN civicrm_phone a2 ON a1.id <> a2.id AND a2.is_primary = 1
3691 AND a1.contact_id = a2.contact_id
3694 AND a2.id IS NOT NULL
3695 AND a1.contact_id IS NOT NULL
3697 SELECT a1.contact_id
3698 FROM civicrm_phone a1
3699 LEFT JOIN civicrm_phone a2 ON a1.id <> a2.id AND a2.is_primary = 1
3700 AND a1.contact_id = a2.contact_id
3701 WHERE a1.is_primary = 0
3703 AND a1.contact_id IS NOT NULL
3707 SELECT a1.contact_id
3709 LEFT JOIN civicrm_im a2 ON a1.id <> a2.id AND a2.is_primary = 1
3710 AND a1.contact_id = a2.contact_id
3713 AND a2.id IS NOT NULL
3714 AND a1.contact_id IS NOT NULL
3716 SELECT a1.contact_id
3718 LEFT JOIN civicrm_im a2 ON a1.id <> a2.id AND a2.is_primary = 1
3719 AND a1.contact_id = a2.contact_id
3720 WHERE a1.is_primary = 0
3722 AND a1.contact_id IS NOT NULL
3726 SELECT a1.contact_id
3727 FROM civicrm_openid a1
3728 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3729 AND a1.contact_id = a2.contact_id
3730 WHERE (a1.is_primary = 1 AND a2.id IS NOT NULL)
3733 SELECT a1.contact_id
3734 FROM civicrm_openid a1
3735 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3736 AND a1.contact_id = a2.contact_id
3739 AND a2.id IS NOT NULL
3740 AND a1.contact_id IS NOT NULL
3742 SELECT a1.contact_id
3743 FROM civicrm_openid a1
3744 LEFT JOIN civicrm_openid a2 ON a1.id <> a2.id AND a2.is_primary = 1
3745 AND a1.contact_id = a2.contact_id
3746 WHERE a1.is_primary = 0
3748 AND a1.contact_id IS NOT NULL) as primary_descrepancies
3753 * Ensure the specified mysql mode/s are activated.
3755 * @param array $modes
3757 protected function ensureMySQLMode(array $modes): void
{
3758 $currentModes = array_fill_keys(CRM_Utils_SQL
::getSqlModes(), 1);
3759 $currentModes = array_merge($currentModes, array_fill_keys($modes, 1));
3760 CRM_Core_DAO
::executeQuery("SET GLOBAL sql_mode = '" . implode(',', array_keys($currentModes)) . "'");
3761 CRM_Core_DAO
::executeQuery("SET sql_mode = '" . implode(',', array_keys($currentModes)) . "'");
3765 * Delete any extraneous relationship types.
3767 * @throws \API_Exception
3768 * @throws \Civi\API\Exception\UnauthorizedException
3770 protected function deleteNonDefaultRelationshipTypes(): void
{
3771 RelationshipType
::delete(FALSE)->addWhere('name_a_b', 'NOT IN', [
3778 'Head of Household for',
3779 'Household Member of',
3780 'Case Coordinator is',
3786 * Delete any existing custom data groups.
3788 protected function cleanupCustomGroups(): void
{
3790 CustomField
::get(FALSE)->setSelect(['option_group_id', 'custom_group_id'])
3791 ->addChain('delete_options', OptionGroup
::delete()
3792 ->addWhere('id', '=', '$option_group_id')
3794 ->addChain('delete_fields', CustomField
::delete()
3795 ->addWhere('id', '=', '$id')
3798 CustomGroup
::delete(FALSE)->addWhere('id', '>', 0)->execute();
3800 catch (API_Exception
$e) {
3801 $this->fail('failed to cleanup custom groups ' . $e->getMessage());
3806 * Ensure the default price set & field exist for memberships.
3808 protected function ensureMembershipPriceSetExists(): void
{
3809 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_price_set (`id`, `name`, `title`, `extends`)
3810 VALUES (2, 'default_membership_type_amount', 'Membership Amount', 3)
3811 ON DUPLICATE KEY UPDATE `name` = 'default_membership_type_amount', title = 'Membership Amount';
3813 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_price_field
3814 (`id`, `name`, `price_set_id`, `label`, `html_type`)
3815 VALUES (2, 1, 2, 'Membership Amount', 'Radio')
3816 ON DUPLICATE KEY UPDATE `name` = '1', price_set_id = 1, label = 'Membership Amount', html_type = 'Radio'
3821 * Add an address block to the current domain.
3823 * @noinspection PhpUnhandledExceptionInspection
3825 protected function addLocationBlockToDomain(): void
{
3826 $contactID = CRM_Core_BAO_Domain
::getDomain()->contact_id
;
3828 ->setValues(['phone' => 123, 'contact_id' => $contactID])
3831 Address
::create()->setValues([
3832 'street_address' => '10 Downing Street',
3834 'contact_id' => $contactID,
3835 ])->execute()->first();