3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
32 * Include class definitions
34 require_once 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
56 use \Civi\Test\Api3DocTrait
;
59 * Database has been initialized.
63 private static $dbInit = FALSE;
66 * Database connection.
68 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
77 static protected $_dbName;
80 * Track tables we have modified during a test.
82 protected $_tablesToTruncate = array();
85 * @var array of temporary directory names
90 * @var boolean populateOnce allows to skip db resets in setUp
92 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
93 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
96 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
98 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
100 public static $populateOnce = FALSE;
103 * @var boolean DBResetRequired allows skipping DB reset
104 * in specific test case. If you still need
105 * to reset single test (method) of such case, call
106 * $this->cleanDB() in the first line of this
109 public $DBResetRequired = TRUE;
112 * @var CRM_Core_Transaction|NULL
117 * Class used for hooks during tests.
119 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
121 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
123 * @var CRM_Utils_Hook_UnitTests hookClass
125 public $hookClass = NULL;
128 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
130 protected $_params = array();
133 * @var CRM_Extension_System
135 protected $origExtensionSystem;
138 * Array of IDs created during test setup routine.
140 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
144 public $setupIDs = array();
147 * PHPUnit Mock Method to use.
151 public $mockMethod = 'getMock';
156 * Because we are overriding the parent class constructor, we
157 * need to show the same arguments as exist in the constructor of
158 * PHPUnit_Framework_TestCase, since
159 * PHPUnit_Framework_TestSuite::createTest() creates a
160 * ReflectionClass of the Test class and checks the constructor
161 * of that class to decide how to set up the test.
163 * @param string $name
165 * @param string $dataName
167 public function __construct($name = NULL, array$data = array(), $dataName = '') {
168 parent
::__construct($name, $data, $dataName);
170 // we need full error reporting
171 error_reporting(E_ALL
& ~E_NOTICE
);
173 self
::$_dbName = self
::getDBName();
175 // also load the class loader
176 require_once 'CRM/Core/ClassLoader.php';
177 CRM_Core_ClassLoader
::singleton()->register();
178 if (function_exists('_civix_phpunit_setUp')) {
179 // FIXME: loosen coupling
180 _civix_phpunit_setUp();
182 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
183 $this->mockMethod
= 'createMock';
188 * Override to run the test and assert its state.
191 * @throws \PHPUnit_Framework_IncompleteTest
192 * @throws \PHPUnit_Framework_SkippedTest
194 protected function runTest() {
196 return parent
::runTest();
198 catch (PEAR_Exception
$e) {
199 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
200 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
207 public function requireDBReset() {
208 return $this->DBResetRequired
;
214 public static function getDBName() {
215 static $dbName = NULL;
216 if ($dbName === NULL) {
217 require_once "DB.php";
218 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
219 $dbName = $dsninfo['database'];
225 * Create database connection for this instance.
227 * Initialize the test database if it hasn't been initialized
229 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
231 protected function getConnection() {
232 $dbName = self
::$_dbName;
233 if (!self
::$dbInit) {
234 $dbName = self
::getDBName();
236 // install test database
237 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
239 static::_populateDB(FALSE, $this);
241 self
::$dbInit = TRUE;
244 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
248 * Required implementation of abstract method.
250 protected function getDataSet() {
254 * @param bool $perClass
255 * @param null $object
257 * TRUE if the populate logic runs; FALSE if it is skipped
259 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
260 if (CIVICRM_UF
!== 'UnitTests') {
261 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
264 if ($perClass ||
$object == NULL) {
268 $dbreset = $object->requireDBReset();
271 if (self
::$populateOnce ||
!$dbreset) {
274 self
::$populateOnce = NULL;
276 Civi\Test
::data()->populate();
281 public static function setUpBeforeClass() {
282 static::_populateDB(TRUE);
284 // also set this global hack
285 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
289 * Common setup functions for all unit tests.
291 protected function setUp() {
292 $session = CRM_Core_Session
::singleton();
293 $session->set('userID', NULL);
295 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
296 // Use a temporary file for STDIN
297 $GLOBALS['stdin'] = tmpfile();
298 if ($GLOBALS['stdin'] === FALSE) {
299 echo "Couldn't open temporary file\n";
303 // Get and save a connection to the database
304 $this->_dbconn
= $this->getConnection();
306 // reload database before each test
307 // $this->_populateDB();
309 // "initialize" CiviCRM to avoid problems when running single tests
310 // FIXME: look at it closer in second stage
312 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
313 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
315 // disable any left-over test extensions
316 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
318 // reset all the caches
319 CRM_Utils_System
::flushCache();
321 // initialize the object once db is loaded
323 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
325 // when running unit tests, use mockup user framework
326 $this->hookClass
= CRM_Utils_Hook
::singleton();
328 // Make sure the DB connection is setup properly
329 $config->userSystem
->setMySQLTimeZone();
330 $env = new CRM_Utils_Check_Component_Env();
331 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
333 // clear permissions stub to not check permissions
334 $config->userPermissionClass
->permissions
= NULL;
336 //flush component settings
337 CRM_Core_Component
::getEnabledComponents(TRUE);
339 error_reporting(E_ALL
);
341 $this->_sethtmlGlobals();
345 * Read everything from the datasets directory and insert into the db.
347 public function loadAllFixtures() {
348 $fixturesDir = __DIR__
. '/../../fixtures';
350 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
352 $xmlFiles = glob($fixturesDir . '/*.xml');
353 foreach ($xmlFiles as $xmlFixture) {
354 $op = new PHPUnit_Extensions_Database_Operation_Insert();
355 $dataset = $this->createXMLDataSet($xmlFixture);
356 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
357 $op->execute($this->_dbconn
, $dataset);
360 $yamlFiles = glob($fixturesDir . '/*.yaml');
361 foreach ($yamlFiles as $yamlFixture) {
362 $op = new PHPUnit_Extensions_Database_Operation_Insert();
363 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
364 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
365 $op->execute($this->_dbconn
, $dataset);
368 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
372 * Emulate a logged in user since certain functions use that.
373 * value to store a record in the DB (like activity)
377 * Contact ID of the created user.
379 public function createLoggedInUser() {
381 'first_name' => 'Logged In',
382 'last_name' => 'User ' . rand(),
383 'contact_type' => 'Individual',
385 $contactID = $this->individualCreate($params);
386 $this->callAPISuccess('UFMatch', 'create', array(
387 'contact_id' => $contactID,
388 'uf_name' => 'superman',
392 $session = CRM_Core_Session
::singleton();
393 $session->set('userID', $contactID);
398 * Create default domain contacts for the two domains added during test class.
399 * database population.
401 public function createDomainContacts() {
402 $this->organizationCreate();
403 $this->organizationCreate(array('organization_name' => 'Second Domain'));
407 * Common teardown functions for all unit tests.
409 protected function tearDown() {
410 error_reporting(E_ALL
& ~E_NOTICE
);
411 CRM_Utils_Hook
::singleton()->reset();
412 if ($this->hookClass
) {
413 $this->hookClass
->reset();
415 $session = CRM_Core_Session
::singleton();
416 $session->set('userID', NULL);
419 $this->tx
->rollback()->commit();
422 CRM_Core_Transaction
::forceRollbackIfEnabled();
423 \Civi\Core\Transaction\Manager
::singleton(TRUE);
426 CRM_Core_Transaction
::forceRollbackIfEnabled();
427 \Civi\Core\Transaction\Manager
::singleton(TRUE);
429 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
430 $this->quickCleanup($tablesToTruncate);
431 $this->createDomainContacts();
434 $this->cleanTempDirs();
435 $this->unsetExtensionSystem();
439 * Generic function to compare expected values after an api call to retrieved.
442 * @daoName string DAO Name of object we're evaluating.
443 * @id int Id of object
444 * @match array Associative array of field name => expected value. Empty if asserting
445 * that a DELETE occurred
446 * @delete boolean True if we're checking that a DELETE action occurred.
450 * @param bool $delete
451 * @throws \PHPUnit_Framework_AssertionFailedError
453 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
455 // adding this here since developers forget to check for an id
456 // and hence we get the first value in the db
457 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
460 $object = new $daoName();
464 // If we're asserting successful record deletion, make sure object is NOT found.
466 if ($object->find(TRUE)) {
467 $this->fail("Object not deleted by delete operation: $daoName, $id");
472 // Otherwise check matches of DAO field values against expected values in $match.
473 if ($object->find(TRUE)) {
474 $fields = &$object->fields();
475 foreach ($fields as $name => $value) {
476 $dbName = $value['name'];
477 if (isset($match[$name])) {
479 $this->assertEquals($object->$dbName, $match[$name]);
481 elseif (isset($match[$dbName])) {
483 $this->assertEquals($object->$dbName, $match[$dbName]);
488 $this->fail("Could not retrieve object: $daoName, $id");
491 $matchSize = count($match);
492 if ($verifiedCount != $matchSize) {
493 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
498 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
499 * @param string $daoName
500 * @param $searchValue
501 * @param $returnColumn
502 * @param $searchColumn
505 * @return null|string
506 * @throws PHPUnit_Framework_AssertionFailedError
508 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
509 if (empty($searchValue)) {
510 $this->fail("empty value passed to assertDBNotNull");
512 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
513 $this->assertNotNull($value, $message);
519 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
520 * @param string $daoName
521 * @param $searchValue
522 * @param $returnColumn
523 * @param $searchColumn
526 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
527 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
528 $this->assertNull($value, $message);
532 * Request a record from the DB by id. Success if row not found.
533 * @param string $daoName
535 * @param null $message
537 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
538 $message = $message ?
$message : "$daoName (#$id) should not exist";
539 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
540 $this->assertNull($value, $message);
544 * Request a record from the DB by id. Success if row not found.
545 * @param string $daoName
547 * @param null $message
549 public function assertDBRowExist($daoName, $id, $message = NULL) {
550 $message = $message ?
$message : "$daoName (#$id) should exist";
551 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
552 $this->assertEquals($id, $value, $message);
556 * Compare a single column value in a retrieved DB record to an expected value.
557 * @param string $daoName
558 * @param $searchValue
559 * @param $returnColumn
560 * @param $searchColumn
561 * @param $expectedValue
564 public function assertDBCompareValue(
565 $daoName, $searchValue, $returnColumn, $searchColumn,
566 $expectedValue, $message
568 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
569 $this->assertEquals($expectedValue, $value, $message);
573 * Compare all values in a single retrieved DB record to an array of expected values.
574 * @param string $daoName
575 * @param array $searchParams
576 * @param $expectedValues
578 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
579 //get the values from db
581 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
583 // compare db values with expected values
584 self
::assertAttributesEquals($expectedValues, $dbValues);
588 * Assert that a SQL query returns a given value.
590 * The first argument is an expected value. The remaining arguments are passed
591 * to CRM_Core_DAO::singleValueQuery
593 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
594 * array(1 => array("Whiz", "String")));
597 * @param array $params
598 * @param string $message
600 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
604 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
605 $this->assertEquals($expected, $actual,
606 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
607 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
613 * Assert that two array-trees are exactly equal, notwithstanding
614 * the sorting of keys
616 * @param array $expected
617 * @param array $actual
619 public function assertTreeEquals($expected, $actual) {
622 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
623 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
627 $this->assertEquals($e, $a);
631 * Assert that two numbers are approximately equal.
633 * @param int|float $expected
634 * @param int|float $actual
635 * @param int|float $tolerance
636 * @param string $message
638 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
639 if ($message === NULL) {
640 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
642 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
646 * Assert attributes are equal.
648 * @param $expectedValues
649 * @param $actualValues
650 * @param string $message
652 * @throws PHPUnit_Framework_AssertionFailedError
654 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
655 foreach ($expectedValues as $paramName => $paramValue) {
656 if (isset($actualValues[$paramName])) {
657 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
660 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
669 public function assertArrayKeyExists($key, &$list) {
670 $result = isset($list[$key]) ?
TRUE : FALSE;
671 $this->assertTrue($result, ts("%1 element exists?",
680 public function assertArrayValueNotNull($key, &$list) {
681 $this->assertArrayKeyExists($key, $list);
683 $value = isset($list[$key]) ?
$list[$key] : NULL;
684 $this->assertTrue($value,
685 ts("%1 element not null?",
692 * Assert the 2 arrays have the same values.
694 * @param array $array1
695 * @param array $array2
697 public function assertArrayValuesEqual($array1, $array2) {
698 $array1 = array_values($array1);
699 $array2 = array_values($array2);
702 $this->assertEquals($array1, $array2);
708 * @param string $message
710 public function assertType($expected, $actual, $message = '') {
711 return $this->assertInternalType($expected, $actual, $message);
715 * Create a batch of external API calls which can
716 * be executed concurrently.
719 * $calls = $this->createExternalAPI()
720 * ->addCall('Contact', 'get', ...)
721 * ->addCall('Contact', 'get', ...)
727 * @return \Civi\API\ExternalBatch
728 * @throws PHPUnit_Framework_SkippedTestError
730 public function createExternalAPI() {
731 global $civicrm_root;
732 $defaultParams = array(
733 'version' => $this->_apiversion
,
737 $calls = new \Civi\API\
ExternalBatch($defaultParams);
739 if (!$calls->isSupported()) {
740 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
747 * Create required data based on $this->entity & $this->params
748 * This is just a way to set up the test data for delete & get functions
749 * so the distinction between set
750 * up & tested functions is clearer
755 public function createTestEntity() {
756 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
760 * Generic function to create Organisation, to be used in test cases
762 * @param array $params
763 * parameters for civicrm_contact_add api function call
765 * sequence number if creating multiple organizations
768 * id of Organisation created
770 public function organizationCreate($params = array(), $seq = 0) {
774 $params = array_merge($this->sampleContact('Organization', $seq), $params);
775 return $this->_contactCreate($params);
779 * Generic function to create Individual, to be used in test cases
781 * @param array $params
782 * parameters for civicrm_contact_add api function call
784 * sequence number if creating multiple individuals
785 * @param bool $random
788 * id of Individual created
790 public function individualCreate($params = array(), $seq = 0, $random = FALSE) {
791 $params = array_merge($this->sampleContact('Individual', $seq, $random), $params);
792 return $this->_contactCreate($params);
796 * Generic function to create Household, to be used in test cases
798 * @param array $params
799 * parameters for civicrm_contact_add api function call
801 * sequence number if creating multiple households
804 * id of Household created
806 public function householdCreate($params = array(), $seq = 0) {
807 $params = array_merge($this->sampleContact('Household', $seq), $params);
808 return $this->_contactCreate($params);
812 * Helper function for getting sample contact properties.
814 * @param string $contact_type
815 * enum contact type: Individual, Organization
817 * sequence number for the values of this type
820 * properties of sample contact (ie. $params for API call)
822 public function sampleContact($contact_type, $seq = 0, $random = FALSE) {
824 'Individual' => array(
825 // The number of values in each list need to be coprime numbers to not have duplicates
826 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
827 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
828 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
830 'Organization' => array(
831 'organization_name' => array(
832 'Unit Test Organization',
839 'Household' => array(
840 'household_name' => array('Unit Test household'),
843 $params = array('contact_type' => $contact_type);
844 foreach ($samples[$contact_type] as $key => $values) {
845 $params[$key] = $values[$seq %
count($values)];
847 $params[$key] .= substr(sha1(rand()), 0, 5);
850 if ($contact_type == 'Individual') {
851 $params['email'] = strtolower(
852 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
854 $params['prefix_id'] = 3;
855 $params['suffix_id'] = 3;
861 * Private helper function for calling civicrm_contact_add.
863 * @param array $params
864 * For civicrm_contact_add api function call.
869 * id of Household created
871 private function _contactCreate($params) {
872 $result = $this->callAPISuccess('contact', 'create', $params);
873 if (!empty($result['is_error']) ||
empty($result['id'])) {
874 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
876 return $result['id'];
880 * Delete contact, ensuring it is not the domain contact
882 * @param int $contactID
883 * Contact ID to delete
885 public function contactDelete($contactID) {
886 $domain = new CRM_Core_BAO_Domain();
887 $domain->contact_id
= $contactID;
888 if (!$domain->find(TRUE)) {
889 $this->callAPISuccess('contact', 'delete', array(
891 'skip_undelete' => 1,
897 * @param int $contactTypeId
901 public function contactTypeDelete($contactTypeId) {
902 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
904 throw new Exception('Could not delete contact type');
909 * @param array $params
913 public function membershipTypeCreate($params = array()) {
914 CRM_Member_PseudoConstant
::flush('membershipType');
915 CRM_Core_Config
::clearDBCache();
916 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
917 $params = array_merge(array(
919 'duration_unit' => 'year',
920 'duration_interval' => 1,
921 'period_type' => 'rolling',
922 'member_of_contact_id' => $memberOfOrganization,
924 'financial_type_id' => 2,
927 'visibility' => 'Public',
930 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
932 CRM_Member_PseudoConstant
::flush('membershipType');
933 CRM_Utils_Cache
::singleton()->flush();
935 return $result['id'];
939 * @param array $params
943 public function contactMembershipCreate($params) {
944 $params = array_merge(array(
945 'join_date' => '2007-01-21',
946 'start_date' => '2007-01-21',
947 'end_date' => '2007-12-21',
948 'source' => 'Payment',
949 'membership_type_id' => 'General',
951 if (!is_numeric($params['membership_type_id'])) {
952 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
953 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
954 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
958 $result = $this->callAPISuccess('Membership', 'create', $params);
959 return $result['id'];
963 * Delete Membership Type.
965 * @param array $params
967 public function membershipTypeDelete($params) {
968 $this->callAPISuccess('MembershipType', 'Delete', $params);
972 * @param int $membershipID
974 public function membershipDelete($membershipID) {
975 $deleteParams = array('id' => $membershipID);
976 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
980 * @param string $name
984 public function membershipStatusCreate($name = 'test member status') {
985 $params['name'] = $name;
986 $params['start_event'] = 'start_date';
987 $params['end_event'] = 'end_date';
988 $params['is_current_member'] = 1;
989 $params['is_active'] = 1;
991 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
992 CRM_Member_PseudoConstant
::flush('membershipStatus');
993 return $result['id'];
997 * @param int $membershipStatusID
999 public function membershipStatusDelete($membershipStatusID) {
1000 if (!$membershipStatusID) {
1003 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1006 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
1007 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
1008 $renewedMembershipEndDate = new DateTime($membershipEndDate);
1009 switch ($durationUnit) {
1011 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
1015 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
1016 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
1017 $renewedMembershipEndDate->add(new DateInterval('P1D'));
1018 $renewedMembershipEndDate->add(new DateInterval('P1M'));
1019 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
1022 return $renewedMembershipEndDate->format('Y-m-d');
1026 * @param array $params
1030 public function relationshipTypeCreate($params = array()) {
1031 $params = array_merge(array(
1032 'name_a_b' => 'Relation 1 for relationship type create',
1033 'name_b_a' => 'Relation 2 for relationship type create',
1034 'contact_type_a' => 'Individual',
1035 'contact_type_b' => 'Organization',
1042 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1043 CRM_Core_PseudoConstant
::flush('relationshipType');
1045 return $result['id'];
1049 * Delete Relatinship Type.
1051 * @param int $relationshipTypeID
1053 public function relationshipTypeDelete($relationshipTypeID) {
1054 $params['id'] = $relationshipTypeID;
1055 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1056 if (!empty($check['count'])) {
1057 $this->callAPISuccess('relationship_type', 'delete', $params);
1062 * @param array $params
1066 public function paymentProcessorTypeCreate($params = NULL) {
1067 if (is_null($params)) {
1069 'name' => 'API_Test_PP',
1070 'title' => 'API Test Payment Processor',
1071 'class_name' => 'CRM_Core_Payment_APITest',
1072 'billing_mode' => 'form',
1078 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1080 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1082 return $result['id'];
1086 * Create test Authorize.net instance.
1088 * @param array $params
1092 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1093 $params = array_merge(array(
1094 'name' => 'Authorize',
1095 'domain_id' => CRM_Core_Config
::domainID(),
1096 'payment_processor_type_id' => 'AuthNet',
1097 'title' => 'AuthNet',
1102 'user_name' => '4y5BfuW7jm',
1103 'password' => '4cAmW927n8uLf5J8',
1104 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1105 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1106 'class_name' => 'Payment_AuthorizeNet',
1107 'billing_mode' => 1,
1110 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1111 return $result['id'];
1115 * Create Participant.
1117 * @param array $params
1118 * Array of contact id and event id values.
1121 * $id of participant created
1123 public function participantCreate($params = []) {
1124 if (empty($params['contact_id'])) {
1125 $params['contact_id'] = $this->individualCreate();
1127 if (empty($params['event_id'])) {
1128 $event = $this->eventCreate();
1129 $params['event_id'] = $event['id'];
1134 'register_date' => 20070219,
1135 'source' => 'Wimbeldon',
1136 'event_level' => 'Payment',
1140 $params = array_merge($defaults, $params);
1141 $result = $this->callAPISuccess('Participant', 'create', $params);
1142 return $result['id'];
1146 * Create Payment Processor.
1149 * Id Payment Processor
1151 public function processorCreate($params = array()) {
1152 $processorParams = array(
1155 'payment_processor_type_id' => 'Dummy',
1156 'financial_account_id' => 12,
1160 'url_site' => 'http://dummy.com',
1161 'url_recur' => 'http://dummy.com',
1162 'billing_mode' => 1,
1164 'payment_instrument_id' => 'Debit Card',
1166 $processorParams = array_merge($processorParams, $params);
1167 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1168 return $processor['id'];
1172 * Create Payment Processor.
1174 * @param array $processorParams
1176 * @return \CRM_Core_Payment_Dummy
1177 * Instance of Dummy Payment Processor
1179 public function dummyProcessorCreate($processorParams = array()) {
1180 $paymentProcessorID = $this->processorCreate($processorParams);
1181 return System
::singleton()->getById($paymentProcessorID);
1185 * Create contribution page.
1187 * @param array $params
1189 * Array of contribution page
1191 public function contributionPageCreate($params = array()) {
1192 $this->_pageParams
= array_merge(array(
1193 'title' => 'Test Contribution Page',
1194 'financial_type_id' => 1,
1195 'currency' => 'USD',
1196 'financial_account_id' => 1,
1198 'is_allow_other_amount' => 1,
1200 'max_amount' => 1000,
1202 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1206 * Create a sample batch.
1208 public function batchCreate() {
1209 $params = $this->_params
;
1210 $params['name'] = $params['title'] = 'Batch_433397';
1211 $params['status_id'] = 1;
1212 $result = $this->callAPISuccess('batch', 'create', $params);
1213 return $result['id'];
1219 * @param array $params
1221 * result of created tag
1223 public function tagCreate($params = array()) {
1225 'name' => 'New Tag3',
1226 'description' => 'This is description for Our New Tag ',
1229 $params = array_merge($defaults, $params);
1230 $result = $this->callAPISuccess('Tag', 'create', $params);
1231 return $result['values'][$result['id']];
1238 * Id of the tag to be deleted.
1242 public function tagDelete($tagId) {
1243 require_once 'api/api.php';
1247 $result = $this->callAPISuccess('Tag', 'delete', $params);
1248 return $result['id'];
1252 * Add entity(s) to the tag
1254 * @param array $params
1258 public function entityTagAdd($params) {
1259 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1266 * @param array $params
1270 * id of created pledge
1272 public function pledgeCreate($params) {
1273 $params = array_merge(array(
1274 'pledge_create_date' => date('Ymd'),
1275 'start_date' => date('Ymd'),
1276 'scheduled_date' => date('Ymd'),
1278 'pledge_status_id' => '2',
1279 'financial_type_id' => '1',
1280 'pledge_original_installment_amount' => 20,
1281 'frequency_interval' => 5,
1282 'frequency_unit' => 'year',
1283 'frequency_day' => 15,
1284 'installments' => 5,
1288 $result = $this->callAPISuccess('Pledge', 'create', $params);
1289 return $result['id'];
1293 * Delete contribution.
1295 * @param int $pledgeId
1297 public function pledgeDelete($pledgeId) {
1299 'pledge_id' => $pledgeId,
1301 $this->callAPISuccess('Pledge', 'delete', $params);
1305 * Create contribution.
1307 * @param array $params
1308 * Array of parameters.
1311 * id of created contribution
1313 public function contributionCreate($params) {
1315 $params = array_merge(array(
1317 'receive_date' => date('Ymd'),
1318 'total_amount' => 100.00,
1319 'fee_amount' => 5.00,
1320 'financial_type_id' => 1,
1321 'payment_instrument_id' => 1,
1322 'non_deductible_amount' => 10.00,
1324 'contribution_status_id' => 1,
1327 $result = $this->callAPISuccess('contribution', 'create', $params);
1328 return $result['id'];
1332 * Delete contribution.
1334 * @param int $contributionId
1338 public function contributionDelete($contributionId) {
1340 'contribution_id' => $contributionId,
1342 $result = $this->callAPISuccess('contribution', 'delete', $params);
1349 * @param array $params
1350 * Name-value pair for an event.
1354 public function eventCreate($params = array()) {
1355 // if no contact was passed, make up a dummy event creator
1356 if (!isset($params['contact_id'])) {
1357 $params['contact_id'] = $this->_contactCreate(array(
1358 'contact_type' => 'Individual',
1359 'first_name' => 'Event',
1360 'last_name' => 'Creator',
1364 // set defaults for missing params
1365 $params = array_merge(array(
1366 'title' => 'Annual CiviCRM meet',
1367 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1368 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1369 'event_type_id' => 1,
1371 'start_date' => 20081021,
1372 'end_date' => 20081023,
1373 'is_online_registration' => 1,
1374 'registration_start_date' => 20080601,
1375 'registration_end_date' => 20081015,
1376 'max_participants' => 100,
1377 'event_full_text' => 'Sorry! We are already full',
1380 'is_show_location' => 0,
1383 return $this->callAPISuccess('Event', 'create', $params);
1387 * Create a paid event.
1389 * @param array $params
1393 protected function eventCreatePaid($params) {
1394 $event = $this->eventCreate($params);
1395 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1396 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1397 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1398 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1399 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1411 public function eventDelete($id) {
1415 return $this->callAPISuccess('event', 'delete', $params);
1419 * Delete participant.
1421 * @param int $participantID
1425 public function participantDelete($participantID) {
1427 'id' => $participantID,
1429 $check = $this->callAPISuccess('Participant', 'get', $params);
1430 if ($check['count'] > 0) {
1431 return $this->callAPISuccess('Participant', 'delete', $params);
1436 * Create participant payment.
1438 * @param int $participantID
1439 * @param int $contributionID
1441 * $id of created payment
1443 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1444 //Create Participant Payment record With Values
1446 'participant_id' => $participantID,
1447 'contribution_id' => $contributionID,
1450 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1451 return $result['id'];
1455 * Delete participant payment.
1457 * @param int $paymentID
1459 public function participantPaymentDelete($paymentID) {
1463 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1469 * @param int $contactID
1471 * location id of created location
1473 public function locationAdd($contactID) {
1476 'location_type' => 'New Location Type',
1478 'name' => 'Saint Helier St',
1479 'county' => 'Marin',
1480 'country' => 'UNITED STATES',
1481 'state_province' => 'Michigan',
1482 'supplemental_address_1' => 'Hallmark Ct',
1483 'supplemental_address_2' => 'Jersey Village',
1484 'supplemental_address_3' => 'My Town',
1489 'contact_id' => $contactID,
1490 'address' => $address,
1491 'location_format' => '2.0',
1492 'location_type' => 'New Location Type',
1495 $result = $this->callAPISuccess('Location', 'create', $params);
1500 * Delete Locations of contact.
1502 * @param array $params
1505 public function locationDelete($params) {
1506 $this->callAPISuccess('Location', 'delete', $params);
1510 * Add a Location Type.
1512 * @param array $params
1513 * @return CRM_Core_DAO_LocationType
1514 * location id of created location
1516 public function locationTypeCreate($params = NULL) {
1517 if ($params === NULL) {
1519 'name' => 'New Location Type',
1520 'vcard_name' => 'New Location Type',
1521 'description' => 'Location Type for Delete',
1526 $locationType = new CRM_Core_DAO_LocationType();
1527 $locationType->copyValues($params);
1528 $locationType->save();
1529 // clear getfields cache
1530 CRM_Core_PseudoConstant
::flush();
1531 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1532 return $locationType;
1536 * Delete a Location Type.
1538 * @param int $locationTypeId
1540 public function locationTypeDelete($locationTypeId) {
1541 $locationType = new CRM_Core_DAO_LocationType();
1542 $locationType->id
= $locationTypeId;
1543 $locationType->delete();
1549 * @param array $params
1550 * @return CRM_Core_DAO_Mapping
1551 * Mapping id of created mapping
1553 public function mappingCreate($params = NULL) {
1554 if ($params === NULL) {
1556 'name' => 'Mapping name',
1557 'description' => 'Mapping description',
1558 // 'Export Contact' mapping.
1559 'mapping_type_id' => 7,
1563 $mapping = new CRM_Core_DAO_Mapping();
1564 $mapping->copyValues($params);
1566 // clear getfields cache
1567 CRM_Core_PseudoConstant
::flush();
1568 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1575 * @param int $mappingId
1577 public function mappingDelete($mappingId) {
1578 $mapping = new CRM_Core_DAO_Mapping();
1579 $mapping->id
= $mappingId;
1586 * @param array $params
1588 * groupId of created group
1590 public function groupCreate($params = array()) {
1591 $params = array_merge(array(
1592 'name' => 'Test Group 1',
1594 'title' => 'New Test Group Created',
1595 'description' => 'New Test Group Created',
1597 'visibility' => 'Public Pages',
1598 'group_type' => array(
1604 $result = $this->callAPISuccess('Group', 'create', $params);
1605 return $result['id'];
1609 * Prepare class for ACLs.
1611 protected function prepareForACLs() {
1612 $config = CRM_Core_Config
::singleton();
1613 $config->userPermissionClass
->permissions
= array();
1619 protected function cleanUpAfterACLs() {
1620 CRM_Utils_Hook
::singleton()->reset();
1621 $tablesToTruncate = array(
1623 'civicrm_acl_cache',
1624 'civicrm_acl_entity_role',
1625 'civicrm_acl_contact_cache',
1627 $this->quickCleanup($tablesToTruncate);
1628 $config = CRM_Core_Config
::singleton();
1629 unset($config->userPermissionClass
->permissions
);
1632 * Create a smart group.
1634 * By default it will be a group of households.
1636 * @param array $smartGroupParams
1637 * @param array $groupParams
1640 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1641 $smartGroupParams = array_merge(array(
1642 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1645 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1647 $groupParams['saved_search_id'] = $savedSearch->id
;
1648 return $this->groupCreate($groupParams);
1652 * Function to add a Group.
1654 * @params array to add group
1656 * @param int $groupID
1657 * @param int $totalCount
1658 * @param bool $random
1660 * groupId of created group
1662 public function groupContactCreate($groupID, $totalCount = 10, $random = FALSE) {
1663 $params = array('group_id' => $groupID);
1664 for ($i = 1; $i <= $totalCount; $i++
) {
1665 $contactID = $this->individualCreate(array(), 0, $random);
1667 $params +
= array('contact_id' => $contactID);
1670 $params +
= array("contact_id.$i" => $contactID);
1673 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1683 public function groupDelete($gid) {
1689 $this->callAPISuccess('Group', 'delete', $params);
1694 * @param array $params
1696 public function uFFieldCreate($params = array()) {
1697 $params = array_merge(array(
1699 'field_name' => 'first_name',
1702 'visibility' => 'Public Pages and Listings',
1703 'is_searchable' => '1',
1704 'label' => 'first_name',
1705 'field_type' => 'Individual',
1708 $this->callAPISuccess('uf_field', 'create', $params);
1712 * Add a UF Join Entry.
1714 * @param array $params
1716 * $id of created UF Join
1718 public function ufjoinCreate($params = NULL) {
1719 if ($params === NULL) {
1722 'module' => 'CiviEvent',
1723 'entity_table' => 'civicrm_event',
1729 $result = $this->callAPISuccess('uf_join', 'create', $params);
1734 * @param array $params
1735 * Optional parameters.
1736 * @param bool $reloadConfig
1737 * While enabling CiviCampaign component, we shouldn't always forcibly
1738 * reload config as this hinder hook call in test environment
1743 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1744 $this->enableCiviCampaign($reloadConfig);
1745 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1746 'name' => 'big_campaign',
1747 'title' => 'Campaign',
1749 return $campaign['id'];
1753 * Create Group for a contact.
1755 * @param int $contactId
1757 public function contactGroupCreate($contactId) {
1759 'contact_id.1' => $contactId,
1763 $this->callAPISuccess('GroupContact', 'Create', $params);
1767 * Delete Group for a contact.
1769 * @param int $contactId
1771 public function contactGroupDelete($contactId) {
1773 'contact_id.1' => $contactId,
1776 $this->civicrm_api('GroupContact', 'Delete', $params);
1782 * @param array $params
1785 public function activityCreate($params = array()) {
1786 $params = array_merge(array(
1787 'subject' => 'Discussion on warm beer',
1788 'activity_date_time' => date('Ymd'),
1789 'duration_hours' => 30,
1790 'duration_minutes' => 20,
1791 'location' => 'Baker Street',
1792 'details' => 'Lets schedule a meeting',
1794 'activity_type_id' => 'Meeting',
1796 if (!isset($params['source_contact_id'])) {
1797 $params['source_contact_id'] = $this->individualCreate();
1799 if (!isset($params['target_contact_id'])) {
1800 $params['target_contact_id'] = $this->individualCreate(array(
1801 'first_name' => 'Julia',
1802 'Last_name' => 'Anderson',
1804 'email' => 'julia_anderson@civicrm.org',
1805 'contact_type' => 'Individual',
1808 if (!isset($params['assignee_contact_id'])) {
1809 $params['assignee_contact_id'] = $params['target_contact_id'];
1812 $result = $this->callAPISuccess('Activity', 'create', $params);
1814 $result['target_contact_id'] = $params['target_contact_id'];
1815 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1820 * Create an activity type.
1822 * @param array $params
1826 public function activityTypeCreate($params) {
1827 return $this->callAPISuccess('ActivityType', 'create', $params);
1831 * Delete activity type.
1833 * @param int $activityTypeId
1834 * Id of the activity type.
1837 public function activityTypeDelete($activityTypeId) {
1838 $params['activity_type_id'] = $activityTypeId;
1839 return $this->callAPISuccess('ActivityType', 'delete', $params);
1843 * Create custom group.
1845 * @param array $params
1848 public function customGroupCreate($params = array()) {
1850 'title' => 'new custom group',
1851 'extends' => 'Contact',
1853 'style' => 'Inline',
1857 $params = array_merge($defaults, $params);
1859 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1860 $this->callAPISuccess('custom_group', 'get', array(
1861 'title' => $params['title'],
1862 array('api.custom_group.delete' => 1),
1865 return $this->callAPISuccess('custom_group', 'create', $params);
1869 * Existing function doesn't allow params to be over-ridden so need a new one
1870 * this one allows you to only pass in the params you want to change
1871 * @param array $params
1874 public function CustomGroupCreateByParams($params = array()) {
1876 'title' => "API Custom Group",
1877 'extends' => 'Contact',
1879 'style' => 'Inline',
1882 $params = array_merge($defaults, $params);
1883 return $this->callAPISuccess('custom_group', 'create', $params);
1887 * Create custom group with multi fields.
1888 * @param array $params
1891 public function CustomGroupMultipleCreateByParams($params = array()) {
1896 $params = array_merge($defaults, $params);
1897 return $this->CustomGroupCreateByParams($params);
1901 * Create custom group with multi fields.
1902 * @param array $params
1905 public function CustomGroupMultipleCreateWithFields($params = array()) {
1906 // also need to pass on $params['custom_field'] if not set but not in place yet
1908 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1909 $ids['custom_group_id'] = $customGroup['id'];
1911 $customField = $this->customFieldCreate(array(
1912 'custom_group_id' => $ids['custom_group_id'],
1913 'label' => 'field_1' . $ids['custom_group_id'],
1917 $ids['custom_field_id'][] = $customField['id'];
1919 $customField = $this->customFieldCreate(array(
1920 'custom_group_id' => $ids['custom_group_id'],
1921 'default_value' => '',
1922 'label' => 'field_2' . $ids['custom_group_id'],
1925 $ids['custom_field_id'][] = $customField['id'];
1927 $customField = $this->customFieldCreate(array(
1928 'custom_group_id' => $ids['custom_group_id'],
1929 'default_value' => '',
1930 'label' => 'field_3' . $ids['custom_group_id'],
1933 $ids['custom_field_id'][] = $customField['id'];
1939 * Create a custom group with a single text custom field. See
1940 * participant:testCreateWithCustom for how to use this
1942 * @param string $function
1944 * @param string $filename
1948 * ids of created objects
1950 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1951 $params = array('title' => $function);
1952 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1953 $params['extends'] = $entity ?
$entity : 'Contact';
1954 $customGroup = $this->CustomGroupCreate($params);
1955 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1956 CRM_Core_PseudoConstant
::flush();
1958 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1962 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1963 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1965 * @param string $function
1967 * @param string $filename
1971 * ids of created objects
1973 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1974 $params = array('title' => $function);
1975 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1976 $params['extends'] = $entity ?
$entity : 'Contact';
1977 $customGroup = $this->CustomGroupCreate($params);
1978 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1979 CRM_Core_PseudoConstant
::flush();
1981 'defaultValue' => 'Default Value',
1982 'lowercasevalue' => 'Lowercase Value',
1983 1 => 'Integer Value',
1986 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1987 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1988 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1989 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1990 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1991 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1992 foreach ($options as $option_value => $option_label) {
1993 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1994 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1997 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);
2002 * Delete custom group.
2004 * @param int $customGroupID
2008 public function customGroupDelete($customGroupID) {
2009 $params['id'] = $customGroupID;
2010 return $this->callAPISuccess('custom_group', 'delete', $params);
2014 * Create custom field.
2016 * @param array $params
2017 * (custom_group_id) is required.
2020 public function customFieldCreate($params) {
2021 $params = array_merge(array(
2022 'label' => 'Custom Field',
2023 'data_type' => 'String',
2024 'html_type' => 'Text',
2025 'is_searchable' => 1,
2027 'default_value' => 'defaultValue',
2030 $result = $this->callAPISuccess('custom_field', 'create', $params);
2031 // these 2 functions are called with force to flush static caches
2032 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2033 CRM_Core_Component
::getEnabledComponents(1);
2038 * Delete custom field.
2040 * @param int $customFieldID
2044 public function customFieldDelete($customFieldID) {
2046 $params['id'] = $customFieldID;
2047 return $this->callAPISuccess('custom_field', 'delete', $params);
2056 public function noteCreate($cId) {
2058 'entity_table' => 'civicrm_contact',
2059 'entity_id' => $cId,
2060 'note' => 'hello I am testing Note',
2061 'contact_id' => $cId,
2062 'modified_date' => date('Ymd'),
2063 'subject' => 'Test Note',
2066 return $this->callAPISuccess('Note', 'create', $params);
2070 * Enable CiviCampaign Component.
2072 * @param bool $reloadConfig
2073 * Force relaod config or not
2075 public function enableCiviCampaign($reloadConfig = TRUE) {
2076 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2077 if ($reloadConfig) {
2078 // force reload of config object
2079 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2081 //flush cache by calling with reset
2082 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2086 * Create custom field with Option Values.
2088 * @param array $customGroup
2089 * @param string $name
2090 * Name of custom field.
2091 * @param array $extraParams
2092 * Additional parameters to pass through.
2096 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2097 $fieldParams = array(
2098 'custom_group_id' => $customGroup['id'],
2099 'name' => 'test_custom_group',
2100 'label' => 'Country',
2101 'html_type' => 'Select',
2102 'data_type' => 'String',
2105 'is_searchable' => 0,
2109 $optionGroup = array(
2111 'name' => 'option_group1',
2112 'label' => 'option_group_label1',
2115 $optionValue = array(
2116 'option_label' => array('Label1', 'Label2'),
2117 'option_value' => array('value1', 'value2'),
2118 'option_name' => array($name . '_1', $name . '_2'),
2119 'option_weight' => array(1, 2),
2120 'option_status' => 1,
2123 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2125 return $this->callAPISuccess('custom_field', 'create', $params);
2133 public function confirmEntitiesDeleted($entities) {
2134 foreach ($entities as $entity) {
2136 $result = $this->callAPISuccess($entity, 'Get', array());
2137 if ($result['error'] == 1 ||
$result['count'] > 0) {
2138 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2146 * Quick clean by emptying tables created for the test.
2148 * @param array $tablesToTruncate
2149 * @param bool $dropCustomValueTables
2150 * @throws \Exception
2152 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2154 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2156 if ($dropCustomValueTables) {
2157 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2158 while ($optionGroupResult->fetch()) {
2159 if (!empty($optionGroupResult->option_group_id
)) {
2160 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2163 $tablesToTruncate[] = 'civicrm_custom_group';
2164 $tablesToTruncate[] = 'civicrm_custom_field';
2167 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2169 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2170 foreach ($tablesToTruncate as $table) {
2171 $sql = "TRUNCATE TABLE $table";
2172 CRM_Core_DAO
::executeQuery($sql);
2174 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2176 if ($dropCustomValueTables) {
2177 $dbName = self
::getDBName();
2179 SELECT TABLE_NAME as tableName
2180 FROM INFORMATION_SCHEMA.TABLES
2181 WHERE TABLE_SCHEMA = '{$dbName}'
2182 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2185 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2186 while ($tableDAO->fetch()) {
2187 $sql = "DROP TABLE {$tableDAO->tableName}";
2188 CRM_Core_DAO
::executeQuery($sql);
2194 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2196 public function quickCleanUpFinancialEntities() {
2197 $tablesToTruncate = array(
2199 'civicrm_activity_contact',
2200 'civicrm_contribution',
2201 'civicrm_contribution_soft',
2202 'civicrm_contribution_product',
2203 'civicrm_financial_trxn',
2204 'civicrm_financial_item',
2205 'civicrm_contribution_recur',
2206 'civicrm_line_item',
2207 'civicrm_contribution_page',
2208 'civicrm_payment_processor',
2209 'civicrm_entity_financial_trxn',
2210 'civicrm_membership',
2211 'civicrm_membership_type',
2212 'civicrm_membership_payment',
2213 'civicrm_membership_log',
2214 'civicrm_membership_block',
2216 'civicrm_participant',
2217 'civicrm_participant_payment',
2219 'civicrm_pledge_payment',
2220 'civicrm_price_set_entity',
2221 'civicrm_price_field_value',
2222 'civicrm_price_field',
2224 $this->quickCleanup($tablesToTruncate);
2225 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2226 $this->restoreDefaultPriceSetConfig();
2228 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2229 $this->disableTaxAndInvoicing();
2230 $this->setCurrencySeparators(',');
2231 CRM_Core_PseudoConstant
::flush('taxRates');
2232 System
::singleton()->flushProcessors();
2235 public function restoreDefaultPriceSetConfig() {
2236 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2237 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2238 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)");
2239 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)");
2242 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2243 * Default behaviour is to also delete the entity
2244 * @param array $params
2245 * Params array to check against.
2247 * Id of the entity concerned.
2248 * @param string $entity
2249 * Name of entity concerned (e.g. membership).
2250 * @param bool $delete
2251 * Should the entity be deleted as part of this check.
2252 * @param string $errorText
2253 * Text to print on error.
2256 * @param array $params
2259 * @param int $delete
2260 * @param string $errorText
2264 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2266 $result = $this->callAPISuccessGetSingle($entity, array(
2271 $this->callAPISuccess($entity, 'Delete', array(
2275 $dateFields = $keys = $dateTimeFields = array();
2276 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2277 foreach ($fields['values'] as $field => $settings) {
2278 if (array_key_exists($field, $result)) {
2279 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2282 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2284 $type = CRM_Utils_Array
::value('type', $settings);
2285 if ($type == CRM_Utils_Type
::T_DATE
) {
2286 $dateFields[] = $settings['name'];
2287 // we should identify both real names & unique names as dates
2288 if ($field != $settings['name']) {
2289 $dateFields[] = $field;
2292 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2293 $dateTimeFields[] = $settings['name'];
2294 // we should identify both real names & unique names as dates
2295 if ($field != $settings['name']) {
2296 $dateTimeFields[] = $field;
2301 if (strtolower($entity) == 'contribution') {
2302 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2303 // this is not returned in id format
2304 unset($params['payment_instrument_id']);
2305 $params['contribution_source'] = $params['source'];
2306 unset($params['source']);
2309 foreach ($params as $key => $value) {
2310 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2313 if (in_array($key, $dateFields)) {
2314 $value = date('Y-m-d', strtotime($value));
2315 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2317 if (in_array($key, $dateTimeFields)) {
2318 $value = date('Y-m-d H:i:s', strtotime($value));
2319 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2321 $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);
2326 * Get formatted values in the actual and expected result.
2327 * @param array $actual
2328 * Actual calculated values.
2329 * @param array $expected
2332 public function checkArrayEquals(&$actual, &$expected) {
2333 self
::unsetId($actual);
2334 self
::unsetId($expected);
2335 $this->assertEquals($actual, $expected);
2339 * Unset the key 'id' from the array
2340 * @param array $unformattedArray
2341 * The array from which the 'id' has to be unset.
2343 public static function unsetId(&$unformattedArray) {
2344 $formattedArray = array();
2345 if (array_key_exists('id', $unformattedArray)) {
2346 unset($unformattedArray['id']);
2348 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2349 foreach ($unformattedArray['values'] as $key => $value) {
2350 if (is_array($value)) {
2351 foreach ($value as $k => $v) {
2357 elseif ($key == 'id') {
2358 $unformattedArray[$key];
2360 $formattedArray = array($value);
2362 $unformattedArray['values'] = $formattedArray;
2367 * Helper to enable/disable custom directory support
2369 * @param array $customDirs
2371 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2372 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2374 public function customDirectories($customDirs) {
2375 $config = CRM_Core_Config
::singleton();
2377 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2378 unset($config->customPHPPathDir
);
2380 elseif ($customDirs['php_path'] === TRUE) {
2381 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2384 $config->customPHPPathDir
= $php_path;
2387 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2388 unset($config->customTemplateDir
);
2390 elseif ($customDirs['template_path'] === TRUE) {
2391 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2394 $config->customTemplateDir
= $template_path;
2399 * Generate a temporary folder.
2401 * @param string $prefix
2404 public function createTempDir($prefix = 'test-') {
2405 $tempDir = CRM_Utils_File
::tempdir($prefix);
2406 $this->tempDirs
[] = $tempDir;
2410 public function cleanTempDirs() {
2411 if (!is_array($this->tempDirs
)) {
2412 // fix test errors where this is not set
2415 foreach ($this->tempDirs
as $tempDir) {
2416 if (is_dir($tempDir)) {
2417 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2423 * Temporarily replace the singleton extension with a different one.
2424 * @param \CRM_Extension_System $system
2426 public function setExtensionSystem(CRM_Extension_System
$system) {
2427 if ($this->origExtensionSystem
== NULL) {
2428 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2430 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2433 public function unsetExtensionSystem() {
2434 if ($this->origExtensionSystem
!== NULL) {
2435 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2436 $this->origExtensionSystem
= NULL;
2441 * Temporarily alter the settings-metadata to add a mock setting.
2443 * WARNING: The setting metadata will disappear on the next cache-clear.
2448 public function setMockSettingsMetaData($extras) {
2449 Civi
::service('settings_manager')->flush();
2451 CRM_Utils_Hook
::singleton()
2452 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2453 $metadata = array_merge($metadata, $extras);
2456 $fields = $this->callAPISuccess('setting', 'getfields', array());
2457 foreach ($extras as $key => $spec) {
2458 $this->assertNotEmpty($spec['title']);
2459 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2464 * @param string $name
2466 public function financialAccountDelete($name) {
2467 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2468 $financialAccount->name
= $name;
2469 if ($financialAccount->find(TRUE)) {
2470 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2471 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2472 $entityFinancialType->delete();
2473 $financialAccount->delete();
2478 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2479 * (NB unclear if this is still required)
2481 public function _sethtmlGlobals() {
2482 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2483 'required' => array(
2484 'html_quickform_rule_required',
2485 'HTML/QuickForm/Rule/Required.php',
2487 'maxlength' => array(
2488 'html_quickform_rule_range',
2489 'HTML/QuickForm/Rule/Range.php',
2491 'minlength' => array(
2492 'html_quickform_rule_range',
2493 'HTML/QuickForm/Rule/Range.php',
2495 'rangelength' => array(
2496 'html_quickform_rule_range',
2497 'HTML/QuickForm/Rule/Range.php',
2500 'html_quickform_rule_email',
2501 'HTML/QuickForm/Rule/Email.php',
2504 'html_quickform_rule_regex',
2505 'HTML/QuickForm/Rule/Regex.php',
2507 'lettersonly' => array(
2508 'html_quickform_rule_regex',
2509 'HTML/QuickForm/Rule/Regex.php',
2511 'alphanumeric' => array(
2512 'html_quickform_rule_regex',
2513 'HTML/QuickForm/Rule/Regex.php',
2516 'html_quickform_rule_regex',
2517 'HTML/QuickForm/Rule/Regex.php',
2519 'nopunctuation' => array(
2520 'html_quickform_rule_regex',
2521 'HTML/QuickForm/Rule/Regex.php',
2524 'html_quickform_rule_regex',
2525 'HTML/QuickForm/Rule/Regex.php',
2527 'callback' => array(
2528 'html_quickform_rule_callback',
2529 'HTML/QuickForm/Rule/Callback.php',
2532 'html_quickform_rule_compare',
2533 'HTML/QuickForm/Rule/Compare.php',
2536 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2537 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2539 'HTML/QuickForm/group.php',
2540 'HTML_QuickForm_group',
2543 'HTML/QuickForm/hidden.php',
2544 'HTML_QuickForm_hidden',
2547 'HTML/QuickForm/reset.php',
2548 'HTML_QuickForm_reset',
2550 'checkbox' => array(
2551 'HTML/QuickForm/checkbox.php',
2552 'HTML_QuickForm_checkbox',
2555 'HTML/QuickForm/file.php',
2556 'HTML_QuickForm_file',
2559 'HTML/QuickForm/image.php',
2560 'HTML_QuickForm_image',
2562 'password' => array(
2563 'HTML/QuickForm/password.php',
2564 'HTML_QuickForm_password',
2567 'HTML/QuickForm/radio.php',
2568 'HTML_QuickForm_radio',
2571 'HTML/QuickForm/button.php',
2572 'HTML_QuickForm_button',
2575 'HTML/QuickForm/submit.php',
2576 'HTML_QuickForm_submit',
2579 'HTML/QuickForm/select.php',
2580 'HTML_QuickForm_select',
2582 'hiddenselect' => array(
2583 'HTML/QuickForm/hiddenselect.php',
2584 'HTML_QuickForm_hiddenselect',
2587 'HTML/QuickForm/text.php',
2588 'HTML_QuickForm_text',
2590 'textarea' => array(
2591 'HTML/QuickForm/textarea.php',
2592 'HTML_QuickForm_textarea',
2594 'fckeditor' => array(
2595 'HTML/QuickForm/fckeditor.php',
2596 'HTML_QuickForm_FCKEditor',
2599 'HTML/QuickForm/tinymce.php',
2600 'HTML_QuickForm_TinyMCE',
2602 'dojoeditor' => array(
2603 'HTML/QuickForm/dojoeditor.php',
2604 'HTML_QuickForm_dojoeditor',
2607 'HTML/QuickForm/link.php',
2608 'HTML_QuickForm_link',
2610 'advcheckbox' => array(
2611 'HTML/QuickForm/advcheckbox.php',
2612 'HTML_QuickForm_advcheckbox',
2615 'HTML/QuickForm/date.php',
2616 'HTML_QuickForm_date',
2619 'HTML/QuickForm/static.php',
2620 'HTML_QuickForm_static',
2623 'HTML/QuickForm/header.php',
2624 'HTML_QuickForm_header',
2627 'HTML/QuickForm/html.php',
2628 'HTML_QuickForm_html',
2630 'hierselect' => array(
2631 'HTML/QuickForm/hierselect.php',
2632 'HTML_QuickForm_hierselect',
2634 'autocomplete' => array(
2635 'HTML/QuickForm/autocomplete.php',
2636 'HTML_QuickForm_autocomplete',
2639 'HTML/QuickForm/xbutton.php',
2640 'HTML_QuickForm_xbutton',
2642 'advmultiselect' => array(
2643 'HTML/QuickForm/advmultiselect.php',
2644 'HTML_QuickForm_advmultiselect',
2650 * Set up an acl allowing contact to see 2 specified groups
2651 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2653 * You need to have pre-created these groups & created the user e.g
2654 * $this->createLoggedInUser();
2655 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2656 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2658 * @param bool $isProfile
2660 public function setupACL($isProfile = FALSE) {
2662 $_REQUEST = $this->_params
;
2664 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2665 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2666 $ov = new CRM_Core_DAO_OptionValue();
2667 $ov->option_group_id
= $optionGroupID;
2669 if ($ov->find(TRUE)) {
2670 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2672 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2673 'option_group_id' => $optionGroupID,
2674 'label' => 'pick me',
2678 CRM_Core_DAO
::executeQuery("
2679 TRUNCATE civicrm_acl_cache
2682 CRM_Core_DAO
::executeQuery("
2683 TRUNCATE civicrm_acl_contact_cache
2686 CRM_Core_DAO
::executeQuery("
2687 INSERT INTO civicrm_acl_entity_role (
2688 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2689 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2693 CRM_Core_DAO
::executeQuery("
2694 INSERT INTO civicrm_acl (
2695 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2698 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2703 CRM_Core_DAO
::executeQuery("
2704 INSERT INTO civicrm_acl (
2705 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2708 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2712 CRM_Core_DAO
::executeQuery("
2713 INSERT INTO civicrm_acl (
2714 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2717 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2722 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2723 $this->callAPISuccess('group_contact', 'create', array(
2724 'group_id' => $this->_permissionedGroup
,
2725 'contact_id' => $this->_loggedInUser
,
2730 CRM_ACL_BAO_Cache
::resetCache();
2731 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2736 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2738 public function offsetDefaultPriceSet() {
2739 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2740 $firstID = $contributionPriceSet['id'];
2741 $this->callAPISuccess('price_set', 'create', array(
2742 'id' => $contributionPriceSet['id'],
2746 unset($contributionPriceSet['id']);
2747 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2748 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2749 'price_set_id' => $firstID,
2750 'options' => array('limit' => 1),
2752 unset($priceField['id']);
2753 $priceField['price_set_id'] = $newPriceSet['id'];
2754 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2755 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2756 'price_set_id' => $firstID,
2758 'options' => array('limit' => 1),
2761 unset($priceFieldValue['id']);
2762 //create some padding to use up ids
2763 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2764 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2765 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2769 * Create an instance of the paypal processor.
2770 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2771 * this parent class & we don't have a structure for that yet
2772 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2773 * & the best protection against that is the functions this class affords
2774 * @param array $params
2775 * @return int $result['id'] payment processor id
2777 public function paymentProcessorCreate($params = array()) {
2778 $params = array_merge(array(
2780 'domain_id' => CRM_Core_Config
::domainID(),
2781 'payment_processor_type_id' => 'PayPal',
2785 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2786 'password' => '1183377788',
2787 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2788 'url_site' => 'https://www.sandbox.paypal.com/',
2789 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2790 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2791 'class_name' => 'Payment_PayPalImpl',
2792 'billing_mode' => 3,
2793 'financial_type_id' => 1,
2794 'financial_account_id' => 12,
2795 // Credit card = 1 so can pass 'by accident'.
2796 'payment_instrument_id' => 'Debit Card',
2799 if (!is_numeric($params['payment_processor_type_id'])) {
2800 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2802 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2803 'name' => $params['payment_processor_type_id'],
2807 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2808 return $result['id'];
2812 * Set up initial recurring payment allowing subsequent IPN payments.
2814 * @param array $recurParams (Optional)
2815 * @param array $contributionParams (Optional)
2817 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2818 $contributionParams = array_merge([
2819 'total_amount' => '200',
2820 'invoice_id' => $this->_invoiceID
,
2821 'financial_type_id' => 'Donation',
2822 'contribution_status_id' => 'Pending',
2823 'contact_id' => $this->_contactID
,
2824 'contribution_page_id' => $this->_contributionPageID
,
2825 'payment_processor_id' => $this->_paymentProcessorID
,
2827 'skipCleanMoney' => TRUE,
2831 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2832 'contact_id' => $this->_contactID
,
2835 'installments' => 5,
2836 'frequency_unit' => 'Month',
2837 'frequency_interval' => 1,
2838 'invoice_id' => $this->_invoiceID
,
2839 'contribution_status_id' => 2,
2840 'payment_processor_id' => $this->_paymentProcessorID
,
2841 // processor provided ID - use contact ID as proxy.
2842 'processor_id' => $this->_contactID
,
2843 'api.contribution.create' => $contributionParams,
2845 $this->_contributionRecurID
= $contributionRecur['id'];
2846 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2850 * 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
2852 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2854 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2855 $membershipParams = $recurParams = array();
2856 if (!empty($params['duration_unit'])) {
2857 $membershipParams['duration_unit'] = $params['duration_unit'];
2859 if (!empty($params['frequency_unit'])) {
2860 $recurParams['frequency_unit'] = $params['frequency_unit'];
2863 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2864 //create a contribution so our membership & contribution don't both have id = 1
2865 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2866 $this->contributionCreate(array(
2867 'contact_id' => $this->_contactID
,
2869 'financial_type_id' => 1,
2870 'invoice_id' => 'abcd',
2874 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2876 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2877 'contact_id' => $this->_contactID
,
2878 'membership_type_id' => $this->ids
['membership_type'],
2879 'contribution_recur_id' => $this->_contributionRecurID
,
2880 'format.only_id' => TRUE,
2882 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2883 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2885 $this->callAPISuccess('line_item', 'create', array(
2886 'entity_table' => 'civicrm_membership',
2887 'entity_id' => $this->ids
['membership'],
2888 'contribution_id' => $this->_contributionID
,
2889 'label' => 'General',
2891 'unit_price' => 200,
2892 'line_total' => 200,
2893 'financial_type_id' => 1,
2894 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2896 'label' => 'Membership Amount',
2897 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2899 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2901 'label' => 'General',
2902 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2905 $this->callAPISuccess('membership_payment', 'create', array(
2906 'contribution_id' => $this->_contributionID
,
2907 'membership_id' => $this->ids
['membership'],
2916 public function CiviUnitTestCase_fatalErrorHandler($message) {
2917 throw new Exception("{$message['message']}: {$message['code']}");
2921 * Helper function to create new mailing.
2923 * @param array $params
2927 public function createMailing($params = array()) {
2928 $params = array_merge(array(
2929 'subject' => 'maild' . rand(),
2930 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2931 'name' => 'mailing name' . rand(),
2935 $result = $this->callAPISuccess('Mailing', 'create', $params);
2936 return $result['id'];
2940 * Helper function to delete mailing.
2943 public function deleteMailing($id) {
2948 $this->callAPISuccess('Mailing', 'delete', $params);
2952 * Wrap the entire test case in a transaction.
2954 * Only subsequent DB statements will be wrapped in TX -- this cannot
2955 * retroactively wrap old DB statements. Therefore, it makes sense to
2956 * call this at the beginning of setUp().
2958 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2959 * this option does not work with, e.g., custom-data.
2961 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2962 * if TRUNCATE or ALTER is called while using a transaction.
2965 * Whether to use nesting or reference-counting.
2967 public function useTransaction($nest = TRUE) {
2969 $this->tx
= new CRM_Core_Transaction($nest);
2970 $this->tx
->rollback();
2975 * Assert the attachment exists.
2977 * @param bool $exists
2978 * @param array $apiResult
2980 protected function assertAttachmentExistence($exists, $apiResult) {
2981 $fileId = $apiResult['id'];
2982 $this->assertTrue(is_numeric($fileId));
2983 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2984 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2985 1 => array($fileId, 'Int'),
2987 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2988 1 => array($fileId, 'Int'),
2993 * Create a price set for an event.
2995 * @param int $feeTotal
2996 * @param int $minAmt
2997 * @param string $type
3002 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3003 // creating price set, price field
3004 $paramsSet['title'] = 'Price Set';
3005 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3006 $paramsSet['is_active'] = FALSE;
3007 $paramsSet['extends'] = 1;
3008 $paramsSet['min_amount'] = $minAmt;
3010 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
3011 $this->_ids
['price_set'] = $priceSet->id
;
3013 $paramsField = array(
3014 'label' => 'Price Field',
3015 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3016 'html_type' => $type,
3017 'price' => $feeTotal,
3018 'option_label' => array('1' => 'Price Field'),
3019 'option_value' => array('1' => $feeTotal),
3020 'option_name' => array('1' => $feeTotal),
3021 'option_weight' => array('1' => 1),
3022 'option_amount' => array('1' => 1),
3023 'is_display_amounts' => 1,
3025 'options_per_line' => 1,
3026 'is_active' => array('1' => 1),
3027 'price_set_id' => $this->_ids
['price_set'],
3028 'is_enter_qty' => 1,
3029 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3031 if ($type === 'Radio') {
3032 $paramsField['is_enter_qty'] = 0;
3033 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3034 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3036 CRM_Price_BAO_PriceField
::create($paramsField);
3037 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
3038 $this->_ids
['price_field'] = array_keys($fields['values']);
3039 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
3040 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
3042 return $this->_ids
['price_set'];
3046 * Add a profile to a contribution page.
3048 * @param string $name
3049 * @param int $contributionPageID
3050 * @param string $module
3052 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
3054 'uf_group_id' => $name,
3055 'module' => $module,
3056 'entity_table' => 'civicrm_contribution_page',
3057 'entity_id' => $contributionPageID,
3060 if ($module !== 'CiviContribute') {
3061 $params['module_data'] = [$module => []];
3063 $this->callAPISuccess('UFJoin', 'create', $params);
3067 * Add participant with contribution
3071 protected function createParticipantWithContribution() {
3072 // creating price set, price field
3073 $this->_contactId
= $this->individualCreate();
3074 $event = $this->eventCreate();
3075 $this->_eventId
= $event['id'];
3076 $eventParams = array(
3077 'id' => $this->_eventId
,
3078 'financial_type_id' => 4,
3081 $this->callAPISuccess('event', 'create', $eventParams);
3082 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3083 $participantParams = array(
3084 'financial_type_id' => 4,
3085 'event_id' => $this->_eventId
,
3088 'fee_currency' => 'USD',
3089 'contact_id' => $this->_contactId
,
3091 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3092 $contributionParams = array(
3093 'total_amount' => 150,
3094 'currency' => 'USD',
3095 'contact_id' => $this->_contactId
,
3096 'financial_type_id' => 4,
3097 'contribution_status_id' => 1,
3098 'partial_payment_total' => 300.00,
3099 'partial_amount_to_pay' => 150,
3100 'contribution_mode' => 'participant',
3101 'participant_id' => $participant['id'],
3103 foreach ($priceFields['values'] as $key => $priceField) {
3104 $lineItems[1][$key] = array(
3105 'price_field_id' => $priceField['price_field_id'],
3106 'price_field_value_id' => $priceField['id'],
3107 'label' => $priceField['label'],
3108 'field_title' => $priceField['label'],
3110 'unit_price' => $priceField['amount'],
3111 'line_total' => $priceField['amount'],
3112 'financial_type_id' => $priceField['financial_type_id'],
3115 $contributionParams['line_item'] = $lineItems;
3116 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3117 $paymentParticipant = array(
3118 'participant_id' => $participant['id'],
3119 'contribution_id' => $contribution['id'],
3121 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3122 return array($lineItems, $contribution);
3128 * @param string $component
3129 * @param int $componentId
3133 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3134 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3135 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3136 $paramsSet['is_active'] = TRUE;
3137 $paramsSet['financial_type_id'] = 'Event Fee';
3138 $paramsSet['extends'] = 1;
3139 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3140 $priceSetId = $priceSet['id'];
3141 //Checking for priceset added in the table.
3142 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3143 'id', $paramsSet['title'], 'Check DB for created priceset'
3145 $paramsField = array_merge(array(
3146 'label' => 'Price Field',
3147 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3148 'html_type' => 'CheckBox',
3149 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3150 'option_value' => array('1' => 100, '2' => 200),
3151 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3152 'option_weight' => array('1' => 1, '2' => 2),
3153 'option_amount' => array('1' => 100, '2' => 200),
3154 'is_display_amounts' => 1,
3156 'options_per_line' => 1,
3157 'is_active' => array('1' => 1, '2' => 1),
3158 'price_set_id' => $priceSet['id'],
3159 'is_enter_qty' => 1,
3160 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3161 ), $priceFieldOptions);
3163 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3165 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3167 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3171 * Replace the template with a test-oriented template designed to show all the variables.
3173 * @param string $templateName
3175 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3176 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3177 CRM_Core_DAO
::executeQuery(
3178 "UPDATE civicrm_option_group og
3179 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3180 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3181 SET m.msg_html = '{$testTemplate}'
3182 WHERE og.name = 'msg_tpl_workflow_contribution'
3183 AND ov.name = '{$templateName}'
3184 AND m.is_default = 1"
3189 * Reinstate the default template.
3191 * @param string $templateName
3193 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3194 CRM_Core_DAO
::executeQuery(
3195 "UPDATE civicrm_option_group og
3196 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3197 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3198 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3199 SET m.msg_html = m2.msg_html
3200 WHERE og.name = 'msg_tpl_workflow_contribution'
3201 AND ov.name = '{$templateName}'
3202 AND m.is_default = 1"
3207 * Flush statics relating to financial type.
3209 protected function flushFinancialTypeStatics() {
3210 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3211 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3213 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3214 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3216 CRM_Contribute_PseudoConstant
::flush('financialType');
3217 CRM_Contribute_PseudoConstant
::flush('membershipType');
3218 // Pseudoconstants may be saved to the cache table.
3219 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3220 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3221 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3225 * Set the permissions to the supplied array.
3227 * @param array $permissions
3229 protected function setPermissions($permissions) {
3230 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3231 $this->flushFinancialTypeStatics();
3235 * @param array $params
3238 public function _checkFinancialRecords($params, $context) {
3239 $entityParams = array(
3240 'entity_id' => $params['id'],
3241 'entity_table' => 'civicrm_contribution',
3243 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3244 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3245 if ($context == 'pending') {
3246 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3247 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3250 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3251 $trxnParams = array(
3252 'id' => $trxn['financial_trxn_id'],
3254 if ($context != 'online' && $context != 'payLater') {
3255 $compareParams = array(
3256 'to_financial_account_id' => 6,
3257 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3261 if ($context == 'feeAmount') {
3262 $compareParams['fee_amount'] = 50;
3264 elseif ($context == 'online') {
3265 $compareParams = array(
3266 'to_financial_account_id' => 12,
3267 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3269 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3272 elseif ($context == 'payLater') {
3273 $compareParams = array(
3274 'to_financial_account_id' => 7,
3275 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3279 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3280 $entityParams = array(
3281 'financial_trxn_id' => $trxn['financial_trxn_id'],
3282 'entity_table' => 'civicrm_financial_item',
3284 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3285 $fitemParams = array(
3286 'id' => $entityTrxn['entity_id'],
3288 $compareParams = array(
3289 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3291 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3293 if ($context == 'payLater') {
3294 $compareParams = array(
3295 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3297 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3300 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3301 if ($context == 'feeAmount') {
3303 'entity_id' => $params['id'],
3304 'entity_table' => 'civicrm_contribution',
3306 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3307 $trxnParams = array(
3308 'id' => $maxTrxn['financial_trxn_id'],
3310 $compareParams = array(
3311 'to_financial_account_id' => 5,
3312 'from_financial_account_id' => 6,
3313 'total_amount' => 50,
3316 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3317 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3318 $fitemParams = array(
3319 'entity_id' => $trxnId['financialTrxnId'],
3320 'entity_table' => 'civicrm_financial_trxn',
3322 $compareParams = array(
3325 'financial_account_id' => 5,
3327 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3329 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3330 // line should be copied into all the functions that call this function & evaluated there
3331 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3332 // when calling completeTransaction or repeatTransaction.
3333 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3337 * Return financial type id on basis of name
3339 * @param string $name Financial type m/c name
3343 public function getFinancialTypeId($name) {
3344 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3348 * Cleanup function for contents of $this->ids.
3350 * This is a best effort cleanup to use in tear downs etc.
3352 * It will not fail if the data has already been removed (some tests may do
3353 * their own cleanup).
3355 protected function cleanUpSetUpIDs() {
3356 foreach ($this->setupIDs
as $entity => $id) {
3358 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3360 catch (CiviCRM_API3_Exception
$e) {
3361 // This is a best-effort cleanup function, ignore.
3367 * Create Financial Type.
3369 * @param array $params
3373 protected function createFinancialType($params = array()) {
3374 $params = array_merge($params,
3376 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3380 return $this->callAPISuccess('FinancialType', 'create', $params);
3384 * Create Payment Instrument.
3386 * @param array $params
3387 * @param string $financialAccountName
3391 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
3392 $params = array_merge(array(
3393 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
3394 'option_group_id' => 'payment_instrument',
3399 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
3401 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3403 $financialAccountParams = [
3404 'entity_table' => 'civicrm_option_value',
3405 'entity_id' => $newPaymentInstrument,
3406 'account_relationship' => $relationTypeID,
3407 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
3409 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
3411 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
3415 * Enable Tax and Invoicing
3417 protected function enableTaxAndInvoicing($params = array()) {
3418 // Enable component contribute setting
3419 $contributeSetting = array_merge($params,
3422 'invoice_prefix' => 'INV_',
3423 'credit_notes_prefix' => 'CN_',
3425 'due_date_period' => 'days',
3427 'is_email_pdf' => 1,
3428 'tax_term' => 'Sales Tax',
3429 'tax_display_settings' => 'Inclusive',
3432 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3436 * Enable Tax and Invoicing
3438 protected function disableTaxAndInvoicing($params = array()) {
3439 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3440 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3442 // Enable component contribute setting
3443 $contributeSetting = array_merge($params,
3448 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3452 * Add Sales Tax relation for financial type with financial account.
3454 * @param int $financialTypeId
3458 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3460 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3461 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3462 'is_deductible' => 1,
3467 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3468 $entityParams = array(
3469 'entity_table' => 'civicrm_financial_type',
3470 'entity_id' => $financialTypeId,
3471 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3474 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3475 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3477 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3478 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3479 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3480 $dao->copyValues($entityParams);
3482 if ($dao->fetch()) {
3483 $entityParams['id'] = $dao->id
;
3485 $entityParams['financial_account_id'] = $account->id
;
3487 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3491 * Create price set with contribution test for test setup.
3493 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3494 * on parent class at some point (fn is not in 4.4).
3497 * @param array $params
3499 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3500 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3501 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3502 'title' => "Test Contribution Page",
3503 'financial_type_id' => 1,
3504 'currency' => 'NZD',
3505 'goal_amount' => 50,
3506 'is_pay_later' => 1,
3507 'is_monetary' => TRUE,
3508 'is_email_receipt' => FALSE,
3510 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3511 'is_quick_config' => 0,
3512 'extends' => 'CiviMember',
3513 'financial_type_id' => 1,
3514 'title' => 'my Page',
3516 $priceSetID = $priceSet['id'];
3518 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3519 $priceField = $this->callAPISuccess('price_field', 'create', array(
3520 'price_set_id' => $priceSetID,
3521 'label' => 'Goat Breed',
3522 'html_type' => 'Radio',
3524 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3525 'price_set_id' => $priceSetID,
3526 'price_field_id' => $priceField['id'],
3527 'label' => 'Long Haired Goat',
3529 'financial_type_id' => 'Donation',
3530 'membership_type_id' => $membershipTypeID,
3531 'membership_num_terms' => 1,
3534 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3535 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3536 'price_set_id' => $priceSetID,
3537 'price_field_id' => $priceField['id'],
3538 'label' => 'Shoe-eating Goat',
3540 'financial_type_id' => 'Donation',
3541 'membership_type_id' => $membershipTypeID,
3542 'membership_num_terms' => 2,
3545 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3547 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3548 'price_set_id' => $priceSetID,
3549 'price_field_id' => $priceField['id'],
3550 'label' => 'Shoe-eating Goat',
3552 'financial_type_id' => 'Donation',
3555 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3557 $this->_ids
['price_set'] = $priceSetID;
3558 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3559 $this->_ids
['price_field'] = array($priceField['id']);
3561 $this->_ids
['membership_type'] = $membershipTypeID;
3565 * Only specified contact returned.
3566 * @implements CRM_Utils_Hook::aclWhereClause
3569 * @param $whereTables
3573 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3574 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3578 * @implements CRM_Utils_Hook::selectWhereClause
3580 * @param string $entity
3581 * @param array $clauses
3583 public function selectWhereClauseHook($entity, &$clauses) {
3584 if ($entity == 'Event') {
3585 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3590 * An implementation of hook_civicrm_post used with all our test cases.
3593 * @param string $objectName
3594 * @param int $objectId
3597 public function onPost($op, $objectName, $objectId, &$objectRef) {
3598 if ($op == 'create' && $objectName == 'Individual') {
3599 CRM_Core_DAO
::executeQuery(
3600 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3602 1 => array($objectId, 'Integer'),
3607 if ($op == 'edit' && $objectName == 'Participant') {
3609 1 => array($objectId, 'Integer'),
3611 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3612 CRM_Core_DAO
::executeQuery($query, $params);
3618 * Instantiate form object.
3620 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3622 * @param string $class
3623 * Name of form class.
3625 * @return \CRM_Core_Form
3627 public function getFormObject($class) {
3628 $form = new $class();
3629 $_SERVER['REQUEST_METHOD'] = 'GET';
3630 $form->controller
= new CRM_Core_Controller();
3635 * Get possible thousand separators.
3639 public function getThousandSeparators() {
3640 return array(array('.'), array(','));
3644 * Set the separators for thousands and decimal points.
3646 * @param string $thousandSeparator
3648 protected function setCurrencySeparators($thousandSeparator) {
3649 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3651 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3655 * Format money as it would be input.
3657 * @param string $amount
3661 protected function formatMoneyInput($amount) {
3662 return CRM_Utils_Money
::format($amount, NULL, '%a');
3667 * Get the contribution object.
3669 * @param int $contributionID
3671 * @return \CRM_Contribute_BAO_Contribution
3673 protected function getContributionObject($contributionID) {
3674 $contributionObj = new CRM_Contribute_BAO_Contribution();
3675 $contributionObj->id
= $contributionID;
3676 $contributionObj->find(TRUE);
3677 return $contributionObj;
3681 * Enable multilingual.
3683 public function enableMultilingual() {
3684 $this->callAPISuccess('Setting', 'create', array(
3685 'lcMessages' => 'en_US',
3686 'languageLimit' => array(
3691 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3694 $dbLocale = '_en_US';