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_Extensions_Database_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 (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
199 $this->mockMethod
= 'createMock';
204 * Override to run the test and assert its state.
207 * @throws \PHPUnit_Framework_IncompleteTest
208 * @throws \PHPUnit_Framework_SkippedTest
210 protected function runTest() {
212 return parent
::runTest();
214 catch (PEAR_Exception
$e) {
215 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
216 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
223 public function requireDBReset() {
224 return $this->DBResetRequired
;
230 public static function getDBName() {
231 static $dbName = NULL;
232 if ($dbName === NULL) {
233 require_once "DB.php";
234 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
235 $dbName = $dsninfo['database'];
241 * Create database connection for this instance.
243 * Initialize the test database if it hasn't been initialized
245 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
247 protected function getConnection() {
248 $dbName = self
::$_dbName;
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;
260 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
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);
312 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
313 // Use a temporary file for STDIN
314 $GLOBALS['stdin'] = tmpfile();
315 if ($GLOBALS['stdin'] === FALSE) {
316 echo "Couldn't open temporary file\n";
320 // Get and save a connection to the database
321 $this->_dbconn
= $this->getConnection();
323 // reload database before each test
324 // $this->_populateDB();
326 // "initialize" CiviCRM to avoid problems when running single tests
327 // FIXME: look at it closer in second stage
329 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
330 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
332 // disable any left-over test extensions
333 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
335 $extensions = \CRM_Extension_System
::singleton()->getManager();
336 $api4Status = $extensions->getStatus('org.civicrm.api4');
337 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
338 $extensions->enable(['org.civicrm.api4']);
341 // reset all the caches
342 CRM_Utils_System
::flushCache();
344 // initialize the object once db is loaded
347 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
349 // when running unit tests, use mockup user framework
350 $this->hookClass
= CRM_Utils_Hook
::singleton();
352 // Make sure the DB connection is setup properly
353 $config->userSystem
->setMySQLTimeZone();
354 $env = new CRM_Utils_Check_Component_Env();
355 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
357 // clear permissions stub to not check permissions
358 $config->userPermissionClass
->permissions
= NULL;
360 //flush component settings
361 CRM_Core_Component
::getEnabledComponents(TRUE);
363 $_REQUEST = $_GET = $_POST = [];
364 error_reporting(E_ALL
);
366 $this->_sethtmlGlobals();
370 * Read everything from the datasets directory and insert into the db.
372 public function loadAllFixtures() {
373 $fixturesDir = __DIR__
. '/../../fixtures';
375 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
377 $yamlFiles = glob($fixturesDir . '/*.yaml');
378 foreach ($yamlFiles as $yamlFixture) {
379 $yaml = Yaml
::parse(file_get_contents($yamlFixture));
380 foreach ($yaml as $tableName => $vars) {
381 if ($tableName === 'civicrm_contact') {
382 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');
385 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
387 foreach ($vars as $entity) {
388 $keys = $values = [];
389 foreach ($entity as $key => $value) {
391 $values[] = is_numeric($value) ?
$value : "'{$value}'";
393 CRM_Core_DAO
::executeQuery("
394 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
401 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
405 * Load the data that used to be handled by the discontinued dbunit class.
407 * This could do with further tidy up - the initial priority is simply to get rid of
408 * the dbunity package which is no longer supported.
410 * @param string $fileName
412 protected function loadXMLDataSet($fileName) {
413 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
414 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
415 foreach ($xml as $tableName => $element) {
416 if (!empty($element)) {
417 foreach ($element as $row) {
418 $keys = $values = [];
419 if (isset($row['@attributes'])) {
420 foreach ($row['@attributes'] as $key => $value) {
422 $values[] = is_numeric($value) ?
$value : "'{$value}'";
425 elseif (!empty($row)) {
426 // cos we copied it & it is inconsistent....
427 foreach ($row as $key => $value) {
429 $values[] = is_numeric($value) ?
$value : "'{$value}'";
433 if (!empty($values)) {
434 CRM_Core_DAO
::executeQuery("
435 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
441 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
445 * Create default domain contacts for the two domains added during test class.
446 * database population.
448 public function createDomainContacts() {
449 $this->organizationCreate();
450 $this->organizationCreate(array('organization_name' => 'Second Domain'));
454 * Common teardown functions for all unit tests.
456 protected function tearDown() {
457 error_reporting(E_ALL
& ~E_NOTICE
);
458 CRM_Utils_Hook
::singleton()->reset();
459 if ($this->hookClass
) {
460 $this->hookClass
->reset();
462 CRM_Core_Session
::singleton()->reset(1);
465 $this->tx
->rollback()->commit();
468 CRM_Core_Transaction
::forceRollbackIfEnabled();
469 \Civi\Core\Transaction\Manager
::singleton(TRUE);
472 CRM_Core_Transaction
::forceRollbackIfEnabled();
473 \Civi\Core\Transaction\Manager
::singleton(TRUE);
475 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
476 $this->quickCleanup($tablesToTruncate);
477 $this->createDomainContacts();
480 $this->cleanTempDirs();
481 $this->unsetExtensionSystem();
485 * Create a batch of external API calls which can
486 * be executed concurrently.
489 * $calls = $this->createExternalAPI()
490 * ->addCall('Contact', 'get', ...)
491 * ->addCall('Contact', 'get', ...)
497 * @return \Civi\API\ExternalBatch
498 * @throws PHPUnit_Framework_SkippedTestError
500 public function createExternalAPI() {
501 global $civicrm_root;
502 $defaultParams = array(
503 'version' => $this->_apiversion
,
507 $calls = new \Civi\API\
ExternalBatch($defaultParams);
509 if (!$calls->isSupported()) {
510 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
517 * Create required data based on $this->entity & $this->params
518 * This is just a way to set up the test data for delete & get functions
519 * so the distinction between set
520 * up & tested functions is clearer
525 public function createTestEntity() {
526 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
530 * @param int $contactTypeId
534 public function contactTypeDelete($contactTypeId) {
535 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
537 throw new Exception('Could not delete contact type');
542 * @param array $params
546 public function membershipTypeCreate($params = array()) {
547 CRM_Member_PseudoConstant
::flush('membershipType');
548 CRM_Core_Config
::clearDBCache();
549 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
550 $params = array_merge(array(
552 'duration_unit' => 'year',
553 'duration_interval' => 1,
554 'period_type' => 'rolling',
555 'member_of_contact_id' => $memberOfOrganization,
557 'financial_type_id' => 2,
560 'visibility' => 'Public',
563 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
565 CRM_Member_PseudoConstant
::flush('membershipType');
566 CRM_Utils_Cache
::singleton()->flush();
568 return $result['id'];
572 * @param array $params
576 public function contactMembershipCreate($params) {
577 $params = array_merge(array(
578 'join_date' => '2007-01-21',
579 'start_date' => '2007-01-21',
580 'end_date' => '2007-12-21',
581 'source' => 'Payment',
582 'membership_type_id' => 'General',
584 if (!is_numeric($params['membership_type_id'])) {
585 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
586 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
587 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
591 $result = $this->callAPISuccess('Membership', 'create', $params);
592 return $result['id'];
596 * Delete Membership Type.
598 * @param array $params
600 public function membershipTypeDelete($params) {
601 $this->callAPISuccess('MembershipType', 'Delete', $params);
605 * @param int $membershipID
607 public function membershipDelete($membershipID) {
608 $deleteParams = array('id' => $membershipID);
609 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
613 * @param string $name
617 public function membershipStatusCreate($name = 'test member status') {
618 $params['name'] = $name;
619 $params['start_event'] = 'start_date';
620 $params['end_event'] = 'end_date';
621 $params['is_current_member'] = 1;
622 $params['is_active'] = 1;
624 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
625 CRM_Member_PseudoConstant
::flush('membershipStatus');
626 return $result['id'];
630 * @param int $membershipStatusID
632 public function membershipStatusDelete($membershipStatusID) {
633 if (!$membershipStatusID) {
636 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
639 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
640 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
641 $renewedMembershipEndDate = new DateTime($membershipEndDate);
642 switch ($durationUnit) {
644 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
648 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
649 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
650 $renewedMembershipEndDate->add(new DateInterval('P1D'));
651 $renewedMembershipEndDate->add(new DateInterval('P1M'));
652 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
655 return $renewedMembershipEndDate->format('Y-m-d');
659 * @param array $params
663 public function relationshipTypeCreate($params = array()) {
664 $params = array_merge(array(
665 'name_a_b' => 'Relation 1 for relationship type create',
666 'name_b_a' => 'Relation 2 for relationship type create',
667 'contact_type_a' => 'Individual',
668 'contact_type_b' => 'Organization',
673 $result = $this->callAPISuccess('relationship_type', 'create', $params);
674 CRM_Core_PseudoConstant
::flush('relationshipType');
676 return $result['id'];
680 * Delete Relatinship Type.
682 * @param int $relationshipTypeID
684 public function relationshipTypeDelete($relationshipTypeID) {
685 $params['id'] = $relationshipTypeID;
686 $check = $this->callAPISuccess('relationship_type', 'get', $params);
687 if (!empty($check['count'])) {
688 $this->callAPISuccess('relationship_type', 'delete', $params);
693 * @param array $params
697 public function paymentProcessorTypeCreate($params = NULL) {
698 if (is_null($params)) {
700 'name' => 'API_Test_PP',
701 'title' => 'API Test Payment Processor',
702 'class_name' => 'CRM_Core_Payment_APITest',
703 'billing_mode' => 'form',
709 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
711 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
713 return $result['id'];
717 * Create test Authorize.net instance.
719 * @param array $params
723 public function paymentProcessorAuthorizeNetCreate($params = array()) {
724 $params = array_merge(array(
725 'name' => 'Authorize',
726 'domain_id' => CRM_Core_Config
::domainID(),
727 'payment_processor_type_id' => 'AuthNet',
728 'title' => 'AuthNet',
733 'user_name' => '4y5BfuW7jm',
734 'password' => '4cAmW927n8uLf5J8',
735 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
736 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
737 'class_name' => 'Payment_AuthorizeNet',
741 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
742 return $result['id'];
746 * Create Participant.
748 * @param array $params
749 * Array of contact id and event id values.
752 * $id of participant created
754 public function participantCreate($params = []) {
755 if (empty($params['contact_id'])) {
756 $params['contact_id'] = $this->individualCreate();
758 if (empty($params['event_id'])) {
759 $event = $this->eventCreate();
760 $params['event_id'] = $event['id'];
765 'register_date' => 20070219,
766 'source' => 'Wimbeldon',
767 'event_level' => 'Payment',
771 $params = array_merge($defaults, $params);
772 $result = $this->callAPISuccess('Participant', 'create', $params);
773 return $result['id'];
777 * Create Payment Processor.
780 * Id Payment Processor
782 public function processorCreate($params = array()) {
783 $processorParams = array(
786 'payment_processor_type_id' => 'Dummy',
787 'financial_account_id' => 12,
791 'url_site' => 'http://dummy.com',
792 'url_recur' => 'http://dummy.com',
795 'payment_instrument_id' => 'Debit Card',
797 $processorParams = array_merge($processorParams, $params);
798 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
799 return $processor['id'];
803 * Create Payment Processor.
805 * @param array $processorParams
807 * @return \CRM_Core_Payment_Dummy
808 * Instance of Dummy Payment Processor
810 public function dummyProcessorCreate($processorParams = array()) {
811 $paymentProcessorID = $this->processorCreate($processorParams);
812 return System
::singleton()->getById($paymentProcessorID);
816 * Create contribution page.
818 * @param array $params
820 * Array of contribution page
822 public function contributionPageCreate($params = array()) {
823 $this->_pageParams
= array_merge(array(
824 'title' => 'Test Contribution Page',
825 'financial_type_id' => 1,
827 'financial_account_id' => 1,
829 'is_allow_other_amount' => 1,
831 'max_amount' => 1000,
833 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
837 * Create a sample batch.
839 public function batchCreate() {
840 $params = $this->_params
;
841 $params['name'] = $params['title'] = 'Batch_433397';
842 $params['status_id'] = 1;
843 $result = $this->callAPISuccess('batch', 'create', $params);
844 return $result['id'];
850 * @param array $params
852 * result of created tag
854 public function tagCreate($params = array()) {
856 'name' => 'New Tag3',
857 'description' => 'This is description for Our New Tag ',
860 $params = array_merge($defaults, $params);
861 $result = $this->callAPISuccess('Tag', 'create', $params);
862 return $result['values'][$result['id']];
869 * Id of the tag to be deleted.
873 public function tagDelete($tagId) {
874 require_once 'api/api.php';
878 $result = $this->callAPISuccess('Tag', 'delete', $params);
879 return $result['id'];
883 * Add entity(s) to the tag
885 * @param array $params
889 public function entityTagAdd($params) {
890 $result = $this->callAPISuccess('entity_tag', 'create', $params);
897 * @param array $params
901 * id of created pledge
903 public function pledgeCreate($params) {
904 $params = array_merge(array(
905 'pledge_create_date' => date('Ymd'),
906 'start_date' => date('Ymd'),
907 'scheduled_date' => date('Ymd'),
909 'pledge_status_id' => '2',
910 'financial_type_id' => '1',
911 'pledge_original_installment_amount' => 20,
912 'frequency_interval' => 5,
913 'frequency_unit' => 'year',
914 'frequency_day' => 15,
919 $result = $this->callAPISuccess('Pledge', 'create', $params);
920 return $result['id'];
924 * Delete contribution.
926 * @param int $pledgeId
928 public function pledgeDelete($pledgeId) {
930 'pledge_id' => $pledgeId,
932 $this->callAPISuccess('Pledge', 'delete', $params);
936 * Create contribution.
938 * @param array $params
939 * Array of parameters.
942 * id of created contribution
944 public function contributionCreate($params) {
946 $params = array_merge(array(
948 'receive_date' => date('Ymd'),
949 'total_amount' => 100.00,
950 'fee_amount' => 5.00,
951 'financial_type_id' => 1,
952 'payment_instrument_id' => 1,
953 'non_deductible_amount' => 10.00,
955 'contribution_status_id' => 1,
958 $result = $this->callAPISuccess('contribution', 'create', $params);
959 return $result['id'];
963 * Delete contribution.
965 * @param int $contributionId
969 public function contributionDelete($contributionId) {
971 'contribution_id' => $contributionId,
973 $result = $this->callAPISuccess('contribution', 'delete', $params);
980 * @param array $params
981 * Name-value pair for an event.
985 public function eventCreate($params = array()) {
986 // if no contact was passed, make up a dummy event creator
987 if (!isset($params['contact_id'])) {
988 $params['contact_id'] = $this->_contactCreate(array(
989 'contact_type' => 'Individual',
990 'first_name' => 'Event',
991 'last_name' => 'Creator',
995 // set defaults for missing params
996 $params = array_merge(array(
997 'title' => 'Annual CiviCRM meet',
998 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
999 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1000 'event_type_id' => 1,
1002 'start_date' => 20081021,
1003 'end_date' => 20081023,
1004 'is_online_registration' => 1,
1005 'registration_start_date' => 20080601,
1006 'registration_end_date' => 20081015,
1007 'max_participants' => 100,
1008 'event_full_text' => 'Sorry! We are already full',
1011 'is_show_location' => 0,
1014 return $this->callAPISuccess('Event', 'create', $params);
1018 * Create a paid event.
1020 * @param array $params
1024 protected function eventCreatePaid($params) {
1025 $event = $this->eventCreate($params);
1026 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1027 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1028 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1029 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1030 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1042 public function eventDelete($id) {
1046 return $this->callAPISuccess('event', 'delete', $params);
1050 * Delete participant.
1052 * @param int $participantID
1056 public function participantDelete($participantID) {
1058 'id' => $participantID,
1060 $check = $this->callAPISuccess('Participant', 'get', $params);
1061 if ($check['count'] > 0) {
1062 return $this->callAPISuccess('Participant', 'delete', $params);
1067 * Create participant payment.
1069 * @param int $participantID
1070 * @param int $contributionID
1072 * $id of created payment
1074 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1075 //Create Participant Payment record With Values
1077 'participant_id' => $participantID,
1078 'contribution_id' => $contributionID,
1081 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1082 return $result['id'];
1086 * Delete participant payment.
1088 * @param int $paymentID
1090 public function participantPaymentDelete($paymentID) {
1094 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1100 * @param int $contactID
1102 * location id of created location
1104 public function locationAdd($contactID) {
1107 'location_type' => 'New Location Type',
1109 'name' => 'Saint Helier St',
1110 'county' => 'Marin',
1111 'country' => 'UNITED STATES',
1112 'state_province' => 'Michigan',
1113 'supplemental_address_1' => 'Hallmark Ct',
1114 'supplemental_address_2' => 'Jersey Village',
1115 'supplemental_address_3' => 'My Town',
1120 'contact_id' => $contactID,
1121 'address' => $address,
1122 'location_format' => '2.0',
1123 'location_type' => 'New Location Type',
1126 $result = $this->callAPISuccess('Location', 'create', $params);
1131 * Delete Locations of contact.
1133 * @param array $params
1136 public function locationDelete($params) {
1137 $this->callAPISuccess('Location', 'delete', $params);
1141 * Add a Location Type.
1143 * @param array $params
1144 * @return CRM_Core_DAO_LocationType
1145 * location id of created location
1147 public function locationTypeCreate($params = NULL) {
1148 if ($params === NULL) {
1150 'name' => 'New Location Type',
1151 'vcard_name' => 'New Location Type',
1152 'description' => 'Location Type for Delete',
1157 $locationType = new CRM_Core_DAO_LocationType();
1158 $locationType->copyValues($params);
1159 $locationType->save();
1160 // clear getfields cache
1161 CRM_Core_PseudoConstant
::flush();
1162 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1163 return $locationType;
1167 * Delete a Location Type.
1169 * @param int $locationTypeId
1171 public function locationTypeDelete($locationTypeId) {
1172 $locationType = new CRM_Core_DAO_LocationType();
1173 $locationType->id
= $locationTypeId;
1174 $locationType->delete();
1180 * @param array $params
1181 * @return CRM_Core_DAO_Mapping
1182 * Mapping id of created mapping
1184 public function mappingCreate($params = NULL) {
1185 if ($params === NULL) {
1187 'name' => 'Mapping name',
1188 'description' => 'Mapping description',
1189 // 'Export Contact' mapping.
1190 'mapping_type_id' => 7,
1194 $mapping = new CRM_Core_DAO_Mapping();
1195 $mapping->copyValues($params);
1197 // clear getfields cache
1198 CRM_Core_PseudoConstant
::flush();
1199 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1206 * @param int $mappingId
1208 public function mappingDelete($mappingId) {
1209 $mapping = new CRM_Core_DAO_Mapping();
1210 $mapping->id
= $mappingId;
1215 * Prepare class for ACLs.
1217 protected function prepareForACLs() {
1218 $config = CRM_Core_Config
::singleton();
1219 $config->userPermissionClass
->permissions
= array();
1225 protected function cleanUpAfterACLs() {
1226 CRM_Utils_Hook
::singleton()->reset();
1227 $tablesToTruncate = array(
1229 'civicrm_acl_cache',
1230 'civicrm_acl_entity_role',
1231 'civicrm_acl_contact_cache',
1233 $this->quickCleanup($tablesToTruncate);
1234 $config = CRM_Core_Config
::singleton();
1235 unset($config->userPermissionClass
->permissions
);
1239 * Create a smart group.
1241 * By default it will be a group of households.
1243 * @param array $smartGroupParams
1244 * @param array $groupParams
1247 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1248 $smartGroupParams = array_merge(array(
1249 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1252 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1254 $groupParams['saved_search_id'] = $savedSearch->id
;
1255 return $this->groupCreate($groupParams);
1260 * @param array $params
1262 public function uFFieldCreate($params = array()) {
1263 $params = array_merge(array(
1265 'field_name' => 'first_name',
1268 'visibility' => 'Public Pages and Listings',
1269 'is_searchable' => '1',
1270 'label' => 'first_name',
1271 'field_type' => 'Individual',
1274 $this->callAPISuccess('uf_field', 'create', $params);
1278 * Add a UF Join Entry.
1280 * @param array $params
1282 * $id of created UF Join
1284 public function ufjoinCreate($params = NULL) {
1285 if ($params === NULL) {
1288 'module' => 'CiviEvent',
1289 'entity_table' => 'civicrm_event',
1295 $result = $this->callAPISuccess('uf_join', 'create', $params);
1300 * @param array $params
1301 * Optional parameters.
1302 * @param bool $reloadConfig
1303 * While enabling CiviCampaign component, we shouldn't always forcibly
1304 * reload config as this hinder hook call in test environment
1309 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1310 $this->enableCiviCampaign($reloadConfig);
1311 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1312 'name' => 'big_campaign',
1313 'title' => 'Campaign',
1315 return $campaign['id'];
1319 * Create Group for a contact.
1321 * @param int $contactId
1323 public function contactGroupCreate($contactId) {
1325 'contact_id.1' => $contactId,
1329 $this->callAPISuccess('GroupContact', 'Create', $params);
1333 * Delete Group for a contact.
1335 * @param int $contactId
1337 public function contactGroupDelete($contactId) {
1339 'contact_id.1' => $contactId,
1342 $this->civicrm_api('GroupContact', 'Delete', $params);
1348 * @param array $params
1351 public function activityCreate($params = array()) {
1352 $params = array_merge(array(
1353 'subject' => 'Discussion on warm beer',
1354 'activity_date_time' => date('Ymd'),
1355 'duration_hours' => 30,
1356 'duration_minutes' => 20,
1357 'location' => 'Baker Street',
1358 'details' => 'Lets schedule a meeting',
1360 'activity_type_id' => 'Meeting',
1362 if (!isset($params['source_contact_id'])) {
1363 $params['source_contact_id'] = $this->individualCreate();
1365 if (!isset($params['target_contact_id'])) {
1366 $params['target_contact_id'] = $this->individualCreate(array(
1367 'first_name' => 'Julia',
1368 'Last_name' => 'Anderson',
1370 'email' => 'julia_anderson@civicrm.org',
1371 'contact_type' => 'Individual',
1374 if (!isset($params['assignee_contact_id'])) {
1375 $params['assignee_contact_id'] = $params['target_contact_id'];
1378 $result = $this->callAPISuccess('Activity', 'create', $params);
1380 $result['target_contact_id'] = $params['target_contact_id'];
1381 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1386 * Create an activity type.
1388 * @param array $params
1392 public function activityTypeCreate($params) {
1393 return $this->callAPISuccess('ActivityType', 'create', $params);
1397 * Delete activity type.
1399 * @param int $activityTypeId
1400 * Id of the activity type.
1403 public function activityTypeDelete($activityTypeId) {
1404 $params['activity_type_id'] = $activityTypeId;
1405 return $this->callAPISuccess('ActivityType', 'delete', $params);
1409 * Create custom group.
1411 * @param array $params
1414 public function customGroupCreate($params = array()) {
1416 'title' => 'new custom group',
1417 'extends' => 'Contact',
1419 'style' => 'Inline',
1423 $params = array_merge($defaults, $params);
1425 return $this->callAPISuccess('custom_group', 'create', $params);
1429 * Existing function doesn't allow params to be over-ridden so need a new one
1430 * this one allows you to only pass in the params you want to change
1431 * @param array $params
1434 public function CustomGroupCreateByParams($params = array()) {
1436 'title' => "API Custom Group",
1437 'extends' => 'Contact',
1439 'style' => 'Inline',
1442 $params = array_merge($defaults, $params);
1443 return $this->callAPISuccess('custom_group', 'create', $params);
1447 * Create custom group with multi fields.
1448 * @param array $params
1451 public function CustomGroupMultipleCreateByParams($params = array()) {
1456 $params = array_merge($defaults, $params);
1457 return $this->CustomGroupCreateByParams($params);
1461 * Create custom group with multi fields.
1462 * @param array $params
1465 public function CustomGroupMultipleCreateWithFields($params = array()) {
1466 // also need to pass on $params['custom_field'] if not set but not in place yet
1468 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1469 $ids['custom_group_id'] = $customGroup['id'];
1471 $customField = $this->customFieldCreate(array(
1472 'custom_group_id' => $ids['custom_group_id'],
1473 'label' => 'field_1' . $ids['custom_group_id'],
1477 $ids['custom_field_id'][] = $customField['id'];
1479 $customField = $this->customFieldCreate(array(
1480 'custom_group_id' => $ids['custom_group_id'],
1481 'default_value' => '',
1482 'label' => 'field_2' . $ids['custom_group_id'],
1485 $ids['custom_field_id'][] = $customField['id'];
1487 $customField = $this->customFieldCreate(array(
1488 'custom_group_id' => $ids['custom_group_id'],
1489 'default_value' => '',
1490 'label' => 'field_3' . $ids['custom_group_id'],
1493 $ids['custom_field_id'][] = $customField['id'];
1499 * Create a custom group with a single text custom field. See
1500 * participant:testCreateWithCustom for how to use this
1502 * @param string $function
1504 * @param string $filename
1508 * ids of created objects
1510 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1511 $params = array('title' => $function);
1512 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1513 $params['extends'] = $entity ?
$entity : 'Contact';
1514 $customGroup = $this->CustomGroupCreate($params);
1515 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1516 CRM_Core_PseudoConstant
::flush();
1518 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1522 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1523 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1525 * @param string $function
1527 * @param string $filename
1531 * ids of created objects
1533 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1534 $params = array('title' => $function);
1535 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1536 $params['extends'] = $entity ?
$entity : 'Contact';
1537 $customGroup = $this->CustomGroupCreate($params);
1538 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1539 CRM_Core_PseudoConstant
::flush();
1541 'defaultValue' => 'Default Value',
1542 'lowercasevalue' => 'Lowercase Value',
1543 1 => 'Integer Value',
1546 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1547 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1548 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1549 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1550 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1551 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1552 foreach ($options as $option_value => $option_label) {
1553 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1554 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1557 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);
1561 * Delete custom group.
1563 * @param int $customGroupID
1567 public function customGroupDelete($customGroupID) {
1568 $params['id'] = $customGroupID;
1569 return $this->callAPISuccess('custom_group', 'delete', $params);
1573 * Create custom field.
1575 * @param array $params
1576 * (custom_group_id) is required.
1579 public function customFieldCreate($params) {
1580 $params = array_merge(array(
1581 'label' => 'Custom Field',
1582 'data_type' => 'String',
1583 'html_type' => 'Text',
1584 'is_searchable' => 1,
1586 'default_value' => 'defaultValue',
1589 $result = $this->callAPISuccess('custom_field', 'create', $params);
1590 // these 2 functions are called with force to flush static caches
1591 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1592 CRM_Core_Component
::getEnabledComponents(1);
1597 * Delete custom field.
1599 * @param int $customFieldID
1603 public function customFieldDelete($customFieldID) {
1605 $params['id'] = $customFieldID;
1606 return $this->callAPISuccess('custom_field', 'delete', $params);
1615 public function noteCreate($cId) {
1617 'entity_table' => 'civicrm_contact',
1618 'entity_id' => $cId,
1619 'note' => 'hello I am testing Note',
1620 'contact_id' => $cId,
1621 'modified_date' => date('Ymd'),
1622 'subject' => 'Test Note',
1625 return $this->callAPISuccess('Note', 'create', $params);
1629 * Enable CiviCampaign Component.
1631 * @param bool $reloadConfig
1632 * Force relaod config or not
1634 public function enableCiviCampaign($reloadConfig = TRUE) {
1635 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1636 if ($reloadConfig) {
1637 // force reload of config object
1638 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1640 //flush cache by calling with reset
1641 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1645 * Create custom field with Option Values.
1647 * @param array $customGroup
1648 * @param string $name
1649 * Name of custom field.
1650 * @param array $extraParams
1651 * Additional parameters to pass through.
1655 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1656 $fieldParams = array(
1657 'custom_group_id' => $customGroup['id'],
1658 'name' => 'test_custom_group',
1659 'label' => 'Country',
1660 'html_type' => 'Select',
1661 'data_type' => 'String',
1664 'is_searchable' => 0,
1668 $optionGroup = array(
1670 'name' => 'option_group1',
1671 'label' => 'option_group_label1',
1674 $optionValue = array(
1675 'option_label' => array('Label1', 'Label2'),
1676 'option_value' => array('value1', 'value2'),
1677 'option_name' => array($name . '_1', $name . '_2'),
1678 'option_weight' => array(1, 2),
1679 'option_status' => 1,
1682 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1684 return $this->callAPISuccess('custom_field', 'create', $params);
1692 public function confirmEntitiesDeleted($entities) {
1693 foreach ($entities as $entity) {
1695 $result = $this->callAPISuccess($entity, 'Get', array());
1696 if ($result['error'] == 1 ||
$result['count'] > 0) {
1697 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1705 * Quick clean by emptying tables created for the test.
1707 * @param array $tablesToTruncate
1708 * @param bool $dropCustomValueTables
1709 * @throws \Exception
1711 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1713 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1715 if ($dropCustomValueTables) {
1716 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1717 while ($optionGroupResult->fetch()) {
1718 if (!empty($optionGroupResult->option_group_id
)) {
1719 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1722 $tablesToTruncate[] = 'civicrm_custom_group';
1723 $tablesToTruncate[] = 'civicrm_custom_field';
1726 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1728 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1729 foreach ($tablesToTruncate as $table) {
1730 $sql = "TRUNCATE TABLE $table";
1731 CRM_Core_DAO
::executeQuery($sql);
1733 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1735 if ($dropCustomValueTables) {
1736 $dbName = self
::getDBName();
1738 SELECT TABLE_NAME as tableName
1739 FROM INFORMATION_SCHEMA.TABLES
1740 WHERE TABLE_SCHEMA = '{$dbName}'
1741 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1744 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1745 while ($tableDAO->fetch()) {
1746 $sql = "DROP TABLE {$tableDAO->tableName}";
1747 CRM_Core_DAO
::executeQuery($sql);
1753 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1755 public function quickCleanUpFinancialEntities() {
1756 $tablesToTruncate = array(
1758 'civicrm_activity_contact',
1759 'civicrm_contribution',
1760 'civicrm_contribution_soft',
1761 'civicrm_contribution_product',
1762 'civicrm_financial_trxn',
1763 'civicrm_financial_item',
1764 'civicrm_contribution_recur',
1765 'civicrm_line_item',
1766 'civicrm_contribution_page',
1767 'civicrm_payment_processor',
1768 'civicrm_entity_financial_trxn',
1769 'civicrm_membership',
1770 'civicrm_membership_type',
1771 'civicrm_membership_payment',
1772 'civicrm_membership_log',
1773 'civicrm_membership_block',
1775 'civicrm_participant',
1776 'civicrm_participant_payment',
1778 'civicrm_pledge_payment',
1779 'civicrm_price_set_entity',
1780 'civicrm_price_field_value',
1781 'civicrm_price_field',
1783 $this->quickCleanup($tablesToTruncate);
1784 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1785 $this->restoreDefaultPriceSetConfig();
1787 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1788 $this->disableTaxAndInvoicing();
1789 $this->setCurrencySeparators(',');
1790 CRM_Core_PseudoConstant
::flush('taxRates');
1791 System
::singleton()->flushProcessors();
1794 public function restoreDefaultPriceSetConfig() {
1795 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1796 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1797 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)");
1798 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)");
1802 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1803 * Default behaviour is to also delete the entity
1804 * @param array $params
1805 * Params array to check against.
1807 * Id of the entity concerned.
1808 * @param string $entity
1809 * Name of entity concerned (e.g. membership).
1810 * @param bool $delete
1811 * Should the entity be deleted as part of this check.
1812 * @param string $errorText
1813 * Text to print on error.
1817 * @param array $params
1820 * @param int $delete
1821 * @param string $errorText
1825 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1827 $result = $this->callAPISuccessGetSingle($entity, array(
1832 $this->callAPISuccess($entity, 'Delete', array(
1836 $dateFields = $keys = $dateTimeFields = array();
1837 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1838 foreach ($fields['values'] as $field => $settings) {
1839 if (array_key_exists($field, $result)) {
1840 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1843 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1845 $type = CRM_Utils_Array
::value('type', $settings);
1846 if ($type == CRM_Utils_Type
::T_DATE
) {
1847 $dateFields[] = $settings['name'];
1848 // we should identify both real names & unique names as dates
1849 if ($field != $settings['name']) {
1850 $dateFields[] = $field;
1853 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1854 $dateTimeFields[] = $settings['name'];
1855 // we should identify both real names & unique names as dates
1856 if ($field != $settings['name']) {
1857 $dateTimeFields[] = $field;
1862 if (strtolower($entity) == 'contribution') {
1863 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1864 // this is not returned in id format
1865 unset($params['payment_instrument_id']);
1866 $params['contribution_source'] = $params['source'];
1867 unset($params['source']);
1870 foreach ($params as $key => $value) {
1871 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1874 if (in_array($key, $dateFields)) {
1875 $value = date('Y-m-d', strtotime($value));
1876 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1878 if (in_array($key, $dateTimeFields)) {
1879 $value = date('Y-m-d H:i:s', strtotime($value));
1880 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1882 $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);
1887 * Get formatted values in the actual and expected result.
1888 * @param array $actual
1889 * Actual calculated values.
1890 * @param array $expected
1893 public function checkArrayEquals(&$actual, &$expected) {
1894 self
::unsetId($actual);
1895 self
::unsetId($expected);
1896 $this->assertEquals($actual, $expected);
1900 * Unset the key 'id' from the array
1901 * @param array $unformattedArray
1902 * The array from which the 'id' has to be unset.
1904 public static function unsetId(&$unformattedArray) {
1905 $formattedArray = array();
1906 if (array_key_exists('id', $unformattedArray)) {
1907 unset($unformattedArray['id']);
1909 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1910 foreach ($unformattedArray['values'] as $key => $value) {
1911 if (is_array($value)) {
1912 foreach ($value as $k => $v) {
1918 elseif ($key == 'id') {
1919 $unformattedArray[$key];
1921 $formattedArray = array($value);
1923 $unformattedArray['values'] = $formattedArray;
1928 * Helper to enable/disable custom directory support
1930 * @param array $customDirs
1932 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1933 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1935 public function customDirectories($customDirs) {
1936 $config = CRM_Core_Config
::singleton();
1938 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1939 unset($config->customPHPPathDir
);
1941 elseif ($customDirs['php_path'] === TRUE) {
1942 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1945 $config->customPHPPathDir
= $php_path;
1948 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1949 unset($config->customTemplateDir
);
1951 elseif ($customDirs['template_path'] === TRUE) {
1952 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1955 $config->customTemplateDir
= $template_path;
1960 * Generate a temporary folder.
1962 * @param string $prefix
1965 public function createTempDir($prefix = 'test-') {
1966 $tempDir = CRM_Utils_File
::tempdir($prefix);
1967 $this->tempDirs
[] = $tempDir;
1971 public function cleanTempDirs() {
1972 if (!is_array($this->tempDirs
)) {
1973 // fix test errors where this is not set
1976 foreach ($this->tempDirs
as $tempDir) {
1977 if (is_dir($tempDir)) {
1978 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1984 * Temporarily replace the singleton extension with a different one.
1985 * @param \CRM_Extension_System $system
1987 public function setExtensionSystem(CRM_Extension_System
$system) {
1988 if ($this->origExtensionSystem
== NULL) {
1989 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1991 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1994 public function unsetExtensionSystem() {
1995 if ($this->origExtensionSystem
!== NULL) {
1996 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1997 $this->origExtensionSystem
= NULL;
2002 * Temporarily alter the settings-metadata to add a mock setting.
2004 * WARNING: The setting metadata will disappear on the next cache-clear.
2009 public function setMockSettingsMetaData($extras) {
2010 CRM_Utils_Hook
::singleton()
2011 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2012 $metadata = array_merge($metadata, $extras);
2015 Civi
::service('settings_manager')->flush();
2017 $fields = $this->callAPISuccess('setting', 'getfields', array());
2018 foreach ($extras as $key => $spec) {
2019 $this->assertNotEmpty($spec['title']);
2020 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2025 * @param string $name
2027 public function financialAccountDelete($name) {
2028 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2029 $financialAccount->name
= $name;
2030 if ($financialAccount->find(TRUE)) {
2031 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2032 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2033 $entityFinancialType->delete();
2034 $financialAccount->delete();
2039 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2040 * (NB unclear if this is still required)
2042 public function _sethtmlGlobals() {
2043 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2044 'required' => array(
2045 'html_quickform_rule_required',
2046 'HTML/QuickForm/Rule/Required.php',
2048 'maxlength' => array(
2049 'html_quickform_rule_range',
2050 'HTML/QuickForm/Rule/Range.php',
2052 'minlength' => array(
2053 'html_quickform_rule_range',
2054 'HTML/QuickForm/Rule/Range.php',
2056 'rangelength' => array(
2057 'html_quickform_rule_range',
2058 'HTML/QuickForm/Rule/Range.php',
2061 'html_quickform_rule_email',
2062 'HTML/QuickForm/Rule/Email.php',
2065 'html_quickform_rule_regex',
2066 'HTML/QuickForm/Rule/Regex.php',
2068 'lettersonly' => array(
2069 'html_quickform_rule_regex',
2070 'HTML/QuickForm/Rule/Regex.php',
2072 'alphanumeric' => array(
2073 'html_quickform_rule_regex',
2074 'HTML/QuickForm/Rule/Regex.php',
2077 'html_quickform_rule_regex',
2078 'HTML/QuickForm/Rule/Regex.php',
2080 'nopunctuation' => array(
2081 'html_quickform_rule_regex',
2082 'HTML/QuickForm/Rule/Regex.php',
2085 'html_quickform_rule_regex',
2086 'HTML/QuickForm/Rule/Regex.php',
2088 'callback' => array(
2089 'html_quickform_rule_callback',
2090 'HTML/QuickForm/Rule/Callback.php',
2093 'html_quickform_rule_compare',
2094 'HTML/QuickForm/Rule/Compare.php',
2097 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2098 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2100 'HTML/QuickForm/group.php',
2101 'HTML_QuickForm_group',
2104 'HTML/QuickForm/hidden.php',
2105 'HTML_QuickForm_hidden',
2108 'HTML/QuickForm/reset.php',
2109 'HTML_QuickForm_reset',
2111 'checkbox' => array(
2112 'HTML/QuickForm/checkbox.php',
2113 'HTML_QuickForm_checkbox',
2116 'HTML/QuickForm/file.php',
2117 'HTML_QuickForm_file',
2120 'HTML/QuickForm/image.php',
2121 'HTML_QuickForm_image',
2123 'password' => array(
2124 'HTML/QuickForm/password.php',
2125 'HTML_QuickForm_password',
2128 'HTML/QuickForm/radio.php',
2129 'HTML_QuickForm_radio',
2132 'HTML/QuickForm/button.php',
2133 'HTML_QuickForm_button',
2136 'HTML/QuickForm/submit.php',
2137 'HTML_QuickForm_submit',
2140 'HTML/QuickForm/select.php',
2141 'HTML_QuickForm_select',
2143 'hiddenselect' => array(
2144 'HTML/QuickForm/hiddenselect.php',
2145 'HTML_QuickForm_hiddenselect',
2148 'HTML/QuickForm/text.php',
2149 'HTML_QuickForm_text',
2151 'textarea' => array(
2152 'HTML/QuickForm/textarea.php',
2153 'HTML_QuickForm_textarea',
2155 'fckeditor' => array(
2156 'HTML/QuickForm/fckeditor.php',
2157 'HTML_QuickForm_FCKEditor',
2160 'HTML/QuickForm/tinymce.php',
2161 'HTML_QuickForm_TinyMCE',
2163 'dojoeditor' => array(
2164 'HTML/QuickForm/dojoeditor.php',
2165 'HTML_QuickForm_dojoeditor',
2168 'HTML/QuickForm/link.php',
2169 'HTML_QuickForm_link',
2171 'advcheckbox' => array(
2172 'HTML/QuickForm/advcheckbox.php',
2173 'HTML_QuickForm_advcheckbox',
2176 'HTML/QuickForm/date.php',
2177 'HTML_QuickForm_date',
2180 'HTML/QuickForm/static.php',
2181 'HTML_QuickForm_static',
2184 'HTML/QuickForm/header.php',
2185 'HTML_QuickForm_header',
2188 'HTML/QuickForm/html.php',
2189 'HTML_QuickForm_html',
2191 'hierselect' => array(
2192 'HTML/QuickForm/hierselect.php',
2193 'HTML_QuickForm_hierselect',
2195 'autocomplete' => array(
2196 'HTML/QuickForm/autocomplete.php',
2197 'HTML_QuickForm_autocomplete',
2200 'HTML/QuickForm/xbutton.php',
2201 'HTML_QuickForm_xbutton',
2203 'advmultiselect' => array(
2204 'HTML/QuickForm/advmultiselect.php',
2205 'HTML_QuickForm_advmultiselect',
2211 * Set up an acl allowing contact to see 2 specified groups
2212 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2214 * You need to have pre-created these groups & created the user e.g
2215 * $this->createLoggedInUser();
2216 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2217 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2219 * @param bool $isProfile
2221 public function setupACL($isProfile = FALSE) {
2223 $_REQUEST = $this->_params
;
2225 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2226 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2227 $ov = new CRM_Core_DAO_OptionValue();
2228 $ov->option_group_id
= $optionGroupID;
2230 if ($ov->find(TRUE)) {
2231 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2233 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2234 'option_group_id' => $optionGroupID,
2235 'label' => 'pick me',
2239 CRM_Core_DAO
::executeQuery("
2240 TRUNCATE civicrm_acl_cache
2243 CRM_Core_DAO
::executeQuery("
2244 TRUNCATE civicrm_acl_contact_cache
2247 CRM_Core_DAO
::executeQuery("
2248 INSERT INTO civicrm_acl_entity_role (
2249 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2250 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2254 CRM_Core_DAO
::executeQuery("
2255 INSERT INTO civicrm_acl (
2256 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2259 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2264 CRM_Core_DAO
::executeQuery("
2265 INSERT INTO civicrm_acl (
2266 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2269 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2273 CRM_Core_DAO
::executeQuery("
2274 INSERT INTO civicrm_acl (
2275 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2278 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2283 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2284 $this->callAPISuccess('group_contact', 'create', array(
2285 'group_id' => $this->_permissionedGroup
,
2286 'contact_id' => $this->_loggedInUser
,
2291 CRM_ACL_BAO_Cache
::resetCache();
2292 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2297 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2299 public function offsetDefaultPriceSet() {
2300 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2301 $firstID = $contributionPriceSet['id'];
2302 $this->callAPISuccess('price_set', 'create', array(
2303 'id' => $contributionPriceSet['id'],
2307 unset($contributionPriceSet['id']);
2308 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2309 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2310 'price_set_id' => $firstID,
2311 'options' => array('limit' => 1),
2313 unset($priceField['id']);
2314 $priceField['price_set_id'] = $newPriceSet['id'];
2315 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2316 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2317 'price_set_id' => $firstID,
2319 'options' => array('limit' => 1),
2322 unset($priceFieldValue['id']);
2323 //create some padding to use up ids
2324 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2325 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2326 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2330 * Create an instance of the paypal processor.
2331 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2332 * this parent class & we don't have a structure for that yet
2333 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2334 * & the best protection against that is the functions this class affords
2335 * @param array $params
2336 * @return int $result['id'] payment processor id
2338 public function paymentProcessorCreate($params = array()) {
2339 $params = array_merge(array(
2341 'domain_id' => CRM_Core_Config
::domainID(),
2342 'payment_processor_type_id' => 'PayPal',
2346 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2347 'password' => '1183377788',
2348 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2349 'url_site' => 'https://www.sandbox.paypal.com/',
2350 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2351 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2352 'class_name' => 'Payment_PayPalImpl',
2353 'billing_mode' => 3,
2354 'financial_type_id' => 1,
2355 'financial_account_id' => 12,
2356 // Credit card = 1 so can pass 'by accident'.
2357 'payment_instrument_id' => 'Debit Card',
2359 if (!is_numeric($params['payment_processor_type_id'])) {
2360 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2362 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2363 'name' => $params['payment_processor_type_id'],
2367 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2368 return $result['id'];
2372 * Set up initial recurring payment allowing subsequent IPN payments.
2374 * @param array $recurParams (Optional)
2375 * @param array $contributionParams (Optional)
2377 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2378 $contributionParams = array_merge([
2379 'total_amount' => '200',
2380 'invoice_id' => $this->_invoiceID
,
2381 'financial_type_id' => 'Donation',
2382 'contribution_status_id' => 'Pending',
2383 'contact_id' => $this->_contactID
,
2384 'contribution_page_id' => $this->_contributionPageID
,
2385 'payment_processor_id' => $this->_paymentProcessorID
,
2387 'skipCleanMoney' => TRUE,
2388 ], $contributionParams);
2389 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2390 'contact_id' => $this->_contactID
,
2393 'installments' => 5,
2394 'frequency_unit' => 'Month',
2395 'frequency_interval' => 1,
2396 'invoice_id' => $this->_invoiceID
,
2397 'contribution_status_id' => 2,
2398 'payment_processor_id' => $this->_paymentProcessorID
,
2399 // processor provided ID - use contact ID as proxy.
2400 'processor_id' => $this->_contactID
,
2401 'api.contribution.create' => $contributionParams,
2403 $this->_contributionRecurID
= $contributionRecur['id'];
2404 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2408 * 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
2410 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2412 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2413 $membershipParams = $recurParams = array();
2414 if (!empty($params['duration_unit'])) {
2415 $membershipParams['duration_unit'] = $params['duration_unit'];
2417 if (!empty($params['frequency_unit'])) {
2418 $recurParams['frequency_unit'] = $params['frequency_unit'];
2421 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2422 //create a contribution so our membership & contribution don't both have id = 1
2423 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2424 $this->contributionCreate(array(
2425 'contact_id' => $this->_contactID
,
2427 'financial_type_id' => 1,
2428 'invoice_id' => 'abcd',
2432 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2434 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2435 'contact_id' => $this->_contactID
,
2436 'membership_type_id' => $this->ids
['membership_type'],
2437 'contribution_recur_id' => $this->_contributionRecurID
,
2438 'format.only_id' => TRUE,
2440 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2441 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2443 $this->callAPISuccess('line_item', 'create', array(
2444 'entity_table' => 'civicrm_membership',
2445 'entity_id' => $this->ids
['membership'],
2446 'contribution_id' => $this->_contributionID
,
2447 'label' => 'General',
2449 'unit_price' => 200,
2450 'line_total' => 200,
2451 'financial_type_id' => 1,
2452 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2454 'label' => 'Membership Amount',
2455 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2457 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2459 'label' => 'General',
2460 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2463 $this->callAPISuccess('membership_payment', 'create', array(
2464 'contribution_id' => $this->_contributionID
,
2465 'membership_id' => $this->ids
['membership'],
2474 public function CiviUnitTestCase_fatalErrorHandler($message) {
2475 throw new Exception("{$message['message']}: {$message['code']}");
2479 * Wrap the entire test case in a transaction.
2481 * Only subsequent DB statements will be wrapped in TX -- this cannot
2482 * retroactively wrap old DB statements. Therefore, it makes sense to
2483 * call this at the beginning of setUp().
2485 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2486 * this option does not work with, e.g., custom-data.
2488 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2489 * if TRUNCATE or ALTER is called while using a transaction.
2492 * Whether to use nesting or reference-counting.
2494 public function useTransaction($nest = TRUE) {
2496 $this->tx
= new CRM_Core_Transaction($nest);
2497 $this->tx
->rollback();
2502 * Assert the attachment exists.
2504 * @param bool $exists
2505 * @param array $apiResult
2507 protected function assertAttachmentExistence($exists, $apiResult) {
2508 $fileId = $apiResult['id'];
2509 $this->assertTrue(is_numeric($fileId));
2510 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2511 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2512 1 => array($fileId, 'Int'),
2514 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2515 1 => array($fileId, 'Int'),
2520 * Create a price set for an event.
2522 * @param int $feeTotal
2523 * @param int $minAmt
2524 * @param string $type
2529 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2530 // creating price set, price field
2531 $paramsSet['title'] = 'Price Set';
2532 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2533 $paramsSet['is_active'] = FALSE;
2534 $paramsSet['extends'] = 1;
2535 $paramsSet['min_amount'] = $minAmt;
2537 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2538 $this->_ids
['price_set'] = $priceSet->id
;
2540 $paramsField = array(
2541 'label' => 'Price Field',
2542 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2543 'html_type' => $type,
2544 'price' => $feeTotal,
2545 'option_label' => array('1' => 'Price Field'),
2546 'option_value' => array('1' => $feeTotal),
2547 'option_name' => array('1' => $feeTotal),
2548 'option_weight' => array('1' => 1),
2549 'option_amount' => array('1' => 1),
2550 'is_display_amounts' => 1,
2552 'options_per_line' => 1,
2553 'is_active' => array('1' => 1),
2554 'price_set_id' => $this->_ids
['price_set'],
2555 'is_enter_qty' => 1,
2556 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2558 if ($type === 'Radio') {
2559 $paramsField['is_enter_qty'] = 0;
2560 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2561 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2563 CRM_Price_BAO_PriceField
::create($paramsField);
2564 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2565 $this->_ids
['price_field'] = array_keys($fields['values']);
2566 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2567 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2569 return $this->_ids
['price_set'];
2573 * Add a profile to a contribution page.
2575 * @param string $name
2576 * @param int $contributionPageID
2577 * @param string $module
2579 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2581 'uf_group_id' => $name,
2582 'module' => $module,
2583 'entity_table' => 'civicrm_contribution_page',
2584 'entity_id' => $contributionPageID,
2587 if ($module !== 'CiviContribute') {
2588 $params['module_data'] = [$module => []];
2590 $this->callAPISuccess('UFJoin', 'create', $params);
2594 * Add participant with contribution
2598 protected function createParticipantWithContribution() {
2599 // creating price set, price field
2600 $this->_contactId
= $this->individualCreate();
2601 $event = $this->eventCreate();
2602 $this->_eventId
= $event['id'];
2603 $eventParams = array(
2604 'id' => $this->_eventId
,
2605 'financial_type_id' => 4,
2608 $this->callAPISuccess('event', 'create', $eventParams);
2609 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2610 $participantParams = array(
2611 'financial_type_id' => 4,
2612 'event_id' => $this->_eventId
,
2615 'fee_currency' => 'USD',
2616 'contact_id' => $this->_contactId
,
2618 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2619 $contributionParams = array(
2620 'total_amount' => 150,
2621 'currency' => 'USD',
2622 'contact_id' => $this->_contactId
,
2623 'financial_type_id' => 4,
2624 'contribution_status_id' => 1,
2625 'partial_payment_total' => 300.00,
2626 'partial_amount_to_pay' => 150,
2627 'contribution_mode' => 'participant',
2628 'participant_id' => $participant['id'],
2630 foreach ($priceFields['values'] as $key => $priceField) {
2631 $lineItems[1][$key] = array(
2632 'price_field_id' => $priceField['price_field_id'],
2633 'price_field_value_id' => $priceField['id'],
2634 'label' => $priceField['label'],
2635 'field_title' => $priceField['label'],
2637 'unit_price' => $priceField['amount'],
2638 'line_total' => $priceField['amount'],
2639 'financial_type_id' => $priceField['financial_type_id'],
2642 $contributionParams['line_item'] = $lineItems;
2643 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2644 $paymentParticipant = array(
2645 'participant_id' => $participant['id'],
2646 'contribution_id' => $contribution['id'],
2648 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2649 return array($lineItems, $contribution);
2655 * @param string $component
2656 * @param int $componentId
2657 * @param array $priceFieldOptions
2661 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2662 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2663 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2664 $paramsSet['is_active'] = TRUE;
2665 $paramsSet['financial_type_id'] = 'Event Fee';
2666 $paramsSet['extends'] = 1;
2667 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2668 $priceSetId = $priceSet['id'];
2669 //Checking for priceset added in the table.
2670 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2671 'id', $paramsSet['title'], 'Check DB for created priceset'
2673 $paramsField = array_merge(array(
2674 'label' => 'Price Field',
2675 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2676 'html_type' => 'CheckBox',
2677 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2678 'option_value' => array('1' => 100, '2' => 200),
2679 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2680 'option_weight' => array('1' => 1, '2' => 2),
2681 'option_amount' => array('1' => 100, '2' => 200),
2682 'is_display_amounts' => 1,
2684 'options_per_line' => 1,
2685 'is_active' => array('1' => 1, '2' => 1),
2686 'price_set_id' => $priceSet['id'],
2687 'is_enter_qty' => 1,
2688 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2689 ), $priceFieldOptions);
2691 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2693 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2695 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2699 * Replace the template with a test-oriented template designed to show all the variables.
2701 * @param string $templateName
2703 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2704 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2705 CRM_Core_DAO
::executeQuery(
2706 "UPDATE civicrm_option_group og
2707 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2708 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2709 SET m.msg_html = '{$testTemplate}'
2710 WHERE og.name = 'msg_tpl_workflow_contribution'
2711 AND ov.name = '{$templateName}'
2712 AND m.is_default = 1"
2717 * Reinstate the default template.
2719 * @param string $templateName
2721 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2722 CRM_Core_DAO
::executeQuery(
2723 "UPDATE civicrm_option_group og
2724 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2725 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2726 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2727 SET m.msg_html = m2.msg_html
2728 WHERE og.name = 'msg_tpl_workflow_contribution'
2729 AND ov.name = '{$templateName}'
2730 AND m.is_default = 1"
2735 * Flush statics relating to financial type.
2737 protected function flushFinancialTypeStatics() {
2738 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2739 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2741 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2742 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2744 CRM_Contribute_PseudoConstant
::flush('financialType');
2745 CRM_Contribute_PseudoConstant
::flush('membershipType');
2746 // Pseudoconstants may be saved to the cache table.
2747 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2748 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2749 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2753 * Set the permissions to the supplied array.
2755 * @param array $permissions
2757 protected function setPermissions($permissions) {
2758 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2759 $this->flushFinancialTypeStatics();
2763 * @param array $params
2766 public function _checkFinancialRecords($params, $context) {
2767 $entityParams = array(
2768 'entity_id' => $params['id'],
2769 'entity_table' => 'civicrm_contribution',
2771 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2772 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2773 if ($context == 'pending') {
2774 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2775 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2778 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2779 $trxnParams = array(
2780 'id' => $trxn['financial_trxn_id'],
2782 if ($context != 'online' && $context != 'payLater') {
2783 $compareParams = array(
2784 'to_financial_account_id' => 6,
2785 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2789 if ($context == 'feeAmount') {
2790 $compareParams['fee_amount'] = 50;
2792 elseif ($context == 'online') {
2793 $compareParams = array(
2794 'to_financial_account_id' => 12,
2795 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2797 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2800 elseif ($context == 'payLater') {
2801 $compareParams = array(
2802 'to_financial_account_id' => 7,
2803 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2807 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2808 $entityParams = array(
2809 'financial_trxn_id' => $trxn['financial_trxn_id'],
2810 'entity_table' => 'civicrm_financial_item',
2812 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2813 $fitemParams = array(
2814 'id' => $entityTrxn['entity_id'],
2816 $compareParams = array(
2817 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2819 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2821 if ($context == 'payLater') {
2822 $compareParams = array(
2823 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2825 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2828 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2829 if ($context == 'feeAmount') {
2831 'entity_id' => $params['id'],
2832 'entity_table' => 'civicrm_contribution',
2834 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2835 $trxnParams = array(
2836 'id' => $maxTrxn['financial_trxn_id'],
2838 $compareParams = array(
2839 'to_financial_account_id' => 5,
2840 'from_financial_account_id' => 6,
2841 'total_amount' => 50,
2844 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2845 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2846 $fitemParams = array(
2847 'entity_id' => $trxnId['financialTrxnId'],
2848 'entity_table' => 'civicrm_financial_trxn',
2850 $compareParams = array(
2853 'financial_account_id' => 5,
2855 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2857 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2858 // line should be copied into all the functions that call this function & evaluated there
2859 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2860 // when calling completeTransaction or repeatTransaction.
2861 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2865 * Return financial type id on basis of name
2867 * @param string $name Financial type m/c name
2871 public function getFinancialTypeId($name) {
2872 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2876 * Cleanup function for contents of $this->ids.
2878 * This is a best effort cleanup to use in tear downs etc.
2880 * It will not fail if the data has already been removed (some tests may do
2881 * their own cleanup).
2883 protected function cleanUpSetUpIDs() {
2884 foreach ($this->setupIDs
as $entity => $id) {
2886 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2888 catch (CiviCRM_API3_Exception
$e) {
2889 // This is a best-effort cleanup function, ignore.
2895 * Create Financial Type.
2897 * @param array $params
2901 protected function createFinancialType($params = array()) {
2902 $params = array_merge($params,
2904 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2908 return $this->callAPISuccess('FinancialType', 'create', $params);
2912 * Create Payment Instrument.
2914 * @param array $params
2915 * @param string $financialAccountName
2919 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2920 $params = array_merge(array(
2921 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2922 'option_group_id' => 'payment_instrument',
2925 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2927 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2929 $financialAccountParams = [
2930 'entity_table' => 'civicrm_option_value',
2931 'entity_id' => $newPaymentInstrument,
2932 'account_relationship' => $relationTypeID,
2933 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2935 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2937 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2941 * Enable Tax and Invoicing
2943 protected function enableTaxAndInvoicing($params = array()) {
2944 // Enable component contribute setting
2945 $contributeSetting = array_merge($params,
2948 'invoice_prefix' => 'INV_',
2949 'credit_notes_prefix' => 'CN_',
2951 'due_date_period' => 'days',
2953 'is_email_pdf' => 1,
2954 'tax_term' => 'Sales Tax',
2955 'tax_display_settings' => 'Inclusive',
2958 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2962 * Enable Tax and Invoicing
2964 protected function disableTaxAndInvoicing($params = array()) {
2965 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2966 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2968 // Enable component contribute setting
2969 $contributeSetting = array_merge($params,
2974 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2978 * Add Sales Tax relation for financial type with financial account.
2980 * @param int $financialTypeId
2984 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2986 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2987 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2988 'is_deductible' => 1,
2993 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
2994 $entityParams = array(
2995 'entity_table' => 'civicrm_financial_type',
2996 'entity_id' => $financialTypeId,
2997 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3000 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3001 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3003 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3004 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3005 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3006 $dao->copyValues($entityParams);
3008 if ($dao->fetch()) {
3009 $entityParams['id'] = $dao->id
;
3011 $entityParams['financial_account_id'] = $account->id
;
3013 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3017 * Create price set with contribution test for test setup.
3019 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3020 * on parent class at some point (fn is not in 4.4).
3023 * @param array $params
3025 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3026 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3027 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3028 'title' => "Test Contribution Page",
3029 'financial_type_id' => 1,
3030 'currency' => 'NZD',
3031 'goal_amount' => 50,
3032 'is_pay_later' => 1,
3033 'is_monetary' => TRUE,
3034 'is_email_receipt' => FALSE,
3036 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3037 'is_quick_config' => 0,
3038 'extends' => 'CiviMember',
3039 'financial_type_id' => 1,
3040 'title' => 'my Page',
3042 $priceSetID = $priceSet['id'];
3044 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3045 $priceField = $this->callAPISuccess('price_field', 'create', array(
3046 'price_set_id' => $priceSetID,
3047 'label' => 'Goat Breed',
3048 'html_type' => 'Radio',
3050 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3051 'price_set_id' => $priceSetID,
3052 'price_field_id' => $priceField['id'],
3053 'label' => 'Long Haired Goat',
3055 'financial_type_id' => 'Donation',
3056 'membership_type_id' => $membershipTypeID,
3057 'membership_num_terms' => 1,
3059 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3060 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3061 'price_set_id' => $priceSetID,
3062 'price_field_id' => $priceField['id'],
3063 'label' => 'Shoe-eating Goat',
3065 'financial_type_id' => 'Donation',
3066 'membership_type_id' => $membershipTypeID,
3067 'membership_num_terms' => 2,
3069 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3071 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3072 'price_set_id' => $priceSetID,
3073 'price_field_id' => $priceField['id'],
3074 'label' => 'Shoe-eating Goat',
3076 'financial_type_id' => 'Donation',
3078 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3080 $this->_ids
['price_set'] = $priceSetID;
3081 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3082 $this->_ids
['price_field'] = array($priceField['id']);
3084 $this->_ids
['membership_type'] = $membershipTypeID;
3088 * Only specified contact returned.
3089 * @implements CRM_Utils_Hook::aclWhereClause
3092 * @param $whereTables
3096 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3097 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3101 * @implements CRM_Utils_Hook::selectWhereClause
3103 * @param string $entity
3104 * @param array $clauses
3106 public function selectWhereClauseHook($entity, &$clauses) {
3107 if ($entity == 'Event') {
3108 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3113 * An implementation of hook_civicrm_post used with all our test cases.
3116 * @param string $objectName
3117 * @param int $objectId
3120 public function onPost($op, $objectName, $objectId, &$objectRef) {
3121 if ($op == 'create' && $objectName == 'Individual') {
3122 CRM_Core_DAO
::executeQuery(
3123 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3125 1 => array($objectId, 'Integer'),
3130 if ($op == 'edit' && $objectName == 'Participant') {
3132 1 => array($objectId, 'Integer'),
3134 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3135 CRM_Core_DAO
::executeQuery($query, $params);
3140 * Instantiate form object.
3142 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3144 * @param string $class
3145 * Name of form class.
3147 * @return \CRM_Core_Form
3149 public function getFormObject($class) {
3150 $form = new $class();
3151 $_SERVER['REQUEST_METHOD'] = 'GET';
3152 $form->controller
= new CRM_Core_Controller();
3157 * Get possible thousand separators.
3161 public function getThousandSeparators() {
3162 return array(array('.'), array(','));
3166 * Set the separators for thousands and decimal points.
3168 * @param string $thousandSeparator
3170 protected function setCurrencySeparators($thousandSeparator) {
3171 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3173 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3177 * Format money as it would be input.
3179 * @param string $amount
3183 protected function formatMoneyInput($amount) {
3184 return CRM_Utils_Money
::format($amount, NULL, '%a');
3188 * Get the contribution object.
3190 * @param int $contributionID
3192 * @return \CRM_Contribute_BAO_Contribution
3194 protected function getContributionObject($contributionID) {
3195 $contributionObj = new CRM_Contribute_BAO_Contribution();
3196 $contributionObj->id
= $contributionID;
3197 $contributionObj->find(TRUE);
3198 return $contributionObj;
3202 * Enable multilingual.
3204 public function enableMultilingual() {
3205 $this->callAPISuccess('Setting', 'create', array(
3206 'lcMessages' => 'en_US',
3207 'languageLimit' => array(
3212 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3215 $dbLocale = '_en_US';
3219 * Setup or clean up SMS tests
3220 * @param bool $teardown
3222 * @throws \CiviCRM_API3_Exception
3224 public function setupForSmsTests($teardown = FALSE) {
3225 require_once 'CiviTest/CiviTestSMSProvider.php';
3227 // Option value params for CiviTestSMSProvider
3228 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3230 'option_group_id' => $groupID,
3231 'label' => 'unittestSMS',
3232 'value' => 'unit.test.sms',
3233 'name' => 'CiviTestSMSProvider',
3240 // Test completed, delete provider
3241 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3242 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3246 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3247 // in CRM/Sms/Provider.php even though it is not an extension.
3248 return civicrm_api3('option_value', 'create', $params);