3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
30 use League\Csv\Reader
;
33 * Include class definitions
35 require_once 'api/api.php';
36 define('API_LATEST_VERSION', 3);
39 * Base class for CiviCRM unit tests
41 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
42 * may opt for one or neither:
44 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
45 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
46 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
47 * 2. useTransaction() executes the test inside a transaction. It's easier to use
48 * (because you don't need to identify specific tables), but it doesn't work for tests
49 * which manipulate schema or truncate data -- and could behave inconsistently
50 * for tests which specifically examine DB transactions.
52 * Common functions for unit tests
55 class CiviUnitTestCase
extends PHPUnit\Framework\TestCase
{
57 use \Civi\Test\Api3DocTrait
;
58 use \Civi\Test\GenericAssertionsTrait
;
59 use \Civi\Test\DbTestTrait
;
60 use \Civi\Test\ContactTestTrait
;
61 use \Civi\Test\MailingTestTrait
;
64 * Database has been initialized.
68 private static $dbInit = FALSE;
71 * Database connection.
73 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
82 static protected $_dbName;
85 * Track tables we have modified during a test.
88 protected $_tablesToTruncate = array();
91 * @var array of temporary directory names
96 * @var bool populateOnce allows to skip db resets in setUp
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
106 public static $populateOnce = FALSE;
109 * @var bool DBResetRequired allows skipping DB reset
110 * in specific test case. If you still need
111 * to reset single test (method) of such case, call
112 * $this->cleanDB() in the first line of this
115 public $DBResetRequired = TRUE;
118 * @var CRM_Core_Transaction|NULL
123 * Array of IDs created to support the test.
126 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
133 * Class used for hooks during tests.
135 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
137 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
139 * @var CRM_Utils_Hook_UnitTests hookClass
141 public $hookClass = NULL;
144 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
146 protected $_params = array();
149 * @var CRM_Extension_System
151 protected $origExtensionSystem;
154 * Array of IDs created during test setup routine.
156 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
160 public $setupIDs = array();
163 * PHPUnit Mock Method to use.
167 public $mockMethod = 'getMock';
172 * Because we are overriding the parent class constructor, we
173 * need to show the same arguments as exist in the constructor of
174 * PHPUnit_Framework_TestCase, since
175 * PHPUnit_Framework_TestSuite::createTest() creates a
176 * ReflectionClass of the Test class and checks the constructor
177 * of that class to decide how to set up the test.
179 * @param string $name
181 * @param string $dataName
183 public function __construct($name = NULL, array $data = array(), $dataName = '') {
184 parent
::__construct($name, $data, $dataName);
186 // we need full error reporting
187 error_reporting(E_ALL
& ~E_NOTICE
);
189 self
::$_dbName = self
::getDBName();
191 // also load the class loader
192 require_once 'CRM/Core/ClassLoader.php';
193 CRM_Core_ClassLoader
::singleton()->register();
194 if (function_exists('_civix_phpunit_setUp')) {
195 // FIXME: loosen coupling
196 _civix_phpunit_setUp();
198 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version
::id(), '5', '>=')) {
199 $this->mockMethod
= 'createMock';
201 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version
::id(), '6', '>=')) {
202 $this->mockMethod
= 'createMock';
207 * Override to run the test and assert its state.
210 * @throws \PHPUnit_Framework_IncompleteTest
211 * @throws \PHPUnit_Framework_SkippedTest
213 protected function runTest() {
215 return parent
::runTest();
217 catch (PEAR_Exception
$e) {
218 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
219 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
226 public function requireDBReset() {
227 return $this->DBResetRequired
;
233 public static function getDBName() {
234 static $dbName = NULL;
235 if ($dbName === NULL) {
236 require_once "DB.php";
237 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
238 $dbName = $dsninfo['database'];
244 * Create database connection for this instance.
246 * Initialize the test database if it hasn't been initialized
249 protected function getConnection() {
250 if (!self
::$dbInit) {
251 $dbName = self
::getDBName();
253 // install test database
254 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
256 static::_populateDB(FALSE, $this);
258 self
::$dbInit = TRUE;
264 * Required implementation of abstract method.
266 protected function getDataSet() {
270 * @param bool $perClass
271 * @param null $object
273 * TRUE if the populate logic runs; FALSE if it is skipped
275 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
276 if (CIVICRM_UF
!== 'UnitTests') {
277 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
280 if ($perClass ||
$object == NULL) {
284 $dbreset = $object->requireDBReset();
287 if (self
::$populateOnce ||
!$dbreset) {
290 self
::$populateOnce = NULL;
292 Civi\Test
::data()->populate();
297 public static function setUpBeforeClass() {
298 static::_populateDB(TRUE);
300 // also set this global hack
301 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
305 * Common setup functions for all unit tests.
307 protected function setUp() {
308 $session = CRM_Core_Session
::singleton();
309 $session->set('userID', NULL);
311 $this->_apiversion
= 3;
314 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
315 // Use a temporary file for STDIN
316 $GLOBALS['stdin'] = tmpfile();
317 if ($GLOBALS['stdin'] === FALSE) {
318 echo "Couldn't open temporary file\n";
322 // Get and save a connection to the database
323 $this->_dbconn
= $this->getConnection();
325 // reload database before each test
326 // $this->_populateDB();
328 // "initialize" CiviCRM to avoid problems when running single tests
329 // FIXME: look at it closer in second stage
331 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
332 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
334 // disable any left-over test extensions
335 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
337 // reset all the caches
338 CRM_Utils_System
::flushCache();
340 // initialize the object once db is loaded
341 \Civi
::$statics = array();
343 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
345 // when running unit tests, use mockup user framework
346 $this->hookClass
= CRM_Utils_Hook
::singleton();
348 // Make sure the DB connection is setup properly
349 $config->userSystem
->setMySQLTimeZone();
350 $env = new CRM_Utils_Check_Component_Env();
351 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
353 // clear permissions stub to not check permissions
354 $config->userPermissionClass
->permissions
= NULL;
356 //flush component settings
357 CRM_Core_Component
::getEnabledComponents(TRUE);
359 $_REQUEST = $_GET = $_POST = [];
360 error_reporting(E_ALL
);
362 $this->_sethtmlGlobals();
366 * Read everything from the datasets directory and insert into the db.
368 public function loadAllFixtures() {
369 $fixturesDir = __DIR__
. '/../../fixtures';
371 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
373 $jsonFiles = glob($fixturesDir . '/*.json');
374 foreach ($jsonFiles as $jsonFixture) {
375 $json = json_decode(file_get_contents($jsonFixture));
376 foreach ($json as $tableName => $vars) {
377 if ($tableName === 'civicrm_contact') {
378 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');
381 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
383 foreach ($vars as $entity) {
384 $keys = $values = [];
385 foreach ($entity as $key => $value) {
387 $values[] = is_numeric($value) ?
$value : "'{$value}'";
389 CRM_Core_DAO
::executeQuery("
390 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
397 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
401 * Load the data that used to be handled by the discontinued dbunit class.
403 * This could do with further tidy up - the initial priority is simply to get rid of
404 * the dbunity package which is no longer supported.
406 * @param string $fileName
408 protected function loadXMLDataSet($fileName) {
409 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
410 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
411 foreach ($xml as $tableName => $element) {
412 if (!empty($element)) {
413 foreach ($element as $row) {
414 $keys = $values = [];
415 if (isset($row['@attributes'])) {
416 foreach ($row['@attributes'] as $key => $value) {
418 $values[] = is_numeric($value) ?
$value : "'{$value}'";
421 elseif (!empty($row)) {
422 // cos we copied it & it is inconsistent....
423 foreach ($row as $key => $value) {
425 $values[] = is_numeric($value) ?
$value : "'{$value}'";
429 if (!empty($values)) {
430 CRM_Core_DAO
::executeQuery("
431 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
437 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
441 * Create default domain contacts for the two domains added during test class.
442 * database population.
444 public function createDomainContacts() {
445 $this->organizationCreate();
446 $this->organizationCreate(array('organization_name' => 'Second Domain'));
450 * Common teardown functions for all unit tests.
452 protected function tearDown() {
453 $this->_apiversion
= 3;
455 error_reporting(E_ALL
& ~E_NOTICE
);
456 CRM_Utils_Hook
::singleton()->reset();
457 if ($this->hookClass
) {
458 $this->hookClass
->reset();
460 CRM_Core_Session
::singleton()->reset(1);
463 $this->tx
->rollback()->commit();
466 CRM_Core_Transaction
::forceRollbackIfEnabled();
467 \Civi\Core\Transaction\Manager
::singleton(TRUE);
470 CRM_Core_Transaction
::forceRollbackIfEnabled();
471 \Civi\Core\Transaction\Manager
::singleton(TRUE);
473 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
474 $this->quickCleanup($tablesToTruncate);
475 $this->createDomainContacts();
478 $this->cleanTempDirs();
479 $this->unsetExtensionSystem();
480 $this->assertEquals([], CRM_Core_DAO
::$_nullArray);
481 $this->assertEquals(NULL, CRM_Core_DAO
::$_nullObject);
485 * Create a batch of external API calls which can
486 * be executed concurrently.
489 * $calls = $this->createExternalAPI()
490 * ->addCall('Contact', 'get', ...)
491 * ->addCall('Contact', 'get', ...)
497 * @return \Civi\API\ExternalBatch
498 * @throws PHPUnit_Framework_SkippedTestError
500 public function createExternalAPI() {
501 global $civicrm_root;
502 $defaultParams = array(
503 'version' => $this->_apiversion
,
507 $calls = new \Civi\API\
ExternalBatch($defaultParams);
509 if (!$calls->isSupported()) {
510 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
517 * Create required data based on $this->entity & $this->params
518 * This is just a way to set up the test data for delete & get functions
519 * so the distinction between set
520 * up & tested functions is clearer
525 public function createTestEntity() {
526 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
530 * @param int $contactTypeId
534 public function contactTypeDelete($contactTypeId) {
535 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
537 throw new Exception('Could not delete contact type');
542 * @param array $params
546 public function membershipTypeCreate($params = array()) {
547 CRM_Member_PseudoConstant
::flush('membershipType');
548 CRM_Core_Config
::clearDBCache();
549 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
550 $params = array_merge(array(
552 'duration_unit' => 'year',
553 'duration_interval' => 1,
554 'period_type' => 'rolling',
555 'member_of_contact_id' => $memberOfOrganization,
557 'financial_type_id' => 2,
560 'visibility' => 'Public',
563 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
565 CRM_Member_PseudoConstant
::flush('membershipType');
566 CRM_Utils_Cache
::singleton()->flush();
568 return $result['id'];
572 * @param array $params
576 public function contactMembershipCreate($params) {
577 $params = array_merge(array(
578 'join_date' => '2007-01-21',
579 'start_date' => '2007-01-21',
580 'end_date' => '2007-12-21',
581 'source' => 'Payment',
582 'membership_type_id' => 'General',
584 if (!is_numeric($params['membership_type_id'])) {
585 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
586 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
587 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
591 $result = $this->callAPISuccess('Membership', 'create', $params);
592 return $result['id'];
596 * Delete Membership Type.
598 * @param array $params
600 public function membershipTypeDelete($params) {
601 $this->callAPISuccess('MembershipType', 'Delete', $params);
605 * @param int $membershipID
607 public function membershipDelete($membershipID) {
608 $deleteParams = array('id' => $membershipID);
609 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
613 * @param string $name
617 public function membershipStatusCreate($name = 'test member status') {
618 $params['name'] = $name;
619 $params['start_event'] = 'start_date';
620 $params['end_event'] = 'end_date';
621 $params['is_current_member'] = 1;
622 $params['is_active'] = 1;
624 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
625 CRM_Member_PseudoConstant
::flush('membershipStatus');
626 return $result['id'];
630 * @param int $membershipStatusID
632 public function membershipStatusDelete($membershipStatusID) {
633 if (!$membershipStatusID) {
636 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
639 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
640 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
641 $renewedMembershipEndDate = new DateTime($membershipEndDate);
642 switch ($durationUnit) {
644 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
648 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
649 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
650 $renewedMembershipEndDate->add(new DateInterval('P1D'));
651 $renewedMembershipEndDate->add(new DateInterval('P1M'));
652 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
655 return $renewedMembershipEndDate->format('Y-m-d');
659 * @param array $params
663 public function relationshipTypeCreate($params = array()) {
664 $params = array_merge(array(
665 'name_a_b' => 'Relation 1 for relationship type create',
666 'name_b_a' => 'Relation 2 for relationship type create',
667 'contact_type_a' => 'Individual',
668 'contact_type_b' => 'Organization',
673 $result = $this->callAPISuccess('relationship_type', 'create', $params);
674 CRM_Core_PseudoConstant
::flush('relationshipType');
676 return $result['id'];
680 * Delete Relatinship Type.
682 * @param int $relationshipTypeID
684 public function relationshipTypeDelete($relationshipTypeID) {
685 $params['id'] = $relationshipTypeID;
686 $check = $this->callAPISuccess('relationship_type', 'get', $params);
687 if (!empty($check['count'])) {
688 $this->callAPISuccess('relationship_type', 'delete', $params);
693 * @param array $params
697 public function paymentProcessorTypeCreate($params = NULL) {
698 if (is_null($params)) {
700 'name' => 'API_Test_PP',
701 'title' => 'API Test Payment Processor',
702 'class_name' => 'CRM_Core_Payment_APITest',
703 'billing_mode' => 'form',
709 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
711 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
713 return $result['id'];
717 * Create test Authorize.net instance.
719 * @param array $params
723 public function paymentProcessorAuthorizeNetCreate($params = array()) {
724 $params = array_merge(array(
725 'name' => 'Authorize',
726 'domain_id' => CRM_Core_Config
::domainID(),
727 'payment_processor_type_id' => 'AuthNet',
728 'title' => 'AuthNet',
733 'user_name' => '4y5BfuW7jm',
734 'password' => '4cAmW927n8uLf5J8',
735 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
736 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
737 'class_name' => 'Payment_AuthorizeNet',
741 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
742 return $result['id'];
746 * Create Participant.
748 * @param array $params
749 * Array of contact id and event id values.
752 * $id of participant created
754 public function participantCreate($params = []) {
755 if (empty($params['contact_id'])) {
756 $params['contact_id'] = $this->individualCreate();
758 if (empty($params['event_id'])) {
759 $event = $this->eventCreate();
760 $params['event_id'] = $event['id'];
765 'register_date' => 20070219,
766 'source' => 'Wimbeldon',
767 'event_level' => 'Payment',
771 $params = array_merge($defaults, $params);
772 $result = $this->callAPISuccess('Participant', 'create', $params);
773 return $result['id'];
777 * Create Payment Processor.
780 * Id Payment Processor
782 public function processorCreate($params = array()) {
783 $processorParams = array(
786 'payment_processor_type_id' => 'Dummy',
787 'financial_account_id' => 12,
791 'url_site' => 'http://dummy.com',
792 'url_recur' => 'http://dummy.com',
795 'payment_instrument_id' => 'Debit Card',
797 $processorParams = array_merge($processorParams, $params);
798 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
799 return $processor['id'];
803 * Create Payment Processor.
805 * @param array $processorParams
807 * @return \CRM_Core_Payment_Dummy
808 * Instance of Dummy Payment Processor
810 public function dummyProcessorCreate($processorParams = array()) {
811 $paymentProcessorID = $this->processorCreate($processorParams);
812 return System
::singleton()->getById($paymentProcessorID);
816 * Create contribution page.
818 * @param array $params
820 * Array of contribution page
822 public function contributionPageCreate($params = array()) {
823 $this->_pageParams
= array_merge(array(
824 'title' => 'Test Contribution Page',
825 'financial_type_id' => 1,
827 'financial_account_id' => 1,
829 'is_allow_other_amount' => 1,
831 'max_amount' => 1000,
833 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
837 * Create a sample batch.
839 public function batchCreate() {
840 $params = $this->_params
;
841 $params['name'] = $params['title'] = 'Batch_433397';
842 $params['status_id'] = 1;
843 $result = $this->callAPISuccess('batch', 'create', $params);
844 return $result['id'];
850 * @param array $params
852 * result of created tag
854 public function tagCreate($params = array()) {
856 'name' => 'New Tag3',
857 'description' => 'This is description for Our New Tag ',
860 $params = array_merge($defaults, $params);
861 $result = $this->callAPISuccess('Tag', 'create', $params);
862 return $result['values'][$result['id']];
869 * Id of the tag to be deleted.
873 public function tagDelete($tagId) {
874 require_once 'api/api.php';
878 $result = $this->callAPISuccess('Tag', 'delete', $params);
879 return $result['id'];
883 * Add entity(s) to the tag
885 * @param array $params
889 public function entityTagAdd($params) {
890 $result = $this->callAPISuccess('entity_tag', 'create', $params);
897 * @param array $params
901 * id of created pledge
903 public function pledgeCreate($params) {
904 $params = array_merge(array(
905 'pledge_create_date' => date('Ymd'),
906 'start_date' => date('Ymd'),
907 'scheduled_date' => date('Ymd'),
909 'pledge_status_id' => '2',
910 'financial_type_id' => '1',
911 'pledge_original_installment_amount' => 20,
912 'frequency_interval' => 5,
913 'frequency_unit' => 'year',
914 'frequency_day' => 15,
919 $result = $this->callAPISuccess('Pledge', 'create', $params);
920 return $result['id'];
924 * Delete contribution.
926 * @param int $pledgeId
928 public function pledgeDelete($pledgeId) {
930 'pledge_id' => $pledgeId,
932 $this->callAPISuccess('Pledge', 'delete', $params);
936 * Create contribution.
938 * @param array $params
939 * Array of parameters.
942 * id of created contribution
944 public function contributionCreate($params) {
946 $params = array_merge(array(
948 'receive_date' => date('Ymd'),
949 'total_amount' => 100.00,
950 'fee_amount' => 5.00,
951 'financial_type_id' => 1,
952 'payment_instrument_id' => 1,
953 'non_deductible_amount' => 10.00,
955 'contribution_status_id' => 1,
958 $result = $this->callAPISuccess('contribution', 'create', $params);
959 return $result['id'];
963 * Delete contribution.
965 * @param int $contributionId
969 public function contributionDelete($contributionId) {
971 'contribution_id' => $contributionId,
973 $result = $this->callAPISuccess('contribution', 'delete', $params);
980 * @param array $params
981 * Name-value pair for an event.
985 public function eventCreate($params = array()) {
986 // if no contact was passed, make up a dummy event creator
987 if (!isset($params['contact_id'])) {
988 $params['contact_id'] = $this->_contactCreate(array(
989 'contact_type' => 'Individual',
990 'first_name' => 'Event',
991 'last_name' => 'Creator',
995 // set defaults for missing params
996 $params = array_merge(array(
997 'title' => 'Annual CiviCRM meet',
998 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
999 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1000 'event_type_id' => 1,
1002 'start_date' => 20081021,
1003 'end_date' => 20081023,
1004 'is_online_registration' => 1,
1005 'registration_start_date' => 20080601,
1006 'registration_end_date' => 20081015,
1007 'max_participants' => 100,
1008 'event_full_text' => 'Sorry! We are already full',
1011 'is_show_location' => 0,
1012 'is_email_confirm' => 1,
1015 return $this->callAPISuccess('Event', 'create', $params);
1019 * Create a paid event.
1021 * @param array $params
1025 protected function eventCreatePaid($params) {
1026 $event = $this->eventCreate($params);
1027 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1028 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1029 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1030 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1031 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1043 public function eventDelete($id) {
1047 return $this->callAPISuccess('event', 'delete', $params);
1051 * Delete participant.
1053 * @param int $participantID
1057 public function participantDelete($participantID) {
1059 'id' => $participantID,
1061 $check = $this->callAPISuccess('Participant', 'get', $params);
1062 if ($check['count'] > 0) {
1063 return $this->callAPISuccess('Participant', 'delete', $params);
1068 * Create participant payment.
1070 * @param int $participantID
1071 * @param int $contributionID
1073 * $id of created payment
1075 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1076 //Create Participant Payment record With Values
1078 'participant_id' => $participantID,
1079 'contribution_id' => $contributionID,
1082 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1083 return $result['id'];
1087 * Delete participant payment.
1089 * @param int $paymentID
1091 public function participantPaymentDelete($paymentID) {
1095 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1101 * @param int $contactID
1103 * location id of created location
1105 public function locationAdd($contactID) {
1108 'location_type' => 'New Location Type',
1110 'name' => 'Saint Helier St',
1111 'county' => 'Marin',
1112 'country' => 'UNITED STATES',
1113 'state_province' => 'Michigan',
1114 'supplemental_address_1' => 'Hallmark Ct',
1115 'supplemental_address_2' => 'Jersey Village',
1116 'supplemental_address_3' => 'My Town',
1121 'contact_id' => $contactID,
1122 'address' => $address,
1123 'location_format' => '2.0',
1124 'location_type' => 'New Location Type',
1127 $result = $this->callAPISuccess('Location', 'create', $params);
1132 * Delete Locations of contact.
1134 * @param array $params
1137 public function locationDelete($params) {
1138 $this->callAPISuccess('Location', 'delete', $params);
1142 * Add a Location Type.
1144 * @param array $params
1145 * @return CRM_Core_DAO_LocationType
1146 * location id of created location
1148 public function locationTypeCreate($params = NULL) {
1149 if ($params === NULL) {
1151 'name' => 'New Location Type',
1152 'vcard_name' => 'New Location Type',
1153 'description' => 'Location Type for Delete',
1158 $locationType = new CRM_Core_DAO_LocationType();
1159 $locationType->copyValues($params);
1160 $locationType->save();
1161 // clear getfields cache
1162 CRM_Core_PseudoConstant
::flush();
1163 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1164 return $locationType;
1168 * Delete a Location Type.
1170 * @param int $locationTypeId
1172 public function locationTypeDelete($locationTypeId) {
1173 $locationType = new CRM_Core_DAO_LocationType();
1174 $locationType->id
= $locationTypeId;
1175 $locationType->delete();
1181 * @param array $params
1182 * @return CRM_Core_DAO_Mapping
1183 * Mapping id of created mapping
1185 public function mappingCreate($params = NULL) {
1186 if ($params === NULL) {
1188 'name' => 'Mapping name',
1189 'description' => 'Mapping description',
1190 // 'Export Contact' mapping.
1191 'mapping_type_id' => 7,
1195 $mapping = new CRM_Core_DAO_Mapping();
1196 $mapping->copyValues($params);
1198 // clear getfields cache
1199 CRM_Core_PseudoConstant
::flush();
1200 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1207 * @param int $mappingId
1209 public function mappingDelete($mappingId) {
1210 $mapping = new CRM_Core_DAO_Mapping();
1211 $mapping->id
= $mappingId;
1216 * Prepare class for ACLs.
1218 protected function prepareForACLs() {
1219 $config = CRM_Core_Config
::singleton();
1220 $config->userPermissionClass
->permissions
= array();
1226 protected function cleanUpAfterACLs() {
1227 CRM_Utils_Hook
::singleton()->reset();
1228 $tablesToTruncate = array(
1230 'civicrm_acl_cache',
1231 'civicrm_acl_entity_role',
1232 'civicrm_acl_contact_cache',
1234 $this->quickCleanup($tablesToTruncate);
1235 $config = CRM_Core_Config
::singleton();
1236 unset($config->userPermissionClass
->permissions
);
1240 * Create a smart group.
1242 * By default it will be a group of households.
1244 * @param array $smartGroupParams
1245 * @param array $groupParams
1246 * @param string $contactType
1250 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1251 $smartGroupParams = array_merge([
1252 'formValues' => ['contact_type' => ['IN' => [$contactType]]],
1255 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1257 $groupParams['saved_search_id'] = $savedSearch->id
;
1258 return $this->groupCreate($groupParams);
1263 * @param array $params
1265 public function uFFieldCreate($params = array()) {
1266 $params = array_merge(array(
1268 'field_name' => 'first_name',
1271 'visibility' => 'Public Pages and Listings',
1272 'is_searchable' => '1',
1273 'label' => 'first_name',
1274 'field_type' => 'Individual',
1277 $this->callAPISuccess('uf_field', 'create', $params);
1281 * Add a UF Join Entry.
1283 * @param array $params
1285 * $id of created UF Join
1287 public function ufjoinCreate($params = NULL) {
1288 if ($params === NULL) {
1291 'module' => 'CiviEvent',
1292 'entity_table' => 'civicrm_event',
1298 $result = $this->callAPISuccess('uf_join', 'create', $params);
1303 * @param array $params
1304 * Optional parameters.
1305 * @param bool $reloadConfig
1306 * While enabling CiviCampaign component, we shouldn't always forcibly
1307 * reload config as this hinder hook call in test environment
1312 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1313 $this->enableCiviCampaign($reloadConfig);
1314 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1315 'name' => 'big_campaign',
1316 'title' => 'Campaign',
1318 return $campaign['id'];
1322 * Create Group for a contact.
1324 * @param int $contactId
1326 public function contactGroupCreate($contactId) {
1328 'contact_id.1' => $contactId,
1332 $this->callAPISuccess('GroupContact', 'Create', $params);
1336 * Delete Group for a contact.
1338 * @param int $contactId
1340 public function contactGroupDelete($contactId) {
1342 'contact_id.1' => $contactId,
1345 $this->civicrm_api('GroupContact', 'Delete', $params);
1351 * @param array $params
1354 public function activityCreate($params = array()) {
1355 $params = array_merge(array(
1356 'subject' => 'Discussion on warm beer',
1357 'activity_date_time' => date('Ymd'),
1358 'duration_hours' => 30,
1359 'duration_minutes' => 20,
1360 'location' => 'Baker Street',
1361 'details' => 'Lets schedule a meeting',
1363 'activity_type_id' => 'Meeting',
1365 if (!isset($params['source_contact_id'])) {
1366 $params['source_contact_id'] = $this->individualCreate();
1368 if (!isset($params['target_contact_id'])) {
1369 $params['target_contact_id'] = $this->individualCreate(array(
1370 'first_name' => 'Julia',
1371 'last_name' => 'Anderson',
1373 'email' => 'julia_anderson@civicrm.org',
1374 'contact_type' => 'Individual',
1377 if (!isset($params['assignee_contact_id'])) {
1378 $params['assignee_contact_id'] = $params['target_contact_id'];
1381 $result = civicrm_api3('Activity', 'create', $params);
1383 $result['target_contact_id'] = $params['target_contact_id'];
1384 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1389 * Create an activity type.
1391 * @param array $params
1395 public function activityTypeCreate($params) {
1396 return $this->callAPISuccess('ActivityType', 'create', $params);
1400 * Delete activity type.
1402 * @param int $activityTypeId
1403 * Id of the activity type.
1406 public function activityTypeDelete($activityTypeId) {
1407 $params['activity_type_id'] = $activityTypeId;
1408 return $this->callAPISuccess('ActivityType', 'delete', $params);
1412 * Create custom group.
1414 * @param array $params
1417 public function customGroupCreate($params = array()) {
1419 'title' => 'new custom group',
1420 'extends' => 'Contact',
1422 'style' => 'Inline',
1426 $params = array_merge($defaults, $params);
1428 return $this->callAPISuccess('custom_group', 'create', $params);
1432 * Existing function doesn't allow params to be over-ridden so need a new one
1433 * this one allows you to only pass in the params you want to change
1434 * @param array $params
1437 public function CustomGroupCreateByParams($params = array()) {
1439 'title' => "API Custom Group",
1440 'extends' => 'Contact',
1442 'style' => 'Inline',
1445 $params = array_merge($defaults, $params);
1446 return $this->callAPISuccess('custom_group', 'create', $params);
1450 * Create custom group with multi fields.
1451 * @param array $params
1454 public function CustomGroupMultipleCreateByParams($params = array()) {
1459 $params = array_merge($defaults, $params);
1460 return $this->CustomGroupCreateByParams($params);
1464 * Create custom group with multi fields.
1465 * @param array $params
1468 public function CustomGroupMultipleCreateWithFields($params = array()) {
1469 // also need to pass on $params['custom_field'] if not set but not in place yet
1471 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1472 $ids['custom_group_id'] = $customGroup['id'];
1474 $customField = $this->customFieldCreate(array(
1475 'custom_group_id' => $ids['custom_group_id'],
1476 'label' => 'field_1' . $ids['custom_group_id'],
1480 $ids['custom_field_id'][] = $customField['id'];
1482 $customField = $this->customFieldCreate(array(
1483 'custom_group_id' => $ids['custom_group_id'],
1484 'default_value' => '',
1485 'label' => 'field_2' . $ids['custom_group_id'],
1488 $ids['custom_field_id'][] = $customField['id'];
1490 $customField = $this->customFieldCreate(array(
1491 'custom_group_id' => $ids['custom_group_id'],
1492 'default_value' => '',
1493 'label' => 'field_3' . $ids['custom_group_id'],
1496 $ids['custom_field_id'][] = $customField['id'];
1502 * Create a custom group with a single text custom field. See
1503 * participant:testCreateWithCustom for how to use this
1505 * @param string $function
1507 * @param string $filename
1511 * ids of created objects
1513 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1514 $params = array('title' => $function);
1515 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1516 $params['extends'] = $entity ?
$entity : 'Contact';
1517 $customGroup = $this->CustomGroupCreate($params);
1518 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1519 CRM_Core_PseudoConstant
::flush();
1521 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1525 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1526 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1528 * @param string $function
1530 * @param string $filename
1534 * ids of created objects
1536 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1537 $params = array('title' => $function);
1538 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1539 $params['extends'] = $entity ?
$entity : 'Contact';
1540 $customGroup = $this->CustomGroupCreate($params);
1541 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1542 CRM_Core_PseudoConstant
::flush();
1544 'defaultValue' => 'Default Value',
1545 'lowercasevalue' => 'Lowercase Value',
1546 1 => 'Integer Value',
1549 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1550 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1551 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1552 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1553 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1554 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1555 foreach ($options as $option_value => $option_label) {
1556 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1557 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1560 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);
1564 * Delete custom group.
1566 * @param int $customGroupID
1570 public function customGroupDelete($customGroupID) {
1571 $params['id'] = $customGroupID;
1572 return $this->callAPISuccess('custom_group', 'delete', $params);
1576 * Create custom field.
1578 * @param array $params
1579 * (custom_group_id) is required.
1582 public function customFieldCreate($params) {
1583 $params = array_merge(array(
1584 'label' => 'Custom Field',
1585 'data_type' => 'String',
1586 'html_type' => 'Text',
1587 'is_searchable' => 1,
1589 'default_value' => 'defaultValue',
1592 $result = $this->callAPISuccess('custom_field', 'create', $params);
1593 // these 2 functions are called with force to flush static caches
1594 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1595 CRM_Core_Component
::getEnabledComponents(1);
1600 * Delete custom field.
1602 * @param int $customFieldID
1606 public function customFieldDelete($customFieldID) {
1608 $params['id'] = $customFieldID;
1609 return $this->callAPISuccess('custom_field', 'delete', $params);
1618 public function noteCreate($cId) {
1620 'entity_table' => 'civicrm_contact',
1621 'entity_id' => $cId,
1622 'note' => 'hello I am testing Note',
1623 'contact_id' => $cId,
1624 'modified_date' => date('Ymd'),
1625 'subject' => 'Test Note',
1628 return $this->callAPISuccess('Note', 'create', $params);
1632 * Enable CiviCampaign Component.
1634 * @param bool $reloadConfig
1635 * Force relaod config or not
1637 public function enableCiviCampaign($reloadConfig = TRUE) {
1638 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1639 if ($reloadConfig) {
1640 // force reload of config object
1641 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1643 //flush cache by calling with reset
1644 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1648 * Create custom field with Option Values.
1650 * @param array $customGroup
1651 * @param string $name
1652 * Name of custom field.
1653 * @param array $extraParams
1654 * Additional parameters to pass through.
1658 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1659 $fieldParams = array(
1660 'custom_group_id' => $customGroup['id'],
1661 'name' => 'test_custom_group',
1662 'label' => 'Country',
1663 'html_type' => 'Select',
1664 'data_type' => 'String',
1667 'is_searchable' => 0,
1671 $optionGroup = array(
1673 'name' => 'option_group1',
1674 'label' => 'option_group_label1',
1677 $optionValue = array(
1678 'option_label' => array('Label1', 'Label2'),
1679 'option_value' => array('value1', 'value2'),
1680 'option_name' => array($name . '_1', $name . '_2'),
1681 'option_weight' => array(1, 2),
1682 'option_status' => array(1, 1),
1685 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1687 return $this->callAPISuccess('custom_field', 'create', $params);
1695 public function confirmEntitiesDeleted($entities) {
1696 foreach ($entities as $entity) {
1698 $result = $this->callAPISuccess($entity, 'Get', array());
1699 if ($result['error'] == 1 ||
$result['count'] > 0) {
1700 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1708 * Quick clean by emptying tables created for the test.
1710 * @param array $tablesToTruncate
1711 * @param bool $dropCustomValueTables
1712 * @throws \CRM_Core_Exception
1714 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1716 throw new \
CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1718 if ($dropCustomValueTables) {
1719 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1720 while ($optionGroupResult->fetch()) {
1721 if (!empty($optionGroupResult->option_group_id
)) {
1722 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1725 $tablesToTruncate[] = 'civicrm_custom_group';
1726 $tablesToTruncate[] = 'civicrm_custom_field';
1729 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1731 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1732 foreach ($tablesToTruncate as $table) {
1733 $sql = "TRUNCATE TABLE $table";
1734 CRM_Core_DAO
::executeQuery($sql);
1736 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1738 if ($dropCustomValueTables) {
1739 $dbName = self
::getDBName();
1741 SELECT TABLE_NAME as tableName
1742 FROM INFORMATION_SCHEMA.TABLES
1743 WHERE TABLE_SCHEMA = '{$dbName}'
1744 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1747 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1748 while ($tableDAO->fetch()) {
1749 $sql = "DROP TABLE {$tableDAO->tableName}";
1750 CRM_Core_DAO
::executeQuery($sql);
1756 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1758 public function quickCleanUpFinancialEntities() {
1759 $tablesToTruncate = array(
1761 'civicrm_activity_contact',
1762 'civicrm_contribution',
1763 'civicrm_contribution_soft',
1764 'civicrm_contribution_product',
1765 'civicrm_financial_trxn',
1766 'civicrm_financial_item',
1767 'civicrm_contribution_recur',
1768 'civicrm_line_item',
1769 'civicrm_contribution_page',
1770 'civicrm_payment_processor',
1771 'civicrm_entity_financial_trxn',
1772 'civicrm_membership',
1773 'civicrm_membership_type',
1774 'civicrm_membership_payment',
1775 'civicrm_membership_log',
1776 'civicrm_membership_block',
1778 'civicrm_participant',
1779 'civicrm_participant_payment',
1781 'civicrm_pledge_block',
1782 'civicrm_pledge_payment',
1783 'civicrm_price_set_entity',
1784 'civicrm_price_field_value',
1785 'civicrm_price_field',
1787 $this->quickCleanup($tablesToTruncate);
1788 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1789 $this->restoreDefaultPriceSetConfig();
1791 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1792 $this->disableTaxAndInvoicing();
1793 $this->setCurrencySeparators(',');
1794 CRM_Core_PseudoConstant
::flush('taxRates');
1795 System
::singleton()->flushProcessors();
1796 // @fixme this parameter is leaking - it should not be defined as a class static
1797 // but for now we just handle in tear down.
1798 CRM_Contribute_BAO_Query
::$_contribOrSoftCredit = 'only contribs';
1801 public function restoreDefaultPriceSetConfig() {
1802 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1803 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1804 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)");
1805 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)");
1809 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1810 * Default behaviour is to also delete the entity
1811 * @param array $params
1812 * Params array to check against.
1814 * Id of the entity concerned.
1815 * @param string $entity
1816 * Name of entity concerned (e.g. membership).
1817 * @param bool $delete
1818 * Should the entity be deleted as part of this check.
1819 * @param string $errorText
1820 * Text to print on error.
1824 * @param array $params
1827 * @param int $delete
1828 * @param string $errorText
1832 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1834 $result = $this->callAPISuccessGetSingle($entity, array(
1839 $this->callAPISuccess($entity, 'Delete', array(
1843 $dateFields = $keys = $dateTimeFields = array();
1844 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1845 foreach ($fields['values'] as $field => $settings) {
1846 if (array_key_exists($field, $result)) {
1847 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1850 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1852 $type = CRM_Utils_Array
::value('type', $settings);
1853 if ($type == CRM_Utils_Type
::T_DATE
) {
1854 $dateFields[] = $settings['name'];
1855 // we should identify both real names & unique names as dates
1856 if ($field != $settings['name']) {
1857 $dateFields[] = $field;
1860 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1861 $dateTimeFields[] = $settings['name'];
1862 // we should identify both real names & unique names as dates
1863 if ($field != $settings['name']) {
1864 $dateTimeFields[] = $field;
1869 if (strtolower($entity) == 'contribution') {
1870 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1871 // this is not returned in id format
1872 unset($params['payment_instrument_id']);
1873 $params['contribution_source'] = $params['source'];
1874 unset($params['source']);
1877 foreach ($params as $key => $value) {
1878 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1881 if (in_array($key, $dateFields)) {
1882 $value = date('Y-m-d', strtotime($value));
1883 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1885 if (in_array($key, $dateTimeFields)) {
1886 $value = date('Y-m-d H:i:s', strtotime($value));
1887 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1889 $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);
1894 * Get formatted values in the actual and expected result.
1895 * @param array $actual
1896 * Actual calculated values.
1897 * @param array $expected
1900 public function checkArrayEquals(&$actual, &$expected) {
1901 self
::unsetId($actual);
1902 self
::unsetId($expected);
1903 $this->assertEquals($expected, $actual);
1907 * Unset the key 'id' from the array
1908 * @param array $unformattedArray
1909 * The array from which the 'id' has to be unset.
1911 public static function unsetId(&$unformattedArray) {
1912 $formattedArray = array();
1913 if (array_key_exists('id', $unformattedArray)) {
1914 unset($unformattedArray['id']);
1916 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1917 foreach ($unformattedArray['values'] as $key => $value) {
1918 if (is_array($value)) {
1919 foreach ($value as $k => $v) {
1925 elseif ($key == 'id') {
1926 $unformattedArray[$key];
1928 $formattedArray = array($value);
1930 $unformattedArray['values'] = $formattedArray;
1935 * Helper to enable/disable custom directory support
1937 * @param array $customDirs
1939 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1940 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1942 public function customDirectories($customDirs) {
1943 $config = CRM_Core_Config
::singleton();
1945 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1946 unset($config->customPHPPathDir
);
1948 elseif ($customDirs['php_path'] === TRUE) {
1949 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1952 $config->customPHPPathDir
= $php_path;
1955 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1956 unset($config->customTemplateDir
);
1958 elseif ($customDirs['template_path'] === TRUE) {
1959 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1962 $config->customTemplateDir
= $template_path;
1967 * Generate a temporary folder.
1969 * @param string $prefix
1972 public function createTempDir($prefix = 'test-') {
1973 $tempDir = CRM_Utils_File
::tempdir($prefix);
1974 $this->tempDirs
[] = $tempDir;
1978 public function cleanTempDirs() {
1979 if (!is_array($this->tempDirs
)) {
1980 // fix test errors where this is not set
1983 foreach ($this->tempDirs
as $tempDir) {
1984 if (is_dir($tempDir)) {
1985 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1991 * Temporarily replace the singleton extension with a different one.
1992 * @param \CRM_Extension_System $system
1994 public function setExtensionSystem(CRM_Extension_System
$system) {
1995 if ($this->origExtensionSystem
== NULL) {
1996 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1998 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2001 public function unsetExtensionSystem() {
2002 if ($this->origExtensionSystem
!== NULL) {
2003 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2004 $this->origExtensionSystem
= NULL;
2009 * Temporarily alter the settings-metadata to add a mock setting.
2011 * WARNING: The setting metadata will disappear on the next cache-clear.
2016 public function setMockSettingsMetaData($extras) {
2017 CRM_Utils_Hook
::singleton()
2018 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2019 $metadata = array_merge($metadata, $extras);
2022 Civi
::service('settings_manager')->flush();
2024 $fields = $this->callAPISuccess('setting', 'getfields', array());
2025 foreach ($extras as $key => $spec) {
2026 $this->assertNotEmpty($spec['title']);
2027 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2032 * @param string $name
2034 public function financialAccountDelete($name) {
2035 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2036 $financialAccount->name
= $name;
2037 if ($financialAccount->find(TRUE)) {
2038 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2039 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2040 $entityFinancialType->delete();
2041 $financialAccount->delete();
2046 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2047 * (NB unclear if this is still required)
2049 public function _sethtmlGlobals() {
2050 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2051 'required' => array(
2052 'html_quickform_rule_required',
2053 'HTML/QuickForm/Rule/Required.php',
2055 'maxlength' => array(
2056 'html_quickform_rule_range',
2057 'HTML/QuickForm/Rule/Range.php',
2059 'minlength' => array(
2060 'html_quickform_rule_range',
2061 'HTML/QuickForm/Rule/Range.php',
2063 'rangelength' => array(
2064 'html_quickform_rule_range',
2065 'HTML/QuickForm/Rule/Range.php',
2068 'html_quickform_rule_email',
2069 'HTML/QuickForm/Rule/Email.php',
2072 'html_quickform_rule_regex',
2073 'HTML/QuickForm/Rule/Regex.php',
2075 'lettersonly' => array(
2076 'html_quickform_rule_regex',
2077 'HTML/QuickForm/Rule/Regex.php',
2079 'alphanumeric' => array(
2080 'html_quickform_rule_regex',
2081 'HTML/QuickForm/Rule/Regex.php',
2084 'html_quickform_rule_regex',
2085 'HTML/QuickForm/Rule/Regex.php',
2087 'nopunctuation' => array(
2088 'html_quickform_rule_regex',
2089 'HTML/QuickForm/Rule/Regex.php',
2092 'html_quickform_rule_regex',
2093 'HTML/QuickForm/Rule/Regex.php',
2095 'callback' => array(
2096 'html_quickform_rule_callback',
2097 'HTML/QuickForm/Rule/Callback.php',
2100 'html_quickform_rule_compare',
2101 'HTML/QuickForm/Rule/Compare.php',
2104 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2105 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2107 'HTML/QuickForm/group.php',
2108 'HTML_QuickForm_group',
2111 'HTML/QuickForm/hidden.php',
2112 'HTML_QuickForm_hidden',
2115 'HTML/QuickForm/reset.php',
2116 'HTML_QuickForm_reset',
2118 'checkbox' => array(
2119 'HTML/QuickForm/checkbox.php',
2120 'HTML_QuickForm_checkbox',
2123 'HTML/QuickForm/file.php',
2124 'HTML_QuickForm_file',
2127 'HTML/QuickForm/image.php',
2128 'HTML_QuickForm_image',
2130 'password' => array(
2131 'HTML/QuickForm/password.php',
2132 'HTML_QuickForm_password',
2135 'HTML/QuickForm/radio.php',
2136 'HTML_QuickForm_radio',
2139 'HTML/QuickForm/button.php',
2140 'HTML_QuickForm_button',
2143 'HTML/QuickForm/submit.php',
2144 'HTML_QuickForm_submit',
2147 'HTML/QuickForm/select.php',
2148 'HTML_QuickForm_select',
2150 'hiddenselect' => array(
2151 'HTML/QuickForm/hiddenselect.php',
2152 'HTML_QuickForm_hiddenselect',
2155 'HTML/QuickForm/text.php',
2156 'HTML_QuickForm_text',
2158 'textarea' => array(
2159 'HTML/QuickForm/textarea.php',
2160 'HTML_QuickForm_textarea',
2162 'fckeditor' => array(
2163 'HTML/QuickForm/fckeditor.php',
2164 'HTML_QuickForm_FCKEditor',
2167 'HTML/QuickForm/tinymce.php',
2168 'HTML_QuickForm_TinyMCE',
2170 'dojoeditor' => array(
2171 'HTML/QuickForm/dojoeditor.php',
2172 'HTML_QuickForm_dojoeditor',
2175 'HTML/QuickForm/link.php',
2176 'HTML_QuickForm_link',
2178 'advcheckbox' => array(
2179 'HTML/QuickForm/advcheckbox.php',
2180 'HTML_QuickForm_advcheckbox',
2183 'HTML/QuickForm/date.php',
2184 'HTML_QuickForm_date',
2187 'HTML/QuickForm/static.php',
2188 'HTML_QuickForm_static',
2191 'HTML/QuickForm/header.php',
2192 'HTML_QuickForm_header',
2195 'HTML/QuickForm/html.php',
2196 'HTML_QuickForm_html',
2198 'hierselect' => array(
2199 'HTML/QuickForm/hierselect.php',
2200 'HTML_QuickForm_hierselect',
2202 'autocomplete' => array(
2203 'HTML/QuickForm/autocomplete.php',
2204 'HTML_QuickForm_autocomplete',
2207 'HTML/QuickForm/xbutton.php',
2208 'HTML_QuickForm_xbutton',
2210 'advmultiselect' => array(
2211 'HTML/QuickForm/advmultiselect.php',
2212 'HTML_QuickForm_advmultiselect',
2218 * Set up an acl allowing contact to see 2 specified groups
2219 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2221 * You need to have pre-created these groups & created the user e.g
2222 * $this->createLoggedInUser();
2223 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2224 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2226 * @param bool $isProfile
2228 public function setupACL($isProfile = FALSE) {
2230 $_REQUEST = $this->_params
;
2232 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2233 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2234 $ov = new CRM_Core_DAO_OptionValue();
2235 $ov->option_group_id
= $optionGroupID;
2237 if ($ov->find(TRUE)) {
2238 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2240 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2241 'option_group_id' => $optionGroupID,
2242 'label' => 'pick me',
2246 CRM_Core_DAO
::executeQuery("
2247 TRUNCATE civicrm_acl_cache
2250 CRM_Core_DAO
::executeQuery("
2251 TRUNCATE civicrm_acl_contact_cache
2254 CRM_Core_DAO
::executeQuery("
2255 INSERT INTO civicrm_acl_entity_role (
2256 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2257 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2261 CRM_Core_DAO
::executeQuery("
2262 INSERT INTO civicrm_acl (
2263 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2266 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2271 CRM_Core_DAO
::executeQuery("
2272 INSERT INTO civicrm_acl (
2273 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2276 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2280 CRM_Core_DAO
::executeQuery("
2281 INSERT INTO civicrm_acl (
2282 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2285 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2290 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2291 $this->callAPISuccess('group_contact', 'create', array(
2292 'group_id' => $this->_permissionedGroup
,
2293 'contact_id' => $this->_loggedInUser
,
2298 CRM_ACL_BAO_Cache
::resetCache();
2299 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2304 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2306 public function offsetDefaultPriceSet() {
2307 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2308 $firstID = $contributionPriceSet['id'];
2309 $this->callAPISuccess('price_set', 'create', array(
2310 'id' => $contributionPriceSet['id'],
2314 unset($contributionPriceSet['id']);
2315 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2316 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2317 'price_set_id' => $firstID,
2318 'options' => array('limit' => 1),
2320 unset($priceField['id']);
2321 $priceField['price_set_id'] = $newPriceSet['id'];
2322 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2323 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2324 'price_set_id' => $firstID,
2326 'options' => array('limit' => 1),
2329 unset($priceFieldValue['id']);
2330 //create some padding to use up ids
2331 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2332 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2333 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2337 * Create an instance of the paypal processor.
2338 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2339 * this parent class & we don't have a structure for that yet
2340 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2341 * & the best protection against that is the functions this class affords
2342 * @param array $params
2343 * @return int $result['id'] payment processor id
2345 public function paymentProcessorCreate($params = array()) {
2346 $params = array_merge(array(
2348 'domain_id' => CRM_Core_Config
::domainID(),
2349 'payment_processor_type_id' => 'PayPal',
2353 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2354 'password' => '1183377788',
2355 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2356 'url_site' => 'https://www.sandbox.paypal.com/',
2357 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2358 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2359 'class_name' => 'Payment_PayPalImpl',
2360 'billing_mode' => 3,
2361 'financial_type_id' => 1,
2362 'financial_account_id' => 12,
2363 // Credit card = 1 so can pass 'by accident'.
2364 'payment_instrument_id' => 'Debit Card',
2366 if (!is_numeric($params['payment_processor_type_id'])) {
2367 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2369 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2370 'name' => $params['payment_processor_type_id'],
2374 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2375 return $result['id'];
2379 * Set up initial recurring payment allowing subsequent IPN payments.
2381 * @param array $recurParams (Optional)
2382 * @param array $contributionParams (Optional)
2384 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2385 $contributionParams = array_merge([
2386 'total_amount' => '200',
2387 'invoice_id' => $this->_invoiceID
,
2388 'financial_type_id' => 'Donation',
2389 'contribution_status_id' => 'Pending',
2390 'contact_id' => $this->_contactID
,
2391 'contribution_page_id' => $this->_contributionPageID
,
2392 'payment_processor_id' => $this->_paymentProcessorID
,
2394 'receive_date' => '2019-07-25 07:34:23',
2395 'skipCleanMoney' => TRUE,
2396 ], $contributionParams);
2397 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2398 'contact_id' => $this->_contactID
,
2401 'installments' => 5,
2402 'frequency_unit' => 'Month',
2403 'frequency_interval' => 1,
2404 'invoice_id' => $this->_invoiceID
,
2405 'contribution_status_id' => 2,
2406 'payment_processor_id' => $this->_paymentProcessorID
,
2407 // processor provided ID - use contact ID as proxy.
2408 'processor_id' => $this->_contactID
,
2409 'api.contribution.create' => $contributionParams,
2411 $this->_contributionRecurID
= $contributionRecur['id'];
2412 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2416 * 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
2418 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2420 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2421 $membershipParams = $recurParams = array();
2422 if (!empty($params['duration_unit'])) {
2423 $membershipParams['duration_unit'] = $params['duration_unit'];
2425 if (!empty($params['frequency_unit'])) {
2426 $recurParams['frequency_unit'] = $params['frequency_unit'];
2429 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2430 //create a contribution so our membership & contribution don't both have id = 1
2431 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2432 $this->contributionCreate(array(
2433 'contact_id' => $this->_contactID
,
2435 'financial_type_id' => 1,
2436 'invoice_id' => 'abcd',
2438 'receive_date' => '2019-07-25 07:34:23',
2441 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2443 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2444 'contact_id' => $this->_contactID
,
2445 'membership_type_id' => $this->ids
['membership_type'],
2446 'contribution_recur_id' => $this->_contributionRecurID
,
2447 'format.only_id' => TRUE,
2448 'source' => 'Payment',
2450 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2451 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2453 $this->callAPISuccess('line_item', 'create', array(
2454 'entity_table' => 'civicrm_membership',
2455 'entity_id' => $this->ids
['membership'],
2456 'contribution_id' => $this->_contributionID
,
2457 'label' => 'General',
2459 'unit_price' => 200,
2460 'line_total' => 200,
2461 'financial_type_id' => 1,
2462 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2464 'label' => 'Membership Amount',
2465 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2467 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2469 'label' => 'General',
2470 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2473 $this->callAPISuccess('membership_payment', 'create', array(
2474 'contribution_id' => $this->_contributionID
,
2475 'membership_id' => $this->ids
['membership'],
2484 public function CiviUnitTestCase_fatalErrorHandler($message) {
2485 throw new Exception("{$message['message']}: {$message['code']}");
2489 * Wrap the entire test case in a transaction.
2491 * Only subsequent DB statements will be wrapped in TX -- this cannot
2492 * retroactively wrap old DB statements. Therefore, it makes sense to
2493 * call this at the beginning of setUp().
2495 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2496 * this option does not work with, e.g., custom-data.
2498 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2499 * if TRUNCATE or ALTER is called while using a transaction.
2502 * Whether to use nesting or reference-counting.
2504 public function useTransaction($nest = TRUE) {
2506 $this->tx
= new CRM_Core_Transaction($nest);
2507 $this->tx
->rollback();
2512 * Assert the attachment exists.
2514 * @param bool $exists
2515 * @param array $apiResult
2517 protected function assertAttachmentExistence($exists, $apiResult) {
2518 $fileId = $apiResult['id'];
2519 $this->assertTrue(is_numeric($fileId));
2520 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2521 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2522 1 => array($fileId, 'Int'),
2524 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2525 1 => array($fileId, 'Int'),
2530 * Assert 2 sql strings are the same, ignoring double spaces.
2532 * @param string $expectedSQL
2533 * @param string $actualSQL
2534 * @param string $message
2536 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2537 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2538 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2539 $this->assertEquals($expected, $actual, $message);
2543 * Create a price set for an event.
2545 * @param int $feeTotal
2546 * @param int $minAmt
2547 * @param string $type
2551 * @throws \CRM_Core_Exception
2553 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2554 // creating price set, price field
2555 $paramsSet['title'] = 'Price Set';
2556 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2557 $paramsSet['is_active'] = FALSE;
2558 $paramsSet['extends'] = 1;
2559 $paramsSet['min_amount'] = $minAmt;
2561 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2562 $this->_ids
['price_set'] = $priceSet->id
;
2564 $paramsField = array(
2565 'label' => 'Price Field',
2566 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2567 'html_type' => $type,
2568 'price' => $feeTotal,
2569 'option_label' => array('1' => 'Price Field'),
2570 'option_value' => array('1' => $feeTotal),
2571 'option_name' => array('1' => $feeTotal),
2572 'option_weight' => array('1' => 1),
2573 'option_amount' => array('1' => 1),
2574 'is_display_amounts' => 1,
2576 'options_per_line' => 1,
2577 'is_active' => array('1' => 1),
2578 'price_set_id' => $this->_ids
['price_set'],
2579 'is_enter_qty' => 1,
2580 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2582 if ($type === 'Radio') {
2583 $paramsField['is_enter_qty'] = 0;
2584 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2585 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2587 $this->callAPISuccess('PriceField', 'create', $paramsField);
2588 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2589 $this->_ids
['price_field'] = array_keys($fields['values']);
2590 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2591 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2593 return $this->_ids
['price_set'];
2597 * Add a profile to a contribution page.
2599 * @param string $name
2600 * @param int $contributionPageID
2601 * @param string $module
2603 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2605 'uf_group_id' => $name,
2606 'module' => $module,
2607 'entity_table' => 'civicrm_contribution_page',
2608 'entity_id' => $contributionPageID,
2611 if ($module !== 'CiviContribute') {
2612 $params['module_data'] = [$module => []];
2614 $this->callAPISuccess('UFJoin', 'create', $params);
2618 * Add participant with contribution
2622 protected function createParticipantWithContribution() {
2623 // creating price set, price field
2624 $this->_contactId
= $this->individualCreate();
2625 $event = $this->eventCreate();
2626 $this->_eventId
= $event['id'];
2627 $eventParams = array(
2628 'id' => $this->_eventId
,
2629 'financial_type_id' => 4,
2632 $this->callAPISuccess('event', 'create', $eventParams);
2633 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2634 $participantParams = array(
2635 'financial_type_id' => 4,
2636 'event_id' => $this->_eventId
,
2639 'fee_currency' => 'USD',
2640 'contact_id' => $this->_contactId
,
2642 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2643 $contributionParams = array(
2644 'total_amount' => 150,
2645 'currency' => 'USD',
2646 'contact_id' => $this->_contactId
,
2647 'financial_type_id' => 4,
2648 'contribution_status_id' => 1,
2649 'partial_payment_total' => 300.00,
2650 'partial_amount_to_pay' => 150,
2651 'contribution_mode' => 'participant',
2652 'participant_id' => $participant['id'],
2654 foreach ($priceFields['values'] as $key => $priceField) {
2655 $lineItems[1][$key] = array(
2656 'price_field_id' => $priceField['price_field_id'],
2657 'price_field_value_id' => $priceField['id'],
2658 'label' => $priceField['label'],
2659 'field_title' => $priceField['label'],
2661 'unit_price' => $priceField['amount'],
2662 'line_total' => $priceField['amount'],
2663 'financial_type_id' => $priceField['financial_type_id'],
2666 $contributionParams['line_item'] = $lineItems;
2667 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2668 $paymentParticipant = array(
2669 'participant_id' => $participant['id'],
2670 'contribution_id' => $contribution['id'],
2672 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2673 return array($lineItems, $contribution);
2679 * @param string $component
2680 * @param int $componentId
2681 * @param array $priceFieldOptions
2685 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2686 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2687 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2688 $paramsSet['is_active'] = TRUE;
2689 $paramsSet['financial_type_id'] = 'Event Fee';
2690 $paramsSet['extends'] = 1;
2691 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2692 $priceSetId = $priceSet['id'];
2693 //Checking for priceset added in the table.
2694 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2695 'id', $paramsSet['title'], 'Check DB for created priceset'
2697 $paramsField = array_merge(array(
2698 'label' => 'Price Field',
2699 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2700 'html_type' => 'CheckBox',
2701 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2702 'option_value' => array('1' => 100, '2' => 200),
2703 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2704 'option_weight' => array('1' => 1, '2' => 2),
2705 'option_amount' => array('1' => 100, '2' => 200),
2706 'is_display_amounts' => 1,
2708 'options_per_line' => 1,
2709 'is_active' => array('1' => 1, '2' => 1),
2710 'price_set_id' => $priceSet['id'],
2711 'is_enter_qty' => 1,
2712 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2713 ), $priceFieldOptions);
2715 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2717 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2719 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2723 * Replace the template with a test-oriented template designed to show all the variables.
2725 * @param string $templateName
2727 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2728 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2729 CRM_Core_DAO
::executeQuery(
2730 "UPDATE civicrm_option_group og
2731 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2732 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2733 SET m.msg_html = '{$testTemplate}'
2734 WHERE og.name = 'msg_tpl_workflow_contribution'
2735 AND ov.name = '{$templateName}'
2736 AND m.is_default = 1"
2741 * Reinstate the default template.
2743 * @param string $templateName
2745 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2746 CRM_Core_DAO
::executeQuery(
2747 "UPDATE civicrm_option_group og
2748 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2749 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2750 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2751 SET m.msg_html = m2.msg_html
2752 WHERE og.name = 'msg_tpl_workflow_contribution'
2753 AND ov.name = '{$templateName}'
2754 AND m.is_default = 1"
2759 * Flush statics relating to financial type.
2761 protected function flushFinancialTypeStatics() {
2762 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2763 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2765 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2766 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2768 CRM_Contribute_PseudoConstant
::flush('financialType');
2769 CRM_Contribute_PseudoConstant
::flush('membershipType');
2770 // Pseudoconstants may be saved to the cache table.
2771 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2772 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2773 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2777 * Set the permissions to the supplied array.
2779 * @param array $permissions
2781 protected function setPermissions($permissions) {
2782 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2783 $this->flushFinancialTypeStatics();
2787 * @param array $params
2790 public function _checkFinancialRecords($params, $context) {
2791 $entityParams = array(
2792 'entity_id' => $params['id'],
2793 'entity_table' => 'civicrm_contribution',
2795 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2796 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2797 if ($context == 'pending') {
2798 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2799 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2802 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2803 $trxnParams = array(
2804 'id' => $trxn['financial_trxn_id'],
2806 if ($context != 'online' && $context != 'payLater') {
2807 $compareParams = array(
2808 'to_financial_account_id' => 6,
2809 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2813 if ($context == 'feeAmount') {
2814 $compareParams['fee_amount'] = 50;
2816 elseif ($context == 'online') {
2817 $compareParams = array(
2818 'to_financial_account_id' => 12,
2819 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2821 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2824 elseif ($context == 'payLater') {
2825 $compareParams = array(
2826 'to_financial_account_id' => 7,
2827 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2831 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2832 $entityParams = array(
2833 'financial_trxn_id' => $trxn['financial_trxn_id'],
2834 'entity_table' => 'civicrm_financial_item',
2836 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2837 $fitemParams = array(
2838 'id' => $entityTrxn['entity_id'],
2840 $compareParams = array(
2841 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2843 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2845 if ($context == 'payLater') {
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),
2852 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2853 if ($context == 'feeAmount') {
2855 'entity_id' => $params['id'],
2856 'entity_table' => 'civicrm_contribution',
2858 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2859 $trxnParams = array(
2860 'id' => $maxTrxn['financial_trxn_id'],
2862 $compareParams = array(
2863 'to_financial_account_id' => 5,
2864 'from_financial_account_id' => 6,
2865 'total_amount' => 50,
2868 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2869 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2870 $fitemParams = array(
2871 'entity_id' => $trxnId['financialTrxnId'],
2872 'entity_table' => 'civicrm_financial_trxn',
2874 $compareParams = array(
2877 'financial_account_id' => 5,
2879 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2881 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2882 // line should be copied into all the functions that call this function & evaluated there
2883 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2884 // when calling completeTransaction or repeatTransaction.
2885 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2889 * Return financial type id on basis of name
2891 * @param string $name Financial type m/c name
2895 public function getFinancialTypeId($name) {
2896 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2900 * Cleanup function for contents of $this->ids.
2902 * This is a best effort cleanup to use in tear downs etc.
2904 * It will not fail if the data has already been removed (some tests may do
2905 * their own cleanup).
2907 protected function cleanUpSetUpIDs() {
2908 foreach ($this->setupIDs
as $entity => $id) {
2910 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2912 catch (CiviCRM_API3_Exception
$e) {
2913 // This is a best-effort cleanup function, ignore.
2919 * Create Financial Type.
2921 * @param array $params
2925 protected function createFinancialType($params = array()) {
2926 $params = array_merge($params,
2928 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2932 return $this->callAPISuccess('FinancialType', 'create', $params);
2936 * Create Payment Instrument.
2938 * @param array $params
2939 * @param string $financialAccountName
2943 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2944 $params = array_merge(array(
2945 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2946 'option_group_id' => 'payment_instrument',
2949 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2951 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2953 $financialAccountParams = [
2954 'entity_table' => 'civicrm_option_value',
2955 'entity_id' => $newPaymentInstrument,
2956 'account_relationship' => $relationTypeID,
2957 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2959 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2961 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2965 * Enable Tax and Invoicing
2967 protected function enableTaxAndInvoicing($params = array()) {
2968 // Enable component contribute setting
2969 $contributeSetting = array_merge($params,
2972 'invoice_prefix' => 'INV_',
2973 'credit_notes_prefix' => 'CN_',
2975 'due_date_period' => 'days',
2977 'is_email_pdf' => 1,
2978 'tax_term' => 'Sales Tax',
2979 'tax_display_settings' => 'Inclusive',
2982 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2986 * Enable Tax and Invoicing
2988 protected function disableTaxAndInvoicing($params = array()) {
2989 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2990 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2992 // Enable component contribute setting
2993 $contributeSetting = array_merge($params,
2998 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3002 * Add Sales Tax relation for financial type with financial account.
3004 * @param int $financialTypeId
3008 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3010 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3011 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3012 'is_deductible' => 1,
3017 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3018 $entityParams = array(
3019 'entity_table' => 'civicrm_financial_type',
3020 'entity_id' => $financialTypeId,
3021 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3024 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3025 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3027 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3028 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3029 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3030 $dao->copyValues($entityParams);
3032 if ($dao->fetch()) {
3033 $entityParams['id'] = $dao->id
;
3035 $entityParams['financial_account_id'] = $account->id
;
3037 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3041 * Create price set with contribution test for test setup.
3043 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3044 * on parent class at some point (fn is not in 4.4).
3047 * @param array $params
3049 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3050 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3051 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3052 'title' => "Test Contribution Page",
3053 'financial_type_id' => 1,
3054 'currency' => 'NZD',
3055 'goal_amount' => 50,
3056 'is_pay_later' => 1,
3057 'is_monetary' => TRUE,
3058 'is_email_receipt' => FALSE,
3060 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3061 'is_quick_config' => 0,
3062 'extends' => 'CiviMember',
3063 'financial_type_id' => 1,
3064 'title' => 'my Page',
3066 $priceSetID = $priceSet['id'];
3068 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3069 $priceField = $this->callAPISuccess('price_field', 'create', array(
3070 'price_set_id' => $priceSetID,
3071 'label' => 'Goat Breed',
3072 'html_type' => 'Radio',
3074 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3075 'price_set_id' => $priceSetID,
3076 'price_field_id' => $priceField['id'],
3077 'label' => 'Long Haired Goat',
3079 'financial_type_id' => 'Donation',
3080 'membership_type_id' => $membershipTypeID,
3081 'membership_num_terms' => 1,
3083 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3084 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3085 'price_set_id' => $priceSetID,
3086 'price_field_id' => $priceField['id'],
3087 'label' => 'Shoe-eating Goat',
3089 'financial_type_id' => 'Donation',
3090 'membership_type_id' => $membershipTypeID,
3091 'membership_num_terms' => 2,
3093 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3095 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3096 'price_set_id' => $priceSetID,
3097 'price_field_id' => $priceField['id'],
3098 'label' => 'Shoe-eating Goat',
3100 'financial_type_id' => 'Donation',
3102 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3104 $this->_ids
['price_set'] = $priceSetID;
3105 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3106 $this->_ids
['price_field'] = array($priceField['id']);
3108 $this->_ids
['membership_type'] = $membershipTypeID;
3112 * Only specified contact returned.
3113 * @implements CRM_Utils_Hook::aclWhereClause
3116 * @param $whereTables
3120 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3121 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3125 * @implements CRM_Utils_Hook::selectWhereClause
3127 * @param string $entity
3128 * @param array $clauses
3130 public function selectWhereClauseHook($entity, &$clauses) {
3131 if ($entity == 'Event') {
3132 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3137 * An implementation of hook_civicrm_post used with all our test cases.
3140 * @param string $objectName
3141 * @param int $objectId
3144 public function onPost($op, $objectName, $objectId, &$objectRef) {
3145 if ($op == 'create' && $objectName == 'Individual') {
3146 CRM_Core_DAO
::executeQuery(
3147 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3149 1 => array($objectId, 'Integer'),
3154 if ($op == 'edit' && $objectName == 'Participant') {
3156 1 => array($objectId, 'Integer'),
3158 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3159 CRM_Core_DAO
::executeQuery($query, $params);
3164 * Instantiate form object.
3166 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3168 * @param string $class
3169 * Name of form class.
3171 * @param array $formValues
3173 * @param string $pageName
3175 * @return \CRM_Core_Form
3176 * @throws \CRM_Core_Exception
3178 public function getFormObject($class, $formValues = [], $pageName = '') {
3179 $form = new $class();
3180 $_SERVER['REQUEST_METHOD'] = 'GET';
3181 $form->controller
= new CRM_Core_Controller();
3182 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3183 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3188 * Get possible thousand separators.
3192 public function getThousandSeparators() {
3193 return array(array('.'), array(','));
3197 * Get the boolean options as a provider.
3201 public function getBooleanDataProvider() {
3202 return [[TRUE], [FALSE]];
3206 * Set the separators for thousands and decimal points.
3208 * @param string $thousandSeparator
3210 protected function setCurrencySeparators($thousandSeparator) {
3211 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3213 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3217 * Format money as it would be input.
3219 * @param string $amount
3223 protected function formatMoneyInput($amount) {
3224 return CRM_Utils_Money
::format($amount, NULL, '%a');
3228 * Get the contribution object.
3230 * @param int $contributionID
3232 * @return \CRM_Contribute_BAO_Contribution
3234 protected function getContributionObject($contributionID) {
3235 $contributionObj = new CRM_Contribute_BAO_Contribution();
3236 $contributionObj->id
= $contributionID;
3237 $contributionObj->find(TRUE);
3238 return $contributionObj;
3242 * Enable multilingual.
3244 public function enableMultilingual() {
3245 $this->callAPISuccess('Setting', 'create', array(
3246 'lcMessages' => 'en_US',
3247 'languageLimit' => array(
3252 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3255 $dbLocale = '_en_US';
3259 * Setup or clean up SMS tests
3260 * @param bool $teardown
3262 * @throws \CiviCRM_API3_Exception
3264 public function setupForSmsTests($teardown = FALSE) {
3265 require_once 'CiviTest/CiviTestSMSProvider.php';
3267 // Option value params for CiviTestSMSProvider
3268 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3270 'option_group_id' => $groupID,
3271 'label' => 'unittestSMS',
3272 'value' => 'unit.test.sms',
3273 'name' => 'CiviTestSMSProvider',
3280 // Test completed, delete provider
3281 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3282 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3286 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3287 // in CRM/Sms/Provider.php even though it is not an extension.
3288 return civicrm_api3('option_value', 'create', $params);
3292 * Start capturing browser output.
3294 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3296 protected function startCapturingOutput() {
3298 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3302 * Stop capturing browser output and return as a csv.
3304 * @param bool $isFirstRowHeaders
3306 * @return \League\Csv\Reader
3308 * @throws \League\Csv\Exception
3310 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3311 $output = ob_get_flush();
3312 $stream = fopen('php://memory', 'r+');
3313 fwrite($stream, $output);
3315 $csv = Reader
::createFromString($output);
3316 if ($isFirstRowHeaders) {
3317 $csv->setHeaderOffset(0);