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 $extensions = \CRM_Extension_System
::singleton()->getManager();
338 $api4Status = $extensions->getStatus('org.civicrm.api4');
339 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
340 $extensions->enable(['org.civicrm.api4']);
343 // reset all the caches
344 CRM_Utils_System
::flushCache();
346 // initialize the object once db is loaded
347 \Civi
::$statics = array();
349 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
351 // when running unit tests, use mockup user framework
352 $this->hookClass
= CRM_Utils_Hook
::singleton();
354 // Make sure the DB connection is setup properly
355 $config->userSystem
->setMySQLTimeZone();
356 $env = new CRM_Utils_Check_Component_Env();
357 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
359 // clear permissions stub to not check permissions
360 $config->userPermissionClass
->permissions
= NULL;
362 //flush component settings
363 CRM_Core_Component
::getEnabledComponents(TRUE);
365 $_REQUEST = $_GET = $_POST = [];
366 error_reporting(E_ALL
);
368 $this->_sethtmlGlobals();
372 * Read everything from the datasets directory and insert into the db.
374 public function loadAllFixtures() {
375 $fixturesDir = __DIR__
. '/../../fixtures';
377 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
379 $jsonFiles = glob($fixturesDir . '/*.json');
380 foreach ($jsonFiles as $jsonFixture) {
381 $json = json_decode(file_get_contents($jsonFixture));
382 foreach ($json as $tableName => $vars) {
383 if ($tableName === 'civicrm_contact') {
384 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');
387 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
389 foreach ($vars as $entity) {
390 $keys = $values = [];
391 foreach ($entity as $key => $value) {
393 $values[] = is_numeric($value) ?
$value : "'{$value}'";
395 CRM_Core_DAO
::executeQuery("
396 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
403 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
407 * Load the data that used to be handled by the discontinued dbunit class.
409 * This could do with further tidy up - the initial priority is simply to get rid of
410 * the dbunity package which is no longer supported.
412 * @param string $fileName
414 protected function loadXMLDataSet($fileName) {
415 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
416 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
417 foreach ($xml as $tableName => $element) {
418 if (!empty($element)) {
419 foreach ($element as $row) {
420 $keys = $values = [];
421 if (isset($row['@attributes'])) {
422 foreach ($row['@attributes'] as $key => $value) {
424 $values[] = is_numeric($value) ?
$value : "'{$value}'";
427 elseif (!empty($row)) {
428 // cos we copied it & it is inconsistent....
429 foreach ($row as $key => $value) {
431 $values[] = is_numeric($value) ?
$value : "'{$value}'";
435 if (!empty($values)) {
436 CRM_Core_DAO
::executeQuery("
437 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
443 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
447 * Create default domain contacts for the two domains added during test class.
448 * database population.
450 public function createDomainContacts() {
451 $this->organizationCreate();
452 $this->organizationCreate(array('organization_name' => 'Second Domain'));
456 * Common teardown functions for all unit tests.
458 protected function tearDown() {
459 $this->_apiversion
= 3;
461 error_reporting(E_ALL
& ~E_NOTICE
);
462 CRM_Utils_Hook
::singleton()->reset();
463 if ($this->hookClass
) {
464 $this->hookClass
->reset();
466 CRM_Core_Session
::singleton()->reset(1);
469 $this->tx
->rollback()->commit();
472 CRM_Core_Transaction
::forceRollbackIfEnabled();
473 \Civi\Core\Transaction\Manager
::singleton(TRUE);
476 CRM_Core_Transaction
::forceRollbackIfEnabled();
477 \Civi\Core\Transaction\Manager
::singleton(TRUE);
479 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
480 $this->quickCleanup($tablesToTruncate);
481 $this->createDomainContacts();
484 $this->cleanTempDirs();
485 $this->unsetExtensionSystem();
486 $this->assertEquals([], CRM_Core_DAO
::$_nullArray);
487 $this->assertEquals(NULL, CRM_Core_DAO
::$_nullObject);
491 * Create a batch of external API calls which can
492 * be executed concurrently.
495 * $calls = $this->createExternalAPI()
496 * ->addCall('Contact', 'get', ...)
497 * ->addCall('Contact', 'get', ...)
503 * @return \Civi\API\ExternalBatch
504 * @throws PHPUnit_Framework_SkippedTestError
506 public function createExternalAPI() {
507 global $civicrm_root;
508 $defaultParams = array(
509 'version' => $this->_apiversion
,
513 $calls = new \Civi\API\
ExternalBatch($defaultParams);
515 if (!$calls->isSupported()) {
516 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
523 * Create required data based on $this->entity & $this->params
524 * This is just a way to set up the test data for delete & get functions
525 * so the distinction between set
526 * up & tested functions is clearer
531 public function createTestEntity() {
532 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
536 * @param int $contactTypeId
540 public function contactTypeDelete($contactTypeId) {
541 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
543 throw new Exception('Could not delete contact type');
548 * @param array $params
552 public function membershipTypeCreate($params = array()) {
553 CRM_Member_PseudoConstant
::flush('membershipType');
554 CRM_Core_Config
::clearDBCache();
555 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
556 $params = array_merge(array(
558 'duration_unit' => 'year',
559 'duration_interval' => 1,
560 'period_type' => 'rolling',
561 'member_of_contact_id' => $memberOfOrganization,
563 'financial_type_id' => 2,
566 'visibility' => 'Public',
569 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
571 CRM_Member_PseudoConstant
::flush('membershipType');
572 CRM_Utils_Cache
::singleton()->flush();
574 return $result['id'];
578 * @param array $params
582 public function contactMembershipCreate($params) {
583 $params = array_merge(array(
584 'join_date' => '2007-01-21',
585 'start_date' => '2007-01-21',
586 'end_date' => '2007-12-21',
587 'source' => 'Payment',
588 'membership_type_id' => 'General',
590 if (!is_numeric($params['membership_type_id'])) {
591 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
592 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
593 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
597 $result = $this->callAPISuccess('Membership', 'create', $params);
598 return $result['id'];
602 * Delete Membership Type.
604 * @param array $params
606 public function membershipTypeDelete($params) {
607 $this->callAPISuccess('MembershipType', 'Delete', $params);
611 * @param int $membershipID
613 public function membershipDelete($membershipID) {
614 $deleteParams = array('id' => $membershipID);
615 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
619 * @param string $name
623 public function membershipStatusCreate($name = 'test member status') {
624 $params['name'] = $name;
625 $params['start_event'] = 'start_date';
626 $params['end_event'] = 'end_date';
627 $params['is_current_member'] = 1;
628 $params['is_active'] = 1;
630 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
631 CRM_Member_PseudoConstant
::flush('membershipStatus');
632 return $result['id'];
636 * @param int $membershipStatusID
638 public function membershipStatusDelete($membershipStatusID) {
639 if (!$membershipStatusID) {
642 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
645 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
646 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
647 $renewedMembershipEndDate = new DateTime($membershipEndDate);
648 switch ($durationUnit) {
650 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
654 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
655 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
656 $renewedMembershipEndDate->add(new DateInterval('P1D'));
657 $renewedMembershipEndDate->add(new DateInterval('P1M'));
658 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
661 return $renewedMembershipEndDate->format('Y-m-d');
665 * @param array $params
669 public function relationshipTypeCreate($params = array()) {
670 $params = array_merge(array(
671 'name_a_b' => 'Relation 1 for relationship type create',
672 'name_b_a' => 'Relation 2 for relationship type create',
673 'contact_type_a' => 'Individual',
674 'contact_type_b' => 'Organization',
679 $result = $this->callAPISuccess('relationship_type', 'create', $params);
680 CRM_Core_PseudoConstant
::flush('relationshipType');
682 return $result['id'];
686 * Delete Relatinship Type.
688 * @param int $relationshipTypeID
690 public function relationshipTypeDelete($relationshipTypeID) {
691 $params['id'] = $relationshipTypeID;
692 $check = $this->callAPISuccess('relationship_type', 'get', $params);
693 if (!empty($check['count'])) {
694 $this->callAPISuccess('relationship_type', 'delete', $params);
699 * @param array $params
703 public function paymentProcessorTypeCreate($params = NULL) {
704 if (is_null($params)) {
706 'name' => 'API_Test_PP',
707 'title' => 'API Test Payment Processor',
708 'class_name' => 'CRM_Core_Payment_APITest',
709 'billing_mode' => 'form',
715 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
717 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
719 return $result['id'];
723 * Create test Authorize.net instance.
725 * @param array $params
729 public function paymentProcessorAuthorizeNetCreate($params = array()) {
730 $params = array_merge(array(
731 'name' => 'Authorize',
732 'domain_id' => CRM_Core_Config
::domainID(),
733 'payment_processor_type_id' => 'AuthNet',
734 'title' => 'AuthNet',
739 'user_name' => '4y5BfuW7jm',
740 'password' => '4cAmW927n8uLf5J8',
741 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
742 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
743 'class_name' => 'Payment_AuthorizeNet',
747 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
748 return $result['id'];
752 * Create Participant.
754 * @param array $params
755 * Array of contact id and event id values.
758 * $id of participant created
760 public function participantCreate($params = []) {
761 if (empty($params['contact_id'])) {
762 $params['contact_id'] = $this->individualCreate();
764 if (empty($params['event_id'])) {
765 $event = $this->eventCreate();
766 $params['event_id'] = $event['id'];
771 'register_date' => 20070219,
772 'source' => 'Wimbeldon',
773 'event_level' => 'Payment',
777 $params = array_merge($defaults, $params);
778 $result = $this->callAPISuccess('Participant', 'create', $params);
779 return $result['id'];
783 * Create Payment Processor.
786 * Id Payment Processor
788 public function processorCreate($params = array()) {
789 $processorParams = array(
792 'payment_processor_type_id' => 'Dummy',
793 'financial_account_id' => 12,
797 'url_site' => 'http://dummy.com',
798 'url_recur' => 'http://dummy.com',
801 'payment_instrument_id' => 'Debit Card',
803 $processorParams = array_merge($processorParams, $params);
804 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
805 return $processor['id'];
809 * Create Payment Processor.
811 * @param array $processorParams
813 * @return \CRM_Core_Payment_Dummy
814 * Instance of Dummy Payment Processor
816 public function dummyProcessorCreate($processorParams = array()) {
817 $paymentProcessorID = $this->processorCreate($processorParams);
818 return System
::singleton()->getById($paymentProcessorID);
822 * Create contribution page.
824 * @param array $params
826 * Array of contribution page
828 public function contributionPageCreate($params = array()) {
829 $this->_pageParams
= array_merge(array(
830 'title' => 'Test Contribution Page',
831 'financial_type_id' => 1,
833 'financial_account_id' => 1,
835 'is_allow_other_amount' => 1,
837 'max_amount' => 1000,
839 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
843 * Create a sample batch.
845 public function batchCreate() {
846 $params = $this->_params
;
847 $params['name'] = $params['title'] = 'Batch_433397';
848 $params['status_id'] = 1;
849 $result = $this->callAPISuccess('batch', 'create', $params);
850 return $result['id'];
856 * @param array $params
858 * result of created tag
860 public function tagCreate($params = array()) {
862 'name' => 'New Tag3',
863 'description' => 'This is description for Our New Tag ',
866 $params = array_merge($defaults, $params);
867 $result = $this->callAPISuccess('Tag', 'create', $params);
868 return $result['values'][$result['id']];
875 * Id of the tag to be deleted.
879 public function tagDelete($tagId) {
880 require_once 'api/api.php';
884 $result = $this->callAPISuccess('Tag', 'delete', $params);
885 return $result['id'];
889 * Add entity(s) to the tag
891 * @param array $params
895 public function entityTagAdd($params) {
896 $result = $this->callAPISuccess('entity_tag', 'create', $params);
903 * @param array $params
907 * id of created pledge
909 public function pledgeCreate($params) {
910 $params = array_merge(array(
911 'pledge_create_date' => date('Ymd'),
912 'start_date' => date('Ymd'),
913 'scheduled_date' => date('Ymd'),
915 'pledge_status_id' => '2',
916 'financial_type_id' => '1',
917 'pledge_original_installment_amount' => 20,
918 'frequency_interval' => 5,
919 'frequency_unit' => 'year',
920 'frequency_day' => 15,
925 $result = $this->callAPISuccess('Pledge', 'create', $params);
926 return $result['id'];
930 * Delete contribution.
932 * @param int $pledgeId
934 public function pledgeDelete($pledgeId) {
936 'pledge_id' => $pledgeId,
938 $this->callAPISuccess('Pledge', 'delete', $params);
942 * Create contribution.
944 * @param array $params
945 * Array of parameters.
948 * id of created contribution
950 public function contributionCreate($params) {
952 $params = array_merge(array(
954 'receive_date' => date('Ymd'),
955 'total_amount' => 100.00,
956 'fee_amount' => 5.00,
957 'financial_type_id' => 1,
958 'payment_instrument_id' => 1,
959 'non_deductible_amount' => 10.00,
961 'contribution_status_id' => 1,
964 $result = $this->callAPISuccess('contribution', 'create', $params);
965 return $result['id'];
969 * Delete contribution.
971 * @param int $contributionId
975 public function contributionDelete($contributionId) {
977 'contribution_id' => $contributionId,
979 $result = $this->callAPISuccess('contribution', 'delete', $params);
986 * @param array $params
987 * Name-value pair for an event.
991 public function eventCreate($params = array()) {
992 // if no contact was passed, make up a dummy event creator
993 if (!isset($params['contact_id'])) {
994 $params['contact_id'] = $this->_contactCreate(array(
995 'contact_type' => 'Individual',
996 'first_name' => 'Event',
997 'last_name' => 'Creator',
1001 // set defaults for missing params
1002 $params = array_merge(array(
1003 'title' => 'Annual CiviCRM meet',
1004 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1005 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1006 'event_type_id' => 1,
1008 'start_date' => 20081021,
1009 'end_date' => 20081023,
1010 'is_online_registration' => 1,
1011 'registration_start_date' => 20080601,
1012 'registration_end_date' => 20081015,
1013 'max_participants' => 100,
1014 'event_full_text' => 'Sorry! We are already full',
1017 'is_show_location' => 0,
1020 return $this->callAPISuccess('Event', 'create', $params);
1024 * Create a paid event.
1026 * @param array $params
1030 protected function eventCreatePaid($params) {
1031 $event = $this->eventCreate($params);
1032 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1033 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1034 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1035 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1036 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1048 public function eventDelete($id) {
1052 return $this->callAPISuccess('event', 'delete', $params);
1056 * Delete participant.
1058 * @param int $participantID
1062 public function participantDelete($participantID) {
1064 'id' => $participantID,
1066 $check = $this->callAPISuccess('Participant', 'get', $params);
1067 if ($check['count'] > 0) {
1068 return $this->callAPISuccess('Participant', 'delete', $params);
1073 * Create participant payment.
1075 * @param int $participantID
1076 * @param int $contributionID
1078 * $id of created payment
1080 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1081 //Create Participant Payment record With Values
1083 'participant_id' => $participantID,
1084 'contribution_id' => $contributionID,
1087 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1088 return $result['id'];
1092 * Delete participant payment.
1094 * @param int $paymentID
1096 public function participantPaymentDelete($paymentID) {
1100 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1106 * @param int $contactID
1108 * location id of created location
1110 public function locationAdd($contactID) {
1113 'location_type' => 'New Location Type',
1115 'name' => 'Saint Helier St',
1116 'county' => 'Marin',
1117 'country' => 'UNITED STATES',
1118 'state_province' => 'Michigan',
1119 'supplemental_address_1' => 'Hallmark Ct',
1120 'supplemental_address_2' => 'Jersey Village',
1121 'supplemental_address_3' => 'My Town',
1126 'contact_id' => $contactID,
1127 'address' => $address,
1128 'location_format' => '2.0',
1129 'location_type' => 'New Location Type',
1132 $result = $this->callAPISuccess('Location', 'create', $params);
1137 * Delete Locations of contact.
1139 * @param array $params
1142 public function locationDelete($params) {
1143 $this->callAPISuccess('Location', 'delete', $params);
1147 * Add a Location Type.
1149 * @param array $params
1150 * @return CRM_Core_DAO_LocationType
1151 * location id of created location
1153 public function locationTypeCreate($params = NULL) {
1154 if ($params === NULL) {
1156 'name' => 'New Location Type',
1157 'vcard_name' => 'New Location Type',
1158 'description' => 'Location Type for Delete',
1163 $locationType = new CRM_Core_DAO_LocationType();
1164 $locationType->copyValues($params);
1165 $locationType->save();
1166 // clear getfields cache
1167 CRM_Core_PseudoConstant
::flush();
1168 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1169 return $locationType;
1173 * Delete a Location Type.
1175 * @param int $locationTypeId
1177 public function locationTypeDelete($locationTypeId) {
1178 $locationType = new CRM_Core_DAO_LocationType();
1179 $locationType->id
= $locationTypeId;
1180 $locationType->delete();
1186 * @param array $params
1187 * @return CRM_Core_DAO_Mapping
1188 * Mapping id of created mapping
1190 public function mappingCreate($params = NULL) {
1191 if ($params === NULL) {
1193 'name' => 'Mapping name',
1194 'description' => 'Mapping description',
1195 // 'Export Contact' mapping.
1196 'mapping_type_id' => 7,
1200 $mapping = new CRM_Core_DAO_Mapping();
1201 $mapping->copyValues($params);
1203 // clear getfields cache
1204 CRM_Core_PseudoConstant
::flush();
1205 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1212 * @param int $mappingId
1214 public function mappingDelete($mappingId) {
1215 $mapping = new CRM_Core_DAO_Mapping();
1216 $mapping->id
= $mappingId;
1221 * Prepare class for ACLs.
1223 protected function prepareForACLs() {
1224 $config = CRM_Core_Config
::singleton();
1225 $config->userPermissionClass
->permissions
= array();
1231 protected function cleanUpAfterACLs() {
1232 CRM_Utils_Hook
::singleton()->reset();
1233 $tablesToTruncate = array(
1235 'civicrm_acl_cache',
1236 'civicrm_acl_entity_role',
1237 'civicrm_acl_contact_cache',
1239 $this->quickCleanup($tablesToTruncate);
1240 $config = CRM_Core_Config
::singleton();
1241 unset($config->userPermissionClass
->permissions
);
1245 * Create a smart group.
1247 * By default it will be a group of households.
1249 * @param array $smartGroupParams
1250 * @param array $groupParams
1251 * @param string $contactType
1255 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1256 $smartGroupParams = array_merge([
1257 'formValues' => ['contact_type' => ['IN' => [$contactType]]],
1260 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1262 $groupParams['saved_search_id'] = $savedSearch->id
;
1263 return $this->groupCreate($groupParams);
1268 * @param array $params
1270 public function uFFieldCreate($params = array()) {
1271 $params = array_merge(array(
1273 'field_name' => 'first_name',
1276 'visibility' => 'Public Pages and Listings',
1277 'is_searchable' => '1',
1278 'label' => 'first_name',
1279 'field_type' => 'Individual',
1282 $this->callAPISuccess('uf_field', 'create', $params);
1286 * Add a UF Join Entry.
1288 * @param array $params
1290 * $id of created UF Join
1292 public function ufjoinCreate($params = NULL) {
1293 if ($params === NULL) {
1296 'module' => 'CiviEvent',
1297 'entity_table' => 'civicrm_event',
1303 $result = $this->callAPISuccess('uf_join', 'create', $params);
1308 * @param array $params
1309 * Optional parameters.
1310 * @param bool $reloadConfig
1311 * While enabling CiviCampaign component, we shouldn't always forcibly
1312 * reload config as this hinder hook call in test environment
1317 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1318 $this->enableCiviCampaign($reloadConfig);
1319 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1320 'name' => 'big_campaign',
1321 'title' => 'Campaign',
1323 return $campaign['id'];
1327 * Create Group for a contact.
1329 * @param int $contactId
1331 public function contactGroupCreate($contactId) {
1333 'contact_id.1' => $contactId,
1337 $this->callAPISuccess('GroupContact', 'Create', $params);
1341 * Delete Group for a contact.
1343 * @param int $contactId
1345 public function contactGroupDelete($contactId) {
1347 'contact_id.1' => $contactId,
1350 $this->civicrm_api('GroupContact', 'Delete', $params);
1356 * @param array $params
1359 public function activityCreate($params = array()) {
1360 $params = array_merge(array(
1361 'subject' => 'Discussion on warm beer',
1362 'activity_date_time' => date('Ymd'),
1363 'duration_hours' => 30,
1364 'duration_minutes' => 20,
1365 'location' => 'Baker Street',
1366 'details' => 'Lets schedule a meeting',
1368 'activity_type_id' => 'Meeting',
1370 if (!isset($params['source_contact_id'])) {
1371 $params['source_contact_id'] = $this->individualCreate();
1373 if (!isset($params['target_contact_id'])) {
1374 $params['target_contact_id'] = $this->individualCreate(array(
1375 'first_name' => 'Julia',
1376 'Last_name' => 'Anderson',
1378 'email' => 'julia_anderson@civicrm.org',
1379 'contact_type' => 'Individual',
1382 if (!isset($params['assignee_contact_id'])) {
1383 $params['assignee_contact_id'] = $params['target_contact_id'];
1386 $result = civicrm_api3('Activity', 'create', $params);
1388 $result['target_contact_id'] = $params['target_contact_id'];
1389 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1394 * Create an activity type.
1396 * @param array $params
1400 public function activityTypeCreate($params) {
1401 return $this->callAPISuccess('ActivityType', 'create', $params);
1405 * Delete activity type.
1407 * @param int $activityTypeId
1408 * Id of the activity type.
1411 public function activityTypeDelete($activityTypeId) {
1412 $params['activity_type_id'] = $activityTypeId;
1413 return $this->callAPISuccess('ActivityType', 'delete', $params);
1417 * Create custom group.
1419 * @param array $params
1422 public function customGroupCreate($params = array()) {
1424 'title' => 'new custom group',
1425 'extends' => 'Contact',
1427 'style' => 'Inline',
1431 $params = array_merge($defaults, $params);
1433 return $this->callAPISuccess('custom_group', 'create', $params);
1437 * Existing function doesn't allow params to be over-ridden so need a new one
1438 * this one allows you to only pass in the params you want to change
1439 * @param array $params
1442 public function CustomGroupCreateByParams($params = array()) {
1444 'title' => "API Custom Group",
1445 'extends' => 'Contact',
1447 'style' => 'Inline',
1450 $params = array_merge($defaults, $params);
1451 return $this->callAPISuccess('custom_group', 'create', $params);
1455 * Create custom group with multi fields.
1456 * @param array $params
1459 public function CustomGroupMultipleCreateByParams($params = array()) {
1464 $params = array_merge($defaults, $params);
1465 return $this->CustomGroupCreateByParams($params);
1469 * Create custom group with multi fields.
1470 * @param array $params
1473 public function CustomGroupMultipleCreateWithFields($params = array()) {
1474 // also need to pass on $params['custom_field'] if not set but not in place yet
1476 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1477 $ids['custom_group_id'] = $customGroup['id'];
1479 $customField = $this->customFieldCreate(array(
1480 'custom_group_id' => $ids['custom_group_id'],
1481 'label' => 'field_1' . $ids['custom_group_id'],
1485 $ids['custom_field_id'][] = $customField['id'];
1487 $customField = $this->customFieldCreate(array(
1488 'custom_group_id' => $ids['custom_group_id'],
1489 'default_value' => '',
1490 'label' => 'field_2' . $ids['custom_group_id'],
1493 $ids['custom_field_id'][] = $customField['id'];
1495 $customField = $this->customFieldCreate(array(
1496 'custom_group_id' => $ids['custom_group_id'],
1497 'default_value' => '',
1498 'label' => 'field_3' . $ids['custom_group_id'],
1501 $ids['custom_field_id'][] = $customField['id'];
1507 * Create a custom group with a single text custom field. See
1508 * participant:testCreateWithCustom for how to use this
1510 * @param string $function
1512 * @param string $filename
1516 * ids of created objects
1518 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1519 $params = array('title' => $function);
1520 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1521 $params['extends'] = $entity ?
$entity : 'Contact';
1522 $customGroup = $this->CustomGroupCreate($params);
1523 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1524 CRM_Core_PseudoConstant
::flush();
1526 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1530 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1531 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1533 * @param string $function
1535 * @param string $filename
1539 * ids of created objects
1541 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1542 $params = array('title' => $function);
1543 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1544 $params['extends'] = $entity ?
$entity : 'Contact';
1545 $customGroup = $this->CustomGroupCreate($params);
1546 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1547 CRM_Core_PseudoConstant
::flush();
1549 'defaultValue' => 'Default Value',
1550 'lowercasevalue' => 'Lowercase Value',
1551 1 => 'Integer Value',
1554 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1555 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1556 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1557 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1558 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1559 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1560 foreach ($options as $option_value => $option_label) {
1561 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1562 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1565 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);
1569 * Delete custom group.
1571 * @param int $customGroupID
1575 public function customGroupDelete($customGroupID) {
1576 $params['id'] = $customGroupID;
1577 return $this->callAPISuccess('custom_group', 'delete', $params);
1581 * Create custom field.
1583 * @param array $params
1584 * (custom_group_id) is required.
1587 public function customFieldCreate($params) {
1588 $params = array_merge(array(
1589 'label' => 'Custom Field',
1590 'data_type' => 'String',
1591 'html_type' => 'Text',
1592 'is_searchable' => 1,
1594 'default_value' => 'defaultValue',
1597 $result = $this->callAPISuccess('custom_field', 'create', $params);
1598 // these 2 functions are called with force to flush static caches
1599 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1600 CRM_Core_Component
::getEnabledComponents(1);
1605 * Delete custom field.
1607 * @param int $customFieldID
1611 public function customFieldDelete($customFieldID) {
1613 $params['id'] = $customFieldID;
1614 return $this->callAPISuccess('custom_field', 'delete', $params);
1623 public function noteCreate($cId) {
1625 'entity_table' => 'civicrm_contact',
1626 'entity_id' => $cId,
1627 'note' => 'hello I am testing Note',
1628 'contact_id' => $cId,
1629 'modified_date' => date('Ymd'),
1630 'subject' => 'Test Note',
1633 return $this->callAPISuccess('Note', 'create', $params);
1637 * Enable CiviCampaign Component.
1639 * @param bool $reloadConfig
1640 * Force relaod config or not
1642 public function enableCiviCampaign($reloadConfig = TRUE) {
1643 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1644 if ($reloadConfig) {
1645 // force reload of config object
1646 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1648 //flush cache by calling with reset
1649 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1653 * Create custom field with Option Values.
1655 * @param array $customGroup
1656 * @param string $name
1657 * Name of custom field.
1658 * @param array $extraParams
1659 * Additional parameters to pass through.
1663 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1664 $fieldParams = array(
1665 'custom_group_id' => $customGroup['id'],
1666 'name' => 'test_custom_group',
1667 'label' => 'Country',
1668 'html_type' => 'Select',
1669 'data_type' => 'String',
1672 'is_searchable' => 0,
1676 $optionGroup = array(
1678 'name' => 'option_group1',
1679 'label' => 'option_group_label1',
1682 $optionValue = array(
1683 'option_label' => array('Label1', 'Label2'),
1684 'option_value' => array('value1', 'value2'),
1685 'option_name' => array($name . '_1', $name . '_2'),
1686 'option_weight' => array(1, 2),
1687 'option_status' => array(1, 1),
1690 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1692 return $this->callAPISuccess('custom_field', 'create', $params);
1700 public function confirmEntitiesDeleted($entities) {
1701 foreach ($entities as $entity) {
1703 $result = $this->callAPISuccess($entity, 'Get', array());
1704 if ($result['error'] == 1 ||
$result['count'] > 0) {
1705 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1713 * Quick clean by emptying tables created for the test.
1715 * @param array $tablesToTruncate
1716 * @param bool $dropCustomValueTables
1717 * @throws \CRM_Core_Exception
1719 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1721 throw new \
CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1723 if ($dropCustomValueTables) {
1724 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1725 while ($optionGroupResult->fetch()) {
1726 if (!empty($optionGroupResult->option_group_id
)) {
1727 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1730 $tablesToTruncate[] = 'civicrm_custom_group';
1731 $tablesToTruncate[] = 'civicrm_custom_field';
1734 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1736 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1737 foreach ($tablesToTruncate as $table) {
1738 $sql = "TRUNCATE TABLE $table";
1739 CRM_Core_DAO
::executeQuery($sql);
1741 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1743 if ($dropCustomValueTables) {
1744 $dbName = self
::getDBName();
1746 SELECT TABLE_NAME as tableName
1747 FROM INFORMATION_SCHEMA.TABLES
1748 WHERE TABLE_SCHEMA = '{$dbName}'
1749 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1752 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1753 while ($tableDAO->fetch()) {
1754 $sql = "DROP TABLE {$tableDAO->tableName}";
1755 CRM_Core_DAO
::executeQuery($sql);
1761 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1763 public function quickCleanUpFinancialEntities() {
1764 $tablesToTruncate = array(
1766 'civicrm_activity_contact',
1767 'civicrm_contribution',
1768 'civicrm_contribution_soft',
1769 'civicrm_contribution_product',
1770 'civicrm_financial_trxn',
1771 'civicrm_financial_item',
1772 'civicrm_contribution_recur',
1773 'civicrm_line_item',
1774 'civicrm_contribution_page',
1775 'civicrm_payment_processor',
1776 'civicrm_entity_financial_trxn',
1777 'civicrm_membership',
1778 'civicrm_membership_type',
1779 'civicrm_membership_payment',
1780 'civicrm_membership_log',
1781 'civicrm_membership_block',
1783 'civicrm_participant',
1784 'civicrm_participant_payment',
1786 'civicrm_pledge_block',
1787 'civicrm_pledge_payment',
1788 'civicrm_price_set_entity',
1789 'civicrm_price_field_value',
1790 'civicrm_price_field',
1792 $this->quickCleanup($tablesToTruncate);
1793 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1794 $this->restoreDefaultPriceSetConfig();
1796 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1797 $this->disableTaxAndInvoicing();
1798 $this->setCurrencySeparators(',');
1799 CRM_Core_PseudoConstant
::flush('taxRates');
1800 System
::singleton()->flushProcessors();
1801 // @fixme this parameter is leaking - it should not be defined as a class static
1802 // but for now we just handle in tear down.
1803 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1806 public function restoreDefaultPriceSetConfig() {
1807 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1808 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1809 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)");
1810 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)");
1814 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1815 * Default behaviour is to also delete the entity
1816 * @param array $params
1817 * Params array to check against.
1819 * Id of the entity concerned.
1820 * @param string $entity
1821 * Name of entity concerned (e.g. membership).
1822 * @param bool $delete
1823 * Should the entity be deleted as part of this check.
1824 * @param string $errorText
1825 * Text to print on error.
1829 * @param array $params
1832 * @param int $delete
1833 * @param string $errorText
1837 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1839 $result = $this->callAPISuccessGetSingle($entity, array(
1844 $this->callAPISuccess($entity, 'Delete', array(
1848 $dateFields = $keys = $dateTimeFields = array();
1849 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1850 foreach ($fields['values'] as $field => $settings) {
1851 if (array_key_exists($field, $result)) {
1852 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1855 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1857 $type = CRM_Utils_Array
::value('type', $settings);
1858 if ($type == CRM_Utils_Type
::T_DATE
) {
1859 $dateFields[] = $settings['name'];
1860 // we should identify both real names & unique names as dates
1861 if ($field != $settings['name']) {
1862 $dateFields[] = $field;
1865 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1866 $dateTimeFields[] = $settings['name'];
1867 // we should identify both real names & unique names as dates
1868 if ($field != $settings['name']) {
1869 $dateTimeFields[] = $field;
1874 if (strtolower($entity) == 'contribution') {
1875 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1876 // this is not returned in id format
1877 unset($params['payment_instrument_id']);
1878 $params['contribution_source'] = $params['source'];
1879 unset($params['source']);
1882 foreach ($params as $key => $value) {
1883 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1886 if (in_array($key, $dateFields)) {
1887 $value = date('Y-m-d', strtotime($value));
1888 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1890 if (in_array($key, $dateTimeFields)) {
1891 $value = date('Y-m-d H:i:s', strtotime($value));
1892 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1894 $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);
1899 * Get formatted values in the actual and expected result.
1900 * @param array $actual
1901 * Actual calculated values.
1902 * @param array $expected
1905 public function checkArrayEquals(&$actual, &$expected) {
1906 self
::unsetId($actual);
1907 self
::unsetId($expected);
1908 $this->assertEquals($expected, $actual);
1912 * Unset the key 'id' from the array
1913 * @param array $unformattedArray
1914 * The array from which the 'id' has to be unset.
1916 public static function unsetId(&$unformattedArray) {
1917 $formattedArray = array();
1918 if (array_key_exists('id', $unformattedArray)) {
1919 unset($unformattedArray['id']);
1921 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1922 foreach ($unformattedArray['values'] as $key => $value) {
1923 if (is_array($value)) {
1924 foreach ($value as $k => $v) {
1930 elseif ($key == 'id') {
1931 $unformattedArray[$key];
1933 $formattedArray = array($value);
1935 $unformattedArray['values'] = $formattedArray;
1940 * Helper to enable/disable custom directory support
1942 * @param array $customDirs
1944 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1945 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1947 public function customDirectories($customDirs) {
1948 $config = CRM_Core_Config
::singleton();
1950 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1951 unset($config->customPHPPathDir
);
1953 elseif ($customDirs['php_path'] === TRUE) {
1954 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1957 $config->customPHPPathDir
= $php_path;
1960 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1961 unset($config->customTemplateDir
);
1963 elseif ($customDirs['template_path'] === TRUE) {
1964 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1967 $config->customTemplateDir
= $template_path;
1972 * Generate a temporary folder.
1974 * @param string $prefix
1977 public function createTempDir($prefix = 'test-') {
1978 $tempDir = CRM_Utils_File
::tempdir($prefix);
1979 $this->tempDirs
[] = $tempDir;
1983 public function cleanTempDirs() {
1984 if (!is_array($this->tempDirs
)) {
1985 // fix test errors where this is not set
1988 foreach ($this->tempDirs
as $tempDir) {
1989 if (is_dir($tempDir)) {
1990 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1996 * Temporarily replace the singleton extension with a different one.
1997 * @param \CRM_Extension_System $system
1999 public function setExtensionSystem(CRM_Extension_System
$system) {
2000 if ($this->origExtensionSystem
== NULL) {
2001 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2003 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2006 public function unsetExtensionSystem() {
2007 if ($this->origExtensionSystem
!== NULL) {
2008 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2009 $this->origExtensionSystem
= NULL;
2014 * Temporarily alter the settings-metadata to add a mock setting.
2016 * WARNING: The setting metadata will disappear on the next cache-clear.
2021 public function setMockSettingsMetaData($extras) {
2022 CRM_Utils_Hook
::singleton()
2023 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2024 $metadata = array_merge($metadata, $extras);
2027 Civi
::service('settings_manager')->flush();
2029 $fields = $this->callAPISuccess('setting', 'getfields', array());
2030 foreach ($extras as $key => $spec) {
2031 $this->assertNotEmpty($spec['title']);
2032 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2037 * @param string $name
2039 public function financialAccountDelete($name) {
2040 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2041 $financialAccount->name
= $name;
2042 if ($financialAccount->find(TRUE)) {
2043 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2044 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2045 $entityFinancialType->delete();
2046 $financialAccount->delete();
2051 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2052 * (NB unclear if this is still required)
2054 public function _sethtmlGlobals() {
2055 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2056 'required' => array(
2057 'html_quickform_rule_required',
2058 'HTML/QuickForm/Rule/Required.php',
2060 'maxlength' => array(
2061 'html_quickform_rule_range',
2062 'HTML/QuickForm/Rule/Range.php',
2064 'minlength' => array(
2065 'html_quickform_rule_range',
2066 'HTML/QuickForm/Rule/Range.php',
2068 'rangelength' => array(
2069 'html_quickform_rule_range',
2070 'HTML/QuickForm/Rule/Range.php',
2073 'html_quickform_rule_email',
2074 'HTML/QuickForm/Rule/Email.php',
2077 'html_quickform_rule_regex',
2078 'HTML/QuickForm/Rule/Regex.php',
2080 'lettersonly' => array(
2081 'html_quickform_rule_regex',
2082 'HTML/QuickForm/Rule/Regex.php',
2084 'alphanumeric' => array(
2085 'html_quickform_rule_regex',
2086 'HTML/QuickForm/Rule/Regex.php',
2089 'html_quickform_rule_regex',
2090 'HTML/QuickForm/Rule/Regex.php',
2092 'nopunctuation' => array(
2093 'html_quickform_rule_regex',
2094 'HTML/QuickForm/Rule/Regex.php',
2097 'html_quickform_rule_regex',
2098 'HTML/QuickForm/Rule/Regex.php',
2100 'callback' => array(
2101 'html_quickform_rule_callback',
2102 'HTML/QuickForm/Rule/Callback.php',
2105 'html_quickform_rule_compare',
2106 'HTML/QuickForm/Rule/Compare.php',
2109 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2110 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2112 'HTML/QuickForm/group.php',
2113 'HTML_QuickForm_group',
2116 'HTML/QuickForm/hidden.php',
2117 'HTML_QuickForm_hidden',
2120 'HTML/QuickForm/reset.php',
2121 'HTML_QuickForm_reset',
2123 'checkbox' => array(
2124 'HTML/QuickForm/checkbox.php',
2125 'HTML_QuickForm_checkbox',
2128 'HTML/QuickForm/file.php',
2129 'HTML_QuickForm_file',
2132 'HTML/QuickForm/image.php',
2133 'HTML_QuickForm_image',
2135 'password' => array(
2136 'HTML/QuickForm/password.php',
2137 'HTML_QuickForm_password',
2140 'HTML/QuickForm/radio.php',
2141 'HTML_QuickForm_radio',
2144 'HTML/QuickForm/button.php',
2145 'HTML_QuickForm_button',
2148 'HTML/QuickForm/submit.php',
2149 'HTML_QuickForm_submit',
2152 'HTML/QuickForm/select.php',
2153 'HTML_QuickForm_select',
2155 'hiddenselect' => array(
2156 'HTML/QuickForm/hiddenselect.php',
2157 'HTML_QuickForm_hiddenselect',
2160 'HTML/QuickForm/text.php',
2161 'HTML_QuickForm_text',
2163 'textarea' => array(
2164 'HTML/QuickForm/textarea.php',
2165 'HTML_QuickForm_textarea',
2167 'fckeditor' => array(
2168 'HTML/QuickForm/fckeditor.php',
2169 'HTML_QuickForm_FCKEditor',
2172 'HTML/QuickForm/tinymce.php',
2173 'HTML_QuickForm_TinyMCE',
2175 'dojoeditor' => array(
2176 'HTML/QuickForm/dojoeditor.php',
2177 'HTML_QuickForm_dojoeditor',
2180 'HTML/QuickForm/link.php',
2181 'HTML_QuickForm_link',
2183 'advcheckbox' => array(
2184 'HTML/QuickForm/advcheckbox.php',
2185 'HTML_QuickForm_advcheckbox',
2188 'HTML/QuickForm/date.php',
2189 'HTML_QuickForm_date',
2192 'HTML/QuickForm/static.php',
2193 'HTML_QuickForm_static',
2196 'HTML/QuickForm/header.php',
2197 'HTML_QuickForm_header',
2200 'HTML/QuickForm/html.php',
2201 'HTML_QuickForm_html',
2203 'hierselect' => array(
2204 'HTML/QuickForm/hierselect.php',
2205 'HTML_QuickForm_hierselect',
2207 'autocomplete' => array(
2208 'HTML/QuickForm/autocomplete.php',
2209 'HTML_QuickForm_autocomplete',
2212 'HTML/QuickForm/xbutton.php',
2213 'HTML_QuickForm_xbutton',
2215 'advmultiselect' => array(
2216 'HTML/QuickForm/advmultiselect.php',
2217 'HTML_QuickForm_advmultiselect',
2223 * Set up an acl allowing contact to see 2 specified groups
2224 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2226 * You need to have pre-created these groups & created the user e.g
2227 * $this->createLoggedInUser();
2228 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2229 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2231 * @param bool $isProfile
2233 public function setupACL($isProfile = FALSE) {
2235 $_REQUEST = $this->_params
;
2237 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2238 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2239 $ov = new CRM_Core_DAO_OptionValue();
2240 $ov->option_group_id
= $optionGroupID;
2242 if ($ov->find(TRUE)) {
2243 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2245 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2246 'option_group_id' => $optionGroupID,
2247 'label' => 'pick me',
2251 CRM_Core_DAO
::executeQuery("
2252 TRUNCATE civicrm_acl_cache
2255 CRM_Core_DAO
::executeQuery("
2256 TRUNCATE civicrm_acl_contact_cache
2259 CRM_Core_DAO
::executeQuery("
2260 INSERT INTO civicrm_acl_entity_role (
2261 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2262 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2266 CRM_Core_DAO
::executeQuery("
2267 INSERT INTO civicrm_acl (
2268 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2271 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2276 CRM_Core_DAO
::executeQuery("
2277 INSERT INTO civicrm_acl (
2278 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2281 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2285 CRM_Core_DAO
::executeQuery("
2286 INSERT INTO civicrm_acl (
2287 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2290 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2295 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2296 $this->callAPISuccess('group_contact', 'create', array(
2297 'group_id' => $this->_permissionedGroup
,
2298 'contact_id' => $this->_loggedInUser
,
2303 CRM_ACL_BAO_Cache
::resetCache();
2304 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2309 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2311 public function offsetDefaultPriceSet() {
2312 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2313 $firstID = $contributionPriceSet['id'];
2314 $this->callAPISuccess('price_set', 'create', array(
2315 'id' => $contributionPriceSet['id'],
2319 unset($contributionPriceSet['id']);
2320 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2321 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2322 'price_set_id' => $firstID,
2323 'options' => array('limit' => 1),
2325 unset($priceField['id']);
2326 $priceField['price_set_id'] = $newPriceSet['id'];
2327 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2328 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2329 'price_set_id' => $firstID,
2331 'options' => array('limit' => 1),
2334 unset($priceFieldValue['id']);
2335 //create some padding to use up ids
2336 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2337 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2338 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2342 * Create an instance of the paypal processor.
2343 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2344 * this parent class & we don't have a structure for that yet
2345 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2346 * & the best protection against that is the functions this class affords
2347 * @param array $params
2348 * @return int $result['id'] payment processor id
2350 public function paymentProcessorCreate($params = array()) {
2351 $params = array_merge(array(
2353 'domain_id' => CRM_Core_Config
::domainID(),
2354 'payment_processor_type_id' => 'PayPal',
2358 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2359 'password' => '1183377788',
2360 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2361 'url_site' => 'https://www.sandbox.paypal.com/',
2362 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2363 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2364 'class_name' => 'Payment_PayPalImpl',
2365 'billing_mode' => 3,
2366 'financial_type_id' => 1,
2367 'financial_account_id' => 12,
2368 // Credit card = 1 so can pass 'by accident'.
2369 'payment_instrument_id' => 'Debit Card',
2371 if (!is_numeric($params['payment_processor_type_id'])) {
2372 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2374 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2375 'name' => $params['payment_processor_type_id'],
2379 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2380 return $result['id'];
2384 * Set up initial recurring payment allowing subsequent IPN payments.
2386 * @param array $recurParams (Optional)
2387 * @param array $contributionParams (Optional)
2389 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2390 $contributionParams = array_merge([
2391 'total_amount' => '200',
2392 'invoice_id' => $this->_invoiceID
,
2393 'financial_type_id' => 'Donation',
2394 'contribution_status_id' => 'Pending',
2395 'contact_id' => $this->_contactID
,
2396 'contribution_page_id' => $this->_contributionPageID
,
2397 'payment_processor_id' => $this->_paymentProcessorID
,
2399 'receive_date' => '2019-07-25 07:34:23',
2400 'skipCleanMoney' => TRUE,
2401 ], $contributionParams);
2402 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2403 'contact_id' => $this->_contactID
,
2406 'installments' => 5,
2407 'frequency_unit' => 'Month',
2408 'frequency_interval' => 1,
2409 'invoice_id' => $this->_invoiceID
,
2410 'contribution_status_id' => 2,
2411 'payment_processor_id' => $this->_paymentProcessorID
,
2412 // processor provided ID - use contact ID as proxy.
2413 'processor_id' => $this->_contactID
,
2414 'api.contribution.create' => $contributionParams,
2416 $this->_contributionRecurID
= $contributionRecur['id'];
2417 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2421 * 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
2423 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2425 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2426 $membershipParams = $recurParams = array();
2427 if (!empty($params['duration_unit'])) {
2428 $membershipParams['duration_unit'] = $params['duration_unit'];
2430 if (!empty($params['frequency_unit'])) {
2431 $recurParams['frequency_unit'] = $params['frequency_unit'];
2434 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2435 //create a contribution so our membership & contribution don't both have id = 1
2436 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2437 $this->contributionCreate(array(
2438 'contact_id' => $this->_contactID
,
2440 'financial_type_id' => 1,
2441 'invoice_id' => 'abcd',
2443 'receive_date' => '2019-07-25 07:34:23',
2446 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2448 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2449 'contact_id' => $this->_contactID
,
2450 'membership_type_id' => $this->ids
['membership_type'],
2451 'contribution_recur_id' => $this->_contributionRecurID
,
2452 'format.only_id' => TRUE,
2453 'source' => 'Payment',
2455 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2456 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2458 $this->callAPISuccess('line_item', 'create', array(
2459 'entity_table' => 'civicrm_membership',
2460 'entity_id' => $this->ids
['membership'],
2461 'contribution_id' => $this->_contributionID
,
2462 'label' => 'General',
2464 'unit_price' => 200,
2465 'line_total' => 200,
2466 'financial_type_id' => 1,
2467 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2469 'label' => 'Membership Amount',
2470 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2472 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2474 'label' => 'General',
2475 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2478 $this->callAPISuccess('membership_payment', 'create', array(
2479 'contribution_id' => $this->_contributionID
,
2480 'membership_id' => $this->ids
['membership'],
2489 public function CiviUnitTestCase_fatalErrorHandler($message) {
2490 throw new Exception("{$message['message']}: {$message['code']}");
2494 * Wrap the entire test case in a transaction.
2496 * Only subsequent DB statements will be wrapped in TX -- this cannot
2497 * retroactively wrap old DB statements. Therefore, it makes sense to
2498 * call this at the beginning of setUp().
2500 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2501 * this option does not work with, e.g., custom-data.
2503 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2504 * if TRUNCATE or ALTER is called while using a transaction.
2507 * Whether to use nesting or reference-counting.
2509 public function useTransaction($nest = TRUE) {
2511 $this->tx
= new CRM_Core_Transaction($nest);
2512 $this->tx
->rollback();
2517 * Assert the attachment exists.
2519 * @param bool $exists
2520 * @param array $apiResult
2522 protected function assertAttachmentExistence($exists, $apiResult) {
2523 $fileId = $apiResult['id'];
2524 $this->assertTrue(is_numeric($fileId));
2525 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2526 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2527 1 => array($fileId, 'Int'),
2529 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2530 1 => array($fileId, 'Int'),
2535 * Assert 2 sql strings are the same, ignoring double spaces.
2537 * @param string $expectedSQL
2538 * @param string $actualSQL
2539 * @param string $message
2541 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2542 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2543 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2544 $this->assertEquals($expected, $actual, $message);
2548 * Create a price set for an event.
2550 * @param int $feeTotal
2551 * @param int $minAmt
2552 * @param string $type
2556 * @throws \CRM_Core_Exception
2558 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2559 // creating price set, price field
2560 $paramsSet['title'] = 'Price Set';
2561 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2562 $paramsSet['is_active'] = FALSE;
2563 $paramsSet['extends'] = 1;
2564 $paramsSet['min_amount'] = $minAmt;
2566 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2567 $this->_ids
['price_set'] = $priceSet->id
;
2569 $paramsField = array(
2570 'label' => 'Price Field',
2571 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2572 'html_type' => $type,
2573 'price' => $feeTotal,
2574 'option_label' => array('1' => 'Price Field'),
2575 'option_value' => array('1' => $feeTotal),
2576 'option_name' => array('1' => $feeTotal),
2577 'option_weight' => array('1' => 1),
2578 'option_amount' => array('1' => 1),
2579 'is_display_amounts' => 1,
2581 'options_per_line' => 1,
2582 'is_active' => array('1' => 1),
2583 'price_set_id' => $this->_ids
['price_set'],
2584 'is_enter_qty' => 1,
2585 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2587 if ($type === 'Radio') {
2588 $paramsField['is_enter_qty'] = 0;
2589 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2590 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2592 $this->callAPISuccess('PriceField', 'create', $paramsField);
2593 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2594 $this->_ids
['price_field'] = array_keys($fields['values']);
2595 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2596 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2598 return $this->_ids
['price_set'];
2602 * Add a profile to a contribution page.
2604 * @param string $name
2605 * @param int $contributionPageID
2606 * @param string $module
2608 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2610 'uf_group_id' => $name,
2611 'module' => $module,
2612 'entity_table' => 'civicrm_contribution_page',
2613 'entity_id' => $contributionPageID,
2616 if ($module !== 'CiviContribute') {
2617 $params['module_data'] = [$module => []];
2619 $this->callAPISuccess('UFJoin', 'create', $params);
2623 * Add participant with contribution
2627 protected function createParticipantWithContribution() {
2628 // creating price set, price field
2629 $this->_contactId
= $this->individualCreate();
2630 $event = $this->eventCreate();
2631 $this->_eventId
= $event['id'];
2632 $eventParams = array(
2633 'id' => $this->_eventId
,
2634 'financial_type_id' => 4,
2637 $this->callAPISuccess('event', 'create', $eventParams);
2638 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2639 $participantParams = array(
2640 'financial_type_id' => 4,
2641 'event_id' => $this->_eventId
,
2644 'fee_currency' => 'USD',
2645 'contact_id' => $this->_contactId
,
2647 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2648 $contributionParams = array(
2649 'total_amount' => 150,
2650 'currency' => 'USD',
2651 'contact_id' => $this->_contactId
,
2652 'financial_type_id' => 4,
2653 'contribution_status_id' => 1,
2654 'partial_payment_total' => 300.00,
2655 'partial_amount_to_pay' => 150,
2656 'contribution_mode' => 'participant',
2657 'participant_id' => $participant['id'],
2659 foreach ($priceFields['values'] as $key => $priceField) {
2660 $lineItems[1][$key] = array(
2661 'price_field_id' => $priceField['price_field_id'],
2662 'price_field_value_id' => $priceField['id'],
2663 'label' => $priceField['label'],
2664 'field_title' => $priceField['label'],
2666 'unit_price' => $priceField['amount'],
2667 'line_total' => $priceField['amount'],
2668 'financial_type_id' => $priceField['financial_type_id'],
2671 $contributionParams['line_item'] = $lineItems;
2672 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2673 $paymentParticipant = array(
2674 'participant_id' => $participant['id'],
2675 'contribution_id' => $contribution['id'],
2677 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2678 return array($lineItems, $contribution);
2684 * @param string $component
2685 * @param int $componentId
2686 * @param array $priceFieldOptions
2690 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2691 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2692 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2693 $paramsSet['is_active'] = TRUE;
2694 $paramsSet['financial_type_id'] = 'Event Fee';
2695 $paramsSet['extends'] = 1;
2696 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2697 $priceSetId = $priceSet['id'];
2698 //Checking for priceset added in the table.
2699 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2700 'id', $paramsSet['title'], 'Check DB for created priceset'
2702 $paramsField = array_merge(array(
2703 'label' => 'Price Field',
2704 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2705 'html_type' => 'CheckBox',
2706 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2707 'option_value' => array('1' => 100, '2' => 200),
2708 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2709 'option_weight' => array('1' => 1, '2' => 2),
2710 'option_amount' => array('1' => 100, '2' => 200),
2711 'is_display_amounts' => 1,
2713 'options_per_line' => 1,
2714 'is_active' => array('1' => 1, '2' => 1),
2715 'price_set_id' => $priceSet['id'],
2716 'is_enter_qty' => 1,
2717 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2718 ), $priceFieldOptions);
2720 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2722 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2724 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2728 * Replace the template with a test-oriented template designed to show all the variables.
2730 * @param string $templateName
2732 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2733 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2734 CRM_Core_DAO
::executeQuery(
2735 "UPDATE civicrm_option_group og
2736 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2737 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2738 SET m.msg_html = '{$testTemplate}'
2739 WHERE og.name = 'msg_tpl_workflow_contribution'
2740 AND ov.name = '{$templateName}'
2741 AND m.is_default = 1"
2746 * Reinstate the default template.
2748 * @param string $templateName
2750 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2751 CRM_Core_DAO
::executeQuery(
2752 "UPDATE civicrm_option_group og
2753 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2754 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2755 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2756 SET m.msg_html = m2.msg_html
2757 WHERE og.name = 'msg_tpl_workflow_contribution'
2758 AND ov.name = '{$templateName}'
2759 AND m.is_default = 1"
2764 * Flush statics relating to financial type.
2766 protected function flushFinancialTypeStatics() {
2767 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2768 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2770 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2771 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2773 CRM_Contribute_PseudoConstant
::flush('financialType');
2774 CRM_Contribute_PseudoConstant
::flush('membershipType');
2775 // Pseudoconstants may be saved to the cache table.
2776 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2777 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2778 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2782 * Set the permissions to the supplied array.
2784 * @param array $permissions
2786 protected function setPermissions($permissions) {
2787 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2788 $this->flushFinancialTypeStatics();
2792 * @param array $params
2795 public function _checkFinancialRecords($params, $context) {
2796 $entityParams = array(
2797 'entity_id' => $params['id'],
2798 'entity_table' => 'civicrm_contribution',
2800 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2801 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2802 if ($context == 'pending') {
2803 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2804 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2807 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2808 $trxnParams = array(
2809 'id' => $trxn['financial_trxn_id'],
2811 if ($context != 'online' && $context != 'payLater') {
2812 $compareParams = array(
2813 'to_financial_account_id' => 6,
2814 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2818 if ($context == 'feeAmount') {
2819 $compareParams['fee_amount'] = 50;
2821 elseif ($context == 'online') {
2822 $compareParams = array(
2823 'to_financial_account_id' => 12,
2824 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2826 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2829 elseif ($context == 'payLater') {
2830 $compareParams = array(
2831 'to_financial_account_id' => 7,
2832 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2836 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2837 $entityParams = array(
2838 'financial_trxn_id' => $trxn['financial_trxn_id'],
2839 'entity_table' => 'civicrm_financial_item',
2841 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2842 $fitemParams = array(
2843 'id' => $entityTrxn['entity_id'],
2845 $compareParams = array(
2846 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2848 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2850 if ($context == 'payLater') {
2851 $compareParams = array(
2852 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2854 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2857 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2858 if ($context == 'feeAmount') {
2860 'entity_id' => $params['id'],
2861 'entity_table' => 'civicrm_contribution',
2863 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2864 $trxnParams = array(
2865 'id' => $maxTrxn['financial_trxn_id'],
2867 $compareParams = array(
2868 'to_financial_account_id' => 5,
2869 'from_financial_account_id' => 6,
2870 'total_amount' => 50,
2873 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2874 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2875 $fitemParams = array(
2876 'entity_id' => $trxnId['financialTrxnId'],
2877 'entity_table' => 'civicrm_financial_trxn',
2879 $compareParams = array(
2882 'financial_account_id' => 5,
2884 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2886 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2887 // line should be copied into all the functions that call this function & evaluated there
2888 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2889 // when calling completeTransaction or repeatTransaction.
2890 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2894 * Return financial type id on basis of name
2896 * @param string $name Financial type m/c name
2900 public function getFinancialTypeId($name) {
2901 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2905 * Cleanup function for contents of $this->ids.
2907 * This is a best effort cleanup to use in tear downs etc.
2909 * It will not fail if the data has already been removed (some tests may do
2910 * their own cleanup).
2912 protected function cleanUpSetUpIDs() {
2913 foreach ($this->setupIDs
as $entity => $id) {
2915 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2917 catch (CiviCRM_API3_Exception
$e) {
2918 // This is a best-effort cleanup function, ignore.
2924 * Create Financial Type.
2926 * @param array $params
2930 protected function createFinancialType($params = array()) {
2931 $params = array_merge($params,
2933 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2937 return $this->callAPISuccess('FinancialType', 'create', $params);
2941 * Create Payment Instrument.
2943 * @param array $params
2944 * @param string $financialAccountName
2948 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2949 $params = array_merge(array(
2950 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2951 'option_group_id' => 'payment_instrument',
2954 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2956 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2958 $financialAccountParams = [
2959 'entity_table' => 'civicrm_option_value',
2960 'entity_id' => $newPaymentInstrument,
2961 'account_relationship' => $relationTypeID,
2962 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2964 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2966 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2970 * Enable Tax and Invoicing
2972 protected function enableTaxAndInvoicing($params = array()) {
2973 // Enable component contribute setting
2974 $contributeSetting = array_merge($params,
2977 'invoice_prefix' => 'INV_',
2978 'credit_notes_prefix' => 'CN_',
2980 'due_date_period' => 'days',
2982 'is_email_pdf' => 1,
2983 'tax_term' => 'Sales Tax',
2984 'tax_display_settings' => 'Inclusive',
2987 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2991 * Enable Tax and Invoicing
2993 protected function disableTaxAndInvoicing($params = array()) {
2994 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2995 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2997 // Enable component contribute setting
2998 $contributeSetting = array_merge($params,
3003 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3007 * Add Sales Tax relation for financial type with financial account.
3009 * @param int $financialTypeId
3013 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3015 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3016 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3017 'is_deductible' => 1,
3022 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3023 $entityParams = array(
3024 'entity_table' => 'civicrm_financial_type',
3025 'entity_id' => $financialTypeId,
3026 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3029 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3030 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3032 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3033 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3034 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3035 $dao->copyValues($entityParams);
3037 if ($dao->fetch()) {
3038 $entityParams['id'] = $dao->id
;
3040 $entityParams['financial_account_id'] = $account->id
;
3042 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3046 * Create price set with contribution test for test setup.
3048 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3049 * on parent class at some point (fn is not in 4.4).
3052 * @param array $params
3054 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3055 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3056 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3057 'title' => "Test Contribution Page",
3058 'financial_type_id' => 1,
3059 'currency' => 'NZD',
3060 'goal_amount' => 50,
3061 'is_pay_later' => 1,
3062 'is_monetary' => TRUE,
3063 'is_email_receipt' => FALSE,
3065 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3066 'is_quick_config' => 0,
3067 'extends' => 'CiviMember',
3068 'financial_type_id' => 1,
3069 'title' => 'my Page',
3071 $priceSetID = $priceSet['id'];
3073 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3074 $priceField = $this->callAPISuccess('price_field', 'create', array(
3075 'price_set_id' => $priceSetID,
3076 'label' => 'Goat Breed',
3077 'html_type' => 'Radio',
3079 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3080 'price_set_id' => $priceSetID,
3081 'price_field_id' => $priceField['id'],
3082 'label' => 'Long Haired Goat',
3084 'financial_type_id' => 'Donation',
3085 'membership_type_id' => $membershipTypeID,
3086 'membership_num_terms' => 1,
3088 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3089 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3090 'price_set_id' => $priceSetID,
3091 'price_field_id' => $priceField['id'],
3092 'label' => 'Shoe-eating Goat',
3094 'financial_type_id' => 'Donation',
3095 'membership_type_id' => $membershipTypeID,
3096 'membership_num_terms' => 2,
3098 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3100 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3101 'price_set_id' => $priceSetID,
3102 'price_field_id' => $priceField['id'],
3103 'label' => 'Shoe-eating Goat',
3105 'financial_type_id' => 'Donation',
3107 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3109 $this->_ids
['price_set'] = $priceSetID;
3110 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3111 $this->_ids
['price_field'] = array($priceField['id']);
3113 $this->_ids
['membership_type'] = $membershipTypeID;
3117 * Only specified contact returned.
3118 * @implements CRM_Utils_Hook::aclWhereClause
3121 * @param $whereTables
3125 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3126 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3130 * @implements CRM_Utils_Hook::selectWhereClause
3132 * @param string $entity
3133 * @param array $clauses
3135 public function selectWhereClauseHook($entity, &$clauses) {
3136 if ($entity == 'Event') {
3137 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3142 * An implementation of hook_civicrm_post used with all our test cases.
3145 * @param string $objectName
3146 * @param int $objectId
3149 public function onPost($op, $objectName, $objectId, &$objectRef) {
3150 if ($op == 'create' && $objectName == 'Individual') {
3151 CRM_Core_DAO
::executeQuery(
3152 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3154 1 => array($objectId, 'Integer'),
3159 if ($op == 'edit' && $objectName == 'Participant') {
3161 1 => array($objectId, 'Integer'),
3163 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3164 CRM_Core_DAO
::executeQuery($query, $params);
3169 * Instantiate form object.
3171 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3173 * @param string $class
3174 * Name of form class.
3176 * @param array $formValues
3178 * @param string $pageName
3180 * @return \CRM_Core_Form
3181 * @throws \CRM_Core_Exception
3183 public function getFormObject($class, $formValues = [], $pageName = '') {
3184 $form = new $class();
3185 $_SERVER['REQUEST_METHOD'] = 'GET';
3186 $form->controller
= new CRM_Core_Controller();
3187 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3188 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3193 * Get possible thousand separators.
3197 public function getThousandSeparators() {
3198 return array(array('.'), array(','));
3202 * Get the boolean options as a provider.
3206 public function getBooleanDataProvider() {
3207 return [[TRUE], [FALSE]];
3211 * Set the separators for thousands and decimal points.
3213 * @param string $thousandSeparator
3215 protected function setCurrencySeparators($thousandSeparator) {
3216 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3218 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3222 * Format money as it would be input.
3224 * @param string $amount
3228 protected function formatMoneyInput($amount) {
3229 return CRM_Utils_Money
::format($amount, NULL, '%a');
3233 * Get the contribution object.
3235 * @param int $contributionID
3237 * @return \CRM_Contribute_BAO_Contribution
3239 protected function getContributionObject($contributionID) {
3240 $contributionObj = new CRM_Contribute_BAO_Contribution();
3241 $contributionObj->id
= $contributionID;
3242 $contributionObj->find(TRUE);
3243 return $contributionObj;
3247 * Enable multilingual.
3249 public function enableMultilingual() {
3250 $this->callAPISuccess('Setting', 'create', array(
3251 'lcMessages' => 'en_US',
3252 'languageLimit' => array(
3257 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3260 $dbLocale = '_en_US';
3264 * Setup or clean up SMS tests
3265 * @param bool $teardown
3267 * @throws \CiviCRM_API3_Exception
3269 public function setupForSmsTests($teardown = FALSE) {
3270 require_once 'CiviTest/CiviTestSMSProvider.php';
3272 // Option value params for CiviTestSMSProvider
3273 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3275 'option_group_id' => $groupID,
3276 'label' => 'unittestSMS',
3277 'value' => 'unit.test.sms',
3278 'name' => 'CiviTestSMSProvider',
3285 // Test completed, delete provider
3286 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3287 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3291 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3292 // in CRM/Sms/Provider.php even though it is not an extension.
3293 return civicrm_api3('option_value', 'create', $params);
3297 * Start capturing browser output.
3299 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3301 protected function startCapturingOutput() {
3303 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3307 * Stop capturing browser output and return as a csv.
3309 * @param bool $isFirstRowHeaders
3311 * @return \League\Csv\Reader
3313 * @throws \League\Csv\Exception
3315 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3316 $output = ob_get_flush();
3317 $stream = fopen('php://memory', 'r+');
3318 fwrite($stream, $output);
3320 $csv = Reader
::createFromString($output);
3321 if ($isFirstRowHeaders) {
3322 $csv->setHeaderOffset(0);