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',
1985 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1986 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1987 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1988 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1989 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1990 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1991 foreach ($options as $option_value => $option_label) {
1992 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1993 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1996 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);
2001 * Delete custom group.
2003 * @param int $customGroupID
2007 public function customGroupDelete($customGroupID) {
2008 $params['id'] = $customGroupID;
2009 return $this->callAPISuccess('custom_group', 'delete', $params);
2013 * Create custom field.
2015 * @param array $params
2016 * (custom_group_id) is required.
2019 public function customFieldCreate($params) {
2020 $params = array_merge(array(
2021 'label' => 'Custom Field',
2022 'data_type' => 'String',
2023 'html_type' => 'Text',
2024 'is_searchable' => 1,
2026 'default_value' => 'defaultValue',
2029 $result = $this->callAPISuccess('custom_field', 'create', $params);
2030 // these 2 functions are called with force to flush static caches
2031 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2032 CRM_Core_Component
::getEnabledComponents(1);
2037 * Delete custom field.
2039 * @param int $customFieldID
2043 public function customFieldDelete($customFieldID) {
2045 $params['id'] = $customFieldID;
2046 return $this->callAPISuccess('custom_field', 'delete', $params);
2055 public function noteCreate($cId) {
2057 'entity_table' => 'civicrm_contact',
2058 'entity_id' => $cId,
2059 'note' => 'hello I am testing Note',
2060 'contact_id' => $cId,
2061 'modified_date' => date('Ymd'),
2062 'subject' => 'Test Note',
2065 return $this->callAPISuccess('Note', 'create', $params);
2069 * Enable CiviCampaign Component.
2071 * @param bool $reloadConfig
2072 * Force relaod config or not
2074 public function enableCiviCampaign($reloadConfig = TRUE) {
2075 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2076 if ($reloadConfig) {
2077 // force reload of config object
2078 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2080 //flush cache by calling with reset
2081 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2085 * Create custom field with Option Values.
2087 * @param array $customGroup
2088 * @param string $name
2089 * Name of custom field.
2090 * @param array $extraParams
2091 * Additional parameters to pass through.
2095 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2096 $fieldParams = array(
2097 'custom_group_id' => $customGroup['id'],
2098 'name' => 'test_custom_group',
2099 'label' => 'Country',
2100 'html_type' => 'Select',
2101 'data_type' => 'String',
2104 'is_searchable' => 0,
2108 $optionGroup = array(
2110 'name' => 'option_group1',
2111 'label' => 'option_group_label1',
2114 $optionValue = array(
2115 'option_label' => array('Label1', 'Label2'),
2116 'option_value' => array('value1', 'value2'),
2117 'option_name' => array($name . '_1', $name . '_2'),
2118 'option_weight' => array(1, 2),
2119 'option_status' => 1,
2122 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2124 return $this->callAPISuccess('custom_field', 'create', $params);
2132 public function confirmEntitiesDeleted($entities) {
2133 foreach ($entities as $entity) {
2135 $result = $this->callAPISuccess($entity, 'Get', array());
2136 if ($result['error'] == 1 ||
$result['count'] > 0) {
2137 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2145 * Quick clean by emptying tables created for the test.
2147 * @param array $tablesToTruncate
2148 * @param bool $dropCustomValueTables
2149 * @throws \Exception
2151 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2153 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2155 if ($dropCustomValueTables) {
2156 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2157 while ($optionGroupResult->fetch()) {
2158 if (!empty($optionGroupResult->option_group_id
)) {
2159 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2162 $tablesToTruncate[] = 'civicrm_custom_group';
2163 $tablesToTruncate[] = 'civicrm_custom_field';
2166 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2168 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2169 foreach ($tablesToTruncate as $table) {
2170 $sql = "TRUNCATE TABLE $table";
2171 CRM_Core_DAO
::executeQuery($sql);
2173 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2175 if ($dropCustomValueTables) {
2176 $dbName = self
::getDBName();
2178 SELECT TABLE_NAME as tableName
2179 FROM INFORMATION_SCHEMA.TABLES
2180 WHERE TABLE_SCHEMA = '{$dbName}'
2181 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2184 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2185 while ($tableDAO->fetch()) {
2186 $sql = "DROP TABLE {$tableDAO->tableName}";
2187 CRM_Core_DAO
::executeQuery($sql);
2193 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2195 public function quickCleanUpFinancialEntities() {
2196 $tablesToTruncate = array(
2198 'civicrm_activity_contact',
2199 'civicrm_contribution',
2200 'civicrm_contribution_soft',
2201 'civicrm_contribution_product',
2202 'civicrm_financial_trxn',
2203 'civicrm_financial_item',
2204 'civicrm_contribution_recur',
2205 'civicrm_line_item',
2206 'civicrm_contribution_page',
2207 'civicrm_payment_processor',
2208 'civicrm_entity_financial_trxn',
2209 'civicrm_membership',
2210 'civicrm_membership_type',
2211 'civicrm_membership_payment',
2212 'civicrm_membership_log',
2213 'civicrm_membership_block',
2215 'civicrm_participant',
2216 'civicrm_participant_payment',
2218 'civicrm_pledge_payment',
2219 'civicrm_price_set_entity',
2220 'civicrm_price_field_value',
2221 'civicrm_price_field',
2223 $this->quickCleanup($tablesToTruncate);
2224 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2225 $this->restoreDefaultPriceSetConfig();
2227 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2228 $this->disableTaxAndInvoicing();
2229 $this->setCurrencySeparators(',');
2230 CRM_Core_PseudoConstant
::flush('taxRates');
2231 System
::singleton()->flushProcessors();
2234 public function restoreDefaultPriceSetConfig() {
2235 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2236 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2237 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)");
2238 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)");
2241 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2242 * Default behaviour is to also delete the entity
2243 * @param array $params
2244 * Params array to check against.
2246 * Id of the entity concerned.
2247 * @param string $entity
2248 * Name of entity concerned (e.g. membership).
2249 * @param bool $delete
2250 * Should the entity be deleted as part of this check.
2251 * @param string $errorText
2252 * Text to print on error.
2255 * @param array $params
2258 * @param int $delete
2259 * @param string $errorText
2263 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2265 $result = $this->callAPISuccessGetSingle($entity, array(
2270 $this->callAPISuccess($entity, 'Delete', array(
2274 $dateFields = $keys = $dateTimeFields = array();
2275 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2276 foreach ($fields['values'] as $field => $settings) {
2277 if (array_key_exists($field, $result)) {
2278 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2281 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2283 $type = CRM_Utils_Array
::value('type', $settings);
2284 if ($type == CRM_Utils_Type
::T_DATE
) {
2285 $dateFields[] = $settings['name'];
2286 // we should identify both real names & unique names as dates
2287 if ($field != $settings['name']) {
2288 $dateFields[] = $field;
2291 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2292 $dateTimeFields[] = $settings['name'];
2293 // we should identify both real names & unique names as dates
2294 if ($field != $settings['name']) {
2295 $dateTimeFields[] = $field;
2300 if (strtolower($entity) == 'contribution') {
2301 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2302 // this is not returned in id format
2303 unset($params['payment_instrument_id']);
2304 $params['contribution_source'] = $params['source'];
2305 unset($params['source']);
2308 foreach ($params as $key => $value) {
2309 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2312 if (in_array($key, $dateFields)) {
2313 $value = date('Y-m-d', strtotime($value));
2314 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2316 if (in_array($key, $dateTimeFields)) {
2317 $value = date('Y-m-d H:i:s', strtotime($value));
2318 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2320 $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);
2325 * Get formatted values in the actual and expected result.
2326 * @param array $actual
2327 * Actual calculated values.
2328 * @param array $expected
2331 public function checkArrayEquals(&$actual, &$expected) {
2332 self
::unsetId($actual);
2333 self
::unsetId($expected);
2334 $this->assertEquals($actual, $expected);
2338 * Unset the key 'id' from the array
2339 * @param array $unformattedArray
2340 * The array from which the 'id' has to be unset.
2342 public static function unsetId(&$unformattedArray) {
2343 $formattedArray = array();
2344 if (array_key_exists('id', $unformattedArray)) {
2345 unset($unformattedArray['id']);
2347 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2348 foreach ($unformattedArray['values'] as $key => $value) {
2349 if (is_array($value)) {
2350 foreach ($value as $k => $v) {
2356 elseif ($key == 'id') {
2357 $unformattedArray[$key];
2359 $formattedArray = array($value);
2361 $unformattedArray['values'] = $formattedArray;
2366 * Helper to enable/disable custom directory support
2368 * @param array $customDirs
2370 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2371 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2373 public function customDirectories($customDirs) {
2374 $config = CRM_Core_Config
::singleton();
2376 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2377 unset($config->customPHPPathDir
);
2379 elseif ($customDirs['php_path'] === TRUE) {
2380 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2383 $config->customPHPPathDir
= $php_path;
2386 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2387 unset($config->customTemplateDir
);
2389 elseif ($customDirs['template_path'] === TRUE) {
2390 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2393 $config->customTemplateDir
= $template_path;
2398 * Generate a temporary folder.
2400 * @param string $prefix
2403 public function createTempDir($prefix = 'test-') {
2404 $tempDir = CRM_Utils_File
::tempdir($prefix);
2405 $this->tempDirs
[] = $tempDir;
2409 public function cleanTempDirs() {
2410 if (!is_array($this->tempDirs
)) {
2411 // fix test errors where this is not set
2414 foreach ($this->tempDirs
as $tempDir) {
2415 if (is_dir($tempDir)) {
2416 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2422 * Temporarily replace the singleton extension with a different one.
2423 * @param \CRM_Extension_System $system
2425 public function setExtensionSystem(CRM_Extension_System
$system) {
2426 if ($this->origExtensionSystem
== NULL) {
2427 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2429 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2432 public function unsetExtensionSystem() {
2433 if ($this->origExtensionSystem
!== NULL) {
2434 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2435 $this->origExtensionSystem
= NULL;
2440 * Temporarily alter the settings-metadata to add a mock setting.
2442 * WARNING: The setting metadata will disappear on the next cache-clear.
2447 public function setMockSettingsMetaData($extras) {
2448 Civi
::service('settings_manager')->flush();
2450 CRM_Utils_Hook
::singleton()
2451 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2452 $metadata = array_merge($metadata, $extras);
2455 $fields = $this->callAPISuccess('setting', 'getfields', array());
2456 foreach ($extras as $key => $spec) {
2457 $this->assertNotEmpty($spec['title']);
2458 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2463 * @param string $name
2465 public function financialAccountDelete($name) {
2466 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2467 $financialAccount->name
= $name;
2468 if ($financialAccount->find(TRUE)) {
2469 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2470 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2471 $entityFinancialType->delete();
2472 $financialAccount->delete();
2477 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2478 * (NB unclear if this is still required)
2480 public function _sethtmlGlobals() {
2481 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2482 'required' => array(
2483 'html_quickform_rule_required',
2484 'HTML/QuickForm/Rule/Required.php',
2486 'maxlength' => array(
2487 'html_quickform_rule_range',
2488 'HTML/QuickForm/Rule/Range.php',
2490 'minlength' => array(
2491 'html_quickform_rule_range',
2492 'HTML/QuickForm/Rule/Range.php',
2494 'rangelength' => array(
2495 'html_quickform_rule_range',
2496 'HTML/QuickForm/Rule/Range.php',
2499 'html_quickform_rule_email',
2500 'HTML/QuickForm/Rule/Email.php',
2503 'html_quickform_rule_regex',
2504 'HTML/QuickForm/Rule/Regex.php',
2506 'lettersonly' => array(
2507 'html_quickform_rule_regex',
2508 'HTML/QuickForm/Rule/Regex.php',
2510 'alphanumeric' => array(
2511 'html_quickform_rule_regex',
2512 'HTML/QuickForm/Rule/Regex.php',
2515 'html_quickform_rule_regex',
2516 'HTML/QuickForm/Rule/Regex.php',
2518 'nopunctuation' => array(
2519 'html_quickform_rule_regex',
2520 'HTML/QuickForm/Rule/Regex.php',
2523 'html_quickform_rule_regex',
2524 'HTML/QuickForm/Rule/Regex.php',
2526 'callback' => array(
2527 'html_quickform_rule_callback',
2528 'HTML/QuickForm/Rule/Callback.php',
2531 'html_quickform_rule_compare',
2532 'HTML/QuickForm/Rule/Compare.php',
2535 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2536 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2538 'HTML/QuickForm/group.php',
2539 'HTML_QuickForm_group',
2542 'HTML/QuickForm/hidden.php',
2543 'HTML_QuickForm_hidden',
2546 'HTML/QuickForm/reset.php',
2547 'HTML_QuickForm_reset',
2549 'checkbox' => array(
2550 'HTML/QuickForm/checkbox.php',
2551 'HTML_QuickForm_checkbox',
2554 'HTML/QuickForm/file.php',
2555 'HTML_QuickForm_file',
2558 'HTML/QuickForm/image.php',
2559 'HTML_QuickForm_image',
2561 'password' => array(
2562 'HTML/QuickForm/password.php',
2563 'HTML_QuickForm_password',
2566 'HTML/QuickForm/radio.php',
2567 'HTML_QuickForm_radio',
2570 'HTML/QuickForm/button.php',
2571 'HTML_QuickForm_button',
2574 'HTML/QuickForm/submit.php',
2575 'HTML_QuickForm_submit',
2578 'HTML/QuickForm/select.php',
2579 'HTML_QuickForm_select',
2581 'hiddenselect' => array(
2582 'HTML/QuickForm/hiddenselect.php',
2583 'HTML_QuickForm_hiddenselect',
2586 'HTML/QuickForm/text.php',
2587 'HTML_QuickForm_text',
2589 'textarea' => array(
2590 'HTML/QuickForm/textarea.php',
2591 'HTML_QuickForm_textarea',
2593 'fckeditor' => array(
2594 'HTML/QuickForm/fckeditor.php',
2595 'HTML_QuickForm_FCKEditor',
2598 'HTML/QuickForm/tinymce.php',
2599 'HTML_QuickForm_TinyMCE',
2601 'dojoeditor' => array(
2602 'HTML/QuickForm/dojoeditor.php',
2603 'HTML_QuickForm_dojoeditor',
2606 'HTML/QuickForm/link.php',
2607 'HTML_QuickForm_link',
2609 'advcheckbox' => array(
2610 'HTML/QuickForm/advcheckbox.php',
2611 'HTML_QuickForm_advcheckbox',
2614 'HTML/QuickForm/date.php',
2615 'HTML_QuickForm_date',
2618 'HTML/QuickForm/static.php',
2619 'HTML_QuickForm_static',
2622 'HTML/QuickForm/header.php',
2623 'HTML_QuickForm_header',
2626 'HTML/QuickForm/html.php',
2627 'HTML_QuickForm_html',
2629 'hierselect' => array(
2630 'HTML/QuickForm/hierselect.php',
2631 'HTML_QuickForm_hierselect',
2633 'autocomplete' => array(
2634 'HTML/QuickForm/autocomplete.php',
2635 'HTML_QuickForm_autocomplete',
2638 'HTML/QuickForm/xbutton.php',
2639 'HTML_QuickForm_xbutton',
2641 'advmultiselect' => array(
2642 'HTML/QuickForm/advmultiselect.php',
2643 'HTML_QuickForm_advmultiselect',
2649 * Set up an acl allowing contact to see 2 specified groups
2650 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2652 * You need to have pre-created these groups & created the user e.g
2653 * $this->createLoggedInUser();
2654 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2655 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2657 * @param bool $isProfile
2659 public function setupACL($isProfile = FALSE) {
2661 $_REQUEST = $this->_params
;
2663 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2664 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2665 $ov = new CRM_Core_DAO_OptionValue();
2666 $ov->option_group_id
= $optionGroupID;
2668 if ($ov->find(TRUE)) {
2669 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2671 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2672 'option_group_id' => $optionGroupID,
2673 'label' => 'pick me',
2677 CRM_Core_DAO
::executeQuery("
2678 TRUNCATE civicrm_acl_cache
2681 CRM_Core_DAO
::executeQuery("
2682 TRUNCATE civicrm_acl_contact_cache
2685 CRM_Core_DAO
::executeQuery("
2686 INSERT INTO civicrm_acl_entity_role (
2687 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2688 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2692 CRM_Core_DAO
::executeQuery("
2693 INSERT INTO civicrm_acl (
2694 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2697 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2702 CRM_Core_DAO
::executeQuery("
2703 INSERT INTO civicrm_acl (
2704 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2707 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2711 CRM_Core_DAO
::executeQuery("
2712 INSERT INTO civicrm_acl (
2713 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2716 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2721 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2722 $this->callAPISuccess('group_contact', 'create', array(
2723 'group_id' => $this->_permissionedGroup
,
2724 'contact_id' => $this->_loggedInUser
,
2729 CRM_ACL_BAO_Cache
::resetCache();
2730 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2735 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2737 public function offsetDefaultPriceSet() {
2738 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2739 $firstID = $contributionPriceSet['id'];
2740 $this->callAPISuccess('price_set', 'create', array(
2741 'id' => $contributionPriceSet['id'],
2745 unset($contributionPriceSet['id']);
2746 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2747 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2748 'price_set_id' => $firstID,
2749 'options' => array('limit' => 1),
2751 unset($priceField['id']);
2752 $priceField['price_set_id'] = $newPriceSet['id'];
2753 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2754 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2755 'price_set_id' => $firstID,
2757 'options' => array('limit' => 1),
2760 unset($priceFieldValue['id']);
2761 //create some padding to use up ids
2762 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2763 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2764 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2768 * Create an instance of the paypal processor.
2769 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2770 * this parent class & we don't have a structure for that yet
2771 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2772 * & the best protection against that is the functions this class affords
2773 * @param array $params
2774 * @return int $result['id'] payment processor id
2776 public function paymentProcessorCreate($params = array()) {
2777 $params = array_merge(array(
2779 'domain_id' => CRM_Core_Config
::domainID(),
2780 'payment_processor_type_id' => 'PayPal',
2784 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2785 'password' => '1183377788',
2786 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2787 'url_site' => 'https://www.sandbox.paypal.com/',
2788 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2789 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2790 'class_name' => 'Payment_PayPalImpl',
2791 'billing_mode' => 3,
2792 'financial_type_id' => 1,
2793 'financial_account_id' => 12,
2794 // Credit card = 1 so can pass 'by accident'.
2795 'payment_instrument_id' => 'Debit Card',
2798 if (!is_numeric($params['payment_processor_type_id'])) {
2799 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2801 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2802 'name' => $params['payment_processor_type_id'],
2806 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2807 return $result['id'];
2811 * Set up initial recurring payment allowing subsequent IPN payments.
2813 * @param array $recurParams (Optional)
2814 * @param array $contributionParams (Optional)
2816 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2817 $contributionParams = array_merge([
2818 'total_amount' => '200',
2819 'invoice_id' => $this->_invoiceID
,
2820 'financial_type_id' => 'Donation',
2821 'contribution_status_id' => 'Pending',
2822 'contact_id' => $this->_contactID
,
2823 'contribution_page_id' => $this->_contributionPageID
,
2824 'payment_processor_id' => $this->_paymentProcessorID
,
2826 'skipCleanMoney' => TRUE,
2830 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2831 'contact_id' => $this->_contactID
,
2834 'installments' => 5,
2835 'frequency_unit' => 'Month',
2836 'frequency_interval' => 1,
2837 'invoice_id' => $this->_invoiceID
,
2838 'contribution_status_id' => 2,
2839 'payment_processor_id' => $this->_paymentProcessorID
,
2840 // processor provided ID - use contact ID as proxy.
2841 'processor_id' => $this->_contactID
,
2842 'api.contribution.create' => $contributionParams,
2844 $this->_contributionRecurID
= $contributionRecur['id'];
2845 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2849 * 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
2851 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2853 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2854 $membershipParams = $recurParams = array();
2855 if (!empty($params['duration_unit'])) {
2856 $membershipParams['duration_unit'] = $params['duration_unit'];
2858 if (!empty($params['frequency_unit'])) {
2859 $recurParams['frequency_unit'] = $params['frequency_unit'];
2862 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2863 //create a contribution so our membership & contribution don't both have id = 1
2864 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2865 $this->contributionCreate(array(
2866 'contact_id' => $this->_contactID
,
2868 'financial_type_id' => 1,
2869 'invoice_id' => 'abcd',
2873 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2875 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2876 'contact_id' => $this->_contactID
,
2877 'membership_type_id' => $this->ids
['membership_type'],
2878 'contribution_recur_id' => $this->_contributionRecurID
,
2879 'format.only_id' => TRUE,
2881 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2882 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2884 $this->callAPISuccess('line_item', 'create', array(
2885 'entity_table' => 'civicrm_membership',
2886 'entity_id' => $this->ids
['membership'],
2887 'contribution_id' => $this->_contributionID
,
2888 'label' => 'General',
2890 'unit_price' => 200,
2891 'line_total' => 200,
2892 'financial_type_id' => 1,
2893 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2895 'label' => 'Membership Amount',
2896 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2898 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2900 'label' => 'General',
2901 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2904 $this->callAPISuccess('membership_payment', 'create', array(
2905 'contribution_id' => $this->_contributionID
,
2906 'membership_id' => $this->ids
['membership'],
2915 public function CiviUnitTestCase_fatalErrorHandler($message) {
2916 throw new Exception("{$message['message']}: {$message['code']}");
2920 * Helper function to create new mailing.
2922 * @param array $params
2926 public function createMailing($params = array()) {
2927 $params = array_merge(array(
2928 'subject' => 'maild' . rand(),
2929 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2930 'name' => 'mailing name' . rand(),
2934 $result = $this->callAPISuccess('Mailing', 'create', $params);
2935 return $result['id'];
2939 * Helper function to delete mailing.
2942 public function deleteMailing($id) {
2947 $this->callAPISuccess('Mailing', 'delete', $params);
2951 * Wrap the entire test case in a transaction.
2953 * Only subsequent DB statements will be wrapped in TX -- this cannot
2954 * retroactively wrap old DB statements. Therefore, it makes sense to
2955 * call this at the beginning of setUp().
2957 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2958 * this option does not work with, e.g., custom-data.
2960 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2961 * if TRUNCATE or ALTER is called while using a transaction.
2964 * Whether to use nesting or reference-counting.
2966 public function useTransaction($nest = TRUE) {
2968 $this->tx
= new CRM_Core_Transaction($nest);
2969 $this->tx
->rollback();
2974 * Assert the attachment exists.
2976 * @param bool $exists
2977 * @param array $apiResult
2979 protected function assertAttachmentExistence($exists, $apiResult) {
2980 $fileId = $apiResult['id'];
2981 $this->assertTrue(is_numeric($fileId));
2982 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2983 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2984 1 => array($fileId, 'Int'),
2986 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2987 1 => array($fileId, 'Int'),
2992 * Create a price set for an event.
2994 * @param int $feeTotal
2995 * @param int $minAmt
2996 * @param string $type
3001 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3002 // creating price set, price field
3003 $paramsSet['title'] = 'Price Set';
3004 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3005 $paramsSet['is_active'] = FALSE;
3006 $paramsSet['extends'] = 1;
3007 $paramsSet['min_amount'] = $minAmt;
3009 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
3010 $this->_ids
['price_set'] = $priceSet->id
;
3012 $paramsField = array(
3013 'label' => 'Price Field',
3014 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3015 'html_type' => $type,
3016 'price' => $feeTotal,
3017 'option_label' => array('1' => 'Price Field'),
3018 'option_value' => array('1' => $feeTotal),
3019 'option_name' => array('1' => $feeTotal),
3020 'option_weight' => array('1' => 1),
3021 'option_amount' => array('1' => 1),
3022 'is_display_amounts' => 1,
3024 'options_per_line' => 1,
3025 'is_active' => array('1' => 1),
3026 'price_set_id' => $this->_ids
['price_set'],
3027 'is_enter_qty' => 1,
3028 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3030 if ($type === 'Radio') {
3031 $paramsField['is_enter_qty'] = 0;
3032 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3033 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3035 CRM_Price_BAO_PriceField
::create($paramsField);
3036 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
3037 $this->_ids
['price_field'] = array_keys($fields['values']);
3038 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
3039 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
3041 return $this->_ids
['price_set'];
3045 * Add a profile to a contribution page.
3047 * @param string $name
3048 * @param int $contributionPageID
3049 * @param string $module
3051 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
3053 'uf_group_id' => $name,
3054 'module' => $module,
3055 'entity_table' => 'civicrm_contribution_page',
3056 'entity_id' => $contributionPageID,
3059 if ($module !== 'CiviContribute') {
3060 $params['module_data'] = [$module => []];
3062 $this->callAPISuccess('UFJoin', 'create', $params);
3066 * Add participant with contribution
3070 protected function createParticipantWithContribution() {
3071 // creating price set, price field
3072 $this->_contactId
= $this->individualCreate();
3073 $event = $this->eventCreate();
3074 $this->_eventId
= $event['id'];
3075 $eventParams = array(
3076 'id' => $this->_eventId
,
3077 'financial_type_id' => 4,
3080 $this->callAPISuccess('event', 'create', $eventParams);
3081 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3082 $participantParams = array(
3083 'financial_type_id' => 4,
3084 'event_id' => $this->_eventId
,
3087 'fee_currency' => 'USD',
3088 'contact_id' => $this->_contactId
,
3090 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3091 $contributionParams = array(
3092 'total_amount' => 150,
3093 'currency' => 'USD',
3094 'contact_id' => $this->_contactId
,
3095 'financial_type_id' => 4,
3096 'contribution_status_id' => 1,
3097 'partial_payment_total' => 300.00,
3098 'partial_amount_to_pay' => 150,
3099 'contribution_mode' => 'participant',
3100 'participant_id' => $participant['id'],
3102 foreach ($priceFields['values'] as $key => $priceField) {
3103 $lineItems[1][$key] = array(
3104 'price_field_id' => $priceField['price_field_id'],
3105 'price_field_value_id' => $priceField['id'],
3106 'label' => $priceField['label'],
3107 'field_title' => $priceField['label'],
3109 'unit_price' => $priceField['amount'],
3110 'line_total' => $priceField['amount'],
3111 'financial_type_id' => $priceField['financial_type_id'],
3114 $contributionParams['line_item'] = $lineItems;
3115 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3116 $paymentParticipant = array(
3117 'participant_id' => $participant['id'],
3118 'contribution_id' => $contribution['id'],
3120 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3121 return array($lineItems, $contribution);
3127 * @param string $component
3128 * @param int $componentId
3132 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3133 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3134 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3135 $paramsSet['is_active'] = TRUE;
3136 $paramsSet['financial_type_id'] = 'Event Fee';
3137 $paramsSet['extends'] = 1;
3138 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3139 $priceSetId = $priceSet['id'];
3140 //Checking for priceset added in the table.
3141 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3142 'id', $paramsSet['title'], 'Check DB for created priceset'
3144 $paramsField = array_merge(array(
3145 'label' => 'Price Field',
3146 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3147 'html_type' => 'CheckBox',
3148 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3149 'option_value' => array('1' => 100, '2' => 200),
3150 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3151 'option_weight' => array('1' => 1, '2' => 2),
3152 'option_amount' => array('1' => 100, '2' => 200),
3153 'is_display_amounts' => 1,
3155 'options_per_line' => 1,
3156 'is_active' => array('1' => 1, '2' => 1),
3157 'price_set_id' => $priceSet['id'],
3158 'is_enter_qty' => 1,
3159 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3160 ), $priceFieldOptions);
3162 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3164 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3166 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3170 * Replace the template with a test-oriented template designed to show all the variables.
3172 * @param string $templateName
3174 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3175 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3176 CRM_Core_DAO
::executeQuery(
3177 "UPDATE civicrm_option_group og
3178 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3179 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3180 SET m.msg_html = '{$testTemplate}'
3181 WHERE og.name = 'msg_tpl_workflow_contribution'
3182 AND ov.name = '{$templateName}'
3183 AND m.is_default = 1"
3188 * Reinstate the default template.
3190 * @param string $templateName
3192 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3193 CRM_Core_DAO
::executeQuery(
3194 "UPDATE civicrm_option_group og
3195 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3196 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3197 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3198 SET m.msg_html = m2.msg_html
3199 WHERE og.name = 'msg_tpl_workflow_contribution'
3200 AND ov.name = '{$templateName}'
3201 AND m.is_default = 1"
3206 * Flush statics relating to financial type.
3208 protected function flushFinancialTypeStatics() {
3209 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3210 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3212 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3213 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3215 CRM_Contribute_PseudoConstant
::flush('financialType');
3216 CRM_Contribute_PseudoConstant
::flush('membershipType');
3217 // Pseudoconstants may be saved to the cache table.
3218 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3219 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3220 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3224 * Set the permissions to the supplied array.
3226 * @param array $permissions
3228 protected function setPermissions($permissions) {
3229 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3230 $this->flushFinancialTypeStatics();
3234 * @param array $params
3237 public function _checkFinancialRecords($params, $context) {
3238 $entityParams = array(
3239 'entity_id' => $params['id'],
3240 'entity_table' => 'civicrm_contribution',
3242 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3243 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3244 if ($context == 'pending') {
3245 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3246 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3249 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3250 $trxnParams = array(
3251 'id' => $trxn['financial_trxn_id'],
3253 if ($context != 'online' && $context != 'payLater') {
3254 $compareParams = array(
3255 'to_financial_account_id' => 6,
3256 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3260 if ($context == 'feeAmount') {
3261 $compareParams['fee_amount'] = 50;
3263 elseif ($context == 'online') {
3264 $compareParams = array(
3265 'to_financial_account_id' => 12,
3266 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3268 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3271 elseif ($context == 'payLater') {
3272 $compareParams = array(
3273 'to_financial_account_id' => 7,
3274 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3278 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3279 $entityParams = array(
3280 'financial_trxn_id' => $trxn['financial_trxn_id'],
3281 'entity_table' => 'civicrm_financial_item',
3283 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3284 $fitemParams = array(
3285 'id' => $entityTrxn['entity_id'],
3287 $compareParams = array(
3288 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3290 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3292 if ($context == 'payLater') {
3293 $compareParams = array(
3294 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3296 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3299 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3300 if ($context == 'feeAmount') {
3302 'entity_id' => $params['id'],
3303 'entity_table' => 'civicrm_contribution',
3305 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3306 $trxnParams = array(
3307 'id' => $maxTrxn['financial_trxn_id'],
3309 $compareParams = array(
3310 'to_financial_account_id' => 5,
3311 'from_financial_account_id' => 6,
3312 'total_amount' => 50,
3315 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3316 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3317 $fitemParams = array(
3318 'entity_id' => $trxnId['financialTrxnId'],
3319 'entity_table' => 'civicrm_financial_trxn',
3321 $compareParams = array(
3324 'financial_account_id' => 5,
3326 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3328 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3329 // line should be copied into all the functions that call this function & evaluated there
3330 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3331 // when calling completeTransaction or repeatTransaction.
3332 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3336 * Return financial type id on basis of name
3338 * @param string $name Financial type m/c name
3342 public function getFinancialTypeId($name) {
3343 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3347 * Cleanup function for contents of $this->ids.
3349 * This is a best effort cleanup to use in tear downs etc.
3351 * It will not fail if the data has already been removed (some tests may do
3352 * their own cleanup).
3354 protected function cleanUpSetUpIDs() {
3355 foreach ($this->setupIDs
as $entity => $id) {
3357 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3359 catch (CiviCRM_API3_Exception
$e) {
3360 // This is a best-effort cleanup function, ignore.
3366 * Create Financial Type.
3368 * @param array $params
3372 protected function createFinancialType($params = array()) {
3373 $params = array_merge($params,
3375 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3379 return $this->callAPISuccess('FinancialType', 'create', $params);
3383 * Create Payment Instrument.
3385 * @param array $params
3386 * @param string $financialAccountName
3390 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
3391 $params = array_merge(array(
3392 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
3393 'option_group_id' => 'payment_instrument',
3398 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params);
3400 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3402 $financialAccountParams = [
3403 'entity_table' => 'civicrm_option_value',
3404 'entity_id' => key($newPaymentInstrument),
3405 'account_relationship' => $relationTypeID,
3406 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
3408 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
3410 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
3414 * Enable Tax and Invoicing
3416 protected function enableTaxAndInvoicing($params = array()) {
3417 // Enable component contribute setting
3418 $contributeSetting = array_merge($params,
3421 'invoice_prefix' => 'INV_',
3422 'credit_notes_prefix' => 'CN_',
3424 'due_date_period' => 'days',
3426 'is_email_pdf' => 1,
3427 'tax_term' => 'Sales Tax',
3428 'tax_display_settings' => 'Inclusive',
3431 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3435 * Enable Tax and Invoicing
3437 protected function disableTaxAndInvoicing($params = array()) {
3438 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3439 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3441 // Enable component contribute setting
3442 $contributeSetting = array_merge($params,
3447 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3451 * Add Sales Tax relation for financial type with financial account.
3453 * @param int $financialTypeId
3457 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3459 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3460 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3461 'is_deductible' => 1,
3466 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3467 $entityParams = array(
3468 'entity_table' => 'civicrm_financial_type',
3469 'entity_id' => $financialTypeId,
3470 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3473 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3474 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3476 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3477 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3478 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3479 $dao->copyValues($entityParams);
3481 if ($dao->fetch()) {
3482 $entityParams['id'] = $dao->id
;
3484 $entityParams['financial_account_id'] = $account->id
;
3486 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3490 * Create price set with contribution test for test setup.
3492 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3493 * on parent class at some point (fn is not in 4.4).
3496 * @param array $params
3498 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3499 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3500 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3501 'title' => "Test Contribution Page",
3502 'financial_type_id' => 1,
3503 'currency' => 'NZD',
3504 'goal_amount' => 50,
3505 'is_pay_later' => 1,
3506 'is_monetary' => TRUE,
3507 'is_email_receipt' => FALSE,
3509 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3510 'is_quick_config' => 0,
3511 'extends' => 'CiviMember',
3512 'financial_type_id' => 1,
3513 'title' => 'my Page',
3515 $priceSetID = $priceSet['id'];
3517 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3518 $priceField = $this->callAPISuccess('price_field', 'create', array(
3519 'price_set_id' => $priceSetID,
3520 'label' => 'Goat Breed',
3521 'html_type' => 'Radio',
3523 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3524 'price_set_id' => $priceSetID,
3525 'price_field_id' => $priceField['id'],
3526 'label' => 'Long Haired Goat',
3528 'financial_type_id' => 'Donation',
3529 'membership_type_id' => $membershipTypeID,
3530 'membership_num_terms' => 1,
3533 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3534 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3535 'price_set_id' => $priceSetID,
3536 'price_field_id' => $priceField['id'],
3537 'label' => 'Shoe-eating Goat',
3539 'financial_type_id' => 'Donation',
3540 'membership_type_id' => $membershipTypeID,
3541 'membership_num_terms' => 2,
3544 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3546 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3547 'price_set_id' => $priceSetID,
3548 'price_field_id' => $priceField['id'],
3549 'label' => 'Shoe-eating Goat',
3551 'financial_type_id' => 'Donation',
3554 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3556 $this->_ids
['price_set'] = $priceSetID;
3557 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3558 $this->_ids
['price_field'] = array($priceField['id']);
3560 $this->_ids
['membership_type'] = $membershipTypeID;
3564 * Only specified contact returned.
3565 * @implements CRM_Utils_Hook::aclWhereClause
3568 * @param $whereTables
3572 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3573 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3577 * @implements CRM_Utils_Hook::selectWhereClause
3579 * @param string $entity
3580 * @param array $clauses
3582 public function selectWhereClauseHook($entity, &$clauses) {
3583 if ($entity == 'Event') {
3584 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3589 * An implementation of hook_civicrm_post used with all our test cases.
3592 * @param string $objectName
3593 * @param int $objectId
3596 public function onPost($op, $objectName, $objectId, &$objectRef) {
3597 if ($op == 'create' && $objectName == 'Individual') {
3598 CRM_Core_DAO
::executeQuery(
3599 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3601 1 => array($objectId, 'Integer'),
3606 if ($op == 'edit' && $objectName == 'Participant') {
3608 1 => array($objectId, 'Integer'),
3610 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3611 CRM_Core_DAO
::executeQuery($query, $params);
3617 * Instantiate form object.
3619 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3621 * @param string $class
3622 * Name of form class.
3624 * @return \CRM_Core_Form
3626 public function getFormObject($class) {
3627 $form = new $class();
3628 $_SERVER['REQUEST_METHOD'] = 'GET';
3629 $form->controller
= new CRM_Core_Controller();
3634 * Get possible thousand separators.
3638 public function getThousandSeparators() {
3639 return array(array('.'), array(','));
3643 * Set the separators for thousands and decimal points.
3645 * @param string $thousandSeparator
3647 protected function setCurrencySeparators($thousandSeparator) {
3648 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3650 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3654 * Format money as it would be input.
3656 * @param string $amount
3660 protected function formatMoneyInput($amount) {
3661 return CRM_Utils_Money
::format($amount, NULL, '%a');
3666 * Get the contribution object.
3668 * @param int $contributionID
3670 * @return \CRM_Contribute_BAO_Contribution
3672 protected function getContributionObject($contributionID) {
3673 $contributionObj = new CRM_Contribute_BAO_Contribution();
3674 $contributionObj->id
= $contributionID;
3675 $contributionObj->find(TRUE);
3676 return $contributionObj;
3680 * Enable multilingual.
3682 public function enableMultilingual() {
3683 $this->callAPISuccess('Setting', 'create', array(
3684 'lcMessages' => 'en_US',
3685 'languageLimit' => array(
3690 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3693 $dbLocale = '_en_US';