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 Symfony\Component\Yaml\Yaml
;
33 * Include class definitions
35 require_once 'api/api.php';
36 define('API_LATEST_VERSION', 3);
39 * Base class for CiviCRM unit tests
41 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
42 * may opt for one or neither:
44 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
45 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
46 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
47 * 2. useTransaction() executes the test inside a transaction. It's easier to use
48 * (because you don't need to identify specific tables), but it doesn't work for tests
49 * which manipulate schema or truncate data -- and could behave inconsistently
50 * for tests which specifically examine DB transactions.
52 * Common functions for unit tests
55 class CiviUnitTestCase
extends PHPUnit\Framework\TestCase
{
57 use \Civi\Test\Api3DocTrait
;
58 use \Civi\Test\GenericAssertionsTrait
;
59 use \Civi\Test\DbTestTrait
;
60 use \Civi\Test\ContactTestTrait
;
61 use \Civi\Test\MailingTestTrait
;
64 * Database has been initialized.
68 private static $dbInit = FALSE;
71 * Database connection.
73 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
82 static protected $_dbName;
85 * Track tables we have modified during a test.
88 protected $_tablesToTruncate = array();
91 * @var array of temporary directory names
96 * @var bool populateOnce allows to skip db resets in setUp
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
106 public static $populateOnce = FALSE;
109 * @var bool DBResetRequired allows skipping DB reset
110 * in specific test case. If you still need
111 * to reset single test (method) of such case, call
112 * $this->cleanDB() in the first line of this
115 public $DBResetRequired = TRUE;
118 * @var CRM_Core_Transaction|NULL
123 * Array of IDs created to support the test.
126 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
133 * Class used for hooks during tests.
135 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
137 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
139 * @var CRM_Utils_Hook_UnitTests hookClass
141 public $hookClass = NULL;
144 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
146 protected $_params = array();
149 * @var CRM_Extension_System
151 protected $origExtensionSystem;
154 * Array of IDs created during test setup routine.
156 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
160 public $setupIDs = array();
163 * PHPUnit Mock Method to use.
167 public $mockMethod = 'getMock';
172 * Because we are overriding the parent class constructor, we
173 * need to show the same arguments as exist in the constructor of
174 * PHPUnit_Framework_TestCase, since
175 * PHPUnit_Framework_TestSuite::createTest() creates a
176 * ReflectionClass of the Test class and checks the constructor
177 * of that class to decide how to set up the test.
179 * @param string $name
181 * @param string $dataName
183 public function __construct($name = NULL, array $data = array(), $dataName = '') {
184 parent
::__construct($name, $data, $dataName);
186 // we need full error reporting
187 error_reporting(E_ALL
& ~E_NOTICE
);
189 self
::$_dbName = self
::getDBName();
191 // also load the class loader
192 require_once 'CRM/Core/ClassLoader.php';
193 CRM_Core_ClassLoader
::singleton()->register();
194 if (function_exists('_civix_phpunit_setUp')) {
195 // FIXME: loosen coupling
196 _civix_phpunit_setUp();
198 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version
::id(), '5', '>=')) {
199 $this->mockMethod
= 'createMock';
201 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version
::id(), '6', '>=')) {
202 $this->mockMethod
= 'createMock';
207 * Override to run the test and assert its state.
210 * @throws \PHPUnit_Framework_IncompleteTest
211 * @throws \PHPUnit_Framework_SkippedTest
213 protected function runTest() {
215 return parent
::runTest();
217 catch (PEAR_Exception
$e) {
218 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
219 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
226 public function requireDBReset() {
227 return $this->DBResetRequired
;
233 public static function getDBName() {
234 static $dbName = NULL;
235 if ($dbName === NULL) {
236 require_once "DB.php";
237 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
238 $dbName = $dsninfo['database'];
244 * Create database connection for this instance.
246 * Initialize the test database if it hasn't been initialized
249 protected function getConnection() {
250 if (!self
::$dbInit) {
251 $dbName = self
::getDBName();
253 // install test database
254 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
256 static::_populateDB(FALSE, $this);
258 self
::$dbInit = TRUE;
264 * Required implementation of abstract method.
266 protected function getDataSet() {
270 * @param bool $perClass
271 * @param null $object
273 * TRUE if the populate logic runs; FALSE if it is skipped
275 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
276 if (CIVICRM_UF
!== 'UnitTests') {
277 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
280 if ($perClass ||
$object == NULL) {
284 $dbreset = $object->requireDBReset();
287 if (self
::$populateOnce ||
!$dbreset) {
290 self
::$populateOnce = NULL;
292 Civi\Test
::data()->populate();
297 public static function setUpBeforeClass() {
298 static::_populateDB(TRUE);
300 // also set this global hack
301 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
305 * Common setup functions for all unit tests.
307 protected function setUp() {
308 $session = CRM_Core_Session
::singleton();
309 $session->set('userID', NULL);
311 $this->_apiversion
= 3;
314 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
315 // Use a temporary file for STDIN
316 $GLOBALS['stdin'] = tmpfile();
317 if ($GLOBALS['stdin'] === FALSE) {
318 echo "Couldn't open temporary file\n";
322 // Get and save a connection to the database
323 $this->_dbconn
= $this->getConnection();
325 // reload database before each test
326 // $this->_populateDB();
328 // "initialize" CiviCRM to avoid problems when running single tests
329 // FIXME: look at it closer in second stage
331 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
332 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
334 // disable any left-over test extensions
335 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
337 $extensions = \CRM_Extension_System
::singleton()->getManager();
338 $api4Status = $extensions->getStatus('org.civicrm.api4');
339 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
340 $extensions->enable(['org.civicrm.api4']);
343 // reset all the caches
344 CRM_Utils_System
::flushCache();
346 // initialize the object once db is loaded
349 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
351 // when running unit tests, use mockup user framework
352 $this->hookClass
= CRM_Utils_Hook
::singleton();
354 // Make sure the DB connection is setup properly
355 $config->userSystem
->setMySQLTimeZone();
356 $env = new CRM_Utils_Check_Component_Env();
357 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
359 // clear permissions stub to not check permissions
360 $config->userPermissionClass
->permissions
= NULL;
362 //flush component settings
363 CRM_Core_Component
::getEnabledComponents(TRUE);
365 $_REQUEST = $_GET = $_POST = [];
366 error_reporting(E_ALL
);
368 $this->_sethtmlGlobals();
372 * Read everything from the datasets directory and insert into the db.
374 public function loadAllFixtures() {
375 $fixturesDir = __DIR__
. '/../../fixtures';
377 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
379 $yamlFiles = glob($fixturesDir . '/*.yaml');
380 foreach ($yamlFiles as $yamlFixture) {
381 $yaml = Yaml
::parse(file_get_contents($yamlFixture));
382 foreach ($yaml as $tableName => $vars) {
383 if ($tableName === 'civicrm_contact') {
384 CRM_Core_DAO
::executeQuery('DELETE c FROM civicrm_contact c LEFT JOIN civicrm_domain d ON d.contact_id = c.id WHERE d.id IS NULL');
387 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
389 foreach ($vars as $entity) {
390 $keys = $values = [];
391 foreach ($entity as $key => $value) {
393 $values[] = is_numeric($value) ?
$value : "'{$value}'";
395 CRM_Core_DAO
::executeQuery("
396 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
403 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
407 * Load the data that used to be handled by the discontinued dbunit class.
409 * This could do with further tidy up - the initial priority is simply to get rid of
410 * the dbunity package which is no longer supported.
412 * @param string $fileName
414 protected function loadXMLDataSet($fileName) {
415 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
416 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
417 foreach ($xml as $tableName => $element) {
418 if (!empty($element)) {
419 foreach ($element as $row) {
420 $keys = $values = [];
421 if (isset($row['@attributes'])) {
422 foreach ($row['@attributes'] as $key => $value) {
424 $values[] = is_numeric($value) ?
$value : "'{$value}'";
427 elseif (!empty($row)) {
428 // cos we copied it & it is inconsistent....
429 foreach ($row as $key => $value) {
431 $values[] = is_numeric($value) ?
$value : "'{$value}'";
435 if (!empty($values)) {
436 CRM_Core_DAO
::executeQuery("
437 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
443 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
447 * Create default domain contacts for the two domains added during test class.
448 * database population.
450 public function createDomainContacts() {
451 $this->organizationCreate();
452 $this->organizationCreate(array('organization_name' => 'Second Domain'));
456 * Common teardown functions for all unit tests.
458 protected function tearDown() {
459 $this->_apiversion
= 3;
461 error_reporting(E_ALL
& ~E_NOTICE
);
462 CRM_Utils_Hook
::singleton()->reset();
463 if ($this->hookClass
) {
464 $this->hookClass
->reset();
466 CRM_Core_Session
::singleton()->reset(1);
469 $this->tx
->rollback()->commit();
472 CRM_Core_Transaction
::forceRollbackIfEnabled();
473 \Civi\Core\Transaction\Manager
::singleton(TRUE);
476 CRM_Core_Transaction
::forceRollbackIfEnabled();
477 \Civi\Core\Transaction\Manager
::singleton(TRUE);
479 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
480 $this->quickCleanup($tablesToTruncate);
481 $this->createDomainContacts();
484 $this->cleanTempDirs();
485 $this->unsetExtensionSystem();
489 * Create a batch of external API calls which can
490 * be executed concurrently.
493 * $calls = $this->createExternalAPI()
494 * ->addCall('Contact', 'get', ...)
495 * ->addCall('Contact', 'get', ...)
501 * @return \Civi\API\ExternalBatch
502 * @throws PHPUnit_Framework_SkippedTestError
504 public function createExternalAPI() {
505 global $civicrm_root;
506 $defaultParams = array(
507 'version' => $this->_apiversion
,
511 $calls = new \Civi\API\
ExternalBatch($defaultParams);
513 if (!$calls->isSupported()) {
514 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
521 * Create required data based on $this->entity & $this->params
522 * This is just a way to set up the test data for delete & get functions
523 * so the distinction between set
524 * up & tested functions is clearer
529 public function createTestEntity() {
530 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
534 * @param int $contactTypeId
538 public function contactTypeDelete($contactTypeId) {
539 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
541 throw new Exception('Could not delete contact type');
546 * @param array $params
550 public function membershipTypeCreate($params = array()) {
551 CRM_Member_PseudoConstant
::flush('membershipType');
552 CRM_Core_Config
::clearDBCache();
553 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
554 $params = array_merge(array(
556 'duration_unit' => 'year',
557 'duration_interval' => 1,
558 'period_type' => 'rolling',
559 'member_of_contact_id' => $memberOfOrganization,
561 'financial_type_id' => 2,
564 'visibility' => 'Public',
567 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
569 CRM_Member_PseudoConstant
::flush('membershipType');
570 CRM_Utils_Cache
::singleton()->flush();
572 return $result['id'];
576 * @param array $params
580 public function contactMembershipCreate($params) {
581 $params = array_merge(array(
582 'join_date' => '2007-01-21',
583 'start_date' => '2007-01-21',
584 'end_date' => '2007-12-21',
585 'source' => 'Payment',
586 'membership_type_id' => 'General',
588 if (!is_numeric($params['membership_type_id'])) {
589 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
590 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
591 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
595 $result = $this->callAPISuccess('Membership', 'create', $params);
596 return $result['id'];
600 * Delete Membership Type.
602 * @param array $params
604 public function membershipTypeDelete($params) {
605 $this->callAPISuccess('MembershipType', 'Delete', $params);
609 * @param int $membershipID
611 public function membershipDelete($membershipID) {
612 $deleteParams = array('id' => $membershipID);
613 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
617 * @param string $name
621 public function membershipStatusCreate($name = 'test member status') {
622 $params['name'] = $name;
623 $params['start_event'] = 'start_date';
624 $params['end_event'] = 'end_date';
625 $params['is_current_member'] = 1;
626 $params['is_active'] = 1;
628 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
629 CRM_Member_PseudoConstant
::flush('membershipStatus');
630 return $result['id'];
634 * @param int $membershipStatusID
636 public function membershipStatusDelete($membershipStatusID) {
637 if (!$membershipStatusID) {
640 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
643 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
644 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
645 $renewedMembershipEndDate = new DateTime($membershipEndDate);
646 switch ($durationUnit) {
648 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
652 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
653 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
654 $renewedMembershipEndDate->add(new DateInterval('P1D'));
655 $renewedMembershipEndDate->add(new DateInterval('P1M'));
656 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
659 return $renewedMembershipEndDate->format('Y-m-d');
663 * @param array $params
667 public function relationshipTypeCreate($params = array()) {
668 $params = array_merge(array(
669 'name_a_b' => 'Relation 1 for relationship type create',
670 'name_b_a' => 'Relation 2 for relationship type create',
671 'contact_type_a' => 'Individual',
672 'contact_type_b' => 'Organization',
677 $result = $this->callAPISuccess('relationship_type', 'create', $params);
678 CRM_Core_PseudoConstant
::flush('relationshipType');
680 return $result['id'];
684 * Delete Relatinship Type.
686 * @param int $relationshipTypeID
688 public function relationshipTypeDelete($relationshipTypeID) {
689 $params['id'] = $relationshipTypeID;
690 $check = $this->callAPISuccess('relationship_type', 'get', $params);
691 if (!empty($check['count'])) {
692 $this->callAPISuccess('relationship_type', 'delete', $params);
697 * @param array $params
701 public function paymentProcessorTypeCreate($params = NULL) {
702 if (is_null($params)) {
704 'name' => 'API_Test_PP',
705 'title' => 'API Test Payment Processor',
706 'class_name' => 'CRM_Core_Payment_APITest',
707 'billing_mode' => 'form',
713 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
715 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
717 return $result['id'];
721 * Create test Authorize.net instance.
723 * @param array $params
727 public function paymentProcessorAuthorizeNetCreate($params = array()) {
728 $params = array_merge(array(
729 'name' => 'Authorize',
730 'domain_id' => CRM_Core_Config
::domainID(),
731 'payment_processor_type_id' => 'AuthNet',
732 'title' => 'AuthNet',
737 'user_name' => '4y5BfuW7jm',
738 'password' => '4cAmW927n8uLf5J8',
739 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
740 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
741 'class_name' => 'Payment_AuthorizeNet',
745 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
746 return $result['id'];
750 * Create Participant.
752 * @param array $params
753 * Array of contact id and event id values.
756 * $id of participant created
758 public function participantCreate($params = []) {
759 if (empty($params['contact_id'])) {
760 $params['contact_id'] = $this->individualCreate();
762 if (empty($params['event_id'])) {
763 $event = $this->eventCreate();
764 $params['event_id'] = $event['id'];
769 'register_date' => 20070219,
770 'source' => 'Wimbeldon',
771 'event_level' => 'Payment',
775 $params = array_merge($defaults, $params);
776 $result = $this->callAPISuccess('Participant', 'create', $params);
777 return $result['id'];
781 * Create Payment Processor.
784 * Id Payment Processor
786 public function processorCreate($params = array()) {
787 $processorParams = array(
790 'payment_processor_type_id' => 'Dummy',
791 'financial_account_id' => 12,
795 'url_site' => 'http://dummy.com',
796 'url_recur' => 'http://dummy.com',
799 'payment_instrument_id' => 'Debit Card',
801 $processorParams = array_merge($processorParams, $params);
802 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
803 return $processor['id'];
807 * Create Payment Processor.
809 * @param array $processorParams
811 * @return \CRM_Core_Payment_Dummy
812 * Instance of Dummy Payment Processor
814 public function dummyProcessorCreate($processorParams = array()) {
815 $paymentProcessorID = $this->processorCreate($processorParams);
816 return System
::singleton()->getById($paymentProcessorID);
820 * Create contribution page.
822 * @param array $params
824 * Array of contribution page
826 public function contributionPageCreate($params = array()) {
827 $this->_pageParams
= array_merge(array(
828 'title' => 'Test Contribution Page',
829 'financial_type_id' => 1,
831 'financial_account_id' => 1,
833 'is_allow_other_amount' => 1,
835 'max_amount' => 1000,
837 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
841 * Create a sample batch.
843 public function batchCreate() {
844 $params = $this->_params
;
845 $params['name'] = $params['title'] = 'Batch_433397';
846 $params['status_id'] = 1;
847 $result = $this->callAPISuccess('batch', 'create', $params);
848 return $result['id'];
854 * @param array $params
856 * result of created tag
858 public function tagCreate($params = array()) {
860 'name' => 'New Tag3',
861 'description' => 'This is description for Our New Tag ',
864 $params = array_merge($defaults, $params);
865 $result = $this->callAPISuccess('Tag', 'create', $params);
866 return $result['values'][$result['id']];
873 * Id of the tag to be deleted.
877 public function tagDelete($tagId) {
878 require_once 'api/api.php';
882 $result = $this->callAPISuccess('Tag', 'delete', $params);
883 return $result['id'];
887 * Add entity(s) to the tag
889 * @param array $params
893 public function entityTagAdd($params) {
894 $result = $this->callAPISuccess('entity_tag', 'create', $params);
901 * @param array $params
905 * id of created pledge
907 public function pledgeCreate($params) {
908 $params = array_merge(array(
909 'pledge_create_date' => date('Ymd'),
910 'start_date' => date('Ymd'),
911 'scheduled_date' => date('Ymd'),
913 'pledge_status_id' => '2',
914 'financial_type_id' => '1',
915 'pledge_original_installment_amount' => 20,
916 'frequency_interval' => 5,
917 'frequency_unit' => 'year',
918 'frequency_day' => 15,
923 $result = $this->callAPISuccess('Pledge', 'create', $params);
924 return $result['id'];
928 * Delete contribution.
930 * @param int $pledgeId
932 public function pledgeDelete($pledgeId) {
934 'pledge_id' => $pledgeId,
936 $this->callAPISuccess('Pledge', 'delete', $params);
940 * Create contribution.
942 * @param array $params
943 * Array of parameters.
946 * id of created contribution
948 public function contributionCreate($params) {
950 $params = array_merge(array(
952 'receive_date' => date('Ymd'),
953 'total_amount' => 100.00,
954 'fee_amount' => 5.00,
955 'financial_type_id' => 1,
956 'payment_instrument_id' => 1,
957 'non_deductible_amount' => 10.00,
959 'contribution_status_id' => 1,
962 $result = $this->callAPISuccess('contribution', 'create', $params);
963 return $result['id'];
967 * Delete contribution.
969 * @param int $contributionId
973 public function contributionDelete($contributionId) {
975 'contribution_id' => $contributionId,
977 $result = $this->callAPISuccess('contribution', 'delete', $params);
984 * @param array $params
985 * Name-value pair for an event.
989 public function eventCreate($params = array()) {
990 // if no contact was passed, make up a dummy event creator
991 if (!isset($params['contact_id'])) {
992 $params['contact_id'] = $this->_contactCreate(array(
993 'contact_type' => 'Individual',
994 'first_name' => 'Event',
995 'last_name' => 'Creator',
999 // set defaults for missing params
1000 $params = array_merge(array(
1001 'title' => 'Annual CiviCRM meet',
1002 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1003 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1004 'event_type_id' => 1,
1006 'start_date' => 20081021,
1007 'end_date' => 20081023,
1008 'is_online_registration' => 1,
1009 'registration_start_date' => 20080601,
1010 'registration_end_date' => 20081015,
1011 'max_participants' => 100,
1012 'event_full_text' => 'Sorry! We are already full',
1015 'is_show_location' => 0,
1018 return $this->callAPISuccess('Event', 'create', $params);
1022 * Create a paid event.
1024 * @param array $params
1028 protected function eventCreatePaid($params) {
1029 $event = $this->eventCreate($params);
1030 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1031 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1032 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1033 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1034 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1046 public function eventDelete($id) {
1050 return $this->callAPISuccess('event', 'delete', $params);
1054 * Delete participant.
1056 * @param int $participantID
1060 public function participantDelete($participantID) {
1062 'id' => $participantID,
1064 $check = $this->callAPISuccess('Participant', 'get', $params);
1065 if ($check['count'] > 0) {
1066 return $this->callAPISuccess('Participant', 'delete', $params);
1071 * Create participant payment.
1073 * @param int $participantID
1074 * @param int $contributionID
1076 * $id of created payment
1078 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1079 //Create Participant Payment record With Values
1081 'participant_id' => $participantID,
1082 'contribution_id' => $contributionID,
1085 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1086 return $result['id'];
1090 * Delete participant payment.
1092 * @param int $paymentID
1094 public function participantPaymentDelete($paymentID) {
1098 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1104 * @param int $contactID
1106 * location id of created location
1108 public function locationAdd($contactID) {
1111 'location_type' => 'New Location Type',
1113 'name' => 'Saint Helier St',
1114 'county' => 'Marin',
1115 'country' => 'UNITED STATES',
1116 'state_province' => 'Michigan',
1117 'supplemental_address_1' => 'Hallmark Ct',
1118 'supplemental_address_2' => 'Jersey Village',
1119 'supplemental_address_3' => 'My Town',
1124 'contact_id' => $contactID,
1125 'address' => $address,
1126 'location_format' => '2.0',
1127 'location_type' => 'New Location Type',
1130 $result = $this->callAPISuccess('Location', 'create', $params);
1135 * Delete Locations of contact.
1137 * @param array $params
1140 public function locationDelete($params) {
1141 $this->callAPISuccess('Location', 'delete', $params);
1145 * Add a Location Type.
1147 * @param array $params
1148 * @return CRM_Core_DAO_LocationType
1149 * location id of created location
1151 public function locationTypeCreate($params = NULL) {
1152 if ($params === NULL) {
1154 'name' => 'New Location Type',
1155 'vcard_name' => 'New Location Type',
1156 'description' => 'Location Type for Delete',
1161 $locationType = new CRM_Core_DAO_LocationType();
1162 $locationType->copyValues($params);
1163 $locationType->save();
1164 // clear getfields cache
1165 CRM_Core_PseudoConstant
::flush();
1166 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1167 return $locationType;
1171 * Delete a Location Type.
1173 * @param int $locationTypeId
1175 public function locationTypeDelete($locationTypeId) {
1176 $locationType = new CRM_Core_DAO_LocationType();
1177 $locationType->id
= $locationTypeId;
1178 $locationType->delete();
1184 * @param array $params
1185 * @return CRM_Core_DAO_Mapping
1186 * Mapping id of created mapping
1188 public function mappingCreate($params = NULL) {
1189 if ($params === NULL) {
1191 'name' => 'Mapping name',
1192 'description' => 'Mapping description',
1193 // 'Export Contact' mapping.
1194 'mapping_type_id' => 7,
1198 $mapping = new CRM_Core_DAO_Mapping();
1199 $mapping->copyValues($params);
1201 // clear getfields cache
1202 CRM_Core_PseudoConstant
::flush();
1203 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1210 * @param int $mappingId
1212 public function mappingDelete($mappingId) {
1213 $mapping = new CRM_Core_DAO_Mapping();
1214 $mapping->id
= $mappingId;
1219 * Prepare class for ACLs.
1221 protected function prepareForACLs() {
1222 $config = CRM_Core_Config
::singleton();
1223 $config->userPermissionClass
->permissions
= array();
1229 protected function cleanUpAfterACLs() {
1230 CRM_Utils_Hook
::singleton()->reset();
1231 $tablesToTruncate = array(
1233 'civicrm_acl_cache',
1234 'civicrm_acl_entity_role',
1235 'civicrm_acl_contact_cache',
1237 $this->quickCleanup($tablesToTruncate);
1238 $config = CRM_Core_Config
::singleton();
1239 unset($config->userPermissionClass
->permissions
);
1243 * Create a smart group.
1245 * By default it will be a group of households.
1247 * @param array $smartGroupParams
1248 * @param array $groupParams
1251 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1252 $smartGroupParams = array_merge(array(
1253 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1256 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1258 $groupParams['saved_search_id'] = $savedSearch->id
;
1259 return $this->groupCreate($groupParams);
1264 * @param array $params
1266 public function uFFieldCreate($params = array()) {
1267 $params = array_merge(array(
1269 'field_name' => 'first_name',
1272 'visibility' => 'Public Pages and Listings',
1273 'is_searchable' => '1',
1274 'label' => 'first_name',
1275 'field_type' => 'Individual',
1278 $this->callAPISuccess('uf_field', 'create', $params);
1282 * Add a UF Join Entry.
1284 * @param array $params
1286 * $id of created UF Join
1288 public function ufjoinCreate($params = NULL) {
1289 if ($params === NULL) {
1292 'module' => 'CiviEvent',
1293 'entity_table' => 'civicrm_event',
1299 $result = $this->callAPISuccess('uf_join', 'create', $params);
1304 * @param array $params
1305 * Optional parameters.
1306 * @param bool $reloadConfig
1307 * While enabling CiviCampaign component, we shouldn't always forcibly
1308 * reload config as this hinder hook call in test environment
1313 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1314 $this->enableCiviCampaign($reloadConfig);
1315 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1316 'name' => 'big_campaign',
1317 'title' => 'Campaign',
1319 return $campaign['id'];
1323 * Create Group for a contact.
1325 * @param int $contactId
1327 public function contactGroupCreate($contactId) {
1329 'contact_id.1' => $contactId,
1333 $this->callAPISuccess('GroupContact', 'Create', $params);
1337 * Delete Group for a contact.
1339 * @param int $contactId
1341 public function contactGroupDelete($contactId) {
1343 'contact_id.1' => $contactId,
1346 $this->civicrm_api('GroupContact', 'Delete', $params);
1352 * @param array $params
1355 public function activityCreate($params = array()) {
1356 $params = array_merge(array(
1357 'subject' => 'Discussion on warm beer',
1358 'activity_date_time' => date('Ymd'),
1359 'duration_hours' => 30,
1360 'duration_minutes' => 20,
1361 'location' => 'Baker Street',
1362 'details' => 'Lets schedule a meeting',
1364 'activity_type_id' => 'Meeting',
1366 if (!isset($params['source_contact_id'])) {
1367 $params['source_contact_id'] = $this->individualCreate();
1369 if (!isset($params['target_contact_id'])) {
1370 $params['target_contact_id'] = $this->individualCreate(array(
1371 'first_name' => 'Julia',
1372 'Last_name' => 'Anderson',
1374 'email' => 'julia_anderson@civicrm.org',
1375 'contact_type' => 'Individual',
1378 if (!isset($params['assignee_contact_id'])) {
1379 $params['assignee_contact_id'] = $params['target_contact_id'];
1382 $result = civicrm_api3('Activity', 'create', $params);
1384 $result['target_contact_id'] = $params['target_contact_id'];
1385 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1390 * Create an activity type.
1392 * @param array $params
1396 public function activityTypeCreate($params) {
1397 return $this->callAPISuccess('ActivityType', 'create', $params);
1401 * Delete activity type.
1403 * @param int $activityTypeId
1404 * Id of the activity type.
1407 public function activityTypeDelete($activityTypeId) {
1408 $params['activity_type_id'] = $activityTypeId;
1409 return $this->callAPISuccess('ActivityType', 'delete', $params);
1413 * Create custom group.
1415 * @param array $params
1418 public function customGroupCreate($params = array()) {
1420 'title' => 'new custom group',
1421 'extends' => 'Contact',
1423 'style' => 'Inline',
1427 $params = array_merge($defaults, $params);
1429 return $this->callAPISuccess('custom_group', 'create', $params);
1433 * Existing function doesn't allow params to be over-ridden so need a new one
1434 * this one allows you to only pass in the params you want to change
1435 * @param array $params
1438 public function CustomGroupCreateByParams($params = array()) {
1440 'title' => "API Custom Group",
1441 'extends' => 'Contact',
1443 'style' => 'Inline',
1446 $params = array_merge($defaults, $params);
1447 return $this->callAPISuccess('custom_group', 'create', $params);
1451 * Create custom group with multi fields.
1452 * @param array $params
1455 public function CustomGroupMultipleCreateByParams($params = array()) {
1460 $params = array_merge($defaults, $params);
1461 return $this->CustomGroupCreateByParams($params);
1465 * Create custom group with multi fields.
1466 * @param array $params
1469 public function CustomGroupMultipleCreateWithFields($params = array()) {
1470 // also need to pass on $params['custom_field'] if not set but not in place yet
1472 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1473 $ids['custom_group_id'] = $customGroup['id'];
1475 $customField = $this->customFieldCreate(array(
1476 'custom_group_id' => $ids['custom_group_id'],
1477 'label' => 'field_1' . $ids['custom_group_id'],
1481 $ids['custom_field_id'][] = $customField['id'];
1483 $customField = $this->customFieldCreate(array(
1484 'custom_group_id' => $ids['custom_group_id'],
1485 'default_value' => '',
1486 'label' => 'field_2' . $ids['custom_group_id'],
1489 $ids['custom_field_id'][] = $customField['id'];
1491 $customField = $this->customFieldCreate(array(
1492 'custom_group_id' => $ids['custom_group_id'],
1493 'default_value' => '',
1494 'label' => 'field_3' . $ids['custom_group_id'],
1497 $ids['custom_field_id'][] = $customField['id'];
1503 * Create a custom group with a single text custom field. See
1504 * participant:testCreateWithCustom for how to use this
1506 * @param string $function
1508 * @param string $filename
1512 * ids of created objects
1514 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1515 $params = array('title' => $function);
1516 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1517 $params['extends'] = $entity ?
$entity : 'Contact';
1518 $customGroup = $this->CustomGroupCreate($params);
1519 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1520 CRM_Core_PseudoConstant
::flush();
1522 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1526 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1527 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1529 * @param string $function
1531 * @param string $filename
1535 * ids of created objects
1537 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1538 $params = array('title' => $function);
1539 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1540 $params['extends'] = $entity ?
$entity : 'Contact';
1541 $customGroup = $this->CustomGroupCreate($params);
1542 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1543 CRM_Core_PseudoConstant
::flush();
1545 'defaultValue' => 'Default Value',
1546 'lowercasevalue' => 'Lowercase Value',
1547 1 => 'Integer Value',
1550 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1551 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1552 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1553 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1554 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1555 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1556 foreach ($options as $option_value => $option_label) {
1557 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1558 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1561 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);
1565 * Delete custom group.
1567 * @param int $customGroupID
1571 public function customGroupDelete($customGroupID) {
1572 $params['id'] = $customGroupID;
1573 return $this->callAPISuccess('custom_group', 'delete', $params);
1577 * Create custom field.
1579 * @param array $params
1580 * (custom_group_id) is required.
1583 public function customFieldCreate($params) {
1584 $params = array_merge(array(
1585 'label' => 'Custom Field',
1586 'data_type' => 'String',
1587 'html_type' => 'Text',
1588 'is_searchable' => 1,
1590 'default_value' => 'defaultValue',
1593 $result = $this->callAPISuccess('custom_field', 'create', $params);
1594 // these 2 functions are called with force to flush static caches
1595 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1596 CRM_Core_Component
::getEnabledComponents(1);
1601 * Delete custom field.
1603 * @param int $customFieldID
1607 public function customFieldDelete($customFieldID) {
1609 $params['id'] = $customFieldID;
1610 return $this->callAPISuccess('custom_field', 'delete', $params);
1619 public function noteCreate($cId) {
1621 'entity_table' => 'civicrm_contact',
1622 'entity_id' => $cId,
1623 'note' => 'hello I am testing Note',
1624 'contact_id' => $cId,
1625 'modified_date' => date('Ymd'),
1626 'subject' => 'Test Note',
1629 return $this->callAPISuccess('Note', 'create', $params);
1633 * Enable CiviCampaign Component.
1635 * @param bool $reloadConfig
1636 * Force relaod config or not
1638 public function enableCiviCampaign($reloadConfig = TRUE) {
1639 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1640 if ($reloadConfig) {
1641 // force reload of config object
1642 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1644 //flush cache by calling with reset
1645 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1649 * Create custom field with Option Values.
1651 * @param array $customGroup
1652 * @param string $name
1653 * Name of custom field.
1654 * @param array $extraParams
1655 * Additional parameters to pass through.
1659 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1660 $fieldParams = array(
1661 'custom_group_id' => $customGroup['id'],
1662 'name' => 'test_custom_group',
1663 'label' => 'Country',
1664 'html_type' => 'Select',
1665 'data_type' => 'String',
1668 'is_searchable' => 0,
1672 $optionGroup = array(
1674 'name' => 'option_group1',
1675 'label' => 'option_group_label1',
1678 $optionValue = array(
1679 'option_label' => array('Label1', 'Label2'),
1680 'option_value' => array('value1', 'value2'),
1681 'option_name' => array($name . '_1', $name . '_2'),
1682 'option_weight' => array(1, 2),
1683 'option_status' => 1,
1686 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1688 return $this->callAPISuccess('custom_field', 'create', $params);
1696 public function confirmEntitiesDeleted($entities) {
1697 foreach ($entities as $entity) {
1699 $result = $this->callAPISuccess($entity, 'Get', array());
1700 if ($result['error'] == 1 ||
$result['count'] > 0) {
1701 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1709 * Quick clean by emptying tables created for the test.
1711 * @param array $tablesToTruncate
1712 * @param bool $dropCustomValueTables
1713 * @throws \Exception
1715 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1717 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1719 if ($dropCustomValueTables) {
1720 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1721 while ($optionGroupResult->fetch()) {
1722 if (!empty($optionGroupResult->option_group_id
)) {
1723 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1726 $tablesToTruncate[] = 'civicrm_custom_group';
1727 $tablesToTruncate[] = 'civicrm_custom_field';
1730 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1732 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1733 foreach ($tablesToTruncate as $table) {
1734 $sql = "TRUNCATE TABLE $table";
1735 CRM_Core_DAO
::executeQuery($sql);
1737 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1739 if ($dropCustomValueTables) {
1740 $dbName = self
::getDBName();
1742 SELECT TABLE_NAME as tableName
1743 FROM INFORMATION_SCHEMA.TABLES
1744 WHERE TABLE_SCHEMA = '{$dbName}'
1745 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1748 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1749 while ($tableDAO->fetch()) {
1750 $sql = "DROP TABLE {$tableDAO->tableName}";
1751 CRM_Core_DAO
::executeQuery($sql);
1757 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1759 public function quickCleanUpFinancialEntities() {
1760 $tablesToTruncate = array(
1762 'civicrm_activity_contact',
1763 'civicrm_contribution',
1764 'civicrm_contribution_soft',
1765 'civicrm_contribution_product',
1766 'civicrm_financial_trxn',
1767 'civicrm_financial_item',
1768 'civicrm_contribution_recur',
1769 'civicrm_line_item',
1770 'civicrm_contribution_page',
1771 'civicrm_payment_processor',
1772 'civicrm_entity_financial_trxn',
1773 'civicrm_membership',
1774 'civicrm_membership_type',
1775 'civicrm_membership_payment',
1776 'civicrm_membership_log',
1777 'civicrm_membership_block',
1779 'civicrm_participant',
1780 'civicrm_participant_payment',
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();
1798 public function restoreDefaultPriceSetConfig() {
1799 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1800 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1801 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)");
1802 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)");
1806 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1807 * Default behaviour is to also delete the entity
1808 * @param array $params
1809 * Params array to check against.
1811 * Id of the entity concerned.
1812 * @param string $entity
1813 * Name of entity concerned (e.g. membership).
1814 * @param bool $delete
1815 * Should the entity be deleted as part of this check.
1816 * @param string $errorText
1817 * Text to print on error.
1821 * @param array $params
1824 * @param int $delete
1825 * @param string $errorText
1829 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1831 $result = $this->callAPISuccessGetSingle($entity, array(
1836 $this->callAPISuccess($entity, 'Delete', array(
1840 $dateFields = $keys = $dateTimeFields = array();
1841 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1842 foreach ($fields['values'] as $field => $settings) {
1843 if (array_key_exists($field, $result)) {
1844 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1847 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1849 $type = CRM_Utils_Array
::value('type', $settings);
1850 if ($type == CRM_Utils_Type
::T_DATE
) {
1851 $dateFields[] = $settings['name'];
1852 // we should identify both real names & unique names as dates
1853 if ($field != $settings['name']) {
1854 $dateFields[] = $field;
1857 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1858 $dateTimeFields[] = $settings['name'];
1859 // we should identify both real names & unique names as dates
1860 if ($field != $settings['name']) {
1861 $dateTimeFields[] = $field;
1866 if (strtolower($entity) == 'contribution') {
1867 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1868 // this is not returned in id format
1869 unset($params['payment_instrument_id']);
1870 $params['contribution_source'] = $params['source'];
1871 unset($params['source']);
1874 foreach ($params as $key => $value) {
1875 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1878 if (in_array($key, $dateFields)) {
1879 $value = date('Y-m-d', strtotime($value));
1880 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1882 if (in_array($key, $dateTimeFields)) {
1883 $value = date('Y-m-d H:i:s', strtotime($value));
1884 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1886 $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);
1891 * Get formatted values in the actual and expected result.
1892 * @param array $actual
1893 * Actual calculated values.
1894 * @param array $expected
1897 public function checkArrayEquals(&$actual, &$expected) {
1898 self
::unsetId($actual);
1899 self
::unsetId($expected);
1900 $this->assertEquals($actual, $expected);
1904 * Unset the key 'id' from the array
1905 * @param array $unformattedArray
1906 * The array from which the 'id' has to be unset.
1908 public static function unsetId(&$unformattedArray) {
1909 $formattedArray = array();
1910 if (array_key_exists('id', $unformattedArray)) {
1911 unset($unformattedArray['id']);
1913 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1914 foreach ($unformattedArray['values'] as $key => $value) {
1915 if (is_array($value)) {
1916 foreach ($value as $k => $v) {
1922 elseif ($key == 'id') {
1923 $unformattedArray[$key];
1925 $formattedArray = array($value);
1927 $unformattedArray['values'] = $formattedArray;
1932 * Helper to enable/disable custom directory support
1934 * @param array $customDirs
1936 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1937 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1939 public function customDirectories($customDirs) {
1940 $config = CRM_Core_Config
::singleton();
1942 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1943 unset($config->customPHPPathDir
);
1945 elseif ($customDirs['php_path'] === TRUE) {
1946 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1949 $config->customPHPPathDir
= $php_path;
1952 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1953 unset($config->customTemplateDir
);
1955 elseif ($customDirs['template_path'] === TRUE) {
1956 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1959 $config->customTemplateDir
= $template_path;
1964 * Generate a temporary folder.
1966 * @param string $prefix
1969 public function createTempDir($prefix = 'test-') {
1970 $tempDir = CRM_Utils_File
::tempdir($prefix);
1971 $this->tempDirs
[] = $tempDir;
1975 public function cleanTempDirs() {
1976 if (!is_array($this->tempDirs
)) {
1977 // fix test errors where this is not set
1980 foreach ($this->tempDirs
as $tempDir) {
1981 if (is_dir($tempDir)) {
1982 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1988 * Temporarily replace the singleton extension with a different one.
1989 * @param \CRM_Extension_System $system
1991 public function setExtensionSystem(CRM_Extension_System
$system) {
1992 if ($this->origExtensionSystem
== NULL) {
1993 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1995 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1998 public function unsetExtensionSystem() {
1999 if ($this->origExtensionSystem
!== NULL) {
2000 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2001 $this->origExtensionSystem
= NULL;
2006 * Temporarily alter the settings-metadata to add a mock setting.
2008 * WARNING: The setting metadata will disappear on the next cache-clear.
2013 public function setMockSettingsMetaData($extras) {
2014 CRM_Utils_Hook
::singleton()
2015 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2016 $metadata = array_merge($metadata, $extras);
2019 Civi
::service('settings_manager')->flush();
2021 $fields = $this->callAPISuccess('setting', 'getfields', array());
2022 foreach ($extras as $key => $spec) {
2023 $this->assertNotEmpty($spec['title']);
2024 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2029 * @param string $name
2031 public function financialAccountDelete($name) {
2032 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2033 $financialAccount->name
= $name;
2034 if ($financialAccount->find(TRUE)) {
2035 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2036 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2037 $entityFinancialType->delete();
2038 $financialAccount->delete();
2043 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2044 * (NB unclear if this is still required)
2046 public function _sethtmlGlobals() {
2047 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2048 'required' => array(
2049 'html_quickform_rule_required',
2050 'HTML/QuickForm/Rule/Required.php',
2052 'maxlength' => array(
2053 'html_quickform_rule_range',
2054 'HTML/QuickForm/Rule/Range.php',
2056 'minlength' => array(
2057 'html_quickform_rule_range',
2058 'HTML/QuickForm/Rule/Range.php',
2060 'rangelength' => array(
2061 'html_quickform_rule_range',
2062 'HTML/QuickForm/Rule/Range.php',
2065 'html_quickform_rule_email',
2066 'HTML/QuickForm/Rule/Email.php',
2069 'html_quickform_rule_regex',
2070 'HTML/QuickForm/Rule/Regex.php',
2072 'lettersonly' => array(
2073 'html_quickform_rule_regex',
2074 'HTML/QuickForm/Rule/Regex.php',
2076 'alphanumeric' => array(
2077 'html_quickform_rule_regex',
2078 'HTML/QuickForm/Rule/Regex.php',
2081 'html_quickform_rule_regex',
2082 'HTML/QuickForm/Rule/Regex.php',
2084 'nopunctuation' => array(
2085 'html_quickform_rule_regex',
2086 'HTML/QuickForm/Rule/Regex.php',
2089 'html_quickform_rule_regex',
2090 'HTML/QuickForm/Rule/Regex.php',
2092 'callback' => array(
2093 'html_quickform_rule_callback',
2094 'HTML/QuickForm/Rule/Callback.php',
2097 'html_quickform_rule_compare',
2098 'HTML/QuickForm/Rule/Compare.php',
2101 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2102 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2104 'HTML/QuickForm/group.php',
2105 'HTML_QuickForm_group',
2108 'HTML/QuickForm/hidden.php',
2109 'HTML_QuickForm_hidden',
2112 'HTML/QuickForm/reset.php',
2113 'HTML_QuickForm_reset',
2115 'checkbox' => array(
2116 'HTML/QuickForm/checkbox.php',
2117 'HTML_QuickForm_checkbox',
2120 'HTML/QuickForm/file.php',
2121 'HTML_QuickForm_file',
2124 'HTML/QuickForm/image.php',
2125 'HTML_QuickForm_image',
2127 'password' => array(
2128 'HTML/QuickForm/password.php',
2129 'HTML_QuickForm_password',
2132 'HTML/QuickForm/radio.php',
2133 'HTML_QuickForm_radio',
2136 'HTML/QuickForm/button.php',
2137 'HTML_QuickForm_button',
2140 'HTML/QuickForm/submit.php',
2141 'HTML_QuickForm_submit',
2144 'HTML/QuickForm/select.php',
2145 'HTML_QuickForm_select',
2147 'hiddenselect' => array(
2148 'HTML/QuickForm/hiddenselect.php',
2149 'HTML_QuickForm_hiddenselect',
2152 'HTML/QuickForm/text.php',
2153 'HTML_QuickForm_text',
2155 'textarea' => array(
2156 'HTML/QuickForm/textarea.php',
2157 'HTML_QuickForm_textarea',
2159 'fckeditor' => array(
2160 'HTML/QuickForm/fckeditor.php',
2161 'HTML_QuickForm_FCKEditor',
2164 'HTML/QuickForm/tinymce.php',
2165 'HTML_QuickForm_TinyMCE',
2167 'dojoeditor' => array(
2168 'HTML/QuickForm/dojoeditor.php',
2169 'HTML_QuickForm_dojoeditor',
2172 'HTML/QuickForm/link.php',
2173 'HTML_QuickForm_link',
2175 'advcheckbox' => array(
2176 'HTML/QuickForm/advcheckbox.php',
2177 'HTML_QuickForm_advcheckbox',
2180 'HTML/QuickForm/date.php',
2181 'HTML_QuickForm_date',
2184 'HTML/QuickForm/static.php',
2185 'HTML_QuickForm_static',
2188 'HTML/QuickForm/header.php',
2189 'HTML_QuickForm_header',
2192 'HTML/QuickForm/html.php',
2193 'HTML_QuickForm_html',
2195 'hierselect' => array(
2196 'HTML/QuickForm/hierselect.php',
2197 'HTML_QuickForm_hierselect',
2199 'autocomplete' => array(
2200 'HTML/QuickForm/autocomplete.php',
2201 'HTML_QuickForm_autocomplete',
2204 'HTML/QuickForm/xbutton.php',
2205 'HTML_QuickForm_xbutton',
2207 'advmultiselect' => array(
2208 'HTML/QuickForm/advmultiselect.php',
2209 'HTML_QuickForm_advmultiselect',
2215 * Set up an acl allowing contact to see 2 specified groups
2216 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2218 * You need to have pre-created these groups & created the user e.g
2219 * $this->createLoggedInUser();
2220 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2221 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2223 * @param bool $isProfile
2225 public function setupACL($isProfile = FALSE) {
2227 $_REQUEST = $this->_params
;
2229 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2230 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2231 $ov = new CRM_Core_DAO_OptionValue();
2232 $ov->option_group_id
= $optionGroupID;
2234 if ($ov->find(TRUE)) {
2235 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2237 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2238 'option_group_id' => $optionGroupID,
2239 'label' => 'pick me',
2243 CRM_Core_DAO
::executeQuery("
2244 TRUNCATE civicrm_acl_cache
2247 CRM_Core_DAO
::executeQuery("
2248 TRUNCATE civicrm_acl_contact_cache
2251 CRM_Core_DAO
::executeQuery("
2252 INSERT INTO civicrm_acl_entity_role (
2253 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2254 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2258 CRM_Core_DAO
::executeQuery("
2259 INSERT INTO civicrm_acl (
2260 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2263 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2268 CRM_Core_DAO
::executeQuery("
2269 INSERT INTO civicrm_acl (
2270 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2273 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2277 CRM_Core_DAO
::executeQuery("
2278 INSERT INTO civicrm_acl (
2279 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2282 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2287 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2288 $this->callAPISuccess('group_contact', 'create', array(
2289 'group_id' => $this->_permissionedGroup
,
2290 'contact_id' => $this->_loggedInUser
,
2295 CRM_ACL_BAO_Cache
::resetCache();
2296 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2301 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2303 public function offsetDefaultPriceSet() {
2304 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2305 $firstID = $contributionPriceSet['id'];
2306 $this->callAPISuccess('price_set', 'create', array(
2307 'id' => $contributionPriceSet['id'],
2311 unset($contributionPriceSet['id']);
2312 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2313 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2314 'price_set_id' => $firstID,
2315 'options' => array('limit' => 1),
2317 unset($priceField['id']);
2318 $priceField['price_set_id'] = $newPriceSet['id'];
2319 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2320 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2321 'price_set_id' => $firstID,
2323 'options' => array('limit' => 1),
2326 unset($priceFieldValue['id']);
2327 //create some padding to use up ids
2328 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2329 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2330 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2334 * Create an instance of the paypal processor.
2335 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2336 * this parent class & we don't have a structure for that yet
2337 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2338 * & the best protection against that is the functions this class affords
2339 * @param array $params
2340 * @return int $result['id'] payment processor id
2342 public function paymentProcessorCreate($params = array()) {
2343 $params = array_merge(array(
2345 'domain_id' => CRM_Core_Config
::domainID(),
2346 'payment_processor_type_id' => 'PayPal',
2350 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2351 'password' => '1183377788',
2352 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2353 'url_site' => 'https://www.sandbox.paypal.com/',
2354 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2355 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2356 'class_name' => 'Payment_PayPalImpl',
2357 'billing_mode' => 3,
2358 'financial_type_id' => 1,
2359 'financial_account_id' => 12,
2360 // Credit card = 1 so can pass 'by accident'.
2361 'payment_instrument_id' => 'Debit Card',
2363 if (!is_numeric($params['payment_processor_type_id'])) {
2364 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2366 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2367 'name' => $params['payment_processor_type_id'],
2371 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2372 return $result['id'];
2376 * Set up initial recurring payment allowing subsequent IPN payments.
2378 * @param array $recurParams (Optional)
2379 * @param array $contributionParams (Optional)
2381 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2382 $contributionParams = array_merge([
2383 'total_amount' => '200',
2384 'invoice_id' => $this->_invoiceID
,
2385 'financial_type_id' => 'Donation',
2386 'contribution_status_id' => 'Pending',
2387 'contact_id' => $this->_contactID
,
2388 'contribution_page_id' => $this->_contributionPageID
,
2389 'payment_processor_id' => $this->_paymentProcessorID
,
2391 'skipCleanMoney' => TRUE,
2392 ], $contributionParams);
2393 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2394 'contact_id' => $this->_contactID
,
2397 'installments' => 5,
2398 'frequency_unit' => 'Month',
2399 'frequency_interval' => 1,
2400 'invoice_id' => $this->_invoiceID
,
2401 'contribution_status_id' => 2,
2402 'payment_processor_id' => $this->_paymentProcessorID
,
2403 // processor provided ID - use contact ID as proxy.
2404 'processor_id' => $this->_contactID
,
2405 'api.contribution.create' => $contributionParams,
2407 $this->_contributionRecurID
= $contributionRecur['id'];
2408 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2412 * 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
2414 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2416 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2417 $membershipParams = $recurParams = array();
2418 if (!empty($params['duration_unit'])) {
2419 $membershipParams['duration_unit'] = $params['duration_unit'];
2421 if (!empty($params['frequency_unit'])) {
2422 $recurParams['frequency_unit'] = $params['frequency_unit'];
2425 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2426 //create a contribution so our membership & contribution don't both have id = 1
2427 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2428 $this->contributionCreate(array(
2429 'contact_id' => $this->_contactID
,
2431 'financial_type_id' => 1,
2432 'invoice_id' => 'abcd',
2436 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2438 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2439 'contact_id' => $this->_contactID
,
2440 'membership_type_id' => $this->ids
['membership_type'],
2441 'contribution_recur_id' => $this->_contributionRecurID
,
2442 'format.only_id' => TRUE,
2444 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2445 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2447 $this->callAPISuccess('line_item', 'create', array(
2448 'entity_table' => 'civicrm_membership',
2449 'entity_id' => $this->ids
['membership'],
2450 'contribution_id' => $this->_contributionID
,
2451 'label' => 'General',
2453 'unit_price' => 200,
2454 'line_total' => 200,
2455 'financial_type_id' => 1,
2456 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2458 'label' => 'Membership Amount',
2459 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2461 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2463 'label' => 'General',
2464 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2467 $this->callAPISuccess('membership_payment', 'create', array(
2468 'contribution_id' => $this->_contributionID
,
2469 'membership_id' => $this->ids
['membership'],
2478 public function CiviUnitTestCase_fatalErrorHandler($message) {
2479 throw new Exception("{$message['message']}: {$message['code']}");
2483 * Wrap the entire test case in a transaction.
2485 * Only subsequent DB statements will be wrapped in TX -- this cannot
2486 * retroactively wrap old DB statements. Therefore, it makes sense to
2487 * call this at the beginning of setUp().
2489 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2490 * this option does not work with, e.g., custom-data.
2492 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2493 * if TRUNCATE or ALTER is called while using a transaction.
2496 * Whether to use nesting or reference-counting.
2498 public function useTransaction($nest = TRUE) {
2500 $this->tx
= new CRM_Core_Transaction($nest);
2501 $this->tx
->rollback();
2506 * Assert the attachment exists.
2508 * @param bool $exists
2509 * @param array $apiResult
2511 protected function assertAttachmentExistence($exists, $apiResult) {
2512 $fileId = $apiResult['id'];
2513 $this->assertTrue(is_numeric($fileId));
2514 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2515 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2516 1 => array($fileId, 'Int'),
2518 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2519 1 => array($fileId, 'Int'),
2524 * Create a price set for an event.
2526 * @param int $feeTotal
2527 * @param int $minAmt
2528 * @param string $type
2533 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2534 // creating price set, price field
2535 $paramsSet['title'] = 'Price Set';
2536 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2537 $paramsSet['is_active'] = FALSE;
2538 $paramsSet['extends'] = 1;
2539 $paramsSet['min_amount'] = $minAmt;
2541 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2542 $this->_ids
['price_set'] = $priceSet->id
;
2544 $paramsField = array(
2545 'label' => 'Price Field',
2546 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2547 'html_type' => $type,
2548 'price' => $feeTotal,
2549 'option_label' => array('1' => 'Price Field'),
2550 'option_value' => array('1' => $feeTotal),
2551 'option_name' => array('1' => $feeTotal),
2552 'option_weight' => array('1' => 1),
2553 'option_amount' => array('1' => 1),
2554 'is_display_amounts' => 1,
2556 'options_per_line' => 1,
2557 'is_active' => array('1' => 1),
2558 'price_set_id' => $this->_ids
['price_set'],
2559 'is_enter_qty' => 1,
2560 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2562 if ($type === 'Radio') {
2563 $paramsField['is_enter_qty'] = 0;
2564 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2565 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2567 CRM_Price_BAO_PriceField
::create($paramsField);
2568 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2569 $this->_ids
['price_field'] = array_keys($fields['values']);
2570 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2571 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2573 return $this->_ids
['price_set'];
2577 * Add a profile to a contribution page.
2579 * @param string $name
2580 * @param int $contributionPageID
2581 * @param string $module
2583 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2585 'uf_group_id' => $name,
2586 'module' => $module,
2587 'entity_table' => 'civicrm_contribution_page',
2588 'entity_id' => $contributionPageID,
2591 if ($module !== 'CiviContribute') {
2592 $params['module_data'] = [$module => []];
2594 $this->callAPISuccess('UFJoin', 'create', $params);
2598 * Add participant with contribution
2602 protected function createParticipantWithContribution() {
2603 // creating price set, price field
2604 $this->_contactId
= $this->individualCreate();
2605 $event = $this->eventCreate();
2606 $this->_eventId
= $event['id'];
2607 $eventParams = array(
2608 'id' => $this->_eventId
,
2609 'financial_type_id' => 4,
2612 $this->callAPISuccess('event', 'create', $eventParams);
2613 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2614 $participantParams = array(
2615 'financial_type_id' => 4,
2616 'event_id' => $this->_eventId
,
2619 'fee_currency' => 'USD',
2620 'contact_id' => $this->_contactId
,
2622 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2623 $contributionParams = array(
2624 'total_amount' => 150,
2625 'currency' => 'USD',
2626 'contact_id' => $this->_contactId
,
2627 'financial_type_id' => 4,
2628 'contribution_status_id' => 1,
2629 'partial_payment_total' => 300.00,
2630 'partial_amount_to_pay' => 150,
2631 'contribution_mode' => 'participant',
2632 'participant_id' => $participant['id'],
2634 foreach ($priceFields['values'] as $key => $priceField) {
2635 $lineItems[1][$key] = array(
2636 'price_field_id' => $priceField['price_field_id'],
2637 'price_field_value_id' => $priceField['id'],
2638 'label' => $priceField['label'],
2639 'field_title' => $priceField['label'],
2641 'unit_price' => $priceField['amount'],
2642 'line_total' => $priceField['amount'],
2643 'financial_type_id' => $priceField['financial_type_id'],
2646 $contributionParams['line_item'] = $lineItems;
2647 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2648 $paymentParticipant = array(
2649 'participant_id' => $participant['id'],
2650 'contribution_id' => $contribution['id'],
2652 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2653 return array($lineItems, $contribution);
2659 * @param string $component
2660 * @param int $componentId
2661 * @param array $priceFieldOptions
2665 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2666 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2667 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2668 $paramsSet['is_active'] = TRUE;
2669 $paramsSet['financial_type_id'] = 'Event Fee';
2670 $paramsSet['extends'] = 1;
2671 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2672 $priceSetId = $priceSet['id'];
2673 //Checking for priceset added in the table.
2674 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2675 'id', $paramsSet['title'], 'Check DB for created priceset'
2677 $paramsField = array_merge(array(
2678 'label' => 'Price Field',
2679 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2680 'html_type' => 'CheckBox',
2681 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2682 'option_value' => array('1' => 100, '2' => 200),
2683 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2684 'option_weight' => array('1' => 1, '2' => 2),
2685 'option_amount' => array('1' => 100, '2' => 200),
2686 'is_display_amounts' => 1,
2688 'options_per_line' => 1,
2689 'is_active' => array('1' => 1, '2' => 1),
2690 'price_set_id' => $priceSet['id'],
2691 'is_enter_qty' => 1,
2692 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2693 ), $priceFieldOptions);
2695 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2697 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2699 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2703 * Replace the template with a test-oriented template designed to show all the variables.
2705 * @param string $templateName
2707 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2708 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2709 CRM_Core_DAO
::executeQuery(
2710 "UPDATE civicrm_option_group og
2711 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2712 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2713 SET m.msg_html = '{$testTemplate}'
2714 WHERE og.name = 'msg_tpl_workflow_contribution'
2715 AND ov.name = '{$templateName}'
2716 AND m.is_default = 1"
2721 * Reinstate the default template.
2723 * @param string $templateName
2725 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2726 CRM_Core_DAO
::executeQuery(
2727 "UPDATE civicrm_option_group og
2728 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2729 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2730 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2731 SET m.msg_html = m2.msg_html
2732 WHERE og.name = 'msg_tpl_workflow_contribution'
2733 AND ov.name = '{$templateName}'
2734 AND m.is_default = 1"
2739 * Flush statics relating to financial type.
2741 protected function flushFinancialTypeStatics() {
2742 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2743 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2745 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2746 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2748 CRM_Contribute_PseudoConstant
::flush('financialType');
2749 CRM_Contribute_PseudoConstant
::flush('membershipType');
2750 // Pseudoconstants may be saved to the cache table.
2751 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2752 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2753 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2757 * Set the permissions to the supplied array.
2759 * @param array $permissions
2761 protected function setPermissions($permissions) {
2762 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2763 $this->flushFinancialTypeStatics();
2767 * @param array $params
2770 public function _checkFinancialRecords($params, $context) {
2771 $entityParams = array(
2772 'entity_id' => $params['id'],
2773 'entity_table' => 'civicrm_contribution',
2775 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2776 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2777 if ($context == 'pending') {
2778 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2779 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2782 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2783 $trxnParams = array(
2784 'id' => $trxn['financial_trxn_id'],
2786 if ($context != 'online' && $context != 'payLater') {
2787 $compareParams = array(
2788 'to_financial_account_id' => 6,
2789 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2793 if ($context == 'feeAmount') {
2794 $compareParams['fee_amount'] = 50;
2796 elseif ($context == 'online') {
2797 $compareParams = array(
2798 'to_financial_account_id' => 12,
2799 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2801 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2804 elseif ($context == 'payLater') {
2805 $compareParams = array(
2806 'to_financial_account_id' => 7,
2807 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2811 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2812 $entityParams = array(
2813 'financial_trxn_id' => $trxn['financial_trxn_id'],
2814 'entity_table' => 'civicrm_financial_item',
2816 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2817 $fitemParams = array(
2818 'id' => $entityTrxn['entity_id'],
2820 $compareParams = array(
2821 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2823 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2825 if ($context == 'payLater') {
2826 $compareParams = array(
2827 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2829 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2832 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2833 if ($context == 'feeAmount') {
2835 'entity_id' => $params['id'],
2836 'entity_table' => 'civicrm_contribution',
2838 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2839 $trxnParams = array(
2840 'id' => $maxTrxn['financial_trxn_id'],
2842 $compareParams = array(
2843 'to_financial_account_id' => 5,
2844 'from_financial_account_id' => 6,
2845 'total_amount' => 50,
2848 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2849 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2850 $fitemParams = array(
2851 'entity_id' => $trxnId['financialTrxnId'],
2852 'entity_table' => 'civicrm_financial_trxn',
2854 $compareParams = array(
2857 'financial_account_id' => 5,
2859 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2861 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2862 // line should be copied into all the functions that call this function & evaluated there
2863 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2864 // when calling completeTransaction or repeatTransaction.
2865 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2869 * Return financial type id on basis of name
2871 * @param string $name Financial type m/c name
2875 public function getFinancialTypeId($name) {
2876 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2880 * Cleanup function for contents of $this->ids.
2882 * This is a best effort cleanup to use in tear downs etc.
2884 * It will not fail if the data has already been removed (some tests may do
2885 * their own cleanup).
2887 protected function cleanUpSetUpIDs() {
2888 foreach ($this->setupIDs
as $entity => $id) {
2890 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2892 catch (CiviCRM_API3_Exception
$e) {
2893 // This is a best-effort cleanup function, ignore.
2899 * Create Financial Type.
2901 * @param array $params
2905 protected function createFinancialType($params = array()) {
2906 $params = array_merge($params,
2908 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2912 return $this->callAPISuccess('FinancialType', 'create', $params);
2916 * Create Payment Instrument.
2918 * @param array $params
2919 * @param string $financialAccountName
2923 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2924 $params = array_merge(array(
2925 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2926 'option_group_id' => 'payment_instrument',
2929 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2931 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2933 $financialAccountParams = [
2934 'entity_table' => 'civicrm_option_value',
2935 'entity_id' => $newPaymentInstrument,
2936 'account_relationship' => $relationTypeID,
2937 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2939 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2941 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2945 * Enable Tax and Invoicing
2947 protected function enableTaxAndInvoicing($params = array()) {
2948 // Enable component contribute setting
2949 $contributeSetting = array_merge($params,
2952 'invoice_prefix' => 'INV_',
2953 'credit_notes_prefix' => 'CN_',
2955 'due_date_period' => 'days',
2957 'is_email_pdf' => 1,
2958 'tax_term' => 'Sales Tax',
2959 'tax_display_settings' => 'Inclusive',
2962 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2966 * Enable Tax and Invoicing
2968 protected function disableTaxAndInvoicing($params = array()) {
2969 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2970 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2972 // Enable component contribute setting
2973 $contributeSetting = array_merge($params,
2978 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2982 * Add Sales Tax relation for financial type with financial account.
2984 * @param int $financialTypeId
2988 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2990 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2991 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2992 'is_deductible' => 1,
2997 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
2998 $entityParams = array(
2999 'entity_table' => 'civicrm_financial_type',
3000 'entity_id' => $financialTypeId,
3001 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3004 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3005 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3007 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3008 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3009 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3010 $dao->copyValues($entityParams);
3012 if ($dao->fetch()) {
3013 $entityParams['id'] = $dao->id
;
3015 $entityParams['financial_account_id'] = $account->id
;
3017 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3021 * Create price set with contribution test for test setup.
3023 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3024 * on parent class at some point (fn is not in 4.4).
3027 * @param array $params
3029 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3030 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3031 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3032 'title' => "Test Contribution Page",
3033 'financial_type_id' => 1,
3034 'currency' => 'NZD',
3035 'goal_amount' => 50,
3036 'is_pay_later' => 1,
3037 'is_monetary' => TRUE,
3038 'is_email_receipt' => FALSE,
3040 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3041 'is_quick_config' => 0,
3042 'extends' => 'CiviMember',
3043 'financial_type_id' => 1,
3044 'title' => 'my Page',
3046 $priceSetID = $priceSet['id'];
3048 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3049 $priceField = $this->callAPISuccess('price_field', 'create', array(
3050 'price_set_id' => $priceSetID,
3051 'label' => 'Goat Breed',
3052 'html_type' => 'Radio',
3054 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3055 'price_set_id' => $priceSetID,
3056 'price_field_id' => $priceField['id'],
3057 'label' => 'Long Haired Goat',
3059 'financial_type_id' => 'Donation',
3060 'membership_type_id' => $membershipTypeID,
3061 'membership_num_terms' => 1,
3063 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3064 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3065 'price_set_id' => $priceSetID,
3066 'price_field_id' => $priceField['id'],
3067 'label' => 'Shoe-eating Goat',
3069 'financial_type_id' => 'Donation',
3070 'membership_type_id' => $membershipTypeID,
3071 'membership_num_terms' => 2,
3073 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3075 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3076 'price_set_id' => $priceSetID,
3077 'price_field_id' => $priceField['id'],
3078 'label' => 'Shoe-eating Goat',
3080 'financial_type_id' => 'Donation',
3082 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3084 $this->_ids
['price_set'] = $priceSetID;
3085 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3086 $this->_ids
['price_field'] = array($priceField['id']);
3088 $this->_ids
['membership_type'] = $membershipTypeID;
3092 * Only specified contact returned.
3093 * @implements CRM_Utils_Hook::aclWhereClause
3096 * @param $whereTables
3100 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3101 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3105 * @implements CRM_Utils_Hook::selectWhereClause
3107 * @param string $entity
3108 * @param array $clauses
3110 public function selectWhereClauseHook($entity, &$clauses) {
3111 if ($entity == 'Event') {
3112 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3117 * An implementation of hook_civicrm_post used with all our test cases.
3120 * @param string $objectName
3121 * @param int $objectId
3124 public function onPost($op, $objectName, $objectId, &$objectRef) {
3125 if ($op == 'create' && $objectName == 'Individual') {
3126 CRM_Core_DAO
::executeQuery(
3127 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3129 1 => array($objectId, 'Integer'),
3134 if ($op == 'edit' && $objectName == 'Participant') {
3136 1 => array($objectId, 'Integer'),
3138 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3139 CRM_Core_DAO
::executeQuery($query, $params);
3144 * Instantiate form object.
3146 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3148 * @param string $class
3149 * Name of form class.
3151 * @return \CRM_Core_Form
3153 public function getFormObject($class) {
3154 $form = new $class();
3155 $_SERVER['REQUEST_METHOD'] = 'GET';
3156 $form->controller
= new CRM_Core_Controller();
3161 * Get possible thousand separators.
3165 public function getThousandSeparators() {
3166 return array(array('.'), array(','));
3170 * Set the separators for thousands and decimal points.
3172 * @param string $thousandSeparator
3174 protected function setCurrencySeparators($thousandSeparator) {
3175 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3177 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3181 * Format money as it would be input.
3183 * @param string $amount
3187 protected function formatMoneyInput($amount) {
3188 return CRM_Utils_Money
::format($amount, NULL, '%a');
3192 * Get the contribution object.
3194 * @param int $contributionID
3196 * @return \CRM_Contribute_BAO_Contribution
3198 protected function getContributionObject($contributionID) {
3199 $contributionObj = new CRM_Contribute_BAO_Contribution();
3200 $contributionObj->id
= $contributionID;
3201 $contributionObj->find(TRUE);
3202 return $contributionObj;
3206 * Enable multilingual.
3208 public function enableMultilingual() {
3209 $this->callAPISuccess('Setting', 'create', array(
3210 'lcMessages' => 'en_US',
3211 'languageLimit' => array(
3216 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3219 $dbLocale = '_en_US';
3223 * Setup or clean up SMS tests
3224 * @param bool $teardown
3226 * @throws \CiviCRM_API3_Exception
3228 public function setupForSmsTests($teardown = FALSE) {
3229 require_once 'CiviTest/CiviTestSMSProvider.php';
3231 // Option value params for CiviTestSMSProvider
3232 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3234 'option_group_id' => $groupID,
3235 'label' => 'unittestSMS',
3236 'value' => 'unit.test.sms',
3237 'name' => 'CiviTestSMSProvider',
3244 // Test completed, delete provider
3245 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3246 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3250 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3251 // in CRM/Sms/Provider.php even though it is not an extension.
3252 return civicrm_api3('option_value', 'create', $params);