3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
30 use League\Csv\Reader
;
33 * Include class definitions
35 require_once 'api/api.php';
36 define('API_LATEST_VERSION', 3);
39 * Base class for CiviCRM unit tests
41 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
42 * may opt for one or neither:
44 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
45 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
46 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
47 * 2. useTransaction() executes the test inside a transaction. It's easier to use
48 * (because you don't need to identify specific tables), but it doesn't work for tests
49 * which manipulate schema or truncate data -- and could behave inconsistently
50 * for tests which specifically examine DB transactions.
52 * Common functions for unit tests
55 class CiviUnitTestCase
extends PHPUnit\Framework\TestCase
{
57 use \Civi\Test\Api3DocTrait
;
58 use \Civi\Test\GenericAssertionsTrait
;
59 use \Civi\Test\DbTestTrait
;
60 use \Civi\Test\ContactTestTrait
;
61 use \Civi\Test\MailingTestTrait
;
64 * Database has been initialized.
68 private static $dbInit = FALSE;
71 * Database connection.
73 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
82 static protected $_dbName;
85 * Track tables we have modified during a test.
88 protected $_tablesToTruncate = array();
91 * @var array of temporary directory names
96 * @var bool populateOnce allows to skip db resets in setUp
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
106 public static $populateOnce = FALSE;
109 * @var bool DBResetRequired allows skipping DB reset
110 * in specific test case. If you still need
111 * to reset single test (method) of such case, call
112 * $this->cleanDB() in the first line of this
115 public $DBResetRequired = TRUE;
118 * @var CRM_Core_Transaction|NULL
123 * Array of IDs created to support the test.
126 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
133 * Class used for hooks during tests.
135 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
137 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
139 * @var CRM_Utils_Hook_UnitTests hookClass
141 public $hookClass = NULL;
144 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
146 protected $_params = array();
149 * @var CRM_Extension_System
151 protected $origExtensionSystem;
154 * Array of IDs created during test setup routine.
156 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
160 public $setupIDs = array();
163 * PHPUnit Mock Method to use.
167 public $mockMethod = 'getMock';
172 * Because we are overriding the parent class constructor, we
173 * need to show the same arguments as exist in the constructor of
174 * PHPUnit_Framework_TestCase, since
175 * PHPUnit_Framework_TestSuite::createTest() creates a
176 * ReflectionClass of the Test class and checks the constructor
177 * of that class to decide how to set up the test.
179 * @param string $name
181 * @param string $dataName
183 public function __construct($name = NULL, array $data = array(), $dataName = '') {
184 parent
::__construct($name, $data, $dataName);
186 // we need full error reporting
187 error_reporting(E_ALL
& ~E_NOTICE
);
189 self
::$_dbName = self
::getDBName();
191 // also load the class loader
192 require_once 'CRM/Core/ClassLoader.php';
193 CRM_Core_ClassLoader
::singleton()->register();
194 if (function_exists('_civix_phpunit_setUp')) {
195 // FIXME: loosen coupling
196 _civix_phpunit_setUp();
198 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version
::id(), '5', '>=')) {
199 $this->mockMethod
= 'createMock';
201 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version
::id(), '6', '>=')) {
202 $this->mockMethod
= 'createMock';
207 * Override to run the test and assert its state.
210 * @throws \PHPUnit_Framework_IncompleteTest
211 * @throws \PHPUnit_Framework_SkippedTest
213 protected function runTest() {
215 return parent
::runTest();
217 catch (PEAR_Exception
$e) {
218 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
219 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
226 public function requireDBReset() {
227 return $this->DBResetRequired
;
233 public static function getDBName() {
234 static $dbName = NULL;
235 if ($dbName === NULL) {
236 require_once "DB.php";
237 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
238 $dbName = $dsninfo['database'];
244 * Create database connection for this instance.
246 * Initialize the test database if it hasn't been initialized
249 protected function getConnection() {
250 if (!self
::$dbInit) {
251 $dbName = self
::getDBName();
253 // install test database
254 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
256 static::_populateDB(FALSE, $this);
258 self
::$dbInit = TRUE;
264 * Required implementation of abstract method.
266 protected function getDataSet() {
270 * @param bool $perClass
271 * @param null $object
273 * TRUE if the populate logic runs; FALSE if it is skipped
275 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
276 if (CIVICRM_UF
!== 'UnitTests') {
277 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
280 if ($perClass ||
$object == NULL) {
284 $dbreset = $object->requireDBReset();
287 if (self
::$populateOnce ||
!$dbreset) {
290 self
::$populateOnce = NULL;
292 Civi\Test
::data()->populate();
297 public static function setUpBeforeClass() {
298 static::_populateDB(TRUE);
300 // also set this global hack
301 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
305 * Common setup functions for all unit tests.
307 protected function setUp() {
308 $session = CRM_Core_Session
::singleton();
309 $session->set('userID', NULL);
311 $this->_apiversion
= 3;
314 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
315 // Use a temporary file for STDIN
316 $GLOBALS['stdin'] = tmpfile();
317 if ($GLOBALS['stdin'] === FALSE) {
318 echo "Couldn't open temporary file\n";
322 // Get and save a connection to the database
323 $this->_dbconn
= $this->getConnection();
325 // reload database before each test
326 // $this->_populateDB();
328 // "initialize" CiviCRM to avoid problems when running single tests
329 // FIXME: look at it closer in second stage
331 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
332 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
334 // disable any left-over test extensions
335 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
337 // reset all the caches
338 CRM_Utils_System
::flushCache();
340 // initialize the object once db is loaded
341 \Civi
::$statics = array();
343 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
345 // when running unit tests, use mockup user framework
346 $this->hookClass
= CRM_Utils_Hook
::singleton();
348 // Make sure the DB connection is setup properly
349 $config->userSystem
->setMySQLTimeZone();
350 $env = new CRM_Utils_Check_Component_Env();
351 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
353 // clear permissions stub to not check permissions
354 $config->userPermissionClass
->permissions
= NULL;
356 //flush component settings
357 CRM_Core_Component
::getEnabledComponents(TRUE);
359 $_REQUEST = $_GET = $_POST = [];
360 error_reporting(E_ALL
);
362 $this->renameLabels();
363 $this->_sethtmlGlobals();
367 * Read everything from the datasets directory and insert into the db.
369 public function loadAllFixtures() {
370 $fixturesDir = __DIR__
. '/../../fixtures';
372 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
374 $jsonFiles = glob($fixturesDir . '/*.json');
375 foreach ($jsonFiles as $jsonFixture) {
376 $json = json_decode(file_get_contents($jsonFixture));
377 foreach ($json as $tableName => $vars) {
378 if ($tableName === 'civicrm_contact') {
379 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');
382 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
384 foreach ($vars as $entity) {
385 $keys = $values = [];
386 foreach ($entity as $key => $value) {
388 $values[] = is_numeric($value) ?
$value : "'{$value}'";
390 CRM_Core_DAO
::executeQuery("
391 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
398 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
402 * Load the data that used to be handled by the discontinued dbunit class.
404 * This could do with further tidy up - the initial priority is simply to get rid of
405 * the dbunity package which is no longer supported.
407 * @param string $fileName
409 protected function loadXMLDataSet($fileName) {
410 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
411 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
412 foreach ($xml as $tableName => $element) {
413 if (!empty($element)) {
414 foreach ($element as $row) {
415 $keys = $values = [];
416 if (isset($row['@attributes'])) {
417 foreach ($row['@attributes'] as $key => $value) {
419 $values[] = is_numeric($value) ?
$value : "'{$value}'";
422 elseif (!empty($row)) {
423 // cos we copied it & it is inconsistent....
424 foreach ($row as $key => $value) {
426 $values[] = is_numeric($value) ?
$value : "'{$value}'";
430 if (!empty($values)) {
431 CRM_Core_DAO
::executeQuery("
432 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
438 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
442 * Create default domain contacts for the two domains added during test class.
443 * database population.
445 public function createDomainContacts() {
446 $this->organizationCreate();
447 $this->organizationCreate(array('organization_name' => 'Second Domain'));
451 * Common teardown functions for all unit tests.
453 protected function tearDown() {
454 $this->_apiversion
= 3;
455 $this->resetLabels();
457 error_reporting(E_ALL
& ~E_NOTICE
);
458 CRM_Utils_Hook
::singleton()->reset();
459 if ($this->hookClass
) {
460 $this->hookClass
->reset();
462 CRM_Core_Session
::singleton()->reset(1);
465 $this->tx
->rollback()->commit();
468 CRM_Core_Transaction
::forceRollbackIfEnabled();
469 \Civi\Core\Transaction\Manager
::singleton(TRUE);
472 CRM_Core_Transaction
::forceRollbackIfEnabled();
473 \Civi\Core\Transaction\Manager
::singleton(TRUE);
475 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
476 $this->quickCleanup($tablesToTruncate);
477 $this->createDomainContacts();
480 $this->cleanTempDirs();
481 $this->unsetExtensionSystem();
482 $this->assertEquals([], CRM_Core_DAO
::$_nullArray);
483 $this->assertEquals(NULL, CRM_Core_DAO
::$_nullObject);
487 * Create a batch of external API calls which can
488 * be executed concurrently.
491 * $calls = $this->createExternalAPI()
492 * ->addCall('Contact', 'get', ...)
493 * ->addCall('Contact', 'get', ...)
499 * @return \Civi\API\ExternalBatch
500 * @throws PHPUnit_Framework_SkippedTestError
502 public function createExternalAPI() {
503 global $civicrm_root;
504 $defaultParams = array(
505 'version' => $this->_apiversion
,
509 $calls = new \Civi\API\
ExternalBatch($defaultParams);
511 if (!$calls->isSupported()) {
512 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
519 * Create required data based on $this->entity & $this->params
520 * This is just a way to set up the test data for delete & get functions
521 * so the distinction between set
522 * up & tested functions is clearer
527 public function createTestEntity() {
528 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
532 * @param int $contactTypeId
536 public function contactTypeDelete($contactTypeId) {
537 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
539 throw new Exception('Could not delete contact type');
544 * @param array $params
548 public function membershipTypeCreate($params = array()) {
549 CRM_Member_PseudoConstant
::flush('membershipType');
550 CRM_Core_Config
::clearDBCache();
551 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
552 $params = array_merge(array(
554 'duration_unit' => 'year',
555 'duration_interval' => 1,
556 'period_type' => 'rolling',
557 'member_of_contact_id' => $memberOfOrganization,
559 'financial_type_id' => 2,
562 'visibility' => 'Public',
565 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
567 CRM_Member_PseudoConstant
::flush('membershipType');
568 CRM_Utils_Cache
::singleton()->flush();
570 return $result['id'];
574 * @param array $params
578 public function contactMembershipCreate($params) {
579 $params = array_merge(array(
580 'join_date' => '2007-01-21',
581 'start_date' => '2007-01-21',
582 'end_date' => '2007-12-21',
583 'source' => 'Payment',
584 'membership_type_id' => 'General',
586 if (!is_numeric($params['membership_type_id'])) {
587 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
588 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
589 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
593 $result = $this->callAPISuccess('Membership', 'create', $params);
594 return $result['id'];
598 * Delete Membership Type.
600 * @param array $params
602 public function membershipTypeDelete($params) {
603 $this->callAPISuccess('MembershipType', 'Delete', $params);
607 * @param int $membershipID
609 public function membershipDelete($membershipID) {
610 $deleteParams = array('id' => $membershipID);
611 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
615 * @param string $name
619 public function membershipStatusCreate($name = 'test member status') {
620 $params['name'] = $name;
621 $params['start_event'] = 'start_date';
622 $params['end_event'] = 'end_date';
623 $params['is_current_member'] = 1;
624 $params['is_active'] = 1;
626 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
627 CRM_Member_PseudoConstant
::flush('membershipStatus');
628 return $result['id'];
632 * @param int $membershipStatusID
634 public function membershipStatusDelete($membershipStatusID) {
635 if (!$membershipStatusID) {
638 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
641 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
642 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
643 $renewedMembershipEndDate = new DateTime($membershipEndDate);
644 switch ($durationUnit) {
646 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
650 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
651 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
652 $renewedMembershipEndDate->add(new DateInterval('P1D'));
653 $renewedMembershipEndDate->add(new DateInterval('P1M'));
654 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
657 return $renewedMembershipEndDate->format('Y-m-d');
661 * @param array $params
665 public function relationshipTypeCreate($params = array()) {
666 $params = array_merge(array(
667 'name_a_b' => 'Relation 1 for relationship type create',
668 'name_b_a' => 'Relation 2 for relationship type create',
669 'contact_type_a' => 'Individual',
670 'contact_type_b' => 'Organization',
675 $result = $this->callAPISuccess('relationship_type', 'create', $params);
676 CRM_Core_PseudoConstant
::flush('relationshipType');
678 return $result['id'];
682 * Delete Relatinship Type.
684 * @param int $relationshipTypeID
686 public function relationshipTypeDelete($relationshipTypeID) {
687 $params['id'] = $relationshipTypeID;
688 $check = $this->callAPISuccess('relationship_type', 'get', $params);
689 if (!empty($check['count'])) {
690 $this->callAPISuccess('relationship_type', 'delete', $params);
695 * @param array $params
699 public function paymentProcessorTypeCreate($params = NULL) {
700 if (is_null($params)) {
702 'name' => 'API_Test_PP',
703 'title' => 'API Test Payment Processor',
704 'class_name' => 'CRM_Core_Payment_APITest',
705 'billing_mode' => 'form',
711 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
713 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
715 return $result['id'];
719 * Create test Authorize.net instance.
721 * @param array $params
725 public function paymentProcessorAuthorizeNetCreate($params = array()) {
726 $params = array_merge(array(
727 'name' => 'Authorize',
728 'domain_id' => CRM_Core_Config
::domainID(),
729 'payment_processor_type_id' => 'AuthNet',
730 'title' => 'AuthNet',
735 'user_name' => '4y5BfuW7jm',
736 'password' => '4cAmW927n8uLf5J8',
737 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
738 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
739 'class_name' => 'Payment_AuthorizeNet',
743 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
744 return $result['id'];
748 * Create Participant.
750 * @param array $params
751 * Array of contact id and event id values.
754 * $id of participant created
756 public function participantCreate($params = []) {
757 if (empty($params['contact_id'])) {
758 $params['contact_id'] = $this->individualCreate();
760 if (empty($params['event_id'])) {
761 $event = $this->eventCreate();
762 $params['event_id'] = $event['id'];
767 'register_date' => 20070219,
768 'source' => 'Wimbeldon',
769 'event_level' => 'Payment',
773 $params = array_merge($defaults, $params);
774 $result = $this->callAPISuccess('Participant', 'create', $params);
775 return $result['id'];
779 * Create Payment Processor.
782 * Id Payment Processor
784 public function processorCreate($params = array()) {
785 $processorParams = array(
788 'payment_processor_type_id' => 'Dummy',
789 'financial_account_id' => 12,
793 'url_site' => 'http://dummy.com',
794 'url_recur' => 'http://dummy.com',
797 'payment_instrument_id' => 'Debit Card',
799 $processorParams = array_merge($processorParams, $params);
800 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
801 return $processor['id'];
805 * Create Payment Processor.
807 * @param array $processorParams
809 * @return \CRM_Core_Payment_Dummy
810 * Instance of Dummy Payment Processor
812 public function dummyProcessorCreate($processorParams = array()) {
813 $paymentProcessorID = $this->processorCreate($processorParams);
814 return System
::singleton()->getById($paymentProcessorID);
818 * Create contribution page.
820 * @param array $params
822 * Array of contribution page
824 public function contributionPageCreate($params = array()) {
825 $this->_pageParams
= array_merge(array(
826 'title' => 'Test Contribution Page',
827 'financial_type_id' => 1,
829 'financial_account_id' => 1,
831 'is_allow_other_amount' => 1,
833 'max_amount' => 1000,
835 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
839 * Create a sample batch.
841 public function batchCreate() {
842 $params = $this->_params
;
843 $params['name'] = $params['title'] = 'Batch_433397';
844 $params['status_id'] = 1;
845 $result = $this->callAPISuccess('batch', 'create', $params);
846 return $result['id'];
852 * @param array $params
854 * result of created tag
856 public function tagCreate($params = array()) {
858 'name' => 'New Tag3',
859 'description' => 'This is description for Our New Tag ',
862 $params = array_merge($defaults, $params);
863 $result = $this->callAPISuccess('Tag', 'create', $params);
864 return $result['values'][$result['id']];
871 * Id of the tag to be deleted.
875 public function tagDelete($tagId) {
876 require_once 'api/api.php';
880 $result = $this->callAPISuccess('Tag', 'delete', $params);
881 return $result['id'];
885 * Add entity(s) to the tag
887 * @param array $params
891 public function entityTagAdd($params) {
892 $result = $this->callAPISuccess('entity_tag', 'create', $params);
899 * @param array $params
903 * id of created pledge
905 public function pledgeCreate($params) {
906 $params = array_merge(array(
907 'pledge_create_date' => date('Ymd'),
908 'start_date' => date('Ymd'),
909 'scheduled_date' => date('Ymd'),
911 'pledge_status_id' => '2',
912 'financial_type_id' => '1',
913 'pledge_original_installment_amount' => 20,
914 'frequency_interval' => 5,
915 'frequency_unit' => 'year',
916 'frequency_day' => 15,
921 $result = $this->callAPISuccess('Pledge', 'create', $params);
922 return $result['id'];
926 * Delete contribution.
928 * @param int $pledgeId
930 public function pledgeDelete($pledgeId) {
932 'pledge_id' => $pledgeId,
934 $this->callAPISuccess('Pledge', 'delete', $params);
938 * Create contribution.
940 * @param array $params
941 * Array of parameters.
944 * id of created contribution
946 public function contributionCreate($params) {
948 $params = array_merge(array(
950 'receive_date' => date('Ymd'),
951 'total_amount' => 100.00,
952 'fee_amount' => 5.00,
953 'financial_type_id' => 1,
954 'payment_instrument_id' => 1,
955 'non_deductible_amount' => 10.00,
957 'contribution_status_id' => 1,
960 $result = $this->callAPISuccess('contribution', 'create', $params);
961 return $result['id'];
965 * Delete contribution.
967 * @param int $contributionId
971 public function contributionDelete($contributionId) {
973 'contribution_id' => $contributionId,
975 $result = $this->callAPISuccess('contribution', 'delete', $params);
982 * @param array $params
983 * Name-value pair for an event.
987 public function eventCreate($params = array()) {
988 // if no contact was passed, make up a dummy event creator
989 if (!isset($params['contact_id'])) {
990 $params['contact_id'] = $this->_contactCreate(array(
991 'contact_type' => 'Individual',
992 'first_name' => 'Event',
993 'last_name' => 'Creator',
997 // set defaults for missing params
998 $params = array_merge(array(
999 'title' => 'Annual CiviCRM meet',
1000 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1001 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1002 'event_type_id' => 1,
1004 'start_date' => 20081021,
1005 'end_date' => 20081023,
1006 'is_online_registration' => 1,
1007 'registration_start_date' => 20080601,
1008 'registration_end_date' => 20081015,
1009 'max_participants' => 100,
1010 'event_full_text' => 'Sorry! We are already full',
1013 'is_show_location' => 0,
1014 'is_email_confirm' => 1,
1017 return $this->callAPISuccess('Event', 'create', $params);
1021 * Create a paid event.
1023 * @param array $params
1027 protected function eventCreatePaid($params) {
1028 $event = $this->eventCreate($params);
1029 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1030 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1031 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1032 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1033 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1045 public function eventDelete($id) {
1049 return $this->callAPISuccess('event', 'delete', $params);
1053 * Delete participant.
1055 * @param int $participantID
1059 public function participantDelete($participantID) {
1061 'id' => $participantID,
1063 $check = $this->callAPISuccess('Participant', 'get', $params);
1064 if ($check['count'] > 0) {
1065 return $this->callAPISuccess('Participant', 'delete', $params);
1070 * Create participant payment.
1072 * @param int $participantID
1073 * @param int $contributionID
1075 * $id of created payment
1077 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1078 //Create Participant Payment record With Values
1080 'participant_id' => $participantID,
1081 'contribution_id' => $contributionID,
1084 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1085 return $result['id'];
1089 * Delete participant payment.
1091 * @param int $paymentID
1093 public function participantPaymentDelete($paymentID) {
1097 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1103 * @param int $contactID
1105 * location id of created location
1107 public function locationAdd($contactID) {
1110 'location_type' => 'New Location Type',
1112 'name' => 'Saint Helier St',
1113 'county' => 'Marin',
1114 'country' => 'UNITED STATES',
1115 'state_province' => 'Michigan',
1116 'supplemental_address_1' => 'Hallmark Ct',
1117 'supplemental_address_2' => 'Jersey Village',
1118 'supplemental_address_3' => 'My Town',
1123 'contact_id' => $contactID,
1124 'address' => $address,
1125 'location_format' => '2.0',
1126 'location_type' => 'New Location Type',
1129 $result = $this->callAPISuccess('Location', 'create', $params);
1134 * Delete Locations of contact.
1136 * @param array $params
1139 public function locationDelete($params) {
1140 $this->callAPISuccess('Location', 'delete', $params);
1144 * Add a Location Type.
1146 * @param array $params
1147 * @return CRM_Core_DAO_LocationType
1148 * location id of created location
1150 public function locationTypeCreate($params = NULL) {
1151 if ($params === NULL) {
1153 'name' => 'New Location Type',
1154 'vcard_name' => 'New Location Type',
1155 'description' => 'Location Type for Delete',
1160 $locationType = new CRM_Core_DAO_LocationType();
1161 $locationType->copyValues($params);
1162 $locationType->save();
1163 // clear getfields cache
1164 CRM_Core_PseudoConstant
::flush();
1165 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1166 return $locationType;
1170 * Delete a Location Type.
1172 * @param int $locationTypeId
1174 public function locationTypeDelete($locationTypeId) {
1175 $locationType = new CRM_Core_DAO_LocationType();
1176 $locationType->id
= $locationTypeId;
1177 $locationType->delete();
1183 * @param array $params
1184 * @return CRM_Core_DAO_Mapping
1185 * Mapping id of created mapping
1187 public function mappingCreate($params = NULL) {
1188 if ($params === NULL) {
1190 'name' => 'Mapping name',
1191 'description' => 'Mapping description',
1192 // 'Export Contact' mapping.
1193 'mapping_type_id' => 7,
1197 $mapping = new CRM_Core_DAO_Mapping();
1198 $mapping->copyValues($params);
1200 // clear getfields cache
1201 CRM_Core_PseudoConstant
::flush();
1202 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1209 * @param int $mappingId
1211 public function mappingDelete($mappingId) {
1212 $mapping = new CRM_Core_DAO_Mapping();
1213 $mapping->id
= $mappingId;
1218 * Prepare class for ACLs.
1220 protected function prepareForACLs() {
1221 $config = CRM_Core_Config
::singleton();
1222 $config->userPermissionClass
->permissions
= array();
1228 protected function cleanUpAfterACLs() {
1229 CRM_Utils_Hook
::singleton()->reset();
1230 $tablesToTruncate = array(
1232 'civicrm_acl_cache',
1233 'civicrm_acl_entity_role',
1234 'civicrm_acl_contact_cache',
1236 $this->quickCleanup($tablesToTruncate);
1237 $config = CRM_Core_Config
::singleton();
1238 unset($config->userPermissionClass
->permissions
);
1242 * Create a smart group.
1244 * By default it will be a group of households.
1246 * @param array $smartGroupParams
1247 * @param array $groupParams
1248 * @param string $contactType
1252 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1253 $smartGroupParams = array_merge([
1254 'formValues' => ['contact_type' => ['IN' => [$contactType]]],
1257 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1259 $groupParams['saved_search_id'] = $savedSearch->id
;
1260 return $this->groupCreate($groupParams);
1265 * @param array $params
1267 public function uFFieldCreate($params = array()) {
1268 $params = array_merge(array(
1270 'field_name' => 'first_name',
1273 'visibility' => 'Public Pages and Listings',
1274 'is_searchable' => '1',
1275 'label' => 'first_name',
1276 'field_type' => 'Individual',
1279 $this->callAPISuccess('uf_field', 'create', $params);
1283 * Add a UF Join Entry.
1285 * @param array $params
1287 * $id of created UF Join
1289 public function ufjoinCreate($params = NULL) {
1290 if ($params === NULL) {
1293 'module' => 'CiviEvent',
1294 'entity_table' => 'civicrm_event',
1300 $result = $this->callAPISuccess('uf_join', 'create', $params);
1305 * @param array $params
1306 * Optional parameters.
1307 * @param bool $reloadConfig
1308 * While enabling CiviCampaign component, we shouldn't always forcibly
1309 * reload config as this hinder hook call in test environment
1314 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1315 $this->enableCiviCampaign($reloadConfig);
1316 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1317 'name' => 'big_campaign',
1318 'title' => 'Campaign',
1320 return $campaign['id'];
1324 * Create Group for a contact.
1326 * @param int $contactId
1328 public function contactGroupCreate($contactId) {
1330 'contact_id.1' => $contactId,
1334 $this->callAPISuccess('GroupContact', 'Create', $params);
1338 * Delete Group for a contact.
1340 * @param int $contactId
1342 public function contactGroupDelete($contactId) {
1344 'contact_id.1' => $contactId,
1347 $this->civicrm_api('GroupContact', 'Delete', $params);
1353 * @param array $params
1356 public function activityCreate($params = array()) {
1357 $params = array_merge(array(
1358 'subject' => 'Discussion on warm beer',
1359 'activity_date_time' => date('Ymd'),
1360 'duration_hours' => 30,
1361 'duration_minutes' => 20,
1362 'location' => 'Baker Street',
1363 'details' => 'Lets schedule a meeting',
1365 'activity_type_id' => 'Meeting',
1367 if (!isset($params['source_contact_id'])) {
1368 $params['source_contact_id'] = $this->individualCreate();
1370 if (!isset($params['target_contact_id'])) {
1371 $params['target_contact_id'] = $this->individualCreate(array(
1372 'first_name' => 'Julia',
1373 'last_name' => 'Anderson',
1375 'email' => 'julia_anderson@civicrm.org',
1376 'contact_type' => 'Individual',
1379 if (!isset($params['assignee_contact_id'])) {
1380 $params['assignee_contact_id'] = $params['target_contact_id'];
1383 $result = civicrm_api3('Activity', 'create', $params);
1385 $result['target_contact_id'] = $params['target_contact_id'];
1386 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1391 * Create an activity type.
1393 * @param array $params
1397 public function activityTypeCreate($params) {
1398 return $this->callAPISuccess('ActivityType', 'create', $params);
1402 * Delete activity type.
1404 * @param int $activityTypeId
1405 * Id of the activity type.
1408 public function activityTypeDelete($activityTypeId) {
1409 $params['activity_type_id'] = $activityTypeId;
1410 return $this->callAPISuccess('ActivityType', 'delete', $params);
1414 * Create custom group.
1416 * @param array $params
1419 public function customGroupCreate($params = array()) {
1421 'title' => 'new custom group',
1422 'extends' => 'Contact',
1424 'style' => 'Inline',
1428 $params = array_merge($defaults, $params);
1430 return $this->callAPISuccess('custom_group', 'create', $params);
1434 * Existing function doesn't allow params to be over-ridden so need a new one
1435 * this one allows you to only pass in the params you want to change
1436 * @param array $params
1439 public function CustomGroupCreateByParams($params = array()) {
1441 'title' => "API Custom Group",
1442 'extends' => 'Contact',
1444 'style' => 'Inline',
1447 $params = array_merge($defaults, $params);
1448 return $this->callAPISuccess('custom_group', 'create', $params);
1452 * Create custom group with multi fields.
1453 * @param array $params
1456 public function CustomGroupMultipleCreateByParams($params = array()) {
1461 $params = array_merge($defaults, $params);
1462 return $this->CustomGroupCreateByParams($params);
1466 * Create custom group with multi fields.
1467 * @param array $params
1470 public function CustomGroupMultipleCreateWithFields($params = array()) {
1471 // also need to pass on $params['custom_field'] if not set but not in place yet
1473 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1474 $ids['custom_group_id'] = $customGroup['id'];
1476 $customField = $this->customFieldCreate(array(
1477 'custom_group_id' => $ids['custom_group_id'],
1478 'label' => 'field_1' . $ids['custom_group_id'],
1482 $ids['custom_field_id'][] = $customField['id'];
1484 $customField = $this->customFieldCreate(array(
1485 'custom_group_id' => $ids['custom_group_id'],
1486 'default_value' => '',
1487 'label' => 'field_2' . $ids['custom_group_id'],
1490 $ids['custom_field_id'][] = $customField['id'];
1492 $customField = $this->customFieldCreate(array(
1493 'custom_group_id' => $ids['custom_group_id'],
1494 'default_value' => '',
1495 'label' => 'field_3' . $ids['custom_group_id'],
1498 $ids['custom_field_id'][] = $customField['id'];
1504 * Create a custom group with a single text custom field. See
1505 * participant:testCreateWithCustom for how to use this
1507 * @param string $function
1509 * @param string $filename
1513 * ids of created objects
1515 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1516 $params = array('title' => $function);
1517 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1518 $params['extends'] = $entity ?
$entity : 'Contact';
1519 $customGroup = $this->CustomGroupCreate($params);
1520 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1521 CRM_Core_PseudoConstant
::flush();
1523 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1527 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1528 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1530 * @param string $function
1532 * @param string $filename
1536 * ids of created objects
1538 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1539 $params = array('title' => $function);
1540 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1541 $params['extends'] = $entity ?
$entity : 'Contact';
1542 $customGroup = $this->CustomGroupCreate($params);
1543 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1544 CRM_Core_PseudoConstant
::flush();
1546 'defaultValue' => 'Default Value',
1547 'lowercasevalue' => 'Lowercase Value',
1548 1 => 'Integer Value',
1551 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1552 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1553 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1554 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1555 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1556 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1557 foreach ($options as $option_value => $option_label) {
1558 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1559 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1562 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id'], 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'], 'custom_field_group_options' => $options);
1566 * Delete custom group.
1568 * @param int $customGroupID
1572 public function customGroupDelete($customGroupID) {
1573 $params['id'] = $customGroupID;
1574 return $this->callAPISuccess('custom_group', 'delete', $params);
1578 * Create custom field.
1580 * @param array $params
1581 * (custom_group_id) is required.
1584 public function customFieldCreate($params) {
1585 $params = array_merge(array(
1586 'label' => 'Custom Field',
1587 'data_type' => 'String',
1588 'html_type' => 'Text',
1589 'is_searchable' => 1,
1591 'default_value' => 'defaultValue',
1594 $result = $this->callAPISuccess('custom_field', 'create', $params);
1595 // these 2 functions are called with force to flush static caches
1596 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1597 CRM_Core_Component
::getEnabledComponents(1);
1602 * Delete custom field.
1604 * @param int $customFieldID
1608 public function customFieldDelete($customFieldID) {
1610 $params['id'] = $customFieldID;
1611 return $this->callAPISuccess('custom_field', 'delete', $params);
1620 public function noteCreate($cId) {
1622 'entity_table' => 'civicrm_contact',
1623 'entity_id' => $cId,
1624 'note' => 'hello I am testing Note',
1625 'contact_id' => $cId,
1626 'modified_date' => date('Ymd'),
1627 'subject' => 'Test Note',
1630 return $this->callAPISuccess('Note', 'create', $params);
1634 * Enable CiviCampaign Component.
1636 * @param bool $reloadConfig
1637 * Force relaod config or not
1639 public function enableCiviCampaign($reloadConfig = TRUE) {
1640 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1641 if ($reloadConfig) {
1642 // force reload of config object
1643 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1645 //flush cache by calling with reset
1646 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1650 * Create custom field with Option Values.
1652 * @param array $customGroup
1653 * @param string $name
1654 * Name of custom field.
1655 * @param array $extraParams
1656 * Additional parameters to pass through.
1660 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1661 $fieldParams = array(
1662 'custom_group_id' => $customGroup['id'],
1663 'name' => 'test_custom_group',
1664 'label' => 'Country',
1665 'html_type' => 'Select',
1666 'data_type' => 'String',
1669 'is_searchable' => 0,
1673 $optionGroup = array(
1675 'name' => 'option_group1',
1676 'label' => 'option_group_label1',
1679 $optionValue = array(
1680 'option_label' => array('Label1', 'Label2'),
1681 'option_value' => array('value1', 'value2'),
1682 'option_name' => array($name . '_1', $name . '_2'),
1683 'option_weight' => array(1, 2),
1684 'option_status' => array(1, 1),
1687 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1689 return $this->callAPISuccess('custom_field', 'create', $params);
1697 public function confirmEntitiesDeleted($entities) {
1698 foreach ($entities as $entity) {
1700 $result = $this->callAPISuccess($entity, 'Get', array());
1701 if ($result['error'] == 1 ||
$result['count'] > 0) {
1702 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1710 * Quick clean by emptying tables created for the test.
1712 * @param array $tablesToTruncate
1713 * @param bool $dropCustomValueTables
1714 * @throws \CRM_Core_Exception
1716 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1718 throw new \
CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1720 if ($dropCustomValueTables) {
1721 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1722 while ($optionGroupResult->fetch()) {
1723 if (!empty($optionGroupResult->option_group_id
)) {
1724 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1727 $tablesToTruncate[] = 'civicrm_custom_group';
1728 $tablesToTruncate[] = 'civicrm_custom_field';
1731 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1733 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1734 foreach ($tablesToTruncate as $table) {
1735 $sql = "TRUNCATE TABLE $table";
1736 CRM_Core_DAO
::executeQuery($sql);
1738 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1740 if ($dropCustomValueTables) {
1741 $dbName = self
::getDBName();
1743 SELECT TABLE_NAME as tableName
1744 FROM INFORMATION_SCHEMA.TABLES
1745 WHERE TABLE_SCHEMA = '{$dbName}'
1746 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1749 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1750 while ($tableDAO->fetch()) {
1751 $sql = "DROP TABLE {$tableDAO->tableName}";
1752 CRM_Core_DAO
::executeQuery($sql);
1758 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1760 public function quickCleanUpFinancialEntities() {
1761 $tablesToTruncate = array(
1763 'civicrm_activity_contact',
1764 'civicrm_contribution',
1765 'civicrm_contribution_soft',
1766 'civicrm_contribution_product',
1767 'civicrm_financial_trxn',
1768 'civicrm_financial_item',
1769 'civicrm_contribution_recur',
1770 'civicrm_line_item',
1771 'civicrm_contribution_page',
1772 'civicrm_payment_processor',
1773 'civicrm_entity_financial_trxn',
1774 'civicrm_membership',
1775 'civicrm_membership_type',
1776 'civicrm_membership_payment',
1777 'civicrm_membership_log',
1778 'civicrm_membership_block',
1780 'civicrm_participant',
1781 'civicrm_participant_payment',
1783 'civicrm_pledge_block',
1784 'civicrm_pledge_payment',
1785 'civicrm_price_set_entity',
1786 'civicrm_price_field_value',
1787 'civicrm_price_field',
1789 $this->quickCleanup($tablesToTruncate);
1790 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1791 $this->restoreDefaultPriceSetConfig();
1793 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1794 $this->disableTaxAndInvoicing();
1795 $this->setCurrencySeparators(',');
1796 CRM_Core_PseudoConstant
::flush('taxRates');
1797 System
::singleton()->flushProcessors();
1798 // @fixme this parameter is leaking - it should not be defined as a class static
1799 // but for now we just handle in tear down.
1800 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1803 public function restoreDefaultPriceSetConfig() {
1804 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1805 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1806 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)");
1807 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)");
1811 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1812 * Default behaviour is to also delete the entity
1813 * @param array $params
1814 * Params array to check against.
1816 * Id of the entity concerned.
1817 * @param string $entity
1818 * Name of entity concerned (e.g. membership).
1819 * @param bool $delete
1820 * Should the entity be deleted as part of this check.
1821 * @param string $errorText
1822 * Text to print on error.
1826 * @param array $params
1829 * @param int $delete
1830 * @param string $errorText
1834 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1836 $result = $this->callAPISuccessGetSingle($entity, array(
1841 $this->callAPISuccess($entity, 'Delete', array(
1845 $dateFields = $keys = $dateTimeFields = array();
1846 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1847 foreach ($fields['values'] as $field => $settings) {
1848 if (array_key_exists($field, $result)) {
1849 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1852 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1854 $type = CRM_Utils_Array
::value('type', $settings);
1855 if ($type == CRM_Utils_Type
::T_DATE
) {
1856 $dateFields[] = $settings['name'];
1857 // we should identify both real names & unique names as dates
1858 if ($field != $settings['name']) {
1859 $dateFields[] = $field;
1862 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1863 $dateTimeFields[] = $settings['name'];
1864 // we should identify both real names & unique names as dates
1865 if ($field != $settings['name']) {
1866 $dateTimeFields[] = $field;
1871 if (strtolower($entity) == 'contribution') {
1872 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1873 // this is not returned in id format
1874 unset($params['payment_instrument_id']);
1875 $params['contribution_source'] = $params['source'];
1876 unset($params['source']);
1879 foreach ($params as $key => $value) {
1880 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1883 if (in_array($key, $dateFields)) {
1884 $value = date('Y-m-d', strtotime($value));
1885 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1887 if (in_array($key, $dateTimeFields)) {
1888 $value = date('Y-m-d H:i:s', strtotime($value));
1889 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1891 $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);
1896 * Get formatted values in the actual and expected result.
1897 * @param array $actual
1898 * Actual calculated values.
1899 * @param array $expected
1902 public function checkArrayEquals(&$actual, &$expected) {
1903 self
::unsetId($actual);
1904 self
::unsetId($expected);
1905 $this->assertEquals($expected, $actual);
1909 * Unset the key 'id' from the array
1910 * @param array $unformattedArray
1911 * The array from which the 'id' has to be unset.
1913 public static function unsetId(&$unformattedArray) {
1914 $formattedArray = array();
1915 if (array_key_exists('id', $unformattedArray)) {
1916 unset($unformattedArray['id']);
1918 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1919 foreach ($unformattedArray['values'] as $key => $value) {
1920 if (is_array($value)) {
1921 foreach ($value as $k => $v) {
1927 elseif ($key == 'id') {
1928 $unformattedArray[$key];
1930 $formattedArray = array($value);
1932 $unformattedArray['values'] = $formattedArray;
1937 * Helper to enable/disable custom directory support
1939 * @param array $customDirs
1941 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1942 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1944 public function customDirectories($customDirs) {
1945 $config = CRM_Core_Config
::singleton();
1947 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1948 unset($config->customPHPPathDir
);
1950 elseif ($customDirs['php_path'] === TRUE) {
1951 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1954 $config->customPHPPathDir
= $php_path;
1957 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1958 unset($config->customTemplateDir
);
1960 elseif ($customDirs['template_path'] === TRUE) {
1961 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1964 $config->customTemplateDir
= $template_path;
1969 * Generate a temporary folder.
1971 * @param string $prefix
1974 public function createTempDir($prefix = 'test-') {
1975 $tempDir = CRM_Utils_File
::tempdir($prefix);
1976 $this->tempDirs
[] = $tempDir;
1980 public function cleanTempDirs() {
1981 if (!is_array($this->tempDirs
)) {
1982 // fix test errors where this is not set
1985 foreach ($this->tempDirs
as $tempDir) {
1986 if (is_dir($tempDir)) {
1987 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1993 * Temporarily replace the singleton extension with a different one.
1994 * @param \CRM_Extension_System $system
1996 public function setExtensionSystem(CRM_Extension_System
$system) {
1997 if ($this->origExtensionSystem
== NULL) {
1998 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2000 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2003 public function unsetExtensionSystem() {
2004 if ($this->origExtensionSystem
!== NULL) {
2005 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2006 $this->origExtensionSystem
= NULL;
2011 * Temporarily alter the settings-metadata to add a mock setting.
2013 * WARNING: The setting metadata will disappear on the next cache-clear.
2018 public function setMockSettingsMetaData($extras) {
2019 CRM_Utils_Hook
::singleton()
2020 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2021 $metadata = array_merge($metadata, $extras);
2024 Civi
::service('settings_manager')->flush();
2026 $fields = $this->callAPISuccess('setting', 'getfields', array());
2027 foreach ($extras as $key => $spec) {
2028 $this->assertNotEmpty($spec['title']);
2029 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2034 * @param string $name
2036 public function financialAccountDelete($name) {
2037 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2038 $financialAccount->name
= $name;
2039 if ($financialAccount->find(TRUE)) {
2040 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2041 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2042 $entityFinancialType->delete();
2043 $financialAccount->delete();
2048 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2049 * (NB unclear if this is still required)
2051 public function _sethtmlGlobals() {
2052 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2053 'required' => array(
2054 'html_quickform_rule_required',
2055 'HTML/QuickForm/Rule/Required.php',
2057 'maxlength' => array(
2058 'html_quickform_rule_range',
2059 'HTML/QuickForm/Rule/Range.php',
2061 'minlength' => array(
2062 'html_quickform_rule_range',
2063 'HTML/QuickForm/Rule/Range.php',
2065 'rangelength' => array(
2066 'html_quickform_rule_range',
2067 'HTML/QuickForm/Rule/Range.php',
2070 'html_quickform_rule_email',
2071 'HTML/QuickForm/Rule/Email.php',
2074 'html_quickform_rule_regex',
2075 'HTML/QuickForm/Rule/Regex.php',
2077 'lettersonly' => array(
2078 'html_quickform_rule_regex',
2079 'HTML/QuickForm/Rule/Regex.php',
2081 'alphanumeric' => array(
2082 'html_quickform_rule_regex',
2083 'HTML/QuickForm/Rule/Regex.php',
2086 'html_quickform_rule_regex',
2087 'HTML/QuickForm/Rule/Regex.php',
2089 'nopunctuation' => array(
2090 'html_quickform_rule_regex',
2091 'HTML/QuickForm/Rule/Regex.php',
2094 'html_quickform_rule_regex',
2095 'HTML/QuickForm/Rule/Regex.php',
2097 'callback' => array(
2098 'html_quickform_rule_callback',
2099 'HTML/QuickForm/Rule/Callback.php',
2102 'html_quickform_rule_compare',
2103 'HTML/QuickForm/Rule/Compare.php',
2106 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2107 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2109 'HTML/QuickForm/group.php',
2110 'HTML_QuickForm_group',
2113 'HTML/QuickForm/hidden.php',
2114 'HTML_QuickForm_hidden',
2117 'HTML/QuickForm/reset.php',
2118 'HTML_QuickForm_reset',
2120 'checkbox' => array(
2121 'HTML/QuickForm/checkbox.php',
2122 'HTML_QuickForm_checkbox',
2125 'HTML/QuickForm/file.php',
2126 'HTML_QuickForm_file',
2129 'HTML/QuickForm/image.php',
2130 'HTML_QuickForm_image',
2132 'password' => array(
2133 'HTML/QuickForm/password.php',
2134 'HTML_QuickForm_password',
2137 'HTML/QuickForm/radio.php',
2138 'HTML_QuickForm_radio',
2141 'HTML/QuickForm/button.php',
2142 'HTML_QuickForm_button',
2145 'HTML/QuickForm/submit.php',
2146 'HTML_QuickForm_submit',
2149 'HTML/QuickForm/select.php',
2150 'HTML_QuickForm_select',
2152 'hiddenselect' => array(
2153 'HTML/QuickForm/hiddenselect.php',
2154 'HTML_QuickForm_hiddenselect',
2157 'HTML/QuickForm/text.php',
2158 'HTML_QuickForm_text',
2160 'textarea' => array(
2161 'HTML/QuickForm/textarea.php',
2162 'HTML_QuickForm_textarea',
2164 'fckeditor' => array(
2165 'HTML/QuickForm/fckeditor.php',
2166 'HTML_QuickForm_FCKEditor',
2169 'HTML/QuickForm/tinymce.php',
2170 'HTML_QuickForm_TinyMCE',
2172 'dojoeditor' => array(
2173 'HTML/QuickForm/dojoeditor.php',
2174 'HTML_QuickForm_dojoeditor',
2177 'HTML/QuickForm/link.php',
2178 'HTML_QuickForm_link',
2180 'advcheckbox' => array(
2181 'HTML/QuickForm/advcheckbox.php',
2182 'HTML_QuickForm_advcheckbox',
2185 'HTML/QuickForm/date.php',
2186 'HTML_QuickForm_date',
2189 'HTML/QuickForm/static.php',
2190 'HTML_QuickForm_static',
2193 'HTML/QuickForm/header.php',
2194 'HTML_QuickForm_header',
2197 'HTML/QuickForm/html.php',
2198 'HTML_QuickForm_html',
2200 'hierselect' => array(
2201 'HTML/QuickForm/hierselect.php',
2202 'HTML_QuickForm_hierselect',
2204 'autocomplete' => array(
2205 'HTML/QuickForm/autocomplete.php',
2206 'HTML_QuickForm_autocomplete',
2209 'HTML/QuickForm/xbutton.php',
2210 'HTML_QuickForm_xbutton',
2212 'advmultiselect' => array(
2213 'HTML/QuickForm/advmultiselect.php',
2214 'HTML_QuickForm_advmultiselect',
2220 * Set up an acl allowing contact to see 2 specified groups
2221 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2223 * You need to have pre-created these groups & created the user e.g
2224 * $this->createLoggedInUser();
2225 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2226 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2228 * @param bool $isProfile
2230 public function setupACL($isProfile = FALSE) {
2232 $_REQUEST = $this->_params
;
2234 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2235 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2236 $ov = new CRM_Core_DAO_OptionValue();
2237 $ov->option_group_id
= $optionGroupID;
2239 if ($ov->find(TRUE)) {
2240 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2242 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2243 'option_group_id' => $optionGroupID,
2244 'label' => 'pick me',
2248 CRM_Core_DAO
::executeQuery("
2249 TRUNCATE civicrm_acl_cache
2252 CRM_Core_DAO
::executeQuery("
2253 TRUNCATE civicrm_acl_contact_cache
2256 CRM_Core_DAO
::executeQuery("
2257 INSERT INTO civicrm_acl_entity_role (
2258 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2259 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2263 CRM_Core_DAO
::executeQuery("
2264 INSERT INTO civicrm_acl (
2265 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2268 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2273 CRM_Core_DAO
::executeQuery("
2274 INSERT INTO civicrm_acl (
2275 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2278 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2282 CRM_Core_DAO
::executeQuery("
2283 INSERT INTO civicrm_acl (
2284 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2287 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2292 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2293 $this->callAPISuccess('group_contact', 'create', array(
2294 'group_id' => $this->_permissionedGroup
,
2295 'contact_id' => $this->_loggedInUser
,
2300 CRM_ACL_BAO_Cache
::resetCache();
2301 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2306 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2308 public function offsetDefaultPriceSet() {
2309 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2310 $firstID = $contributionPriceSet['id'];
2311 $this->callAPISuccess('price_set', 'create', array(
2312 'id' => $contributionPriceSet['id'],
2316 unset($contributionPriceSet['id']);
2317 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2318 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2319 'price_set_id' => $firstID,
2320 'options' => array('limit' => 1),
2322 unset($priceField['id']);
2323 $priceField['price_set_id'] = $newPriceSet['id'];
2324 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2325 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2326 'price_set_id' => $firstID,
2328 'options' => array('limit' => 1),
2331 unset($priceFieldValue['id']);
2332 //create some padding to use up ids
2333 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2334 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2335 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2339 * Create an instance of the paypal processor.
2340 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2341 * this parent class & we don't have a structure for that yet
2342 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2343 * & the best protection against that is the functions this class affords
2344 * @param array $params
2345 * @return int $result['id'] payment processor id
2347 public function paymentProcessorCreate($params = array()) {
2348 $params = array_merge(array(
2350 'domain_id' => CRM_Core_Config
::domainID(),
2351 'payment_processor_type_id' => 'PayPal',
2355 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2356 'password' => '1183377788',
2357 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2358 'url_site' => 'https://www.sandbox.paypal.com/',
2359 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2360 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2361 'class_name' => 'Payment_PayPalImpl',
2362 'billing_mode' => 3,
2363 'financial_type_id' => 1,
2364 'financial_account_id' => 12,
2365 // Credit card = 1 so can pass 'by accident'.
2366 'payment_instrument_id' => 'Debit Card',
2368 if (!is_numeric($params['payment_processor_type_id'])) {
2369 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2371 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2372 'name' => $params['payment_processor_type_id'],
2376 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2377 return $result['id'];
2381 * Set up initial recurring payment allowing subsequent IPN payments.
2383 * @param array $recurParams (Optional)
2384 * @param array $contributionParams (Optional)
2386 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2387 $contributionParams = array_merge([
2388 'total_amount' => '200',
2389 'invoice_id' => $this->_invoiceID
,
2390 'financial_type_id' => 'Donation',
2391 'contribution_status_id' => 'Pending',
2392 'contact_id' => $this->_contactID
,
2393 'contribution_page_id' => $this->_contributionPageID
,
2394 'payment_processor_id' => $this->_paymentProcessorID
,
2396 'receive_date' => '2019-07-25 07:34:23',
2397 'skipCleanMoney' => TRUE,
2398 ], $contributionParams);
2399 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2400 'contact_id' => $this->_contactID
,
2403 'installments' => 5,
2404 'frequency_unit' => 'Month',
2405 'frequency_interval' => 1,
2406 'invoice_id' => $this->_invoiceID
,
2407 'contribution_status_id' => 2,
2408 'payment_processor_id' => $this->_paymentProcessorID
,
2409 // processor provided ID - use contact ID as proxy.
2410 'processor_id' => $this->_contactID
,
2411 'api.contribution.create' => $contributionParams,
2413 $this->_contributionRecurID
= $contributionRecur['id'];
2414 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2418 * 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
2420 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2422 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2423 $membershipParams = $recurParams = array();
2424 if (!empty($params['duration_unit'])) {
2425 $membershipParams['duration_unit'] = $params['duration_unit'];
2427 if (!empty($params['frequency_unit'])) {
2428 $recurParams['frequency_unit'] = $params['frequency_unit'];
2431 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2432 //create a contribution so our membership & contribution don't both have id = 1
2433 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2434 $this->contributionCreate(array(
2435 'contact_id' => $this->_contactID
,
2437 'financial_type_id' => 1,
2438 'invoice_id' => 'abcd',
2440 'receive_date' => '2019-07-25 07:34:23',
2443 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2445 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2446 'contact_id' => $this->_contactID
,
2447 'membership_type_id' => $this->ids
['membership_type'],
2448 'contribution_recur_id' => $this->_contributionRecurID
,
2449 'format.only_id' => TRUE,
2450 'source' => 'Payment',
2452 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2453 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2455 $this->callAPISuccess('line_item', 'create', array(
2456 'entity_table' => 'civicrm_membership',
2457 'entity_id' => $this->ids
['membership'],
2458 'contribution_id' => $this->_contributionID
,
2459 'label' => 'General',
2461 'unit_price' => 200,
2462 'line_total' => 200,
2463 'financial_type_id' => 1,
2464 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2466 'label' => 'Membership Amount',
2467 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2469 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2471 'label' => 'General',
2472 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2475 $this->callAPISuccess('membership_payment', 'create', array(
2476 'contribution_id' => $this->_contributionID
,
2477 'membership_id' => $this->ids
['membership'],
2486 public function CiviUnitTestCase_fatalErrorHandler($message) {
2487 throw new Exception("{$message['message']}: {$message['code']}");
2491 * Wrap the entire test case in a transaction.
2493 * Only subsequent DB statements will be wrapped in TX -- this cannot
2494 * retroactively wrap old DB statements. Therefore, it makes sense to
2495 * call this at the beginning of setUp().
2497 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2498 * this option does not work with, e.g., custom-data.
2500 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2501 * if TRUNCATE or ALTER is called while using a transaction.
2504 * Whether to use nesting or reference-counting.
2506 public function useTransaction($nest = TRUE) {
2508 $this->tx
= new CRM_Core_Transaction($nest);
2509 $this->tx
->rollback();
2514 * Assert the attachment exists.
2516 * @param bool $exists
2517 * @param array $apiResult
2519 protected function assertAttachmentExistence($exists, $apiResult) {
2520 $fileId = $apiResult['id'];
2521 $this->assertTrue(is_numeric($fileId));
2522 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2523 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2524 1 => array($fileId, 'Int'),
2526 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2527 1 => array($fileId, 'Int'),
2532 * Assert 2 sql strings are the same, ignoring double spaces.
2534 * @param string $expectedSQL
2535 * @param string $actualSQL
2536 * @param string $message
2538 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2539 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2540 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2541 $this->assertEquals($expected, $actual, $message);
2545 * Create a price set for an event.
2547 * @param int $feeTotal
2548 * @param int $minAmt
2549 * @param string $type
2553 * @throws \CRM_Core_Exception
2555 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2556 // creating price set, price field
2557 $paramsSet['title'] = 'Price Set';
2558 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2559 $paramsSet['is_active'] = FALSE;
2560 $paramsSet['extends'] = 1;
2561 $paramsSet['min_amount'] = $minAmt;
2563 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2564 $this->_ids
['price_set'] = $priceSet->id
;
2566 $paramsField = array(
2567 'label' => 'Price Field',
2568 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2569 'html_type' => $type,
2570 'price' => $feeTotal,
2571 'option_label' => array('1' => 'Price Field'),
2572 'option_value' => array('1' => $feeTotal),
2573 'option_name' => array('1' => $feeTotal),
2574 'option_weight' => array('1' => 1),
2575 'option_amount' => array('1' => 1),
2576 'is_display_amounts' => 1,
2578 'options_per_line' => 1,
2579 'is_active' => array('1' => 1),
2580 'price_set_id' => $this->_ids
['price_set'],
2581 'is_enter_qty' => 1,
2582 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2584 if ($type === 'Radio') {
2585 $paramsField['is_enter_qty'] = 0;
2586 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2587 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2589 $this->callAPISuccess('PriceField', 'create', $paramsField);
2590 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2591 $this->_ids
['price_field'] = array_keys($fields['values']);
2592 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2593 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2595 return $this->_ids
['price_set'];
2599 * Add a profile to a contribution page.
2601 * @param string $name
2602 * @param int $contributionPageID
2603 * @param string $module
2605 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2607 'uf_group_id' => $name,
2608 'module' => $module,
2609 'entity_table' => 'civicrm_contribution_page',
2610 'entity_id' => $contributionPageID,
2613 if ($module !== 'CiviContribute') {
2614 $params['module_data'] = [$module => []];
2616 $this->callAPISuccess('UFJoin', 'create', $params);
2620 * Add participant with contribution
2624 protected function createParticipantWithContribution() {
2625 // creating price set, price field
2626 $this->_contactId
= $this->individualCreate();
2627 $event = $this->eventCreate();
2628 $this->_eventId
= $event['id'];
2629 $eventParams = array(
2630 'id' => $this->_eventId
,
2631 'financial_type_id' => 4,
2634 $this->callAPISuccess('event', 'create', $eventParams);
2635 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2636 $participantParams = array(
2637 'financial_type_id' => 4,
2638 'event_id' => $this->_eventId
,
2641 'fee_currency' => 'USD',
2642 'contact_id' => $this->_contactId
,
2644 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2645 $contributionParams = array(
2646 'total_amount' => 150,
2647 'currency' => 'USD',
2648 'contact_id' => $this->_contactId
,
2649 'financial_type_id' => 4,
2650 'contribution_status_id' => 1,
2651 'partial_payment_total' => 300.00,
2652 'partial_amount_to_pay' => 150,
2653 'contribution_mode' => 'participant',
2654 'participant_id' => $participant['id'],
2656 foreach ($priceFields['values'] as $key => $priceField) {
2657 $lineItems[1][$key] = array(
2658 'price_field_id' => $priceField['price_field_id'],
2659 'price_field_value_id' => $priceField['id'],
2660 'label' => $priceField['label'],
2661 'field_title' => $priceField['label'],
2663 'unit_price' => $priceField['amount'],
2664 'line_total' => $priceField['amount'],
2665 'financial_type_id' => $priceField['financial_type_id'],
2668 $contributionParams['line_item'] = $lineItems;
2669 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2670 $paymentParticipant = array(
2671 'participant_id' => $participant['id'],
2672 'contribution_id' => $contribution['id'],
2674 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2675 return array($lineItems, $contribution);
2681 * @param string $component
2682 * @param int $componentId
2683 * @param array $priceFieldOptions
2687 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2688 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2689 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2690 $paramsSet['is_active'] = TRUE;
2691 $paramsSet['financial_type_id'] = 'Event Fee';
2692 $paramsSet['extends'] = 1;
2693 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2694 $priceSetId = $priceSet['id'];
2695 //Checking for priceset added in the table.
2696 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2697 'id', $paramsSet['title'], 'Check DB for created priceset'
2699 $paramsField = array_merge(array(
2700 'label' => 'Price Field',
2701 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2702 'html_type' => 'CheckBox',
2703 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2704 'option_value' => array('1' => 100, '2' => 200),
2705 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2706 'option_weight' => array('1' => 1, '2' => 2),
2707 'option_amount' => array('1' => 100, '2' => 200),
2708 'is_display_amounts' => 1,
2710 'options_per_line' => 1,
2711 'is_active' => array('1' => 1, '2' => 1),
2712 'price_set_id' => $priceSet['id'],
2713 'is_enter_qty' => 1,
2714 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2715 ), $priceFieldOptions);
2717 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2719 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2721 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2725 * Replace the template with a test-oriented template designed to show all the variables.
2727 * @param string $templateName
2729 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2730 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2731 CRM_Core_DAO
::executeQuery(
2732 "UPDATE civicrm_option_group og
2733 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2734 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2735 SET m.msg_html = '{$testTemplate}'
2736 WHERE og.name = 'msg_tpl_workflow_contribution'
2737 AND ov.name = '{$templateName}'
2738 AND m.is_default = 1"
2743 * Reinstate the default template.
2745 * @param string $templateName
2747 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2748 CRM_Core_DAO
::executeQuery(
2749 "UPDATE civicrm_option_group og
2750 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2751 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2752 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2753 SET m.msg_html = m2.msg_html
2754 WHERE og.name = 'msg_tpl_workflow_contribution'
2755 AND ov.name = '{$templateName}'
2756 AND m.is_default = 1"
2761 * Flush statics relating to financial type.
2763 protected function flushFinancialTypeStatics() {
2764 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2765 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2767 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2768 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2770 CRM_Contribute_PseudoConstant
::flush('financialType');
2771 CRM_Contribute_PseudoConstant
::flush('membershipType');
2772 // Pseudoconstants may be saved to the cache table.
2773 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2774 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2775 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2779 * Set the permissions to the supplied array.
2781 * @param array $permissions
2783 protected function setPermissions($permissions) {
2784 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2785 $this->flushFinancialTypeStatics();
2789 * @param array $params
2792 public function _checkFinancialRecords($params, $context) {
2793 $entityParams = array(
2794 'entity_id' => $params['id'],
2795 'entity_table' => 'civicrm_contribution',
2797 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2798 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2799 if ($context == 'pending') {
2800 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2801 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2804 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2805 $trxnParams = array(
2806 'id' => $trxn['financial_trxn_id'],
2808 if ($context != 'online' && $context != 'payLater') {
2809 $compareParams = array(
2810 'to_financial_account_id' => 6,
2811 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2815 if ($context == 'feeAmount') {
2816 $compareParams['fee_amount'] = 50;
2818 elseif ($context == 'online') {
2819 $compareParams = array(
2820 'to_financial_account_id' => 12,
2821 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2823 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2826 elseif ($context == 'payLater') {
2827 $compareParams = array(
2828 'to_financial_account_id' => 7,
2829 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2833 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2834 $entityParams = array(
2835 'financial_trxn_id' => $trxn['financial_trxn_id'],
2836 'entity_table' => 'civicrm_financial_item',
2838 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2839 $fitemParams = array(
2840 'id' => $entityTrxn['entity_id'],
2842 $compareParams = array(
2843 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2845 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2847 if ($context == 'payLater') {
2848 $compareParams = array(
2849 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2851 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2854 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2855 if ($context == 'feeAmount') {
2857 'entity_id' => $params['id'],
2858 'entity_table' => 'civicrm_contribution',
2860 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2861 $trxnParams = array(
2862 'id' => $maxTrxn['financial_trxn_id'],
2864 $compareParams = array(
2865 'to_financial_account_id' => 5,
2866 'from_financial_account_id' => 6,
2867 'total_amount' => 50,
2870 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2871 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2872 $fitemParams = array(
2873 'entity_id' => $trxnId['financialTrxnId'],
2874 'entity_table' => 'civicrm_financial_trxn',
2876 $compareParams = array(
2879 'financial_account_id' => 5,
2881 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2883 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2884 // line should be copied into all the functions that call this function & evaluated there
2885 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2886 // when calling completeTransaction or repeatTransaction.
2887 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2891 * Return financial type id on basis of name
2893 * @param string $name Financial type m/c name
2897 public function getFinancialTypeId($name) {
2898 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2902 * Cleanup function for contents of $this->ids.
2904 * This is a best effort cleanup to use in tear downs etc.
2906 * It will not fail if the data has already been removed (some tests may do
2907 * their own cleanup).
2909 protected function cleanUpSetUpIDs() {
2910 foreach ($this->setupIDs
as $entity => $id) {
2912 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2914 catch (CiviCRM_API3_Exception
$e) {
2915 // This is a best-effort cleanup function, ignore.
2921 * Create Financial Type.
2923 * @param array $params
2927 protected function createFinancialType($params = array()) {
2928 $params = array_merge($params,
2930 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2934 return $this->callAPISuccess('FinancialType', 'create', $params);
2938 * Create Payment Instrument.
2940 * @param array $params
2941 * @param string $financialAccountName
2945 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2946 $params = array_merge(array(
2947 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2948 'option_group_id' => 'payment_instrument',
2951 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2953 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2955 $financialAccountParams = [
2956 'entity_table' => 'civicrm_option_value',
2957 'entity_id' => $newPaymentInstrument,
2958 'account_relationship' => $relationTypeID,
2959 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2961 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2963 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2967 * Enable Tax and Invoicing
2969 protected function enableTaxAndInvoicing($params = array()) {
2970 // Enable component contribute setting
2971 $contributeSetting = array_merge($params,
2974 'invoice_prefix' => 'INV_',
2975 'credit_notes_prefix' => 'CN_',
2977 'due_date_period' => 'days',
2979 'is_email_pdf' => 1,
2980 'tax_term' => 'Sales Tax',
2981 'tax_display_settings' => 'Inclusive',
2984 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2988 * Enable Tax and Invoicing
2990 protected function disableTaxAndInvoicing($params = array()) {
2991 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2992 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2994 // Enable component contribute setting
2995 $contributeSetting = array_merge($params,
3000 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3004 * Add Sales Tax relation for financial type with financial account.
3006 * @param int $financialTypeId
3010 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3012 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3013 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3014 'is_deductible' => 1,
3019 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3020 $entityParams = array(
3021 'entity_table' => 'civicrm_financial_type',
3022 'entity_id' => $financialTypeId,
3023 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3026 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3027 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3029 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3030 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3031 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3032 $dao->copyValues($entityParams);
3034 if ($dao->fetch()) {
3035 $entityParams['id'] = $dao->id
;
3037 $entityParams['financial_account_id'] = $account->id
;
3039 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3043 * Create price set with contribution test for test setup.
3045 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3046 * on parent class at some point (fn is not in 4.4).
3049 * @param array $params
3051 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3052 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3053 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3054 'title' => "Test Contribution Page",
3055 'financial_type_id' => 1,
3056 'currency' => 'NZD',
3057 'goal_amount' => 50,
3058 'is_pay_later' => 1,
3059 'is_monetary' => TRUE,
3060 'is_email_receipt' => FALSE,
3062 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3063 'is_quick_config' => 0,
3064 'extends' => 'CiviMember',
3065 'financial_type_id' => 1,
3066 'title' => 'my Page',
3068 $priceSetID = $priceSet['id'];
3070 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3071 $priceField = $this->callAPISuccess('price_field', 'create', array(
3072 'price_set_id' => $priceSetID,
3073 'label' => 'Goat Breed',
3074 'html_type' => 'Radio',
3076 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3077 'price_set_id' => $priceSetID,
3078 'price_field_id' => $priceField['id'],
3079 'label' => 'Long Haired Goat',
3081 'financial_type_id' => 'Donation',
3082 'membership_type_id' => $membershipTypeID,
3083 'membership_num_terms' => 1,
3085 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3086 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3087 'price_set_id' => $priceSetID,
3088 'price_field_id' => $priceField['id'],
3089 'label' => 'Shoe-eating Goat',
3091 'financial_type_id' => 'Donation',
3092 'membership_type_id' => $membershipTypeID,
3093 'membership_num_terms' => 2,
3095 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3097 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3098 'price_set_id' => $priceSetID,
3099 'price_field_id' => $priceField['id'],
3100 'label' => 'Shoe-eating Goat',
3102 'financial_type_id' => 'Donation',
3104 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3106 $this->_ids
['price_set'] = $priceSetID;
3107 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3108 $this->_ids
['price_field'] = array($priceField['id']);
3110 $this->_ids
['membership_type'] = $membershipTypeID;
3114 * Only specified contact returned.
3115 * @implements CRM_Utils_Hook::aclWhereClause
3118 * @param $whereTables
3122 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3123 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3127 * @implements CRM_Utils_Hook::selectWhereClause
3129 * @param string $entity
3130 * @param array $clauses
3132 public function selectWhereClauseHook($entity, &$clauses) {
3133 if ($entity == 'Event') {
3134 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3139 * An implementation of hook_civicrm_post used with all our test cases.
3142 * @param string $objectName
3143 * @param int $objectId
3146 public function onPost($op, $objectName, $objectId, &$objectRef) {
3147 if ($op == 'create' && $objectName == 'Individual') {
3148 CRM_Core_DAO
::executeQuery(
3149 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3151 1 => array($objectId, 'Integer'),
3156 if ($op == 'edit' && $objectName == 'Participant') {
3158 1 => array($objectId, 'Integer'),
3160 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3161 CRM_Core_DAO
::executeQuery($query, $params);
3166 * Instantiate form object.
3168 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3170 * @param string $class
3171 * Name of form class.
3173 * @param array $formValues
3175 * @param string $pageName
3177 * @return \CRM_Core_Form
3178 * @throws \CRM_Core_Exception
3180 public function getFormObject($class, $formValues = [], $pageName = '') {
3181 $form = new $class();
3182 $_SERVER['REQUEST_METHOD'] = 'GET';
3183 $form->controller
= new CRM_Core_Controller();
3184 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3185 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3190 * Get possible thousand separators.
3194 public function getThousandSeparators() {
3195 return array(array('.'), array(','));
3199 * Get the boolean options as a provider.
3203 public function getBooleanDataProvider() {
3204 return [[TRUE], [FALSE]];
3208 * Set the separators for thousands and decimal points.
3210 * @param string $thousandSeparator
3212 protected function setCurrencySeparators($thousandSeparator) {
3213 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3215 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3219 * Format money as it would be input.
3221 * @param string $amount
3225 protected function formatMoneyInput($amount) {
3226 return CRM_Utils_Money
::format($amount, NULL, '%a');
3230 * Get the contribution object.
3232 * @param int $contributionID
3234 * @return \CRM_Contribute_BAO_Contribution
3236 protected function getContributionObject($contributionID) {
3237 $contributionObj = new CRM_Contribute_BAO_Contribution();
3238 $contributionObj->id
= $contributionID;
3239 $contributionObj->find(TRUE);
3240 return $contributionObj;
3244 * Enable multilingual.
3246 public function enableMultilingual() {
3247 $this->callAPISuccess('Setting', 'create', array(
3248 'lcMessages' => 'en_US',
3249 'languageLimit' => array(
3254 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3257 $dbLocale = '_en_US';
3261 * Setup or clean up SMS tests
3262 * @param bool $teardown
3264 * @throws \CiviCRM_API3_Exception
3266 public function setupForSmsTests($teardown = FALSE) {
3267 require_once 'CiviTest/CiviTestSMSProvider.php';
3269 // Option value params for CiviTestSMSProvider
3270 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3272 'option_group_id' => $groupID,
3273 'label' => 'unittestSMS',
3274 'value' => 'unit.test.sms',
3275 'name' => 'CiviTestSMSProvider',
3282 // Test completed, delete provider
3283 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3284 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3288 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3289 // in CRM/Sms/Provider.php even though it is not an extension.
3290 return civicrm_api3('option_value', 'create', $params);
3294 * Start capturing browser output.
3296 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3298 protected function startCapturingOutput() {
3300 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3304 * Stop capturing browser output and return as a csv.
3306 * @param bool $isFirstRowHeaders
3308 * @return \League\Csv\Reader
3310 * @throws \League\Csv\Exception
3312 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3313 $output = ob_get_flush();
3314 $stream = fopen('php://memory', 'r+');
3315 fwrite($stream, $output);
3317 $csv = Reader
::createFromString($output);
3318 if ($isFirstRowHeaders) {
3319 $csv->setHeaderOffset(0);
3326 * Rename various labels to not match the names.
3328 * Doing these mimics the fact the name != the label in international installs & triggers failures in
3329 * code that expects it to.
3331 protected function renameLabels() {
3332 $replacements = ['Pending', 'Refunded'];
3333 foreach ($replacements as $name) {
3334 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = '{$name} Label**' where label = '{$name}' AND name = '{$name}'");
3339 * Undo any label renaming.
3341 protected function resetLabels() {
3342 CRM_Core_DAO
::executeQuery("UPDATE civicrm_option_value SET label = REPLACE(name, ' Label**', '') WHERE label LIKE '% Label**'");