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
;
32 * Include class definitions
34 require_once 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit\Framework\TestCase
{
56 use \Civi\Test\Api3DocTrait
;
57 use \Civi\Test\GenericAssertionsTrait
;
58 use \Civi\Test\DbTestTrait
;
59 use \Civi\Test\ContactTestTrait
;
60 use \Civi\Test\MailingTestTrait
;
63 * Database has been initialized.
67 private static $dbInit = FALSE;
70 * Database connection.
72 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
81 static protected $_dbName;
84 * Track tables we have modified during a test.
87 protected $_tablesToTruncate = array();
90 * @var array of temporary directory names
95 * @var bool populateOnce allows to skip db resets in setUp
97 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
98 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
101 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
103 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
105 public static $populateOnce = FALSE;
108 * @var bool DBResetRequired allows skipping DB reset
109 * in specific test case. If you still need
110 * to reset single test (method) of such case, call
111 * $this->cleanDB() in the first line of this
114 public $DBResetRequired = TRUE;
117 * @var CRM_Core_Transaction|NULL
122 * Array of IDs created to support the test.
125 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
132 * Class used for hooks during tests.
134 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
136 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
138 * @var CRM_Utils_Hook_UnitTests hookClass
140 public $hookClass = NULL;
143 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
145 protected $_params = array();
148 * @var CRM_Extension_System
150 protected $origExtensionSystem;
153 * Array of IDs created during test setup routine.
155 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
159 public $setupIDs = array();
162 * PHPUnit Mock Method to use.
166 public $mockMethod = 'getMock';
171 * Because we are overriding the parent class constructor, we
172 * need to show the same arguments as exist in the constructor of
173 * PHPUnit_Framework_TestCase, since
174 * PHPUnit_Framework_TestSuite::createTest() creates a
175 * ReflectionClass of the Test class and checks the constructor
176 * of that class to decide how to set up the test.
178 * @param string $name
180 * @param string $dataName
182 public function __construct($name = NULL, array $data = array(), $dataName = '') {
183 parent
::__construct($name, $data, $dataName);
185 // we need full error reporting
186 error_reporting(E_ALL
& ~E_NOTICE
);
188 self
::$_dbName = self
::getDBName();
190 // also load the class loader
191 require_once 'CRM/Core/ClassLoader.php';
192 CRM_Core_ClassLoader
::singleton()->register();
193 if (function_exists('_civix_phpunit_setUp')) {
194 // FIXME: loosen coupling
195 _civix_phpunit_setUp();
197 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version
::id(), '5', '>=')) {
198 $this->mockMethod
= 'createMock';
200 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version
::id(), '6', '>=')) {
201 $this->mockMethod
= 'createMock';
206 * Override to run the test and assert its state.
209 * @throws \PHPUnit_Framework_IncompleteTest
210 * @throws \PHPUnit_Framework_SkippedTest
212 protected function runTest() {
214 return parent
::runTest();
216 catch (PEAR_Exception
$e) {
217 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
218 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
225 public function requireDBReset() {
226 return $this->DBResetRequired
;
232 public static function getDBName() {
233 static $dbName = NULL;
234 if ($dbName === NULL) {
235 require_once "DB.php";
236 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
237 $dbName = $dsninfo['database'];
243 * Create database connection for this instance.
245 * Initialize the test database if it hasn't been initialized
248 protected function getConnection() {
249 if (!self
::$dbInit) {
250 $dbName = self
::getDBName();
252 // install test database
253 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
255 static::_populateDB(FALSE, $this);
257 self
::$dbInit = TRUE;
263 * Required implementation of abstract method.
265 protected function getDataSet() {
269 * @param bool $perClass
270 * @param null $object
272 * TRUE if the populate logic runs; FALSE if it is skipped
274 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
275 if (CIVICRM_UF
!== 'UnitTests') {
276 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
279 if ($perClass ||
$object == NULL) {
283 $dbreset = $object->requireDBReset();
286 if (self
::$populateOnce ||
!$dbreset) {
289 self
::$populateOnce = NULL;
291 Civi\Test
::data()->populate();
296 public static function setUpBeforeClass() {
297 static::_populateDB(TRUE);
299 // also set this global hack
300 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
304 * Common setup functions for all unit tests.
306 protected function setUp() {
307 $session = CRM_Core_Session
::singleton();
308 $session->set('userID', NULL);
310 $this->_apiversion
= 3;
313 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
314 // Use a temporary file for STDIN
315 $GLOBALS['stdin'] = tmpfile();
316 if ($GLOBALS['stdin'] === FALSE) {
317 echo "Couldn't open temporary file\n";
321 // Get and save a connection to the database
322 $this->_dbconn
= $this->getConnection();
324 // reload database before each test
325 // $this->_populateDB();
327 // "initialize" CiviCRM to avoid problems when running single tests
328 // FIXME: look at it closer in second stage
330 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
331 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
333 // disable any left-over test extensions
334 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
336 $extensions = \CRM_Extension_System
::singleton()->getManager();
337 $api4Status = $extensions->getStatus('org.civicrm.api4');
338 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
339 $extensions->enable(['org.civicrm.api4']);
342 // reset all the caches
343 CRM_Utils_System
::flushCache();
345 // initialize the object once db is loaded
348 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
350 // when running unit tests, use mockup user framework
351 $this->hookClass
= CRM_Utils_Hook
::singleton();
353 // Make sure the DB connection is setup properly
354 $config->userSystem
->setMySQLTimeZone();
355 $env = new CRM_Utils_Check_Component_Env();
356 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
358 // clear permissions stub to not check permissions
359 $config->userPermissionClass
->permissions
= NULL;
361 //flush component settings
362 CRM_Core_Component
::getEnabledComponents(TRUE);
364 $_REQUEST = $_GET = $_POST = [];
365 error_reporting(E_ALL
);
367 $this->_sethtmlGlobals();
371 * Read everything from the datasets directory and insert into the db.
373 public function loadAllFixtures() {
374 $fixturesDir = __DIR__
. '/../../fixtures';
376 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
378 $jsonFiles = glob($fixturesDir . '/*.json');
379 foreach ($jsonFiles as $jsonFixture) {
380 $json = json_decode(file_get_contents($jsonFixture));
381 foreach ($json as $tableName => $vars) {
382 if ($tableName === 'civicrm_contact') {
383 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');
386 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
388 foreach ($vars as $entity) {
389 $keys = $values = [];
390 foreach ($entity as $key => $value) {
392 $values[] = is_numeric($value) ?
$value : "'{$value}'";
394 CRM_Core_DAO
::executeQuery("
395 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
402 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
406 * Load the data that used to be handled by the discontinued dbunit class.
408 * This could do with further tidy up - the initial priority is simply to get rid of
409 * the dbunity package which is no longer supported.
411 * @param string $fileName
413 protected function loadXMLDataSet($fileName) {
414 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
415 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
416 foreach ($xml as $tableName => $element) {
417 if (!empty($element)) {
418 foreach ($element as $row) {
419 $keys = $values = [];
420 if (isset($row['@attributes'])) {
421 foreach ($row['@attributes'] as $key => $value) {
423 $values[] = is_numeric($value) ?
$value : "'{$value}'";
426 elseif (!empty($row)) {
427 // cos we copied it & it is inconsistent....
428 foreach ($row as $key => $value) {
430 $values[] = is_numeric($value) ?
$value : "'{$value}'";
434 if (!empty($values)) {
435 CRM_Core_DAO
::executeQuery("
436 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
442 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
446 * Create default domain contacts for the two domains added during test class.
447 * database population.
449 public function createDomainContacts() {
450 $this->organizationCreate();
451 $this->organizationCreate(array('organization_name' => 'Second Domain'));
455 * Common teardown functions for all unit tests.
457 protected function tearDown() {
458 $this->_apiversion
= 3;
460 error_reporting(E_ALL
& ~E_NOTICE
);
461 CRM_Utils_Hook
::singleton()->reset();
462 if ($this->hookClass
) {
463 $this->hookClass
->reset();
465 CRM_Core_Session
::singleton()->reset(1);
468 $this->tx
->rollback()->commit();
471 CRM_Core_Transaction
::forceRollbackIfEnabled();
472 \Civi\Core\Transaction\Manager
::singleton(TRUE);
475 CRM_Core_Transaction
::forceRollbackIfEnabled();
476 \Civi\Core\Transaction\Manager
::singleton(TRUE);
478 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
479 $this->quickCleanup($tablesToTruncate);
480 $this->createDomainContacts();
483 $this->cleanTempDirs();
484 $this->unsetExtensionSystem();
485 $this->assertEquals([], CRM_Core_DAO
::$_nullArray);
486 $this->assertEquals(NULL, CRM_Core_DAO
::$_nullObject);
490 * Create a batch of external API calls which can
491 * be executed concurrently.
494 * $calls = $this->createExternalAPI()
495 * ->addCall('Contact', 'get', ...)
496 * ->addCall('Contact', 'get', ...)
502 * @return \Civi\API\ExternalBatch
503 * @throws PHPUnit_Framework_SkippedTestError
505 public function createExternalAPI() {
506 global $civicrm_root;
507 $defaultParams = array(
508 'version' => $this->_apiversion
,
512 $calls = new \Civi\API\
ExternalBatch($defaultParams);
514 if (!$calls->isSupported()) {
515 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
522 * Create required data based on $this->entity & $this->params
523 * This is just a way to set up the test data for delete & get functions
524 * so the distinction between set
525 * up & tested functions is clearer
530 public function createTestEntity() {
531 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
535 * @param int $contactTypeId
539 public function contactTypeDelete($contactTypeId) {
540 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
542 throw new Exception('Could not delete contact type');
547 * @param array $params
551 public function membershipTypeCreate($params = array()) {
552 CRM_Member_PseudoConstant
::flush('membershipType');
553 CRM_Core_Config
::clearDBCache();
554 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
555 $params = array_merge(array(
557 'duration_unit' => 'year',
558 'duration_interval' => 1,
559 'period_type' => 'rolling',
560 'member_of_contact_id' => $memberOfOrganization,
562 'financial_type_id' => 2,
565 'visibility' => 'Public',
568 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
570 CRM_Member_PseudoConstant
::flush('membershipType');
571 CRM_Utils_Cache
::singleton()->flush();
573 return $result['id'];
577 * @param array $params
581 public function contactMembershipCreate($params) {
582 $params = array_merge(array(
583 'join_date' => '2007-01-21',
584 'start_date' => '2007-01-21',
585 'end_date' => '2007-12-21',
586 'source' => 'Payment',
587 'membership_type_id' => 'General',
589 if (!is_numeric($params['membership_type_id'])) {
590 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
591 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
592 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
596 $result = $this->callAPISuccess('Membership', 'create', $params);
597 return $result['id'];
601 * Delete Membership Type.
603 * @param array $params
605 public function membershipTypeDelete($params) {
606 $this->callAPISuccess('MembershipType', 'Delete', $params);
610 * @param int $membershipID
612 public function membershipDelete($membershipID) {
613 $deleteParams = array('id' => $membershipID);
614 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
618 * @param string $name
622 public function membershipStatusCreate($name = 'test member status') {
623 $params['name'] = $name;
624 $params['start_event'] = 'start_date';
625 $params['end_event'] = 'end_date';
626 $params['is_current_member'] = 1;
627 $params['is_active'] = 1;
629 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
630 CRM_Member_PseudoConstant
::flush('membershipStatus');
631 return $result['id'];
635 * @param int $membershipStatusID
637 public function membershipStatusDelete($membershipStatusID) {
638 if (!$membershipStatusID) {
641 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
644 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
645 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
646 $renewedMembershipEndDate = new DateTime($membershipEndDate);
647 switch ($durationUnit) {
649 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
653 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
654 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
655 $renewedMembershipEndDate->add(new DateInterval('P1D'));
656 $renewedMembershipEndDate->add(new DateInterval('P1M'));
657 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
660 return $renewedMembershipEndDate->format('Y-m-d');
664 * @param array $params
668 public function relationshipTypeCreate($params = array()) {
669 $params = array_merge(array(
670 'name_a_b' => 'Relation 1 for relationship type create',
671 'name_b_a' => 'Relation 2 for relationship type create',
672 'contact_type_a' => 'Individual',
673 'contact_type_b' => 'Organization',
678 $result = $this->callAPISuccess('relationship_type', 'create', $params);
679 CRM_Core_PseudoConstant
::flush('relationshipType');
681 return $result['id'];
685 * Delete Relatinship Type.
687 * @param int $relationshipTypeID
689 public function relationshipTypeDelete($relationshipTypeID) {
690 $params['id'] = $relationshipTypeID;
691 $check = $this->callAPISuccess('relationship_type', 'get', $params);
692 if (!empty($check['count'])) {
693 $this->callAPISuccess('relationship_type', 'delete', $params);
698 * @param array $params
702 public function paymentProcessorTypeCreate($params = NULL) {
703 if (is_null($params)) {
705 'name' => 'API_Test_PP',
706 'title' => 'API Test Payment Processor',
707 'class_name' => 'CRM_Core_Payment_APITest',
708 'billing_mode' => 'form',
714 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
716 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
718 return $result['id'];
722 * Create test Authorize.net instance.
724 * @param array $params
728 public function paymentProcessorAuthorizeNetCreate($params = array()) {
729 $params = array_merge(array(
730 'name' => 'Authorize',
731 'domain_id' => CRM_Core_Config
::domainID(),
732 'payment_processor_type_id' => 'AuthNet',
733 'title' => 'AuthNet',
738 'user_name' => '4y5BfuW7jm',
739 'password' => '4cAmW927n8uLf5J8',
740 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
741 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
742 'class_name' => 'Payment_AuthorizeNet',
746 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
747 return $result['id'];
751 * Create Participant.
753 * @param array $params
754 * Array of contact id and event id values.
757 * $id of participant created
759 public function participantCreate($params = []) {
760 if (empty($params['contact_id'])) {
761 $params['contact_id'] = $this->individualCreate();
763 if (empty($params['event_id'])) {
764 $event = $this->eventCreate();
765 $params['event_id'] = $event['id'];
770 'register_date' => 20070219,
771 'source' => 'Wimbeldon',
772 'event_level' => 'Payment',
776 $params = array_merge($defaults, $params);
777 $result = $this->callAPISuccess('Participant', 'create', $params);
778 return $result['id'];
782 * Create Payment Processor.
785 * Id Payment Processor
787 public function processorCreate($params = array()) {
788 $processorParams = array(
791 'payment_processor_type_id' => 'Dummy',
792 'financial_account_id' => 12,
796 'url_site' => 'http://dummy.com',
797 'url_recur' => 'http://dummy.com',
800 'payment_instrument_id' => 'Debit Card',
802 $processorParams = array_merge($processorParams, $params);
803 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
804 return $processor['id'];
808 * Create Payment Processor.
810 * @param array $processorParams
812 * @return \CRM_Core_Payment_Dummy
813 * Instance of Dummy Payment Processor
815 public function dummyProcessorCreate($processorParams = array()) {
816 $paymentProcessorID = $this->processorCreate($processorParams);
817 return System
::singleton()->getById($paymentProcessorID);
821 * Create contribution page.
823 * @param array $params
825 * Array of contribution page
827 public function contributionPageCreate($params = array()) {
828 $this->_pageParams
= array_merge(array(
829 'title' => 'Test Contribution Page',
830 'financial_type_id' => 1,
832 'financial_account_id' => 1,
834 'is_allow_other_amount' => 1,
836 'max_amount' => 1000,
838 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
842 * Create a sample batch.
844 public function batchCreate() {
845 $params = $this->_params
;
846 $params['name'] = $params['title'] = 'Batch_433397';
847 $params['status_id'] = 1;
848 $result = $this->callAPISuccess('batch', 'create', $params);
849 return $result['id'];
855 * @param array $params
857 * result of created tag
859 public function tagCreate($params = array()) {
861 'name' => 'New Tag3',
862 'description' => 'This is description for Our New Tag ',
865 $params = array_merge($defaults, $params);
866 $result = $this->callAPISuccess('Tag', 'create', $params);
867 return $result['values'][$result['id']];
874 * Id of the tag to be deleted.
878 public function tagDelete($tagId) {
879 require_once 'api/api.php';
883 $result = $this->callAPISuccess('Tag', 'delete', $params);
884 return $result['id'];
888 * Add entity(s) to the tag
890 * @param array $params
894 public function entityTagAdd($params) {
895 $result = $this->callAPISuccess('entity_tag', 'create', $params);
902 * @param array $params
906 * id of created pledge
908 public function pledgeCreate($params) {
909 $params = array_merge(array(
910 'pledge_create_date' => date('Ymd'),
911 'start_date' => date('Ymd'),
912 'scheduled_date' => date('Ymd'),
914 'pledge_status_id' => '2',
915 'financial_type_id' => '1',
916 'pledge_original_installment_amount' => 20,
917 'frequency_interval' => 5,
918 'frequency_unit' => 'year',
919 'frequency_day' => 15,
924 $result = $this->callAPISuccess('Pledge', 'create', $params);
925 return $result['id'];
929 * Delete contribution.
931 * @param int $pledgeId
933 public function pledgeDelete($pledgeId) {
935 'pledge_id' => $pledgeId,
937 $this->callAPISuccess('Pledge', 'delete', $params);
941 * Create contribution.
943 * @param array $params
944 * Array of parameters.
947 * id of created contribution
949 public function contributionCreate($params) {
951 $params = array_merge(array(
953 'receive_date' => date('Ymd'),
954 'total_amount' => 100.00,
955 'fee_amount' => 5.00,
956 'financial_type_id' => 1,
957 'payment_instrument_id' => 1,
958 'non_deductible_amount' => 10.00,
960 'contribution_status_id' => 1,
963 $result = $this->callAPISuccess('contribution', 'create', $params);
964 return $result['id'];
968 * Delete contribution.
970 * @param int $contributionId
974 public function contributionDelete($contributionId) {
976 'contribution_id' => $contributionId,
978 $result = $this->callAPISuccess('contribution', 'delete', $params);
985 * @param array $params
986 * Name-value pair for an event.
990 public function eventCreate($params = array()) {
991 // if no contact was passed, make up a dummy event creator
992 if (!isset($params['contact_id'])) {
993 $params['contact_id'] = $this->_contactCreate(array(
994 'contact_type' => 'Individual',
995 'first_name' => 'Event',
996 'last_name' => 'Creator',
1000 // set defaults for missing params
1001 $params = array_merge(array(
1002 'title' => 'Annual CiviCRM meet',
1003 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1004 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1005 'event_type_id' => 1,
1007 'start_date' => 20081021,
1008 'end_date' => 20081023,
1009 'is_online_registration' => 1,
1010 'registration_start_date' => 20080601,
1011 'registration_end_date' => 20081015,
1012 'max_participants' => 100,
1013 'event_full_text' => 'Sorry! We are already full',
1016 'is_show_location' => 0,
1019 return $this->callAPISuccess('Event', 'create', $params);
1023 * Create a paid event.
1025 * @param array $params
1029 protected function eventCreatePaid($params) {
1030 $event = $this->eventCreate($params);
1031 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1032 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1033 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1034 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1035 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1047 public function eventDelete($id) {
1051 return $this->callAPISuccess('event', 'delete', $params);
1055 * Delete participant.
1057 * @param int $participantID
1061 public function participantDelete($participantID) {
1063 'id' => $participantID,
1065 $check = $this->callAPISuccess('Participant', 'get', $params);
1066 if ($check['count'] > 0) {
1067 return $this->callAPISuccess('Participant', 'delete', $params);
1072 * Create participant payment.
1074 * @param int $participantID
1075 * @param int $contributionID
1077 * $id of created payment
1079 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1080 //Create Participant Payment record With Values
1082 'participant_id' => $participantID,
1083 'contribution_id' => $contributionID,
1086 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1087 return $result['id'];
1091 * Delete participant payment.
1093 * @param int $paymentID
1095 public function participantPaymentDelete($paymentID) {
1099 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1105 * @param int $contactID
1107 * location id of created location
1109 public function locationAdd($contactID) {
1112 'location_type' => 'New Location Type',
1114 'name' => 'Saint Helier St',
1115 'county' => 'Marin',
1116 'country' => 'UNITED STATES',
1117 'state_province' => 'Michigan',
1118 'supplemental_address_1' => 'Hallmark Ct',
1119 'supplemental_address_2' => 'Jersey Village',
1120 'supplemental_address_3' => 'My Town',
1125 'contact_id' => $contactID,
1126 'address' => $address,
1127 'location_format' => '2.0',
1128 'location_type' => 'New Location Type',
1131 $result = $this->callAPISuccess('Location', 'create', $params);
1136 * Delete Locations of contact.
1138 * @param array $params
1141 public function locationDelete($params) {
1142 $this->callAPISuccess('Location', 'delete', $params);
1146 * Add a Location Type.
1148 * @param array $params
1149 * @return CRM_Core_DAO_LocationType
1150 * location id of created location
1152 public function locationTypeCreate($params = NULL) {
1153 if ($params === NULL) {
1155 'name' => 'New Location Type',
1156 'vcard_name' => 'New Location Type',
1157 'description' => 'Location Type for Delete',
1162 $locationType = new CRM_Core_DAO_LocationType();
1163 $locationType->copyValues($params);
1164 $locationType->save();
1165 // clear getfields cache
1166 CRM_Core_PseudoConstant
::flush();
1167 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1168 return $locationType;
1172 * Delete a Location Type.
1174 * @param int $locationTypeId
1176 public function locationTypeDelete($locationTypeId) {
1177 $locationType = new CRM_Core_DAO_LocationType();
1178 $locationType->id
= $locationTypeId;
1179 $locationType->delete();
1185 * @param array $params
1186 * @return CRM_Core_DAO_Mapping
1187 * Mapping id of created mapping
1189 public function mappingCreate($params = NULL) {
1190 if ($params === NULL) {
1192 'name' => 'Mapping name',
1193 'description' => 'Mapping description',
1194 // 'Export Contact' mapping.
1195 'mapping_type_id' => 7,
1199 $mapping = new CRM_Core_DAO_Mapping();
1200 $mapping->copyValues($params);
1202 // clear getfields cache
1203 CRM_Core_PseudoConstant
::flush();
1204 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1211 * @param int $mappingId
1213 public function mappingDelete($mappingId) {
1214 $mapping = new CRM_Core_DAO_Mapping();
1215 $mapping->id
= $mappingId;
1220 * Prepare class for ACLs.
1222 protected function prepareForACLs() {
1223 $config = CRM_Core_Config
::singleton();
1224 $config->userPermissionClass
->permissions
= array();
1230 protected function cleanUpAfterACLs() {
1231 CRM_Utils_Hook
::singleton()->reset();
1232 $tablesToTruncate = array(
1234 'civicrm_acl_cache',
1235 'civicrm_acl_entity_role',
1236 'civicrm_acl_contact_cache',
1238 $this->quickCleanup($tablesToTruncate);
1239 $config = CRM_Core_Config
::singleton();
1240 unset($config->userPermissionClass
->permissions
);
1244 * Create a smart group.
1246 * By default it will be a group of households.
1248 * @param array $smartGroupParams
1249 * @param array $groupParams
1252 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1253 $smartGroupParams = array_merge(array(
1254 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1257 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1259 $groupParams['saved_search_id'] = $savedSearch->id
;
1260 return $this->groupCreate($groupParams);
1265 * @param array $params
1267 public function uFFieldCreate($params = array()) {
1268 $params = array_merge(array(
1270 'field_name' => 'first_name',
1273 'visibility' => 'Public Pages and Listings',
1274 'is_searchable' => '1',
1275 'label' => 'first_name',
1276 'field_type' => 'Individual',
1279 $this->callAPISuccess('uf_field', 'create', $params);
1283 * Add a UF Join Entry.
1285 * @param array $params
1287 * $id of created UF Join
1289 public function ufjoinCreate($params = NULL) {
1290 if ($params === NULL) {
1293 'module' => 'CiviEvent',
1294 'entity_table' => 'civicrm_event',
1300 $result = $this->callAPISuccess('uf_join', 'create', $params);
1305 * @param array $params
1306 * Optional parameters.
1307 * @param bool $reloadConfig
1308 * While enabling CiviCampaign component, we shouldn't always forcibly
1309 * reload config as this hinder hook call in test environment
1314 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1315 $this->enableCiviCampaign($reloadConfig);
1316 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1317 'name' => 'big_campaign',
1318 'title' => 'Campaign',
1320 return $campaign['id'];
1324 * Create Group for a contact.
1326 * @param int $contactId
1328 public function contactGroupCreate($contactId) {
1330 'contact_id.1' => $contactId,
1334 $this->callAPISuccess('GroupContact', 'Create', $params);
1338 * Delete Group for a contact.
1340 * @param int $contactId
1342 public function contactGroupDelete($contactId) {
1344 'contact_id.1' => $contactId,
1347 $this->civicrm_api('GroupContact', 'Delete', $params);
1353 * @param array $params
1356 public function activityCreate($params = array()) {
1357 $params = array_merge(array(
1358 'subject' => 'Discussion on warm beer',
1359 'activity_date_time' => date('Ymd'),
1360 'duration_hours' => 30,
1361 'duration_minutes' => 20,
1362 'location' => 'Baker Street',
1363 'details' => 'Lets schedule a meeting',
1365 'activity_type_id' => 'Meeting',
1367 if (!isset($params['source_contact_id'])) {
1368 $params['source_contact_id'] = $this->individualCreate();
1370 if (!isset($params['target_contact_id'])) {
1371 $params['target_contact_id'] = $this->individualCreate(array(
1372 'first_name' => 'Julia',
1373 'Last_name' => 'Anderson',
1375 'email' => 'julia_anderson@civicrm.org',
1376 'contact_type' => 'Individual',
1379 if (!isset($params['assignee_contact_id'])) {
1380 $params['assignee_contact_id'] = $params['target_contact_id'];
1383 $result = civicrm_api3('Activity', 'create', $params);
1385 $result['target_contact_id'] = $params['target_contact_id'];
1386 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1391 * Create an activity type.
1393 * @param array $params
1397 public function activityTypeCreate($params) {
1398 return $this->callAPISuccess('ActivityType', 'create', $params);
1402 * Delete activity type.
1404 * @param int $activityTypeId
1405 * Id of the activity type.
1408 public function activityTypeDelete($activityTypeId) {
1409 $params['activity_type_id'] = $activityTypeId;
1410 return $this->callAPISuccess('ActivityType', 'delete', $params);
1414 * Create custom group.
1416 * @param array $params
1419 public function customGroupCreate($params = array()) {
1421 'title' => 'new custom group',
1422 'extends' => 'Contact',
1424 'style' => 'Inline',
1428 $params = array_merge($defaults, $params);
1430 return $this->callAPISuccess('custom_group', 'create', $params);
1434 * Existing function doesn't allow params to be over-ridden so need a new one
1435 * this one allows you to only pass in the params you want to change
1436 * @param array $params
1439 public function CustomGroupCreateByParams($params = array()) {
1441 'title' => "API Custom Group",
1442 'extends' => 'Contact',
1444 'style' => 'Inline',
1447 $params = array_merge($defaults, $params);
1448 return $this->callAPISuccess('custom_group', 'create', $params);
1452 * Create custom group with multi fields.
1453 * @param array $params
1456 public function CustomGroupMultipleCreateByParams($params = array()) {
1461 $params = array_merge($defaults, $params);
1462 return $this->CustomGroupCreateByParams($params);
1466 * Create custom group with multi fields.
1467 * @param array $params
1470 public function CustomGroupMultipleCreateWithFields($params = array()) {
1471 // also need to pass on $params['custom_field'] if not set but not in place yet
1473 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1474 $ids['custom_group_id'] = $customGroup['id'];
1476 $customField = $this->customFieldCreate(array(
1477 'custom_group_id' => $ids['custom_group_id'],
1478 'label' => 'field_1' . $ids['custom_group_id'],
1482 $ids['custom_field_id'][] = $customField['id'];
1484 $customField = $this->customFieldCreate(array(
1485 'custom_group_id' => $ids['custom_group_id'],
1486 'default_value' => '',
1487 'label' => 'field_2' . $ids['custom_group_id'],
1490 $ids['custom_field_id'][] = $customField['id'];
1492 $customField = $this->customFieldCreate(array(
1493 'custom_group_id' => $ids['custom_group_id'],
1494 'default_value' => '',
1495 'label' => 'field_3' . $ids['custom_group_id'],
1498 $ids['custom_field_id'][] = $customField['id'];
1504 * Create a custom group with a single text custom field. See
1505 * participant:testCreateWithCustom for how to use this
1507 * @param string $function
1509 * @param string $filename
1513 * ids of created objects
1515 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1516 $params = array('title' => $function);
1517 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1518 $params['extends'] = $entity ?
$entity : 'Contact';
1519 $customGroup = $this->CustomGroupCreate($params);
1520 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1521 CRM_Core_PseudoConstant
::flush();
1523 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1527 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1528 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1530 * @param string $function
1532 * @param string $filename
1536 * ids of created objects
1538 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1539 $params = array('title' => $function);
1540 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1541 $params['extends'] = $entity ?
$entity : 'Contact';
1542 $customGroup = $this->CustomGroupCreate($params);
1543 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1544 CRM_Core_PseudoConstant
::flush();
1546 'defaultValue' => 'Default Value',
1547 'lowercasevalue' => 'Lowercase Value',
1548 1 => 'Integer Value',
1551 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1552 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1553 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1554 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1555 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1556 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1557 foreach ($options as $option_value => $option_label) {
1558 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1559 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1562 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id'], 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'], 'custom_field_group_options' => $options);
1566 * Delete custom group.
1568 * @param int $customGroupID
1572 public function customGroupDelete($customGroupID) {
1573 $params['id'] = $customGroupID;
1574 return $this->callAPISuccess('custom_group', 'delete', $params);
1578 * Create custom field.
1580 * @param array $params
1581 * (custom_group_id) is required.
1584 public function customFieldCreate($params) {
1585 $params = array_merge(array(
1586 'label' => 'Custom Field',
1587 'data_type' => 'String',
1588 'html_type' => 'Text',
1589 'is_searchable' => 1,
1591 'default_value' => 'defaultValue',
1594 $result = $this->callAPISuccess('custom_field', 'create', $params);
1595 // these 2 functions are called with force to flush static caches
1596 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1597 CRM_Core_Component
::getEnabledComponents(1);
1602 * Delete custom field.
1604 * @param int $customFieldID
1608 public function customFieldDelete($customFieldID) {
1610 $params['id'] = $customFieldID;
1611 return $this->callAPISuccess('custom_field', 'delete', $params);
1620 public function noteCreate($cId) {
1622 'entity_table' => 'civicrm_contact',
1623 'entity_id' => $cId,
1624 'note' => 'hello I am testing Note',
1625 'contact_id' => $cId,
1626 'modified_date' => date('Ymd'),
1627 'subject' => 'Test Note',
1630 return $this->callAPISuccess('Note', 'create', $params);
1634 * Enable CiviCampaign Component.
1636 * @param bool $reloadConfig
1637 * Force relaod config or not
1639 public function enableCiviCampaign($reloadConfig = TRUE) {
1640 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1641 if ($reloadConfig) {
1642 // force reload of config object
1643 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1645 //flush cache by calling with reset
1646 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1650 * Create custom field with Option Values.
1652 * @param array $customGroup
1653 * @param string $name
1654 * Name of custom field.
1655 * @param array $extraParams
1656 * Additional parameters to pass through.
1660 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1661 $fieldParams = array(
1662 'custom_group_id' => $customGroup['id'],
1663 'name' => 'test_custom_group',
1664 'label' => 'Country',
1665 'html_type' => 'Select',
1666 'data_type' => 'String',
1669 'is_searchable' => 0,
1673 $optionGroup = array(
1675 'name' => 'option_group1',
1676 'label' => 'option_group_label1',
1679 $optionValue = array(
1680 'option_label' => array('Label1', 'Label2'),
1681 'option_value' => array('value1', 'value2'),
1682 'option_name' => array($name . '_1', $name . '_2'),
1683 'option_weight' => array(1, 2),
1684 'option_status' => 1,
1687 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1689 return $this->callAPISuccess('custom_field', 'create', $params);
1697 public function confirmEntitiesDeleted($entities) {
1698 foreach ($entities as $entity) {
1700 $result = $this->callAPISuccess($entity, 'Get', array());
1701 if ($result['error'] == 1 ||
$result['count'] > 0) {
1702 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1710 * Quick clean by emptying tables created for the test.
1712 * @param array $tablesToTruncate
1713 * @param bool $dropCustomValueTables
1714 * @throws \Exception
1716 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1718 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1720 if ($dropCustomValueTables) {
1721 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1722 while ($optionGroupResult->fetch()) {
1723 if (!empty($optionGroupResult->option_group_id
)) {
1724 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1727 $tablesToTruncate[] = 'civicrm_custom_group';
1728 $tablesToTruncate[] = 'civicrm_custom_field';
1731 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1733 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1734 foreach ($tablesToTruncate as $table) {
1735 $sql = "TRUNCATE TABLE $table";
1736 CRM_Core_DAO
::executeQuery($sql);
1738 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1740 if ($dropCustomValueTables) {
1741 $dbName = self
::getDBName();
1743 SELECT TABLE_NAME as tableName
1744 FROM INFORMATION_SCHEMA.TABLES
1745 WHERE TABLE_SCHEMA = '{$dbName}'
1746 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1749 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1750 while ($tableDAO->fetch()) {
1751 $sql = "DROP TABLE {$tableDAO->tableName}";
1752 CRM_Core_DAO
::executeQuery($sql);
1758 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1760 public function quickCleanUpFinancialEntities() {
1761 $tablesToTruncate = array(
1763 'civicrm_activity_contact',
1764 'civicrm_contribution',
1765 'civicrm_contribution_soft',
1766 'civicrm_contribution_product',
1767 'civicrm_financial_trxn',
1768 'civicrm_financial_item',
1769 'civicrm_contribution_recur',
1770 'civicrm_line_item',
1771 'civicrm_contribution_page',
1772 'civicrm_payment_processor',
1773 'civicrm_entity_financial_trxn',
1774 'civicrm_membership',
1775 'civicrm_membership_type',
1776 'civicrm_membership_payment',
1777 'civicrm_membership_log',
1778 'civicrm_membership_block',
1780 'civicrm_participant',
1781 'civicrm_participant_payment',
1783 'civicrm_pledge_block',
1784 'civicrm_pledge_payment',
1785 'civicrm_price_set_entity',
1786 'civicrm_price_field_value',
1787 'civicrm_price_field',
1789 $this->quickCleanup($tablesToTruncate);
1790 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1791 $this->restoreDefaultPriceSetConfig();
1793 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1794 $this->disableTaxAndInvoicing();
1795 $this->setCurrencySeparators(',');
1796 CRM_Core_PseudoConstant
::flush('taxRates');
1797 System
::singleton()->flushProcessors();
1800 public function restoreDefaultPriceSetConfig() {
1801 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1802 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1803 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)");
1804 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)");
1808 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1809 * Default behaviour is to also delete the entity
1810 * @param array $params
1811 * Params array to check against.
1813 * Id of the entity concerned.
1814 * @param string $entity
1815 * Name of entity concerned (e.g. membership).
1816 * @param bool $delete
1817 * Should the entity be deleted as part of this check.
1818 * @param string $errorText
1819 * Text to print on error.
1823 * @param array $params
1826 * @param int $delete
1827 * @param string $errorText
1831 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1833 $result = $this->callAPISuccessGetSingle($entity, array(
1838 $this->callAPISuccess($entity, 'Delete', array(
1842 $dateFields = $keys = $dateTimeFields = array();
1843 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1844 foreach ($fields['values'] as $field => $settings) {
1845 if (array_key_exists($field, $result)) {
1846 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1849 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1851 $type = CRM_Utils_Array
::value('type', $settings);
1852 if ($type == CRM_Utils_Type
::T_DATE
) {
1853 $dateFields[] = $settings['name'];
1854 // we should identify both real names & unique names as dates
1855 if ($field != $settings['name']) {
1856 $dateFields[] = $field;
1859 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1860 $dateTimeFields[] = $settings['name'];
1861 // we should identify both real names & unique names as dates
1862 if ($field != $settings['name']) {
1863 $dateTimeFields[] = $field;
1868 if (strtolower($entity) == 'contribution') {
1869 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1870 // this is not returned in id format
1871 unset($params['payment_instrument_id']);
1872 $params['contribution_source'] = $params['source'];
1873 unset($params['source']);
1876 foreach ($params as $key => $value) {
1877 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1880 if (in_array($key, $dateFields)) {
1881 $value = date('Y-m-d', strtotime($value));
1882 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1884 if (in_array($key, $dateTimeFields)) {
1885 $value = date('Y-m-d H:i:s', strtotime($value));
1886 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1888 $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);
1893 * Get formatted values in the actual and expected result.
1894 * @param array $actual
1895 * Actual calculated values.
1896 * @param array $expected
1899 public function checkArrayEquals(&$actual, &$expected) {
1900 self
::unsetId($actual);
1901 self
::unsetId($expected);
1902 $this->assertEquals($expected, $actual);
1906 * Unset the key 'id' from the array
1907 * @param array $unformattedArray
1908 * The array from which the 'id' has to be unset.
1910 public static function unsetId(&$unformattedArray) {
1911 $formattedArray = array();
1912 if (array_key_exists('id', $unformattedArray)) {
1913 unset($unformattedArray['id']);
1915 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1916 foreach ($unformattedArray['values'] as $key => $value) {
1917 if (is_array($value)) {
1918 foreach ($value as $k => $v) {
1924 elseif ($key == 'id') {
1925 $unformattedArray[$key];
1927 $formattedArray = array($value);
1929 $unformattedArray['values'] = $formattedArray;
1934 * Helper to enable/disable custom directory support
1936 * @param array $customDirs
1938 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1939 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1941 public function customDirectories($customDirs) {
1942 $config = CRM_Core_Config
::singleton();
1944 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1945 unset($config->customPHPPathDir
);
1947 elseif ($customDirs['php_path'] === TRUE) {
1948 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1951 $config->customPHPPathDir
= $php_path;
1954 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1955 unset($config->customTemplateDir
);
1957 elseif ($customDirs['template_path'] === TRUE) {
1958 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1961 $config->customTemplateDir
= $template_path;
1966 * Generate a temporary folder.
1968 * @param string $prefix
1971 public function createTempDir($prefix = 'test-') {
1972 $tempDir = CRM_Utils_File
::tempdir($prefix);
1973 $this->tempDirs
[] = $tempDir;
1977 public function cleanTempDirs() {
1978 if (!is_array($this->tempDirs
)) {
1979 // fix test errors where this is not set
1982 foreach ($this->tempDirs
as $tempDir) {
1983 if (is_dir($tempDir)) {
1984 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1990 * Temporarily replace the singleton extension with a different one.
1991 * @param \CRM_Extension_System $system
1993 public function setExtensionSystem(CRM_Extension_System
$system) {
1994 if ($this->origExtensionSystem
== NULL) {
1995 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1997 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2000 public function unsetExtensionSystem() {
2001 if ($this->origExtensionSystem
!== NULL) {
2002 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2003 $this->origExtensionSystem
= NULL;
2008 * Temporarily alter the settings-metadata to add a mock setting.
2010 * WARNING: The setting metadata will disappear on the next cache-clear.
2015 public function setMockSettingsMetaData($extras) {
2016 CRM_Utils_Hook
::singleton()
2017 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2018 $metadata = array_merge($metadata, $extras);
2021 Civi
::service('settings_manager')->flush();
2023 $fields = $this->callAPISuccess('setting', 'getfields', array());
2024 foreach ($extras as $key => $spec) {
2025 $this->assertNotEmpty($spec['title']);
2026 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2031 * @param string $name
2033 public function financialAccountDelete($name) {
2034 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2035 $financialAccount->name
= $name;
2036 if ($financialAccount->find(TRUE)) {
2037 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2038 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2039 $entityFinancialType->delete();
2040 $financialAccount->delete();
2045 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2046 * (NB unclear if this is still required)
2048 public function _sethtmlGlobals() {
2049 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2050 'required' => array(
2051 'html_quickform_rule_required',
2052 'HTML/QuickForm/Rule/Required.php',
2054 'maxlength' => array(
2055 'html_quickform_rule_range',
2056 'HTML/QuickForm/Rule/Range.php',
2058 'minlength' => array(
2059 'html_quickform_rule_range',
2060 'HTML/QuickForm/Rule/Range.php',
2062 'rangelength' => array(
2063 'html_quickform_rule_range',
2064 'HTML/QuickForm/Rule/Range.php',
2067 'html_quickform_rule_email',
2068 'HTML/QuickForm/Rule/Email.php',
2071 'html_quickform_rule_regex',
2072 'HTML/QuickForm/Rule/Regex.php',
2074 'lettersonly' => array(
2075 'html_quickform_rule_regex',
2076 'HTML/QuickForm/Rule/Regex.php',
2078 'alphanumeric' => array(
2079 'html_quickform_rule_regex',
2080 'HTML/QuickForm/Rule/Regex.php',
2083 'html_quickform_rule_regex',
2084 'HTML/QuickForm/Rule/Regex.php',
2086 'nopunctuation' => array(
2087 'html_quickform_rule_regex',
2088 'HTML/QuickForm/Rule/Regex.php',
2091 'html_quickform_rule_regex',
2092 'HTML/QuickForm/Rule/Regex.php',
2094 'callback' => array(
2095 'html_quickform_rule_callback',
2096 'HTML/QuickForm/Rule/Callback.php',
2099 'html_quickform_rule_compare',
2100 'HTML/QuickForm/Rule/Compare.php',
2103 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2104 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2106 'HTML/QuickForm/group.php',
2107 'HTML_QuickForm_group',
2110 'HTML/QuickForm/hidden.php',
2111 'HTML_QuickForm_hidden',
2114 'HTML/QuickForm/reset.php',
2115 'HTML_QuickForm_reset',
2117 'checkbox' => array(
2118 'HTML/QuickForm/checkbox.php',
2119 'HTML_QuickForm_checkbox',
2122 'HTML/QuickForm/file.php',
2123 'HTML_QuickForm_file',
2126 'HTML/QuickForm/image.php',
2127 'HTML_QuickForm_image',
2129 'password' => array(
2130 'HTML/QuickForm/password.php',
2131 'HTML_QuickForm_password',
2134 'HTML/QuickForm/radio.php',
2135 'HTML_QuickForm_radio',
2138 'HTML/QuickForm/button.php',
2139 'HTML_QuickForm_button',
2142 'HTML/QuickForm/submit.php',
2143 'HTML_QuickForm_submit',
2146 'HTML/QuickForm/select.php',
2147 'HTML_QuickForm_select',
2149 'hiddenselect' => array(
2150 'HTML/QuickForm/hiddenselect.php',
2151 'HTML_QuickForm_hiddenselect',
2154 'HTML/QuickForm/text.php',
2155 'HTML_QuickForm_text',
2157 'textarea' => array(
2158 'HTML/QuickForm/textarea.php',
2159 'HTML_QuickForm_textarea',
2161 'fckeditor' => array(
2162 'HTML/QuickForm/fckeditor.php',
2163 'HTML_QuickForm_FCKEditor',
2166 'HTML/QuickForm/tinymce.php',
2167 'HTML_QuickForm_TinyMCE',
2169 'dojoeditor' => array(
2170 'HTML/QuickForm/dojoeditor.php',
2171 'HTML_QuickForm_dojoeditor',
2174 'HTML/QuickForm/link.php',
2175 'HTML_QuickForm_link',
2177 'advcheckbox' => array(
2178 'HTML/QuickForm/advcheckbox.php',
2179 'HTML_QuickForm_advcheckbox',
2182 'HTML/QuickForm/date.php',
2183 'HTML_QuickForm_date',
2186 'HTML/QuickForm/static.php',
2187 'HTML_QuickForm_static',
2190 'HTML/QuickForm/header.php',
2191 'HTML_QuickForm_header',
2194 'HTML/QuickForm/html.php',
2195 'HTML_QuickForm_html',
2197 'hierselect' => array(
2198 'HTML/QuickForm/hierselect.php',
2199 'HTML_QuickForm_hierselect',
2201 'autocomplete' => array(
2202 'HTML/QuickForm/autocomplete.php',
2203 'HTML_QuickForm_autocomplete',
2206 'HTML/QuickForm/xbutton.php',
2207 'HTML_QuickForm_xbutton',
2209 'advmultiselect' => array(
2210 'HTML/QuickForm/advmultiselect.php',
2211 'HTML_QuickForm_advmultiselect',
2217 * Set up an acl allowing contact to see 2 specified groups
2218 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2220 * You need to have pre-created these groups & created the user e.g
2221 * $this->createLoggedInUser();
2222 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2223 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2225 * @param bool $isProfile
2227 public function setupACL($isProfile = FALSE) {
2229 $_REQUEST = $this->_params
;
2231 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2232 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2233 $ov = new CRM_Core_DAO_OptionValue();
2234 $ov->option_group_id
= $optionGroupID;
2236 if ($ov->find(TRUE)) {
2237 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2239 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2240 'option_group_id' => $optionGroupID,
2241 'label' => 'pick me',
2245 CRM_Core_DAO
::executeQuery("
2246 TRUNCATE civicrm_acl_cache
2249 CRM_Core_DAO
::executeQuery("
2250 TRUNCATE civicrm_acl_contact_cache
2253 CRM_Core_DAO
::executeQuery("
2254 INSERT INTO civicrm_acl_entity_role (
2255 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2256 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2260 CRM_Core_DAO
::executeQuery("
2261 INSERT INTO civicrm_acl (
2262 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2265 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2270 CRM_Core_DAO
::executeQuery("
2271 INSERT INTO civicrm_acl (
2272 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2275 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2279 CRM_Core_DAO
::executeQuery("
2280 INSERT INTO civicrm_acl (
2281 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2284 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2289 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2290 $this->callAPISuccess('group_contact', 'create', array(
2291 'group_id' => $this->_permissionedGroup
,
2292 'contact_id' => $this->_loggedInUser
,
2297 CRM_ACL_BAO_Cache
::resetCache();
2298 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2303 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2305 public function offsetDefaultPriceSet() {
2306 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2307 $firstID = $contributionPriceSet['id'];
2308 $this->callAPISuccess('price_set', 'create', array(
2309 'id' => $contributionPriceSet['id'],
2313 unset($contributionPriceSet['id']);
2314 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2315 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2316 'price_set_id' => $firstID,
2317 'options' => array('limit' => 1),
2319 unset($priceField['id']);
2320 $priceField['price_set_id'] = $newPriceSet['id'];
2321 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2322 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2323 'price_set_id' => $firstID,
2325 'options' => array('limit' => 1),
2328 unset($priceFieldValue['id']);
2329 //create some padding to use up ids
2330 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2331 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2332 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2336 * Create an instance of the paypal processor.
2337 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2338 * this parent class & we don't have a structure for that yet
2339 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2340 * & the best protection against that is the functions this class affords
2341 * @param array $params
2342 * @return int $result['id'] payment processor id
2344 public function paymentProcessorCreate($params = array()) {
2345 $params = array_merge(array(
2347 'domain_id' => CRM_Core_Config
::domainID(),
2348 'payment_processor_type_id' => 'PayPal',
2352 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2353 'password' => '1183377788',
2354 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2355 'url_site' => 'https://www.sandbox.paypal.com/',
2356 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2357 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2358 'class_name' => 'Payment_PayPalImpl',
2359 'billing_mode' => 3,
2360 'financial_type_id' => 1,
2361 'financial_account_id' => 12,
2362 // Credit card = 1 so can pass 'by accident'.
2363 'payment_instrument_id' => 'Debit Card',
2365 if (!is_numeric($params['payment_processor_type_id'])) {
2366 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2368 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2369 'name' => $params['payment_processor_type_id'],
2373 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2374 return $result['id'];
2378 * Set up initial recurring payment allowing subsequent IPN payments.
2380 * @param array $recurParams (Optional)
2381 * @param array $contributionParams (Optional)
2383 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2384 $contributionParams = array_merge([
2385 'total_amount' => '200',
2386 'invoice_id' => $this->_invoiceID
,
2387 'financial_type_id' => 'Donation',
2388 'contribution_status_id' => 'Pending',
2389 'contact_id' => $this->_contactID
,
2390 'contribution_page_id' => $this->_contributionPageID
,
2391 'payment_processor_id' => $this->_paymentProcessorID
,
2393 'skipCleanMoney' => TRUE,
2394 ], $contributionParams);
2395 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2396 'contact_id' => $this->_contactID
,
2399 'installments' => 5,
2400 'frequency_unit' => 'Month',
2401 'frequency_interval' => 1,
2402 'invoice_id' => $this->_invoiceID
,
2403 'contribution_status_id' => 2,
2404 'payment_processor_id' => $this->_paymentProcessorID
,
2405 // processor provided ID - use contact ID as proxy.
2406 'processor_id' => $this->_contactID
,
2407 'api.contribution.create' => $contributionParams,
2409 $this->_contributionRecurID
= $contributionRecur['id'];
2410 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2414 * 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
2416 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2418 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2419 $membershipParams = $recurParams = array();
2420 if (!empty($params['duration_unit'])) {
2421 $membershipParams['duration_unit'] = $params['duration_unit'];
2423 if (!empty($params['frequency_unit'])) {
2424 $recurParams['frequency_unit'] = $params['frequency_unit'];
2427 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2428 //create a contribution so our membership & contribution don't both have id = 1
2429 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2430 $this->contributionCreate(array(
2431 'contact_id' => $this->_contactID
,
2433 'financial_type_id' => 1,
2434 'invoice_id' => 'abcd',
2438 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2440 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2441 'contact_id' => $this->_contactID
,
2442 'membership_type_id' => $this->ids
['membership_type'],
2443 'contribution_recur_id' => $this->_contributionRecurID
,
2444 'format.only_id' => TRUE,
2446 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2447 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2449 $this->callAPISuccess('line_item', 'create', array(
2450 'entity_table' => 'civicrm_membership',
2451 'entity_id' => $this->ids
['membership'],
2452 'contribution_id' => $this->_contributionID
,
2453 'label' => 'General',
2455 'unit_price' => 200,
2456 'line_total' => 200,
2457 'financial_type_id' => 1,
2458 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2460 'label' => 'Membership Amount',
2461 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2463 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2465 'label' => 'General',
2466 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2469 $this->callAPISuccess('membership_payment', 'create', array(
2470 'contribution_id' => $this->_contributionID
,
2471 'membership_id' => $this->ids
['membership'],
2480 public function CiviUnitTestCase_fatalErrorHandler($message) {
2481 throw new Exception("{$message['message']}: {$message['code']}");
2485 * Wrap the entire test case in a transaction.
2487 * Only subsequent DB statements will be wrapped in TX -- this cannot
2488 * retroactively wrap old DB statements. Therefore, it makes sense to
2489 * call this at the beginning of setUp().
2491 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2492 * this option does not work with, e.g., custom-data.
2494 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2495 * if TRUNCATE or ALTER is called while using a transaction.
2498 * Whether to use nesting or reference-counting.
2500 public function useTransaction($nest = TRUE) {
2502 $this->tx
= new CRM_Core_Transaction($nest);
2503 $this->tx
->rollback();
2508 * Assert the attachment exists.
2510 * @param bool $exists
2511 * @param array $apiResult
2513 protected function assertAttachmentExistence($exists, $apiResult) {
2514 $fileId = $apiResult['id'];
2515 $this->assertTrue(is_numeric($fileId));
2516 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2517 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2518 1 => array($fileId, 'Int'),
2520 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2521 1 => array($fileId, 'Int'),
2526 * Assert 2 sql strings are the same, ignoring double spaces.
2528 * @param string $expectedSQL
2529 * @param string $actualSQL
2530 * @param string $message
2532 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2533 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2534 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2535 $this->assertEquals($expected, $actual, $message);
2539 * Create a price set for an event.
2541 * @param int $feeTotal
2542 * @param int $minAmt
2543 * @param string $type
2548 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2549 // creating price set, price field
2550 $paramsSet['title'] = 'Price Set';
2551 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2552 $paramsSet['is_active'] = FALSE;
2553 $paramsSet['extends'] = 1;
2554 $paramsSet['min_amount'] = $minAmt;
2556 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2557 $this->_ids
['price_set'] = $priceSet->id
;
2559 $paramsField = array(
2560 'label' => 'Price Field',
2561 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2562 'html_type' => $type,
2563 'price' => $feeTotal,
2564 'option_label' => array('1' => 'Price Field'),
2565 'option_value' => array('1' => $feeTotal),
2566 'option_name' => array('1' => $feeTotal),
2567 'option_weight' => array('1' => 1),
2568 'option_amount' => array('1' => 1),
2569 'is_display_amounts' => 1,
2571 'options_per_line' => 1,
2572 'is_active' => array('1' => 1),
2573 'price_set_id' => $this->_ids
['price_set'],
2574 'is_enter_qty' => 1,
2575 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2577 if ($type === 'Radio') {
2578 $paramsField['is_enter_qty'] = 0;
2579 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2580 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2582 CRM_Price_BAO_PriceField
::create($paramsField);
2583 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2584 $this->_ids
['price_field'] = array_keys($fields['values']);
2585 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2586 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2588 return $this->_ids
['price_set'];
2592 * Add a profile to a contribution page.
2594 * @param string $name
2595 * @param int $contributionPageID
2596 * @param string $module
2598 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2600 'uf_group_id' => $name,
2601 'module' => $module,
2602 'entity_table' => 'civicrm_contribution_page',
2603 'entity_id' => $contributionPageID,
2606 if ($module !== 'CiviContribute') {
2607 $params['module_data'] = [$module => []];
2609 $this->callAPISuccess('UFJoin', 'create', $params);
2613 * Add participant with contribution
2617 protected function createParticipantWithContribution() {
2618 // creating price set, price field
2619 $this->_contactId
= $this->individualCreate();
2620 $event = $this->eventCreate();
2621 $this->_eventId
= $event['id'];
2622 $eventParams = array(
2623 'id' => $this->_eventId
,
2624 'financial_type_id' => 4,
2627 $this->callAPISuccess('event', 'create', $eventParams);
2628 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2629 $participantParams = array(
2630 'financial_type_id' => 4,
2631 'event_id' => $this->_eventId
,
2634 'fee_currency' => 'USD',
2635 'contact_id' => $this->_contactId
,
2637 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2638 $contributionParams = array(
2639 'total_amount' => 150,
2640 'currency' => 'USD',
2641 'contact_id' => $this->_contactId
,
2642 'financial_type_id' => 4,
2643 'contribution_status_id' => 1,
2644 'partial_payment_total' => 300.00,
2645 'partial_amount_to_pay' => 150,
2646 'contribution_mode' => 'participant',
2647 'participant_id' => $participant['id'],
2649 foreach ($priceFields['values'] as $key => $priceField) {
2650 $lineItems[1][$key] = array(
2651 'price_field_id' => $priceField['price_field_id'],
2652 'price_field_value_id' => $priceField['id'],
2653 'label' => $priceField['label'],
2654 'field_title' => $priceField['label'],
2656 'unit_price' => $priceField['amount'],
2657 'line_total' => $priceField['amount'],
2658 'financial_type_id' => $priceField['financial_type_id'],
2661 $contributionParams['line_item'] = $lineItems;
2662 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2663 $paymentParticipant = array(
2664 'participant_id' => $participant['id'],
2665 'contribution_id' => $contribution['id'],
2667 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2668 return array($lineItems, $contribution);
2674 * @param string $component
2675 * @param int $componentId
2676 * @param array $priceFieldOptions
2680 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2681 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2682 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2683 $paramsSet['is_active'] = TRUE;
2684 $paramsSet['financial_type_id'] = 'Event Fee';
2685 $paramsSet['extends'] = 1;
2686 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2687 $priceSetId = $priceSet['id'];
2688 //Checking for priceset added in the table.
2689 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2690 'id', $paramsSet['title'], 'Check DB for created priceset'
2692 $paramsField = array_merge(array(
2693 'label' => 'Price Field',
2694 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2695 'html_type' => 'CheckBox',
2696 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2697 'option_value' => array('1' => 100, '2' => 200),
2698 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2699 'option_weight' => array('1' => 1, '2' => 2),
2700 'option_amount' => array('1' => 100, '2' => 200),
2701 'is_display_amounts' => 1,
2703 'options_per_line' => 1,
2704 'is_active' => array('1' => 1, '2' => 1),
2705 'price_set_id' => $priceSet['id'],
2706 'is_enter_qty' => 1,
2707 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2708 ), $priceFieldOptions);
2710 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2712 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2714 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2718 * Replace the template with a test-oriented template designed to show all the variables.
2720 * @param string $templateName
2722 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2723 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2724 CRM_Core_DAO
::executeQuery(
2725 "UPDATE civicrm_option_group og
2726 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2727 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2728 SET m.msg_html = '{$testTemplate}'
2729 WHERE og.name = 'msg_tpl_workflow_contribution'
2730 AND ov.name = '{$templateName}'
2731 AND m.is_default = 1"
2736 * Reinstate the default template.
2738 * @param string $templateName
2740 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2741 CRM_Core_DAO
::executeQuery(
2742 "UPDATE civicrm_option_group og
2743 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2744 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2745 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2746 SET m.msg_html = m2.msg_html
2747 WHERE og.name = 'msg_tpl_workflow_contribution'
2748 AND ov.name = '{$templateName}'
2749 AND m.is_default = 1"
2754 * Flush statics relating to financial type.
2756 protected function flushFinancialTypeStatics() {
2757 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2758 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2760 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2761 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2763 CRM_Contribute_PseudoConstant
::flush('financialType');
2764 CRM_Contribute_PseudoConstant
::flush('membershipType');
2765 // Pseudoconstants may be saved to the cache table.
2766 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2767 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2768 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2772 * Set the permissions to the supplied array.
2774 * @param array $permissions
2776 protected function setPermissions($permissions) {
2777 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2778 $this->flushFinancialTypeStatics();
2782 * @param array $params
2785 public function _checkFinancialRecords($params, $context) {
2786 $entityParams = array(
2787 'entity_id' => $params['id'],
2788 'entity_table' => 'civicrm_contribution',
2790 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2791 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2792 if ($context == 'pending') {
2793 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2794 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2797 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2798 $trxnParams = array(
2799 'id' => $trxn['financial_trxn_id'],
2801 if ($context != 'online' && $context != 'payLater') {
2802 $compareParams = array(
2803 'to_financial_account_id' => 6,
2804 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2808 if ($context == 'feeAmount') {
2809 $compareParams['fee_amount'] = 50;
2811 elseif ($context == 'online') {
2812 $compareParams = array(
2813 'to_financial_account_id' => 12,
2814 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2816 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2819 elseif ($context == 'payLater') {
2820 $compareParams = array(
2821 'to_financial_account_id' => 7,
2822 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2826 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2827 $entityParams = array(
2828 'financial_trxn_id' => $trxn['financial_trxn_id'],
2829 'entity_table' => 'civicrm_financial_item',
2831 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2832 $fitemParams = array(
2833 'id' => $entityTrxn['entity_id'],
2835 $compareParams = array(
2836 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2838 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2840 if ($context == 'payLater') {
2841 $compareParams = array(
2842 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2844 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2847 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2848 if ($context == 'feeAmount') {
2850 'entity_id' => $params['id'],
2851 'entity_table' => 'civicrm_contribution',
2853 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2854 $trxnParams = array(
2855 'id' => $maxTrxn['financial_trxn_id'],
2857 $compareParams = array(
2858 'to_financial_account_id' => 5,
2859 'from_financial_account_id' => 6,
2860 'total_amount' => 50,
2863 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2864 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2865 $fitemParams = array(
2866 'entity_id' => $trxnId['financialTrxnId'],
2867 'entity_table' => 'civicrm_financial_trxn',
2869 $compareParams = array(
2872 'financial_account_id' => 5,
2874 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2876 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2877 // line should be copied into all the functions that call this function & evaluated there
2878 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2879 // when calling completeTransaction or repeatTransaction.
2880 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2884 * Return financial type id on basis of name
2886 * @param string $name Financial type m/c name
2890 public function getFinancialTypeId($name) {
2891 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2895 * Cleanup function for contents of $this->ids.
2897 * This is a best effort cleanup to use in tear downs etc.
2899 * It will not fail if the data has already been removed (some tests may do
2900 * their own cleanup).
2902 protected function cleanUpSetUpIDs() {
2903 foreach ($this->setupIDs
as $entity => $id) {
2905 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2907 catch (CiviCRM_API3_Exception
$e) {
2908 // This is a best-effort cleanup function, ignore.
2914 * Create Financial Type.
2916 * @param array $params
2920 protected function createFinancialType($params = array()) {
2921 $params = array_merge($params,
2923 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2927 return $this->callAPISuccess('FinancialType', 'create', $params);
2931 * Create Payment Instrument.
2933 * @param array $params
2934 * @param string $financialAccountName
2938 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2939 $params = array_merge(array(
2940 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2941 'option_group_id' => 'payment_instrument',
2944 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2946 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2948 $financialAccountParams = [
2949 'entity_table' => 'civicrm_option_value',
2950 'entity_id' => $newPaymentInstrument,
2951 'account_relationship' => $relationTypeID,
2952 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2954 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2956 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2960 * Enable Tax and Invoicing
2962 protected function enableTaxAndInvoicing($params = array()) {
2963 // Enable component contribute setting
2964 $contributeSetting = array_merge($params,
2967 'invoice_prefix' => 'INV_',
2968 'credit_notes_prefix' => 'CN_',
2970 'due_date_period' => 'days',
2972 'is_email_pdf' => 1,
2973 'tax_term' => 'Sales Tax',
2974 'tax_display_settings' => 'Inclusive',
2977 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2981 * Enable Tax and Invoicing
2983 protected function disableTaxAndInvoicing($params = array()) {
2984 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2985 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2987 // Enable component contribute setting
2988 $contributeSetting = array_merge($params,
2993 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2997 * Add Sales Tax relation for financial type with financial account.
2999 * @param int $financialTypeId
3003 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3005 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3006 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3007 'is_deductible' => 1,
3012 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3013 $entityParams = array(
3014 'entity_table' => 'civicrm_financial_type',
3015 'entity_id' => $financialTypeId,
3016 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3019 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3020 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3022 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3023 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3024 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3025 $dao->copyValues($entityParams);
3027 if ($dao->fetch()) {
3028 $entityParams['id'] = $dao->id
;
3030 $entityParams['financial_account_id'] = $account->id
;
3032 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3036 * Create price set with contribution test for test setup.
3038 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3039 * on parent class at some point (fn is not in 4.4).
3042 * @param array $params
3044 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3045 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3046 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3047 'title' => "Test Contribution Page",
3048 'financial_type_id' => 1,
3049 'currency' => 'NZD',
3050 'goal_amount' => 50,
3051 'is_pay_later' => 1,
3052 'is_monetary' => TRUE,
3053 'is_email_receipt' => FALSE,
3055 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3056 'is_quick_config' => 0,
3057 'extends' => 'CiviMember',
3058 'financial_type_id' => 1,
3059 'title' => 'my Page',
3061 $priceSetID = $priceSet['id'];
3063 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3064 $priceField = $this->callAPISuccess('price_field', 'create', array(
3065 'price_set_id' => $priceSetID,
3066 'label' => 'Goat Breed',
3067 'html_type' => 'Radio',
3069 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3070 'price_set_id' => $priceSetID,
3071 'price_field_id' => $priceField['id'],
3072 'label' => 'Long Haired Goat',
3074 'financial_type_id' => 'Donation',
3075 'membership_type_id' => $membershipTypeID,
3076 'membership_num_terms' => 1,
3078 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3079 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3080 'price_set_id' => $priceSetID,
3081 'price_field_id' => $priceField['id'],
3082 'label' => 'Shoe-eating Goat',
3084 'financial_type_id' => 'Donation',
3085 'membership_type_id' => $membershipTypeID,
3086 'membership_num_terms' => 2,
3088 $this->_ids
['price_field_value'][] = $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',
3097 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3099 $this->_ids
['price_set'] = $priceSetID;
3100 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3101 $this->_ids
['price_field'] = array($priceField['id']);
3103 $this->_ids
['membership_type'] = $membershipTypeID;
3107 * Only specified contact returned.
3108 * @implements CRM_Utils_Hook::aclWhereClause
3111 * @param $whereTables
3115 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3116 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3120 * @implements CRM_Utils_Hook::selectWhereClause
3122 * @param string $entity
3123 * @param array $clauses
3125 public function selectWhereClauseHook($entity, &$clauses) {
3126 if ($entity == 'Event') {
3127 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3132 * An implementation of hook_civicrm_post used with all our test cases.
3135 * @param string $objectName
3136 * @param int $objectId
3139 public function onPost($op, $objectName, $objectId, &$objectRef) {
3140 if ($op == 'create' && $objectName == 'Individual') {
3141 CRM_Core_DAO
::executeQuery(
3142 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3144 1 => array($objectId, 'Integer'),
3149 if ($op == 'edit' && $objectName == 'Participant') {
3151 1 => array($objectId, 'Integer'),
3153 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3154 CRM_Core_DAO
::executeQuery($query, $params);
3159 * Instantiate form object.
3161 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3163 * @param string $class
3164 * Name of form class.
3166 * @param array $formValues
3168 * @param string $pageName
3170 * @return \CRM_Core_Form
3171 * @throws \CRM_Core_Exception
3173 public function getFormObject($class, $formValues = [], $pageName = '') {
3174 $form = new $class();
3175 $_SERVER['REQUEST_METHOD'] = 'GET';
3176 $form->controller
= new CRM_Core_Controller();
3177 $form->controller
->setStateMachine(new CRM_Core_StateMachine($form->controller
));
3178 $_SESSION['_' . $form->controller
->_name
. '_container']['values'][$pageName] = $formValues;
3183 * Get possible thousand separators.
3187 public function getThousandSeparators() {
3188 return array(array('.'), array(','));
3192 * Get the boolean options as a provider.
3196 public function getBooleanDataProvider() {
3197 return [[TRUE], [FALSE]];
3201 * Set the separators for thousands and decimal points.
3203 * @param string $thousandSeparator
3205 protected function setCurrencySeparators($thousandSeparator) {
3206 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3208 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3212 * Format money as it would be input.
3214 * @param string $amount
3218 protected function formatMoneyInput($amount) {
3219 return CRM_Utils_Money
::format($amount, NULL, '%a');
3223 * Get the contribution object.
3225 * @param int $contributionID
3227 * @return \CRM_Contribute_BAO_Contribution
3229 protected function getContributionObject($contributionID) {
3230 $contributionObj = new CRM_Contribute_BAO_Contribution();
3231 $contributionObj->id
= $contributionID;
3232 $contributionObj->find(TRUE);
3233 return $contributionObj;
3237 * Enable multilingual.
3239 public function enableMultilingual() {
3240 $this->callAPISuccess('Setting', 'create', array(
3241 'lcMessages' => 'en_US',
3242 'languageLimit' => array(
3247 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3250 $dbLocale = '_en_US';
3254 * Setup or clean up SMS tests
3255 * @param bool $teardown
3257 * @throws \CiviCRM_API3_Exception
3259 public function setupForSmsTests($teardown = FALSE) {
3260 require_once 'CiviTest/CiviTestSMSProvider.php';
3262 // Option value params for CiviTestSMSProvider
3263 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3265 'option_group_id' => $groupID,
3266 'label' => 'unittestSMS',
3267 'value' => 'unit.test.sms',
3268 'name' => 'CiviTestSMSProvider',
3275 // Test completed, delete provider
3276 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3277 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3281 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3282 // in CRM/Sms/Provider.php even though it is not an extension.
3283 return civicrm_api3('option_value', 'create', $params);