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,
1018 'is_email_confirm' => 1,
1021 return $this->callAPISuccess('Event', 'create', $params);
1025 * Create a paid event.
1027 * @param array $params
1031 protected function eventCreatePaid($params) {
1032 $event = $this->eventCreate($params);
1033 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1034 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1035 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1036 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1037 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1049 public function eventDelete($id) {
1053 return $this->callAPISuccess('event', 'delete', $params);
1057 * Delete participant.
1059 * @param int $participantID
1063 public function participantDelete($participantID) {
1065 'id' => $participantID,
1067 $check = $this->callAPISuccess('Participant', 'get', $params);
1068 if ($check['count'] > 0) {
1069 return $this->callAPISuccess('Participant', 'delete', $params);
1074 * Create participant payment.
1076 * @param int $participantID
1077 * @param int $contributionID
1079 * $id of created payment
1081 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1082 //Create Participant Payment record With Values
1084 'participant_id' => $participantID,
1085 'contribution_id' => $contributionID,
1088 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1089 return $result['id'];
1093 * Delete participant payment.
1095 * @param int $paymentID
1097 public function participantPaymentDelete($paymentID) {
1101 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1107 * @param int $contactID
1109 * location id of created location
1111 public function locationAdd($contactID) {
1114 'location_type' => 'New Location Type',
1116 'name' => 'Saint Helier St',
1117 'county' => 'Marin',
1118 'country' => 'UNITED STATES',
1119 'state_province' => 'Michigan',
1120 'supplemental_address_1' => 'Hallmark Ct',
1121 'supplemental_address_2' => 'Jersey Village',
1122 'supplemental_address_3' => 'My Town',
1127 'contact_id' => $contactID,
1128 'address' => $address,
1129 'location_format' => '2.0',
1130 'location_type' => 'New Location Type',
1133 $result = $this->callAPISuccess('Location', 'create', $params);
1138 * Delete Locations of contact.
1140 * @param array $params
1143 public function locationDelete($params) {
1144 $this->callAPISuccess('Location', 'delete', $params);
1148 * Add a Location Type.
1150 * @param array $params
1151 * @return CRM_Core_DAO_LocationType
1152 * location id of created location
1154 public function locationTypeCreate($params = NULL) {
1155 if ($params === NULL) {
1157 'name' => 'New Location Type',
1158 'vcard_name' => 'New Location Type',
1159 'description' => 'Location Type for Delete',
1164 $locationType = new CRM_Core_DAO_LocationType();
1165 $locationType->copyValues($params);
1166 $locationType->save();
1167 // clear getfields cache
1168 CRM_Core_PseudoConstant
::flush();
1169 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1170 return $locationType;
1174 * Delete a Location Type.
1176 * @param int $locationTypeId
1178 public function locationTypeDelete($locationTypeId) {
1179 $locationType = new CRM_Core_DAO_LocationType();
1180 $locationType->id
= $locationTypeId;
1181 $locationType->delete();
1187 * @param array $params
1188 * @return CRM_Core_DAO_Mapping
1189 * Mapping id of created mapping
1191 public function mappingCreate($params = NULL) {
1192 if ($params === NULL) {
1194 'name' => 'Mapping name',
1195 'description' => 'Mapping description',
1196 // 'Export Contact' mapping.
1197 'mapping_type_id' => 7,
1201 $mapping = new CRM_Core_DAO_Mapping();
1202 $mapping->copyValues($params);
1204 // clear getfields cache
1205 CRM_Core_PseudoConstant
::flush();
1206 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1213 * @param int $mappingId
1215 public function mappingDelete($mappingId) {
1216 $mapping = new CRM_Core_DAO_Mapping();
1217 $mapping->id
= $mappingId;
1222 * Prepare class for ACLs.
1224 protected function prepareForACLs() {
1225 $config = CRM_Core_Config
::singleton();
1226 $config->userPermissionClass
->permissions
= array();
1232 protected function cleanUpAfterACLs() {
1233 CRM_Utils_Hook
::singleton()->reset();
1234 $tablesToTruncate = array(
1236 'civicrm_acl_cache',
1237 'civicrm_acl_entity_role',
1238 'civicrm_acl_contact_cache',
1240 $this->quickCleanup($tablesToTruncate);
1241 $config = CRM_Core_Config
::singleton();
1242 unset($config->userPermissionClass
->permissions
);
1246 * Create a smart group.
1248 * By default it will be a group of households.
1250 * @param array $smartGroupParams
1251 * @param array $groupParams
1252 * @param string $contactType
1256 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1257 $smartGroupParams = array_merge([
1258 'formValues' => ['contact_type' => ['IN' => [$contactType]]],
1261 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1263 $groupParams['saved_search_id'] = $savedSearch->id
;
1264 return $this->groupCreate($groupParams);
1269 * @param array $params
1271 public function uFFieldCreate($params = array()) {
1272 $params = array_merge(array(
1274 'field_name' => 'first_name',
1277 'visibility' => 'Public Pages and Listings',
1278 'is_searchable' => '1',
1279 'label' => 'first_name',
1280 'field_type' => 'Individual',
1283 $this->callAPISuccess('uf_field', 'create', $params);
1287 * Add a UF Join Entry.
1289 * @param array $params
1291 * $id of created UF Join
1293 public function ufjoinCreate($params = NULL) {
1294 if ($params === NULL) {
1297 'module' => 'CiviEvent',
1298 'entity_table' => 'civicrm_event',
1304 $result = $this->callAPISuccess('uf_join', 'create', $params);
1309 * @param array $params
1310 * Optional parameters.
1311 * @param bool $reloadConfig
1312 * While enabling CiviCampaign component, we shouldn't always forcibly
1313 * reload config as this hinder hook call in test environment
1318 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1319 $this->enableCiviCampaign($reloadConfig);
1320 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1321 'name' => 'big_campaign',
1322 'title' => 'Campaign',
1324 return $campaign['id'];
1328 * Create Group for a contact.
1330 * @param int $contactId
1332 public function contactGroupCreate($contactId) {
1334 'contact_id.1' => $contactId,
1338 $this->callAPISuccess('GroupContact', 'Create', $params);
1342 * Delete Group for a contact.
1344 * @param int $contactId
1346 public function contactGroupDelete($contactId) {
1348 'contact_id.1' => $contactId,
1351 $this->civicrm_api('GroupContact', 'Delete', $params);
1357 * @param array $params
1360 public function activityCreate($params = array()) {
1361 $params = array_merge(array(
1362 'subject' => 'Discussion on warm beer',
1363 'activity_date_time' => date('Ymd'),
1364 'duration_hours' => 30,
1365 'duration_minutes' => 20,
1366 'location' => 'Baker Street',
1367 'details' => 'Lets schedule a meeting',
1369 'activity_type_id' => 'Meeting',
1371 if (!isset($params['source_contact_id'])) {
1372 $params['source_contact_id'] = $this->individualCreate();
1374 if (!isset($params['target_contact_id'])) {
1375 $params['target_contact_id'] = $this->individualCreate(array(
1376 'first_name' => 'Julia',
1377 'last_name' => 'Anderson',
1379 'email' => 'julia_anderson@civicrm.org',
1380 'contact_type' => 'Individual',
1383 if (!isset($params['assignee_contact_id'])) {
1384 $params['assignee_contact_id'] = $params['target_contact_id'];
1387 $result = civicrm_api3('Activity', 'create', $params);
1389 $result['target_contact_id'] = $params['target_contact_id'];
1390 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1395 * Create an activity type.
1397 * @param array $params
1401 public function activityTypeCreate($params) {
1402 return $this->callAPISuccess('ActivityType', 'create', $params);
1406 * Delete activity type.
1408 * @param int $activityTypeId
1409 * Id of the activity type.
1412 public function activityTypeDelete($activityTypeId) {
1413 $params['activity_type_id'] = $activityTypeId;
1414 return $this->callAPISuccess('ActivityType', 'delete', $params);
1418 * Create custom group.
1420 * @param array $params
1423 public function customGroupCreate($params = array()) {
1425 'title' => 'new custom group',
1426 'extends' => 'Contact',
1428 'style' => 'Inline',
1432 $params = array_merge($defaults, $params);
1434 return $this->callAPISuccess('custom_group', 'create', $params);
1438 * Existing function doesn't allow params to be over-ridden so need a new one
1439 * this one allows you to only pass in the params you want to change
1440 * @param array $params
1443 public function CustomGroupCreateByParams($params = array()) {
1445 'title' => "API Custom Group",
1446 'extends' => 'Contact',
1448 'style' => 'Inline',
1451 $params = array_merge($defaults, $params);
1452 return $this->callAPISuccess('custom_group', 'create', $params);
1456 * Create custom group with multi fields.
1457 * @param array $params
1460 public function CustomGroupMultipleCreateByParams($params = array()) {
1465 $params = array_merge($defaults, $params);
1466 return $this->CustomGroupCreateByParams($params);
1470 * Create custom group with multi fields.
1471 * @param array $params
1474 public function CustomGroupMultipleCreateWithFields($params = array()) {
1475 // also need to pass on $params['custom_field'] if not set but not in place yet
1477 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1478 $ids['custom_group_id'] = $customGroup['id'];
1480 $customField = $this->customFieldCreate(array(
1481 'custom_group_id' => $ids['custom_group_id'],
1482 'label' => 'field_1' . $ids['custom_group_id'],
1486 $ids['custom_field_id'][] = $customField['id'];
1488 $customField = $this->customFieldCreate(array(
1489 'custom_group_id' => $ids['custom_group_id'],
1490 'default_value' => '',
1491 'label' => 'field_2' . $ids['custom_group_id'],
1494 $ids['custom_field_id'][] = $customField['id'];
1496 $customField = $this->customFieldCreate(array(
1497 'custom_group_id' => $ids['custom_group_id'],
1498 'default_value' => '',
1499 'label' => 'field_3' . $ids['custom_group_id'],
1502 $ids['custom_field_id'][] = $customField['id'];
1508 * Create a custom group with a single text custom field. See
1509 * participant:testCreateWithCustom for how to use this
1511 * @param string $function
1513 * @param string $filename
1517 * ids of created objects
1519 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1520 $params = array('title' => $function);
1521 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1522 $params['extends'] = $entity ?
$entity : 'Contact';
1523 $customGroup = $this->CustomGroupCreate($params);
1524 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1525 CRM_Core_PseudoConstant
::flush();
1527 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1531 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1532 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1534 * @param string $function
1536 * @param string $filename
1540 * ids of created objects
1542 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1543 $params = array('title' => $function);
1544 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1545 $params['extends'] = $entity ?
$entity : 'Contact';
1546 $customGroup = $this->CustomGroupCreate($params);
1547 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1548 CRM_Core_PseudoConstant
::flush();
1550 'defaultValue' => 'Default Value',
1551 'lowercasevalue' => 'Lowercase Value',
1552 1 => 'Integer Value',
1555 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1556 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1557 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1558 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1559 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1560 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1561 foreach ($options as $option_value => $option_label) {
1562 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1563 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1566 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);
1570 * Delete custom group.
1572 * @param int $customGroupID
1576 public function customGroupDelete($customGroupID) {
1577 $params['id'] = $customGroupID;
1578 return $this->callAPISuccess('custom_group', 'delete', $params);
1582 * Create custom field.
1584 * @param array $params
1585 * (custom_group_id) is required.
1588 public function customFieldCreate($params) {
1589 $params = array_merge(array(
1590 'label' => 'Custom Field',
1591 'data_type' => 'String',
1592 'html_type' => 'Text',
1593 'is_searchable' => 1,
1595 'default_value' => 'defaultValue',
1598 $result = $this->callAPISuccess('custom_field', 'create', $params);
1599 // these 2 functions are called with force to flush static caches
1600 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1601 CRM_Core_Component
::getEnabledComponents(1);
1606 * Delete custom field.
1608 * @param int $customFieldID
1612 public function customFieldDelete($customFieldID) {
1614 $params['id'] = $customFieldID;
1615 return $this->callAPISuccess('custom_field', 'delete', $params);
1624 public function noteCreate($cId) {
1626 'entity_table' => 'civicrm_contact',
1627 'entity_id' => $cId,
1628 'note' => 'hello I am testing Note',
1629 'contact_id' => $cId,
1630 'modified_date' => date('Ymd'),
1631 'subject' => 'Test Note',
1634 return $this->callAPISuccess('Note', 'create', $params);
1638 * Enable CiviCampaign Component.
1640 * @param bool $reloadConfig
1641 * Force relaod config or not
1643 public function enableCiviCampaign($reloadConfig = TRUE) {
1644 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1645 if ($reloadConfig) {
1646 // force reload of config object
1647 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1649 //flush cache by calling with reset
1650 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1654 * Create custom field with Option Values.
1656 * @param array $customGroup
1657 * @param string $name
1658 * Name of custom field.
1659 * @param array $extraParams
1660 * Additional parameters to pass through.
1664 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1665 $fieldParams = array(
1666 'custom_group_id' => $customGroup['id'],
1667 'name' => 'test_custom_group',
1668 'label' => 'Country',
1669 'html_type' => 'Select',
1670 'data_type' => 'String',
1673 'is_searchable' => 0,
1677 $optionGroup = array(
1679 'name' => 'option_group1',
1680 'label' => 'option_group_label1',
1683 $optionValue = array(
1684 'option_label' => array('Label1', 'Label2'),
1685 'option_value' => array('value1', 'value2'),
1686 'option_name' => array($name . '_1', $name . '_2'),
1687 'option_weight' => array(1, 2),
1688 'option_status' => array(1, 1),
1691 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1693 return $this->callAPISuccess('custom_field', 'create', $params);
1701 public function confirmEntitiesDeleted($entities) {
1702 foreach ($entities as $entity) {
1704 $result = $this->callAPISuccess($entity, 'Get', array());
1705 if ($result['error'] == 1 ||
$result['count'] > 0) {
1706 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1714 * Quick clean by emptying tables created for the test.
1716 * @param array $tablesToTruncate
1717 * @param bool $dropCustomValueTables
1718 * @throws \CRM_Core_Exception
1720 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1722 throw new \
CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1724 if ($dropCustomValueTables) {
1725 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1726 while ($optionGroupResult->fetch()) {
1727 if (!empty($optionGroupResult->option_group_id
)) {
1728 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1731 $tablesToTruncate[] = 'civicrm_custom_group';
1732 $tablesToTruncate[] = 'civicrm_custom_field';
1735 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1737 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1738 foreach ($tablesToTruncate as $table) {
1739 $sql = "TRUNCATE TABLE $table";
1740 CRM_Core_DAO
::executeQuery($sql);
1742 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1744 if ($dropCustomValueTables) {
1745 $dbName = self
::getDBName();
1747 SELECT TABLE_NAME as tableName
1748 FROM INFORMATION_SCHEMA.TABLES
1749 WHERE TABLE_SCHEMA = '{$dbName}'
1750 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1753 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1754 while ($tableDAO->fetch()) {
1755 $sql = "DROP TABLE {$tableDAO->tableName}";
1756 CRM_Core_DAO
::executeQuery($sql);
1762 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1764 public function quickCleanUpFinancialEntities() {
1765 $tablesToTruncate = array(
1767 'civicrm_activity_contact',
1768 'civicrm_contribution',
1769 'civicrm_contribution_soft',
1770 'civicrm_contribution_product',
1771 'civicrm_financial_trxn',
1772 'civicrm_financial_item',
1773 'civicrm_contribution_recur',
1774 'civicrm_line_item',
1775 'civicrm_contribution_page',
1776 'civicrm_payment_processor',
1777 'civicrm_entity_financial_trxn',
1778 'civicrm_membership',
1779 'civicrm_membership_type',
1780 'civicrm_membership_payment',
1781 'civicrm_membership_log',
1782 'civicrm_membership_block',
1784 'civicrm_participant',
1785 'civicrm_participant_payment',
1787 'civicrm_pledge_block',
1788 'civicrm_pledge_payment',
1789 'civicrm_price_set_entity',
1790 'civicrm_price_field_value',
1791 'civicrm_price_field',
1793 $this->quickCleanup($tablesToTruncate);
1794 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1795 $this->restoreDefaultPriceSetConfig();
1797 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1798 $this->disableTaxAndInvoicing();
1799 $this->setCurrencySeparators(',');
1800 CRM_Core_PseudoConstant
::flush('taxRates');
1801 System
::singleton()->flushProcessors();
1802 // @fixme this parameter is leaking - it should not be defined as a class static
1803 // but for now we just handle in tear down.
1804 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1807 public function restoreDefaultPriceSetConfig() {
1808 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1809 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1810 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)");
1811 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)");
1815 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1816 * Default behaviour is to also delete the entity
1817 * @param array $params
1818 * Params array to check against.
1820 * Id of the entity concerned.
1821 * @param string $entity
1822 * Name of entity concerned (e.g. membership).
1823 * @param bool $delete
1824 * Should the entity be deleted as part of this check.
1825 * @param string $errorText
1826 * Text to print on error.
1830 * @param array $params
1833 * @param int $delete
1834 * @param string $errorText
1838 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1840 $result = $this->callAPISuccessGetSingle($entity, array(
1845 $this->callAPISuccess($entity, 'Delete', array(
1849 $dateFields = $keys = $dateTimeFields = array();
1850 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1851 foreach ($fields['values'] as $field => $settings) {
1852 if (array_key_exists($field, $result)) {
1853 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1856 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1858 $type = CRM_Utils_Array
::value('type', $settings);
1859 if ($type == CRM_Utils_Type
::T_DATE
) {
1860 $dateFields[] = $settings['name'];
1861 // we should identify both real names & unique names as dates
1862 if ($field != $settings['name']) {
1863 $dateFields[] = $field;
1866 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1867 $dateTimeFields[] = $settings['name'];
1868 // we should identify both real names & unique names as dates
1869 if ($field != $settings['name']) {
1870 $dateTimeFields[] = $field;
1875 if (strtolower($entity) == 'contribution') {
1876 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1877 // this is not returned in id format
1878 unset($params['payment_instrument_id']);
1879 $params['contribution_source'] = $params['source'];
1880 unset($params['source']);
1883 foreach ($params as $key => $value) {
1884 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1887 if (in_array($key, $dateFields)) {
1888 $value = date('Y-m-d', strtotime($value));
1889 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1891 if (in_array($key, $dateTimeFields)) {
1892 $value = date('Y-m-d H:i:s', strtotime($value));
1893 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1895 $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);
1900 * Get formatted values in the actual and expected result.
1901 * @param array $actual
1902 * Actual calculated values.
1903 * @param array $expected
1906 public function checkArrayEquals(&$actual, &$expected) {
1907 self
::unsetId($actual);
1908 self
::unsetId($expected);
1909 $this->assertEquals($expected, $actual);
1913 * Unset the key 'id' from the array
1914 * @param array $unformattedArray
1915 * The array from which the 'id' has to be unset.
1917 public static function unsetId(&$unformattedArray) {
1918 $formattedArray = array();
1919 if (array_key_exists('id', $unformattedArray)) {
1920 unset($unformattedArray['id']);
1922 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1923 foreach ($unformattedArray['values'] as $key => $value) {
1924 if (is_array($value)) {
1925 foreach ($value as $k => $v) {
1931 elseif ($key == 'id') {
1932 $unformattedArray[$key];
1934 $formattedArray = array($value);
1936 $unformattedArray['values'] = $formattedArray;
1941 * Helper to enable/disable custom directory support
1943 * @param array $customDirs
1945 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1946 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1948 public function customDirectories($customDirs) {
1949 $config = CRM_Core_Config
::singleton();
1951 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1952 unset($config->customPHPPathDir
);
1954 elseif ($customDirs['php_path'] === TRUE) {
1955 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1958 $config->customPHPPathDir
= $php_path;
1961 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1962 unset($config->customTemplateDir
);
1964 elseif ($customDirs['template_path'] === TRUE) {
1965 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1968 $config->customTemplateDir
= $template_path;
1973 * Generate a temporary folder.
1975 * @param string $prefix
1978 public function createTempDir($prefix = 'test-') {
1979 $tempDir = CRM_Utils_File
::tempdir($prefix);
1980 $this->tempDirs
[] = $tempDir;
1984 public function cleanTempDirs() {
1985 if (!is_array($this->tempDirs
)) {
1986 // fix test errors where this is not set
1989 foreach ($this->tempDirs
as $tempDir) {
1990 if (is_dir($tempDir)) {
1991 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1997 * Temporarily replace the singleton extension with a different one.
1998 * @param \CRM_Extension_System $system
2000 public function setExtensionSystem(CRM_Extension_System
$system) {
2001 if ($this->origExtensionSystem
== NULL) {
2002 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2004 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2007 public function unsetExtensionSystem() {
2008 if ($this->origExtensionSystem
!== NULL) {
2009 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2010 $this->origExtensionSystem
= NULL;
2015 * Temporarily alter the settings-metadata to add a mock setting.
2017 * WARNING: The setting metadata will disappear on the next cache-clear.
2022 public function setMockSettingsMetaData($extras) {
2023 CRM_Utils_Hook
::singleton()
2024 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2025 $metadata = array_merge($metadata, $extras);
2028 Civi
::service('settings_manager')->flush();
2030 $fields = $this->callAPISuccess('setting', 'getfields', array());
2031 foreach ($extras as $key => $spec) {
2032 $this->assertNotEmpty($spec['title']);
2033 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2038 * @param string $name
2040 public function financialAccountDelete($name) {
2041 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2042 $financialAccount->name
= $name;
2043 if ($financialAccount->find(TRUE)) {
2044 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2045 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2046 $entityFinancialType->delete();
2047 $financialAccount->delete();
2052 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2053 * (NB unclear if this is still required)
2055 public function _sethtmlGlobals() {
2056 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2057 'required' => array(
2058 'html_quickform_rule_required',
2059 'HTML/QuickForm/Rule/Required.php',
2061 'maxlength' => array(
2062 'html_quickform_rule_range',
2063 'HTML/QuickForm/Rule/Range.php',
2065 'minlength' => array(
2066 'html_quickform_rule_range',
2067 'HTML/QuickForm/Rule/Range.php',
2069 'rangelength' => array(
2070 'html_quickform_rule_range',
2071 'HTML/QuickForm/Rule/Range.php',
2074 'html_quickform_rule_email',
2075 'HTML/QuickForm/Rule/Email.php',
2078 'html_quickform_rule_regex',
2079 'HTML/QuickForm/Rule/Regex.php',
2081 'lettersonly' => array(
2082 'html_quickform_rule_regex',
2083 'HTML/QuickForm/Rule/Regex.php',
2085 'alphanumeric' => array(
2086 'html_quickform_rule_regex',
2087 'HTML/QuickForm/Rule/Regex.php',
2090 'html_quickform_rule_regex',
2091 'HTML/QuickForm/Rule/Regex.php',
2093 'nopunctuation' => array(
2094 'html_quickform_rule_regex',
2095 'HTML/QuickForm/Rule/Regex.php',
2098 'html_quickform_rule_regex',
2099 'HTML/QuickForm/Rule/Regex.php',
2101 'callback' => array(
2102 'html_quickform_rule_callback',
2103 'HTML/QuickForm/Rule/Callback.php',
2106 'html_quickform_rule_compare',
2107 'HTML/QuickForm/Rule/Compare.php',
2110 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2111 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2113 'HTML/QuickForm/group.php',
2114 'HTML_QuickForm_group',
2117 'HTML/QuickForm/hidden.php',
2118 'HTML_QuickForm_hidden',
2121 'HTML/QuickForm/reset.php',
2122 'HTML_QuickForm_reset',
2124 'checkbox' => array(
2125 'HTML/QuickForm/checkbox.php',
2126 'HTML_QuickForm_checkbox',
2129 'HTML/QuickForm/file.php',
2130 'HTML_QuickForm_file',
2133 'HTML/QuickForm/image.php',
2134 'HTML_QuickForm_image',
2136 'password' => array(
2137 'HTML/QuickForm/password.php',
2138 'HTML_QuickForm_password',
2141 'HTML/QuickForm/radio.php',
2142 'HTML_QuickForm_radio',
2145 'HTML/QuickForm/button.php',
2146 'HTML_QuickForm_button',
2149 'HTML/QuickForm/submit.php',
2150 'HTML_QuickForm_submit',
2153 'HTML/QuickForm/select.php',
2154 'HTML_QuickForm_select',
2156 'hiddenselect' => array(
2157 'HTML/QuickForm/hiddenselect.php',
2158 'HTML_QuickForm_hiddenselect',
2161 'HTML/QuickForm/text.php',
2162 'HTML_QuickForm_text',
2164 'textarea' => array(
2165 'HTML/QuickForm/textarea.php',
2166 'HTML_QuickForm_textarea',
2168 'fckeditor' => array(
2169 'HTML/QuickForm/fckeditor.php',
2170 'HTML_QuickForm_FCKEditor',
2173 'HTML/QuickForm/tinymce.php',
2174 'HTML_QuickForm_TinyMCE',
2176 'dojoeditor' => array(
2177 'HTML/QuickForm/dojoeditor.php',
2178 'HTML_QuickForm_dojoeditor',
2181 'HTML/QuickForm/link.php',
2182 'HTML_QuickForm_link',
2184 'advcheckbox' => array(
2185 'HTML/QuickForm/advcheckbox.php',
2186 'HTML_QuickForm_advcheckbox',
2189 'HTML/QuickForm/date.php',
2190 'HTML_QuickForm_date',
2193 'HTML/QuickForm/static.php',
2194 'HTML_QuickForm_static',
2197 'HTML/QuickForm/header.php',
2198 'HTML_QuickForm_header',
2201 'HTML/QuickForm/html.php',
2202 'HTML_QuickForm_html',
2204 'hierselect' => array(
2205 'HTML/QuickForm/hierselect.php',
2206 'HTML_QuickForm_hierselect',
2208 'autocomplete' => array(
2209 'HTML/QuickForm/autocomplete.php',
2210 'HTML_QuickForm_autocomplete',
2213 'HTML/QuickForm/xbutton.php',
2214 'HTML_QuickForm_xbutton',
2216 'advmultiselect' => array(
2217 'HTML/QuickForm/advmultiselect.php',
2218 'HTML_QuickForm_advmultiselect',
2224 * Set up an acl allowing contact to see 2 specified groups
2225 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2227 * You need to have pre-created these groups & created the user e.g
2228 * $this->createLoggedInUser();
2229 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2230 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2232 * @param bool $isProfile
2234 public function setupACL($isProfile = FALSE) {
2236 $_REQUEST = $this->_params
;
2238 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2239 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2240 $ov = new CRM_Core_DAO_OptionValue();
2241 $ov->option_group_id
= $optionGroupID;
2243 if ($ov->find(TRUE)) {
2244 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2246 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2247 'option_group_id' => $optionGroupID,
2248 'label' => 'pick me',
2252 CRM_Core_DAO
::executeQuery("
2253 TRUNCATE civicrm_acl_cache
2256 CRM_Core_DAO
::executeQuery("
2257 TRUNCATE civicrm_acl_contact_cache
2260 CRM_Core_DAO
::executeQuery("
2261 INSERT INTO civicrm_acl_entity_role (
2262 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2263 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2267 CRM_Core_DAO
::executeQuery("
2268 INSERT INTO civicrm_acl (
2269 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2272 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2277 CRM_Core_DAO
::executeQuery("
2278 INSERT INTO civicrm_acl (
2279 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2282 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2286 CRM_Core_DAO
::executeQuery("
2287 INSERT INTO civicrm_acl (
2288 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2291 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2296 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2297 $this->callAPISuccess('group_contact', 'create', array(
2298 'group_id' => $this->_permissionedGroup
,
2299 'contact_id' => $this->_loggedInUser
,
2304 CRM_ACL_BAO_Cache
::resetCache();
2305 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2310 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2312 public function offsetDefaultPriceSet() {
2313 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2314 $firstID = $contributionPriceSet['id'];
2315 $this->callAPISuccess('price_set', 'create', array(
2316 'id' => $contributionPriceSet['id'],
2320 unset($contributionPriceSet['id']);
2321 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2322 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2323 'price_set_id' => $firstID,
2324 'options' => array('limit' => 1),
2326 unset($priceField['id']);
2327 $priceField['price_set_id'] = $newPriceSet['id'];
2328 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2329 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2330 'price_set_id' => $firstID,
2332 'options' => array('limit' => 1),
2335 unset($priceFieldValue['id']);
2336 //create some padding to use up ids
2337 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2338 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2339 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2343 * Create an instance of the paypal processor.
2344 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2345 * this parent class & we don't have a structure for that yet
2346 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2347 * & the best protection against that is the functions this class affords
2348 * @param array $params
2349 * @return int $result['id'] payment processor id
2351 public function paymentProcessorCreate($params = array()) {
2352 $params = array_merge(array(
2354 'domain_id' => CRM_Core_Config
::domainID(),
2355 'payment_processor_type_id' => 'PayPal',
2359 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2360 'password' => '1183377788',
2361 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2362 'url_site' => 'https://www.sandbox.paypal.com/',
2363 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2364 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2365 'class_name' => 'Payment_PayPalImpl',
2366 'billing_mode' => 3,
2367 'financial_type_id' => 1,
2368 'financial_account_id' => 12,
2369 // Credit card = 1 so can pass 'by accident'.
2370 'payment_instrument_id' => 'Debit Card',
2372 if (!is_numeric($params['payment_processor_type_id'])) {
2373 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2375 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2376 'name' => $params['payment_processor_type_id'],
2380 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2381 return $result['id'];
2385 * Set up initial recurring payment allowing subsequent IPN payments.
2387 * @param array $recurParams (Optional)
2388 * @param array $contributionParams (Optional)
2390 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2391 $contributionParams = array_merge([
2392 'total_amount' => '200',
2393 'invoice_id' => $this->_invoiceID
,
2394 'financial_type_id' => 'Donation',
2395 'contribution_status_id' => 'Pending',
2396 'contact_id' => $this->_contactID
,
2397 'contribution_page_id' => $this->_contributionPageID
,
2398 'payment_processor_id' => $this->_paymentProcessorID
,
2400 'receive_date' => '2019-07-25 07:34:23',
2401 'skipCleanMoney' => TRUE,
2402 ], $contributionParams);
2403 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2404 'contact_id' => $this->_contactID
,
2407 'installments' => 5,
2408 'frequency_unit' => 'Month',
2409 'frequency_interval' => 1,
2410 'invoice_id' => $this->_invoiceID
,
2411 'contribution_status_id' => 2,
2412 'payment_processor_id' => $this->_paymentProcessorID
,
2413 // processor provided ID - use contact ID as proxy.
2414 'processor_id' => $this->_contactID
,
2415 'api.contribution.create' => $contributionParams,
2417 $this->_contributionRecurID
= $contributionRecur['id'];
2418 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2422 * 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
2424 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2426 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2427 $membershipParams = $recurParams = array();
2428 if (!empty($params['duration_unit'])) {
2429 $membershipParams['duration_unit'] = $params['duration_unit'];
2431 if (!empty($params['frequency_unit'])) {
2432 $recurParams['frequency_unit'] = $params['frequency_unit'];
2435 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2436 //create a contribution so our membership & contribution don't both have id = 1
2437 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2438 $this->contributionCreate(array(
2439 'contact_id' => $this->_contactID
,
2441 'financial_type_id' => 1,
2442 'invoice_id' => 'abcd',
2444 'receive_date' => '2019-07-25 07:34:23',
2447 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2449 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2450 'contact_id' => $this->_contactID
,
2451 'membership_type_id' => $this->ids
['membership_type'],
2452 'contribution_recur_id' => $this->_contributionRecurID
,
2453 'format.only_id' => TRUE,
2454 'source' => 'Payment',
2456 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2457 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2459 $this->callAPISuccess('line_item', 'create', array(
2460 'entity_table' => 'civicrm_membership',
2461 'entity_id' => $this->ids
['membership'],
2462 'contribution_id' => $this->_contributionID
,
2463 'label' => 'General',
2465 'unit_price' => 200,
2466 'line_total' => 200,
2467 'financial_type_id' => 1,
2468 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2470 'label' => 'Membership Amount',
2471 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2473 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2475 'label' => 'General',
2476 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2479 $this->callAPISuccess('membership_payment', 'create', array(
2480 'contribution_id' => $this->_contributionID
,
2481 'membership_id' => $this->ids
['membership'],
2490 public function CiviUnitTestCase_fatalErrorHandler($message) {
2491 throw new Exception("{$message['message']}: {$message['code']}");
2495 * Wrap the entire test case in a transaction.
2497 * Only subsequent DB statements will be wrapped in TX -- this cannot
2498 * retroactively wrap old DB statements. Therefore, it makes sense to
2499 * call this at the beginning of setUp().
2501 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2502 * this option does not work with, e.g., custom-data.
2504 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2505 * if TRUNCATE or ALTER is called while using a transaction.
2508 * Whether to use nesting or reference-counting.
2510 public function useTransaction($nest = TRUE) {
2512 $this->tx
= new CRM_Core_Transaction($nest);
2513 $this->tx
->rollback();
2518 * Assert the attachment exists.
2520 * @param bool $exists
2521 * @param array $apiResult
2523 protected function assertAttachmentExistence($exists, $apiResult) {
2524 $fileId = $apiResult['id'];
2525 $this->assertTrue(is_numeric($fileId));
2526 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2527 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2528 1 => array($fileId, 'Int'),
2530 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2531 1 => array($fileId, 'Int'),
2536 * Assert 2 sql strings are the same, ignoring double spaces.
2538 * @param string $expectedSQL
2539 * @param string $actualSQL
2540 * @param string $message
2542 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2543 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2544 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2545 $this->assertEquals($expected, $actual, $message);
2549 * Create a price set for an event.
2551 * @param int $feeTotal
2552 * @param int $minAmt
2553 * @param string $type
2557 * @throws \CRM_Core_Exception
2559 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2560 // creating price set, price field
2561 $paramsSet['title'] = 'Price Set';
2562 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2563 $paramsSet['is_active'] = FALSE;
2564 $paramsSet['extends'] = 1;
2565 $paramsSet['min_amount'] = $minAmt;
2567 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2568 $this->_ids
['price_set'] = $priceSet->id
;
2570 $paramsField = array(
2571 'label' => 'Price Field',
2572 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2573 'html_type' => $type,
2574 'price' => $feeTotal,
2575 'option_label' => array('1' => 'Price Field'),
2576 'option_value' => array('1' => $feeTotal),
2577 'option_name' => array('1' => $feeTotal),
2578 'option_weight' => array('1' => 1),
2579 'option_amount' => array('1' => 1),
2580 'is_display_amounts' => 1,
2582 'options_per_line' => 1,
2583 'is_active' => array('1' => 1),
2584 'price_set_id' => $this->_ids
['price_set'],
2585 'is_enter_qty' => 1,
2586 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2588 if ($type === 'Radio') {
2589 $paramsField['is_enter_qty'] = 0;
2590 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2591 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2593 $this->callAPISuccess('PriceField', 'create', $paramsField);
2594 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2595 $this->_ids
['price_field'] = array_keys($fields['values']);
2596 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2597 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2599 return $this->_ids
['price_set'];
2603 * Add a profile to a contribution page.
2605 * @param string $name
2606 * @param int $contributionPageID
2607 * @param string $module
2609 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2611 'uf_group_id' => $name,
2612 'module' => $module,
2613 'entity_table' => 'civicrm_contribution_page',
2614 'entity_id' => $contributionPageID,
2617 if ($module !== 'CiviContribute') {
2618 $params['module_data'] = [$module => []];
2620 $this->callAPISuccess('UFJoin', 'create', $params);
2624 * Add participant with contribution
2628 protected function createParticipantWithContribution() {
2629 // creating price set, price field
2630 $this->_contactId
= $this->individualCreate();
2631 $event = $this->eventCreate();
2632 $this->_eventId
= $event['id'];
2633 $eventParams = array(
2634 'id' => $this->_eventId
,
2635 'financial_type_id' => 4,
2638 $this->callAPISuccess('event', 'create', $eventParams);
2639 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2640 $participantParams = array(
2641 'financial_type_id' => 4,
2642 'event_id' => $this->_eventId
,
2645 'fee_currency' => 'USD',
2646 'contact_id' => $this->_contactId
,
2648 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2649 $contributionParams = array(
2650 'total_amount' => 150,
2651 'currency' => 'USD',
2652 'contact_id' => $this->_contactId
,
2653 'financial_type_id' => 4,
2654 'contribution_status_id' => 1,
2655 'partial_payment_total' => 300.00,
2656 'partial_amount_to_pay' => 150,
2657 'contribution_mode' => 'participant',
2658 'participant_id' => $participant['id'],
2660 foreach ($priceFields['values'] as $key => $priceField) {
2661 $lineItems[1][$key] = array(
2662 'price_field_id' => $priceField['price_field_id'],
2663 'price_field_value_id' => $priceField['id'],
2664 'label' => $priceField['label'],
2665 'field_title' => $priceField['label'],
2667 'unit_price' => $priceField['amount'],
2668 'line_total' => $priceField['amount'],
2669 'financial_type_id' => $priceField['financial_type_id'],
2672 $contributionParams['line_item'] = $lineItems;
2673 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2674 $paymentParticipant = array(
2675 'participant_id' => $participant['id'],
2676 'contribution_id' => $contribution['id'],
2678 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2679 return array($lineItems, $contribution);
2685 * @param string $component
2686 * @param int $componentId
2687 * @param array $priceFieldOptions
2691 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2692 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2693 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2694 $paramsSet['is_active'] = TRUE;
2695 $paramsSet['financial_type_id'] = 'Event Fee';
2696 $paramsSet['extends'] = 1;
2697 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2698 $priceSetId = $priceSet['id'];
2699 //Checking for priceset added in the table.
2700 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2701 'id', $paramsSet['title'], 'Check DB for created priceset'
2703 $paramsField = array_merge(array(
2704 'label' => 'Price Field',
2705 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2706 'html_type' => 'CheckBox',
2707 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2708 'option_value' => array('1' => 100, '2' => 200),
2709 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2710 'option_weight' => array('1' => 1, '2' => 2),
2711 'option_amount' => array('1' => 100, '2' => 200),
2712 'is_display_amounts' => 1,
2714 'options_per_line' => 1,
2715 'is_active' => array('1' => 1, '2' => 1),
2716 'price_set_id' => $priceSet['id'],
2717 'is_enter_qty' => 1,
2718 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2719 ), $priceFieldOptions);
2721 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2723 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2725 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2729 * Replace the template with a test-oriented template designed to show all the variables.
2731 * @param string $templateName
2733 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2734 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2735 CRM_Core_DAO
::executeQuery(
2736 "UPDATE civicrm_option_group og
2737 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2738 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2739 SET m.msg_html = '{$testTemplate}'
2740 WHERE og.name = 'msg_tpl_workflow_contribution'
2741 AND ov.name = '{$templateName}'
2742 AND m.is_default = 1"
2747 * Reinstate the default template.
2749 * @param string $templateName
2751 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2752 CRM_Core_DAO
::executeQuery(
2753 "UPDATE civicrm_option_group og
2754 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2755 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2756 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2757 SET m.msg_html = m2.msg_html
2758 WHERE og.name = 'msg_tpl_workflow_contribution'
2759 AND ov.name = '{$templateName}'
2760 AND m.is_default = 1"
2765 * Flush statics relating to financial type.
2767 protected function flushFinancialTypeStatics() {
2768 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2769 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2771 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2772 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2774 CRM_Contribute_PseudoConstant
::flush('financialType');
2775 CRM_Contribute_PseudoConstant
::flush('membershipType');
2776 // Pseudoconstants may be saved to the cache table.
2777 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2778 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2779 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2783 * Set the permissions to the supplied array.
2785 * @param array $permissions
2787 protected function setPermissions($permissions) {
2788 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2789 $this->flushFinancialTypeStatics();
2793 * @param array $params
2796 public function _checkFinancialRecords($params, $context) {
2797 $entityParams = array(
2798 'entity_id' => $params['id'],
2799 'entity_table' => 'civicrm_contribution',
2801 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2802 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2803 if ($context == 'pending') {
2804 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2805 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2808 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2809 $trxnParams = array(
2810 'id' => $trxn['financial_trxn_id'],
2812 if ($context != 'online' && $context != 'payLater') {
2813 $compareParams = array(
2814 'to_financial_account_id' => 6,
2815 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2819 if ($context == 'feeAmount') {
2820 $compareParams['fee_amount'] = 50;
2822 elseif ($context == 'online') {
2823 $compareParams = array(
2824 'to_financial_account_id' => 12,
2825 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2827 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2830 elseif ($context == 'payLater') {
2831 $compareParams = array(
2832 'to_financial_account_id' => 7,
2833 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2837 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2838 $entityParams = array(
2839 'financial_trxn_id' => $trxn['financial_trxn_id'],
2840 'entity_table' => 'civicrm_financial_item',
2842 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2843 $fitemParams = array(
2844 'id' => $entityTrxn['entity_id'],
2846 $compareParams = array(
2847 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2849 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2851 if ($context == 'payLater') {
2852 $compareParams = array(
2853 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2855 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2858 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2859 if ($context == 'feeAmount') {
2861 'entity_id' => $params['id'],
2862 'entity_table' => 'civicrm_contribution',
2864 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2865 $trxnParams = array(
2866 'id' => $maxTrxn['financial_trxn_id'],
2868 $compareParams = array(
2869 'to_financial_account_id' => 5,
2870 'from_financial_account_id' => 6,
2871 'total_amount' => 50,
2874 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2875 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2876 $fitemParams = array(
2877 'entity_id' => $trxnId['financialTrxnId'],
2878 'entity_table' => 'civicrm_financial_trxn',
2880 $compareParams = array(
2883 'financial_account_id' => 5,
2885 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2887 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2888 // line should be copied into all the functions that call this function & evaluated there
2889 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2890 // when calling completeTransaction or repeatTransaction.
2891 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2895 * Return financial type id on basis of name
2897 * @param string $name Financial type m/c name
2901 public function getFinancialTypeId($name) {
2902 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2906 * Cleanup function for contents of $this->ids.
2908 * This is a best effort cleanup to use in tear downs etc.
2910 * It will not fail if the data has already been removed (some tests may do
2911 * their own cleanup).
2913 protected function cleanUpSetUpIDs() {
2914 foreach ($this->setupIDs
as $entity => $id) {
2916 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2918 catch (CiviCRM_API3_Exception
$e) {
2919 // This is a best-effort cleanup function, ignore.
2925 * Create Financial Type.
2927 * @param array $params
2931 protected function createFinancialType($params = array()) {
2932 $params = array_merge($params,
2934 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2938 return $this->callAPISuccess('FinancialType', 'create', $params);
2942 * Create Payment Instrument.
2944 * @param array $params
2945 * @param string $financialAccountName
2949 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2950 $params = array_merge(array(
2951 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2952 'option_group_id' => 'payment_instrument',
2955 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2957 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2959 $financialAccountParams = [
2960 'entity_table' => 'civicrm_option_value',
2961 'entity_id' => $newPaymentInstrument,
2962 'account_relationship' => $relationTypeID,
2963 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2965 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2967 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2971 * Enable Tax and Invoicing
2973 protected function enableTaxAndInvoicing($params = array()) {
2974 // Enable component contribute setting
2975 $contributeSetting = array_merge($params,
2978 'invoice_prefix' => 'INV_',
2979 'credit_notes_prefix' => 'CN_',
2981 'due_date_period' => 'days',
2983 'is_email_pdf' => 1,
2984 'tax_term' => 'Sales Tax',
2985 'tax_display_settings' => 'Inclusive',
2988 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2992 * Enable Tax and Invoicing
2994 protected function disableTaxAndInvoicing($params = array()) {
2995 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2996 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2998 // Enable component contribute setting
2999 $contributeSetting = array_merge($params,
3004 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3008 * Add Sales Tax relation for financial type with financial account.
3010 * @param int $financialTypeId
3014 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3016 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3017 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3018 'is_deductible' => 1,
3023 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3024 $entityParams = array(
3025 'entity_table' => 'civicrm_financial_type',
3026 'entity_id' => $financialTypeId,
3027 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3030 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3031 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3033 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3034 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3035 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3036 $dao->copyValues($entityParams);
3038 if ($dao->fetch()) {
3039 $entityParams['id'] = $dao->id
;
3041 $entityParams['financial_account_id'] = $account->id
;
3043 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3047 * Create price set with contribution test for test setup.
3049 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3050 * on parent class at some point (fn is not in 4.4).
3053 * @param array $params
3055 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3056 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3057 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3058 'title' => "Test Contribution Page",
3059 'financial_type_id' => 1,
3060 'currency' => 'NZD',
3061 'goal_amount' => 50,
3062 'is_pay_later' => 1,
3063 'is_monetary' => TRUE,
3064 'is_email_receipt' => FALSE,
3066 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3067 'is_quick_config' => 0,
3068 'extends' => 'CiviMember',
3069 'financial_type_id' => 1,
3070 'title' => 'my Page',
3072 $priceSetID = $priceSet['id'];
3074 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3075 $priceField = $this->callAPISuccess('price_field', 'create', array(
3076 'price_set_id' => $priceSetID,
3077 'label' => 'Goat Breed',
3078 'html_type' => 'Radio',
3080 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3081 'price_set_id' => $priceSetID,
3082 'price_field_id' => $priceField['id'],
3083 'label' => 'Long Haired Goat',
3085 'financial_type_id' => 'Donation',
3086 'membership_type_id' => $membershipTypeID,
3087 'membership_num_terms' => 1,
3089 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3090 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3091 'price_set_id' => $priceSetID,
3092 'price_field_id' => $priceField['id'],
3093 'label' => 'Shoe-eating Goat',
3095 'financial_type_id' => 'Donation',
3096 'membership_type_id' => $membershipTypeID,
3097 'membership_num_terms' => 2,
3099 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3101 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3102 'price_set_id' => $priceSetID,
3103 'price_field_id' => $priceField['id'],
3104 'label' => 'Shoe-eating Goat',
3106 'financial_type_id' => 'Donation',
3108 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3110 $this->_ids
['price_set'] = $priceSetID;
3111 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3112 $this->_ids
['price_field'] = array($priceField['id']);
3114 $this->_ids
['membership_type'] = $membershipTypeID;
3118 * Only specified contact returned.
3119 * @implements CRM_Utils_Hook::aclWhereClause
3122 * @param $whereTables
3126 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3127 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3131 * @implements CRM_Utils_Hook::selectWhereClause
3133 * @param string $entity
3134 * @param array $clauses
3136 public function selectWhereClauseHook($entity, &$clauses) {
3137 if ($entity == 'Event') {
3138 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3143 * An implementation of hook_civicrm_post used with all our test cases.
3146 * @param string $objectName
3147 * @param int $objectId
3150 public function onPost($op, $objectName, $objectId, &$objectRef) {
3151 if ($op == 'create' && $objectName == 'Individual') {
3152 CRM_Core_DAO
::executeQuery(
3153 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3155 1 => array($objectId, 'Integer'),
3160 if ($op == 'edit' && $objectName == 'Participant') {
3162 1 => array($objectId, 'Integer'),
3164 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3165 CRM_Core_DAO
::executeQuery($query, $params);
3170 * Instantiate form object.
3172 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3174 * @param string $class
3175 * Name of form class.
3177 * @param array $formValues
3179 * @param string $pageName
3181 * @return \CRM_Core_Form
3182 * @throws \CRM_Core_Exception
3184 public function getFormObject($class, $formValues = [], $pageName = '') {
3185 $form = new $class();
3186 $_SERVER['REQUEST_METHOD'] = 'GET';
3187 $form->controller
= new CRM_Core_Controller();
3188 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3189 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3194 * Get possible thousand separators.
3198 public function getThousandSeparators() {
3199 return array(array('.'), array(','));
3203 * Get the boolean options as a provider.
3207 public function getBooleanDataProvider() {
3208 return [[TRUE], [FALSE]];
3212 * Set the separators for thousands and decimal points.
3214 * @param string $thousandSeparator
3216 protected function setCurrencySeparators($thousandSeparator) {
3217 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3219 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3223 * Format money as it would be input.
3225 * @param string $amount
3229 protected function formatMoneyInput($amount) {
3230 return CRM_Utils_Money
::format($amount, NULL, '%a');
3234 * Get the contribution object.
3236 * @param int $contributionID
3238 * @return \CRM_Contribute_BAO_Contribution
3240 protected function getContributionObject($contributionID) {
3241 $contributionObj = new CRM_Contribute_BAO_Contribution();
3242 $contributionObj->id
= $contributionID;
3243 $contributionObj->find(TRUE);
3244 return $contributionObj;
3248 * Enable multilingual.
3250 public function enableMultilingual() {
3251 $this->callAPISuccess('Setting', 'create', array(
3252 'lcMessages' => 'en_US',
3253 'languageLimit' => array(
3258 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3261 $dbLocale = '_en_US';
3265 * Setup or clean up SMS tests
3266 * @param bool $teardown
3268 * @throws \CiviCRM_API3_Exception
3270 public function setupForSmsTests($teardown = FALSE) {
3271 require_once 'CiviTest/CiviTestSMSProvider.php';
3273 // Option value params for CiviTestSMSProvider
3274 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3276 'option_group_id' => $groupID,
3277 'label' => 'unittestSMS',
3278 'value' => 'unit.test.sms',
3279 'name' => 'CiviTestSMSProvider',
3286 // Test completed, delete provider
3287 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3288 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3292 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3293 // in CRM/Sms/Provider.php even though it is not an extension.
3294 return civicrm_api3('option_value', 'create', $params);
3298 * Start capturing browser output.
3300 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3302 protected function startCapturingOutput() {
3304 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3308 * Stop capturing browser output and return as a csv.
3310 * @param bool $isFirstRowHeaders
3312 * @return \League\Csv\Reader
3314 * @throws \League\Csv\Exception
3316 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3317 $output = ob_get_flush();
3318 $stream = fopen('php://memory', 'r+');
3319 fwrite($stream, $output);
3321 $csv = Reader
::createFromString($output);
3322 if ($isFirstRowHeaders) {
3323 $csv->setHeaderOffset(0);