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
;
57 use \Civi\Test\ContactTestTrait
;
60 * Database has been initialized.
64 private static $dbInit = FALSE;
67 * Database connection.
69 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
78 static protected $_dbName;
81 * Track tables we have modified during a test.
84 protected $_tablesToTruncate = array();
87 * @var array of temporary directory names
92 * @var boolean populateOnce allows to skip db resets in setUp
94 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
95 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
98 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
100 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
102 public static $populateOnce = FALSE;
105 * @var boolean DBResetRequired allows skipping DB reset
106 * in specific test case. If you still need
107 * to reset single test (method) of such case, call
108 * $this->cleanDB() in the first line of this
111 public $DBResetRequired = TRUE;
114 * @var CRM_Core_Transaction|NULL
119 * Class used for hooks during tests.
121 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
123 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
125 * @var CRM_Utils_Hook_UnitTests hookClass
127 public $hookClass = NULL;
130 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
132 protected $_params = array();
135 * @var CRM_Extension_System
137 protected $origExtensionSystem;
140 * Array of IDs created during test setup routine.
142 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
146 public $setupIDs = array();
149 * PHPUnit Mock Method to use.
153 public $mockMethod = 'getMock';
158 * Because we are overriding the parent class constructor, we
159 * need to show the same arguments as exist in the constructor of
160 * PHPUnit_Framework_TestCase, since
161 * PHPUnit_Framework_TestSuite::createTest() creates a
162 * ReflectionClass of the Test class and checks the constructor
163 * of that class to decide how to set up the test.
165 * @param string $name
167 * @param string $dataName
169 public function __construct($name = NULL, array $data = array(), $dataName = '') {
170 parent
::__construct($name, $data, $dataName);
172 // we need full error reporting
173 error_reporting(E_ALL
& ~E_NOTICE
);
175 self
::$_dbName = self
::getDBName();
177 // also load the class loader
178 require_once 'CRM/Core/ClassLoader.php';
179 CRM_Core_ClassLoader
::singleton()->register();
180 if (function_exists('_civix_phpunit_setUp')) {
181 // FIXME: loosen coupling
182 _civix_phpunit_setUp();
184 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
185 $this->mockMethod
= 'createMock';
190 * Override to run the test and assert its state.
193 * @throws \PHPUnit_Framework_IncompleteTest
194 * @throws \PHPUnit_Framework_SkippedTest
196 protected function runTest() {
198 return parent
::runTest();
200 catch (PEAR_Exception
$e) {
201 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
202 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
209 public function requireDBReset() {
210 return $this->DBResetRequired
;
216 public static function getDBName() {
217 static $dbName = NULL;
218 if ($dbName === NULL) {
219 require_once "DB.php";
220 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
221 $dbName = $dsninfo['database'];
227 * Create database connection for this instance.
229 * Initialize the test database if it hasn't been initialized
231 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
233 protected function getConnection() {
234 $dbName = self
::$_dbName;
235 if (!self
::$dbInit) {
236 $dbName = self
::getDBName();
238 // install test database
239 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
241 static::_populateDB(FALSE, $this);
243 self
::$dbInit = TRUE;
246 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
250 * Required implementation of abstract method.
252 protected function getDataSet() {
256 * @param bool $perClass
257 * @param null $object
259 * TRUE if the populate logic runs; FALSE if it is skipped
261 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
262 if (CIVICRM_UF
!== 'UnitTests') {
263 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
266 if ($perClass ||
$object == NULL) {
270 $dbreset = $object->requireDBReset();
273 if (self
::$populateOnce ||
!$dbreset) {
276 self
::$populateOnce = NULL;
278 Civi\Test
::data()->populate();
283 public static function setUpBeforeClass() {
284 static::_populateDB(TRUE);
286 // also set this global hack
287 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
291 * Common setup functions for all unit tests.
293 protected function setUp() {
294 $session = CRM_Core_Session
::singleton();
295 $session->set('userID', NULL);
298 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
299 // Use a temporary file for STDIN
300 $GLOBALS['stdin'] = tmpfile();
301 if ($GLOBALS['stdin'] === FALSE) {
302 echo "Couldn't open temporary file\n";
306 // Get and save a connection to the database
307 $this->_dbconn
= $this->getConnection();
309 // reload database before each test
310 // $this->_populateDB();
312 // "initialize" CiviCRM to avoid problems when running single tests
313 // FIXME: look at it closer in second stage
315 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
316 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
318 // disable any left-over test extensions
319 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
321 // reset all the caches
322 CRM_Utils_System
::flushCache();
324 // initialize the object once db is loaded
327 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
329 // when running unit tests, use mockup user framework
330 $this->hookClass
= CRM_Utils_Hook
::singleton();
332 // Make sure the DB connection is setup properly
333 $config->userSystem
->setMySQLTimeZone();
334 $env = new CRM_Utils_Check_Component_Env();
335 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
337 // clear permissions stub to not check permissions
338 $config->userPermissionClass
->permissions
= NULL;
340 //flush component settings
341 CRM_Core_Component
::getEnabledComponents(TRUE);
343 $_REQUEST = $_GET = $_POST = [];
344 error_reporting(E_ALL
);
346 $this->_sethtmlGlobals();
350 * Read everything from the datasets directory and insert into the db.
352 public function loadAllFixtures() {
353 $fixturesDir = __DIR__
. '/../../fixtures';
355 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
357 $xmlFiles = glob($fixturesDir . '/*.xml');
358 foreach ($xmlFiles as $xmlFixture) {
359 $op = new PHPUnit_Extensions_Database_Operation_Insert();
360 $dataset = $this->createXMLDataSet($xmlFixture);
361 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
362 $op->execute($this->_dbconn
, $dataset);
365 $yamlFiles = glob($fixturesDir . '/*.yaml');
366 foreach ($yamlFiles as $yamlFixture) {
367 $op = new PHPUnit_Extensions_Database_Operation_Insert();
368 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
369 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
370 $op->execute($this->_dbconn
, $dataset);
373 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
377 * Create default domain contacts for the two domains added during test class.
378 * database population.
380 public function createDomainContacts() {
381 $this->organizationCreate();
382 $this->organizationCreate(array('organization_name' => 'Second Domain'));
386 * Common teardown functions for all unit tests.
388 protected function tearDown() {
389 error_reporting(E_ALL
& ~E_NOTICE
);
390 CRM_Utils_Hook
::singleton()->reset();
391 if ($this->hookClass
) {
392 $this->hookClass
->reset();
394 CRM_Core_Session
::singleton()->reset(1);
397 $this->tx
->rollback()->commit();
400 CRM_Core_Transaction
::forceRollbackIfEnabled();
401 \Civi\Core\Transaction\Manager
::singleton(TRUE);
404 CRM_Core_Transaction
::forceRollbackIfEnabled();
405 \Civi\Core\Transaction\Manager
::singleton(TRUE);
407 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
408 $this->quickCleanup($tablesToTruncate);
409 $this->createDomainContacts();
412 $this->cleanTempDirs();
413 $this->unsetExtensionSystem();
417 * Generic function to compare expected values after an api call to retrieved.
420 * @daoName string DAO Name of object we're evaluating.
421 * @id int Id of object
422 * @match array Associative array of field name => expected value. Empty if asserting
423 * that a DELETE occurred
424 * @delete boolean True if we're checking that a DELETE action occurred.
428 * @param bool $delete
429 * @throws \PHPUnit_Framework_AssertionFailedError
431 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
433 // adding this here since developers forget to check for an id
434 // and hence we get the first value in the db
435 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
438 $object = new $daoName();
442 // If we're asserting successful record deletion, make sure object is NOT found.
444 if ($object->find(TRUE)) {
445 $this->fail("Object not deleted by delete operation: $daoName, $id");
450 // Otherwise check matches of DAO field values against expected values in $match.
451 if ($object->find(TRUE)) {
452 $fields = &$object->fields();
453 foreach ($fields as $name => $value) {
454 $dbName = $value['name'];
455 if (isset($match[$name])) {
457 $this->assertEquals($object->$dbName, $match[$name]);
459 elseif (isset($match[$dbName])) {
461 $this->assertEquals($object->$dbName, $match[$dbName]);
466 $this->fail("Could not retrieve object: $daoName, $id");
469 $matchSize = count($match);
470 if ($verifiedCount != $matchSize) {
471 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
476 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
477 * @param string $daoName
478 * @param $searchValue
479 * @param $returnColumn
480 * @param $searchColumn
483 * @return null|string
484 * @throws PHPUnit_Framework_AssertionFailedError
486 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
487 if (empty($searchValue)) {
488 $this->fail("empty value passed to assertDBNotNull");
490 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
491 $this->assertNotNull($value, $message);
497 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
498 * @param string $daoName
499 * @param $searchValue
500 * @param $returnColumn
501 * @param $searchColumn
504 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
505 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
506 $this->assertNull($value, $message);
510 * Request a record from the DB by id. Success if row not found.
511 * @param string $daoName
513 * @param null $message
515 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
516 $message = $message ?
$message : "$daoName (#$id) should not exist";
517 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
518 $this->assertNull($value, $message);
522 * Request a record from the DB by id. Success if row not found.
523 * @param string $daoName
525 * @param null $message
527 public function assertDBRowExist($daoName, $id, $message = NULL) {
528 $message = $message ?
$message : "$daoName (#$id) should exist";
529 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
530 $this->assertEquals($id, $value, $message);
534 * Compare a single column value in a retrieved DB record to an expected value.
535 * @param string $daoName
536 * @param $searchValue
537 * @param $returnColumn
538 * @param $searchColumn
539 * @param $expectedValue
542 public function assertDBCompareValue(
543 $daoName, $searchValue, $returnColumn, $searchColumn,
544 $expectedValue, $message
546 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
547 $this->assertEquals($expectedValue, $value, $message);
551 * Compare all values in a single retrieved DB record to an array of expected values.
552 * @param string $daoName
553 * @param array $searchParams
554 * @param $expectedValues
556 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
557 //get the values from db
559 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
561 // compare db values with expected values
562 self
::assertAttributesEquals($expectedValues, $dbValues);
566 * Assert that a SQL query returns a given value.
568 * The first argument is an expected value. The remaining arguments are passed
569 * to CRM_Core_DAO::singleValueQuery
571 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
572 * array(1 => array("Whiz", "String")));
575 * @param array $params
576 * @param string $message
578 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
582 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
583 $this->assertEquals($expected, $actual,
584 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
585 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
591 * Assert that two array-trees are exactly equal, notwithstanding
592 * the sorting of keys
594 * @param array $expected
595 * @param array $actual
597 public function assertTreeEquals($expected, $actual) {
600 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
601 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
605 $this->assertEquals($e, $a);
609 * Assert that two numbers are approximately equal.
611 * @param int|float $expected
612 * @param int|float $actual
613 * @param int|float $tolerance
614 * @param string $message
616 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
617 if ($message === NULL) {
618 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
620 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
624 * Assert attributes are equal.
626 * @param $expectedValues
627 * @param $actualValues
628 * @param string $message
630 * @throws PHPUnit_Framework_AssertionFailedError
632 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
633 foreach ($expectedValues as $paramName => $paramValue) {
634 if (isset($actualValues[$paramName])) {
635 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
638 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
647 public function assertArrayKeyExists($key, &$list) {
648 $result = isset($list[$key]) ?
TRUE : FALSE;
649 $this->assertTrue($result, ts("%1 element exists?",
658 public function assertArrayValueNotNull($key, &$list) {
659 $this->assertArrayKeyExists($key, $list);
661 $value = isset($list[$key]) ?
$list[$key] : NULL;
662 $this->assertTrue($value,
663 ts("%1 element not null?",
670 * Assert the 2 arrays have the same values.
672 * @param array $array1
673 * @param array $array2
675 public function assertArrayValuesEqual($array1, $array2) {
676 $array1 = array_values($array1);
677 $array2 = array_values($array2);
680 $this->assertEquals($array1, $array2);
686 * @param string $message
688 public function assertType($expected, $actual, $message = '') {
689 return $this->assertInternalType($expected, $actual, $message);
693 * Create a batch of external API calls which can
694 * be executed concurrently.
697 * $calls = $this->createExternalAPI()
698 * ->addCall('Contact', 'get', ...)
699 * ->addCall('Contact', 'get', ...)
705 * @return \Civi\API\ExternalBatch
706 * @throws PHPUnit_Framework_SkippedTestError
708 public function createExternalAPI() {
709 global $civicrm_root;
710 $defaultParams = array(
711 'version' => $this->_apiversion
,
715 $calls = new \Civi\API\
ExternalBatch($defaultParams);
717 if (!$calls->isSupported()) {
718 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
725 * Create required data based on $this->entity & $this->params
726 * This is just a way to set up the test data for delete & get functions
727 * so the distinction between set
728 * up & tested functions is clearer
733 public function createTestEntity() {
734 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
738 * @param int $contactTypeId
742 public function contactTypeDelete($contactTypeId) {
743 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
745 throw new Exception('Could not delete contact type');
750 * @param array $params
754 public function membershipTypeCreate($params = array()) {
755 CRM_Member_PseudoConstant
::flush('membershipType');
756 CRM_Core_Config
::clearDBCache();
757 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
758 $params = array_merge(array(
760 'duration_unit' => 'year',
761 'duration_interval' => 1,
762 'period_type' => 'rolling',
763 'member_of_contact_id' => $memberOfOrganization,
765 'financial_type_id' => 2,
768 'visibility' => 'Public',
771 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
773 CRM_Member_PseudoConstant
::flush('membershipType');
774 CRM_Utils_Cache
::singleton()->flush();
776 return $result['id'];
780 * @param array $params
784 public function contactMembershipCreate($params) {
785 $params = array_merge(array(
786 'join_date' => '2007-01-21',
787 'start_date' => '2007-01-21',
788 'end_date' => '2007-12-21',
789 'source' => 'Payment',
790 'membership_type_id' => 'General',
792 if (!is_numeric($params['membership_type_id'])) {
793 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
794 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
795 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
799 $result = $this->callAPISuccess('Membership', 'create', $params);
800 return $result['id'];
804 * Delete Membership Type.
806 * @param array $params
808 public function membershipTypeDelete($params) {
809 $this->callAPISuccess('MembershipType', 'Delete', $params);
813 * @param int $membershipID
815 public function membershipDelete($membershipID) {
816 $deleteParams = array('id' => $membershipID);
817 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
821 * @param string $name
825 public function membershipStatusCreate($name = 'test member status') {
826 $params['name'] = $name;
827 $params['start_event'] = 'start_date';
828 $params['end_event'] = 'end_date';
829 $params['is_current_member'] = 1;
830 $params['is_active'] = 1;
832 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
833 CRM_Member_PseudoConstant
::flush('membershipStatus');
834 return $result['id'];
838 * @param int $membershipStatusID
840 public function membershipStatusDelete($membershipStatusID) {
841 if (!$membershipStatusID) {
844 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
847 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
848 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
849 $renewedMembershipEndDate = new DateTime($membershipEndDate);
850 switch ($durationUnit) {
852 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
856 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
857 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
858 $renewedMembershipEndDate->add(new DateInterval('P1D'));
859 $renewedMembershipEndDate->add(new DateInterval('P1M'));
860 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
863 return $renewedMembershipEndDate->format('Y-m-d');
867 * @param array $params
871 public function relationshipTypeCreate($params = array()) {
872 $params = array_merge(array(
873 'name_a_b' => 'Relation 1 for relationship type create',
874 'name_b_a' => 'Relation 2 for relationship type create',
875 'contact_type_a' => 'Individual',
876 'contact_type_b' => 'Organization',
881 $result = $this->callAPISuccess('relationship_type', 'create', $params);
882 CRM_Core_PseudoConstant
::flush('relationshipType');
884 return $result['id'];
888 * Delete Relatinship Type.
890 * @param int $relationshipTypeID
892 public function relationshipTypeDelete($relationshipTypeID) {
893 $params['id'] = $relationshipTypeID;
894 $check = $this->callAPISuccess('relationship_type', 'get', $params);
895 if (!empty($check['count'])) {
896 $this->callAPISuccess('relationship_type', 'delete', $params);
901 * @param array $params
905 public function paymentProcessorTypeCreate($params = NULL) {
906 if (is_null($params)) {
908 'name' => 'API_Test_PP',
909 'title' => 'API Test Payment Processor',
910 'class_name' => 'CRM_Core_Payment_APITest',
911 'billing_mode' => 'form',
917 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
919 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
921 return $result['id'];
925 * Create test Authorize.net instance.
927 * @param array $params
931 public function paymentProcessorAuthorizeNetCreate($params = array()) {
932 $params = array_merge(array(
933 'name' => 'Authorize',
934 'domain_id' => CRM_Core_Config
::domainID(),
935 'payment_processor_type_id' => 'AuthNet',
936 'title' => 'AuthNet',
941 'user_name' => '4y5BfuW7jm',
942 'password' => '4cAmW927n8uLf5J8',
943 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
944 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
945 'class_name' => 'Payment_AuthorizeNet',
949 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
950 return $result['id'];
954 * Create Participant.
956 * @param array $params
957 * Array of contact id and event id values.
960 * $id of participant created
962 public function participantCreate($params = []) {
963 if (empty($params['contact_id'])) {
964 $params['contact_id'] = $this->individualCreate();
966 if (empty($params['event_id'])) {
967 $event = $this->eventCreate();
968 $params['event_id'] = $event['id'];
973 'register_date' => 20070219,
974 'source' => 'Wimbeldon',
975 'event_level' => 'Payment',
979 $params = array_merge($defaults, $params);
980 $result = $this->callAPISuccess('Participant', 'create', $params);
981 return $result['id'];
985 * Create Payment Processor.
988 * Id Payment Processor
990 public function processorCreate($params = array()) {
991 $processorParams = array(
994 'payment_processor_type_id' => 'Dummy',
995 'financial_account_id' => 12,
999 'url_site' => 'http://dummy.com',
1000 'url_recur' => 'http://dummy.com',
1001 'billing_mode' => 1,
1003 'payment_instrument_id' => 'Debit Card',
1005 $processorParams = array_merge($processorParams, $params);
1006 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1007 return $processor['id'];
1011 * Create Payment Processor.
1013 * @param array $processorParams
1015 * @return \CRM_Core_Payment_Dummy
1016 * Instance of Dummy Payment Processor
1018 public function dummyProcessorCreate($processorParams = array()) {
1019 $paymentProcessorID = $this->processorCreate($processorParams);
1020 return System
::singleton()->getById($paymentProcessorID);
1024 * Create contribution page.
1026 * @param array $params
1028 * Array of contribution page
1030 public function contributionPageCreate($params = array()) {
1031 $this->_pageParams
= array_merge(array(
1032 'title' => 'Test Contribution Page',
1033 'financial_type_id' => 1,
1034 'currency' => 'USD',
1035 'financial_account_id' => 1,
1037 'is_allow_other_amount' => 1,
1039 'max_amount' => 1000,
1041 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1045 * Create a sample batch.
1047 public function batchCreate() {
1048 $params = $this->_params
;
1049 $params['name'] = $params['title'] = 'Batch_433397';
1050 $params['status_id'] = 1;
1051 $result = $this->callAPISuccess('batch', 'create', $params);
1052 return $result['id'];
1058 * @param array $params
1060 * result of created tag
1062 public function tagCreate($params = array()) {
1064 'name' => 'New Tag3',
1065 'description' => 'This is description for Our New Tag ',
1068 $params = array_merge($defaults, $params);
1069 $result = $this->callAPISuccess('Tag', 'create', $params);
1070 return $result['values'][$result['id']];
1077 * Id of the tag to be deleted.
1081 public function tagDelete($tagId) {
1082 require_once 'api/api.php';
1086 $result = $this->callAPISuccess('Tag', 'delete', $params);
1087 return $result['id'];
1091 * Add entity(s) to the tag
1093 * @param array $params
1097 public function entityTagAdd($params) {
1098 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1105 * @param array $params
1109 * id of created pledge
1111 public function pledgeCreate($params) {
1112 $params = array_merge(array(
1113 'pledge_create_date' => date('Ymd'),
1114 'start_date' => date('Ymd'),
1115 'scheduled_date' => date('Ymd'),
1117 'pledge_status_id' => '2',
1118 'financial_type_id' => '1',
1119 'pledge_original_installment_amount' => 20,
1120 'frequency_interval' => 5,
1121 'frequency_unit' => 'year',
1122 'frequency_day' => 15,
1123 'installments' => 5,
1127 $result = $this->callAPISuccess('Pledge', 'create', $params);
1128 return $result['id'];
1132 * Delete contribution.
1134 * @param int $pledgeId
1136 public function pledgeDelete($pledgeId) {
1138 'pledge_id' => $pledgeId,
1140 $this->callAPISuccess('Pledge', 'delete', $params);
1144 * Create contribution.
1146 * @param array $params
1147 * Array of parameters.
1150 * id of created contribution
1152 public function contributionCreate($params) {
1154 $params = array_merge(array(
1156 'receive_date' => date('Ymd'),
1157 'total_amount' => 100.00,
1158 'fee_amount' => 5.00,
1159 'financial_type_id' => 1,
1160 'payment_instrument_id' => 1,
1161 'non_deductible_amount' => 10.00,
1163 'contribution_status_id' => 1,
1166 $result = $this->callAPISuccess('contribution', 'create', $params);
1167 return $result['id'];
1171 * Delete contribution.
1173 * @param int $contributionId
1177 public function contributionDelete($contributionId) {
1179 'contribution_id' => $contributionId,
1181 $result = $this->callAPISuccess('contribution', 'delete', $params);
1188 * @param array $params
1189 * Name-value pair for an event.
1193 public function eventCreate($params = array()) {
1194 // if no contact was passed, make up a dummy event creator
1195 if (!isset($params['contact_id'])) {
1196 $params['contact_id'] = $this->_contactCreate(array(
1197 'contact_type' => 'Individual',
1198 'first_name' => 'Event',
1199 'last_name' => 'Creator',
1203 // set defaults for missing params
1204 $params = array_merge(array(
1205 'title' => 'Annual CiviCRM meet',
1206 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1207 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1208 'event_type_id' => 1,
1210 'start_date' => 20081021,
1211 'end_date' => 20081023,
1212 'is_online_registration' => 1,
1213 'registration_start_date' => 20080601,
1214 'registration_end_date' => 20081015,
1215 'max_participants' => 100,
1216 'event_full_text' => 'Sorry! We are already full',
1219 'is_show_location' => 0,
1222 return $this->callAPISuccess('Event', 'create', $params);
1226 * Create a paid event.
1228 * @param array $params
1232 protected function eventCreatePaid($params) {
1233 $event = $this->eventCreate($params);
1234 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1235 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1236 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1237 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1238 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1250 public function eventDelete($id) {
1254 return $this->callAPISuccess('event', 'delete', $params);
1258 * Delete participant.
1260 * @param int $participantID
1264 public function participantDelete($participantID) {
1266 'id' => $participantID,
1268 $check = $this->callAPISuccess('Participant', 'get', $params);
1269 if ($check['count'] > 0) {
1270 return $this->callAPISuccess('Participant', 'delete', $params);
1275 * Create participant payment.
1277 * @param int $participantID
1278 * @param int $contributionID
1280 * $id of created payment
1282 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1283 //Create Participant Payment record With Values
1285 'participant_id' => $participantID,
1286 'contribution_id' => $contributionID,
1289 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1290 return $result['id'];
1294 * Delete participant payment.
1296 * @param int $paymentID
1298 public function participantPaymentDelete($paymentID) {
1302 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1308 * @param int $contactID
1310 * location id of created location
1312 public function locationAdd($contactID) {
1315 'location_type' => 'New Location Type',
1317 'name' => 'Saint Helier St',
1318 'county' => 'Marin',
1319 'country' => 'UNITED STATES',
1320 'state_province' => 'Michigan',
1321 'supplemental_address_1' => 'Hallmark Ct',
1322 'supplemental_address_2' => 'Jersey Village',
1323 'supplemental_address_3' => 'My Town',
1328 'contact_id' => $contactID,
1329 'address' => $address,
1330 'location_format' => '2.0',
1331 'location_type' => 'New Location Type',
1334 $result = $this->callAPISuccess('Location', 'create', $params);
1339 * Delete Locations of contact.
1341 * @param array $params
1344 public function locationDelete($params) {
1345 $this->callAPISuccess('Location', 'delete', $params);
1349 * Add a Location Type.
1351 * @param array $params
1352 * @return CRM_Core_DAO_LocationType
1353 * location id of created location
1355 public function locationTypeCreate($params = NULL) {
1356 if ($params === NULL) {
1358 'name' => 'New Location Type',
1359 'vcard_name' => 'New Location Type',
1360 'description' => 'Location Type for Delete',
1365 $locationType = new CRM_Core_DAO_LocationType();
1366 $locationType->copyValues($params);
1367 $locationType->save();
1368 // clear getfields cache
1369 CRM_Core_PseudoConstant
::flush();
1370 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1371 return $locationType;
1375 * Delete a Location Type.
1377 * @param int $locationTypeId
1379 public function locationTypeDelete($locationTypeId) {
1380 $locationType = new CRM_Core_DAO_LocationType();
1381 $locationType->id
= $locationTypeId;
1382 $locationType->delete();
1388 * @param array $params
1389 * @return CRM_Core_DAO_Mapping
1390 * Mapping id of created mapping
1392 public function mappingCreate($params = NULL) {
1393 if ($params === NULL) {
1395 'name' => 'Mapping name',
1396 'description' => 'Mapping description',
1397 // 'Export Contact' mapping.
1398 'mapping_type_id' => 7,
1402 $mapping = new CRM_Core_DAO_Mapping();
1403 $mapping->copyValues($params);
1405 // clear getfields cache
1406 CRM_Core_PseudoConstant
::flush();
1407 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1414 * @param int $mappingId
1416 public function mappingDelete($mappingId) {
1417 $mapping = new CRM_Core_DAO_Mapping();
1418 $mapping->id
= $mappingId;
1423 * Prepare class for ACLs.
1425 protected function prepareForACLs() {
1426 $config = CRM_Core_Config
::singleton();
1427 $config->userPermissionClass
->permissions
= array();
1433 protected function cleanUpAfterACLs() {
1434 CRM_Utils_Hook
::singleton()->reset();
1435 $tablesToTruncate = array(
1437 'civicrm_acl_cache',
1438 'civicrm_acl_entity_role',
1439 'civicrm_acl_contact_cache',
1441 $this->quickCleanup($tablesToTruncate);
1442 $config = CRM_Core_Config
::singleton();
1443 unset($config->userPermissionClass
->permissions
);
1447 * Create a smart group.
1449 * By default it will be a group of households.
1451 * @param array $smartGroupParams
1452 * @param array $groupParams
1455 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1456 $smartGroupParams = array_merge(array(
1457 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1460 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1462 $groupParams['saved_search_id'] = $savedSearch->id
;
1463 return $this->groupCreate($groupParams);
1468 * @param array $params
1470 public function uFFieldCreate($params = array()) {
1471 $params = array_merge(array(
1473 'field_name' => 'first_name',
1476 'visibility' => 'Public Pages and Listings',
1477 'is_searchable' => '1',
1478 'label' => 'first_name',
1479 'field_type' => 'Individual',
1482 $this->callAPISuccess('uf_field', 'create', $params);
1486 * Add a UF Join Entry.
1488 * @param array $params
1490 * $id of created UF Join
1492 public function ufjoinCreate($params = NULL) {
1493 if ($params === NULL) {
1496 'module' => 'CiviEvent',
1497 'entity_table' => 'civicrm_event',
1503 $result = $this->callAPISuccess('uf_join', 'create', $params);
1508 * @param array $params
1509 * Optional parameters.
1510 * @param bool $reloadConfig
1511 * While enabling CiviCampaign component, we shouldn't always forcibly
1512 * reload config as this hinder hook call in test environment
1517 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1518 $this->enableCiviCampaign($reloadConfig);
1519 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1520 'name' => 'big_campaign',
1521 'title' => 'Campaign',
1523 return $campaign['id'];
1527 * Create Group for a contact.
1529 * @param int $contactId
1531 public function contactGroupCreate($contactId) {
1533 'contact_id.1' => $contactId,
1537 $this->callAPISuccess('GroupContact', 'Create', $params);
1541 * Delete Group for a contact.
1543 * @param int $contactId
1545 public function contactGroupDelete($contactId) {
1547 'contact_id.1' => $contactId,
1550 $this->civicrm_api('GroupContact', 'Delete', $params);
1556 * @param array $params
1559 public function activityCreate($params = array()) {
1560 $params = array_merge(array(
1561 'subject' => 'Discussion on warm beer',
1562 'activity_date_time' => date('Ymd'),
1563 'duration_hours' => 30,
1564 'duration_minutes' => 20,
1565 'location' => 'Baker Street',
1566 'details' => 'Lets schedule a meeting',
1568 'activity_type_id' => 'Meeting',
1570 if (!isset($params['source_contact_id'])) {
1571 $params['source_contact_id'] = $this->individualCreate();
1573 if (!isset($params['target_contact_id'])) {
1574 $params['target_contact_id'] = $this->individualCreate(array(
1575 'first_name' => 'Julia',
1576 'Last_name' => 'Anderson',
1578 'email' => 'julia_anderson@civicrm.org',
1579 'contact_type' => 'Individual',
1582 if (!isset($params['assignee_contact_id'])) {
1583 $params['assignee_contact_id'] = $params['target_contact_id'];
1586 $result = $this->callAPISuccess('Activity', 'create', $params);
1588 $result['target_contact_id'] = $params['target_contact_id'];
1589 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1594 * Create an activity type.
1596 * @param array $params
1600 public function activityTypeCreate($params) {
1601 return $this->callAPISuccess('ActivityType', 'create', $params);
1605 * Delete activity type.
1607 * @param int $activityTypeId
1608 * Id of the activity type.
1611 public function activityTypeDelete($activityTypeId) {
1612 $params['activity_type_id'] = $activityTypeId;
1613 return $this->callAPISuccess('ActivityType', 'delete', $params);
1617 * Create custom group.
1619 * @param array $params
1622 public function customGroupCreate($params = array()) {
1624 'title' => 'new custom group',
1625 'extends' => 'Contact',
1627 'style' => 'Inline',
1631 $params = array_merge($defaults, $params);
1633 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1634 $this->callAPISuccess('custom_group', 'get', array(
1635 'title' => $params['title'],
1636 array('api.custom_group.delete' => 1),
1639 return $this->callAPISuccess('custom_group', 'create', $params);
1643 * Existing function doesn't allow params to be over-ridden so need a new one
1644 * this one allows you to only pass in the params you want to change
1645 * @param array $params
1648 public function CustomGroupCreateByParams($params = array()) {
1650 'title' => "API Custom Group",
1651 'extends' => 'Contact',
1653 'style' => 'Inline',
1656 $params = array_merge($defaults, $params);
1657 return $this->callAPISuccess('custom_group', 'create', $params);
1661 * Create custom group with multi fields.
1662 * @param array $params
1665 public function CustomGroupMultipleCreateByParams($params = array()) {
1670 $params = array_merge($defaults, $params);
1671 return $this->CustomGroupCreateByParams($params);
1675 * Create custom group with multi fields.
1676 * @param array $params
1679 public function CustomGroupMultipleCreateWithFields($params = array()) {
1680 // also need to pass on $params['custom_field'] if not set but not in place yet
1682 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1683 $ids['custom_group_id'] = $customGroup['id'];
1685 $customField = $this->customFieldCreate(array(
1686 'custom_group_id' => $ids['custom_group_id'],
1687 'label' => 'field_1' . $ids['custom_group_id'],
1691 $ids['custom_field_id'][] = $customField['id'];
1693 $customField = $this->customFieldCreate(array(
1694 'custom_group_id' => $ids['custom_group_id'],
1695 'default_value' => '',
1696 'label' => 'field_2' . $ids['custom_group_id'],
1699 $ids['custom_field_id'][] = $customField['id'];
1701 $customField = $this->customFieldCreate(array(
1702 'custom_group_id' => $ids['custom_group_id'],
1703 'default_value' => '',
1704 'label' => 'field_3' . $ids['custom_group_id'],
1707 $ids['custom_field_id'][] = $customField['id'];
1713 * Create a custom group with a single text custom field. See
1714 * participant:testCreateWithCustom for how to use this
1716 * @param string $function
1718 * @param string $filename
1722 * ids of created objects
1724 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1725 $params = array('title' => $function);
1726 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1727 $params['extends'] = $entity ?
$entity : 'Contact';
1728 $customGroup = $this->CustomGroupCreate($params);
1729 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1730 CRM_Core_PseudoConstant
::flush();
1732 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1736 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1737 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1739 * @param string $function
1741 * @param string $filename
1745 * ids of created objects
1747 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1748 $params = array('title' => $function);
1749 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1750 $params['extends'] = $entity ?
$entity : 'Contact';
1751 $customGroup = $this->CustomGroupCreate($params);
1752 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1753 CRM_Core_PseudoConstant
::flush();
1755 'defaultValue' => 'Default Value',
1756 'lowercasevalue' => 'Lowercase Value',
1757 1 => 'Integer Value',
1760 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1761 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1762 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1763 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1764 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1765 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1766 foreach ($options as $option_value => $option_label) {
1767 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1768 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1771 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);
1775 * Delete custom group.
1777 * @param int $customGroupID
1781 public function customGroupDelete($customGroupID) {
1782 $params['id'] = $customGroupID;
1783 return $this->callAPISuccess('custom_group', 'delete', $params);
1787 * Create custom field.
1789 * @param array $params
1790 * (custom_group_id) is required.
1793 public function customFieldCreate($params) {
1794 $params = array_merge(array(
1795 'label' => 'Custom Field',
1796 'data_type' => 'String',
1797 'html_type' => 'Text',
1798 'is_searchable' => 1,
1800 'default_value' => 'defaultValue',
1803 $result = $this->callAPISuccess('custom_field', 'create', $params);
1804 // these 2 functions are called with force to flush static caches
1805 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1806 CRM_Core_Component
::getEnabledComponents(1);
1811 * Delete custom field.
1813 * @param int $customFieldID
1817 public function customFieldDelete($customFieldID) {
1819 $params['id'] = $customFieldID;
1820 return $this->callAPISuccess('custom_field', 'delete', $params);
1829 public function noteCreate($cId) {
1831 'entity_table' => 'civicrm_contact',
1832 'entity_id' => $cId,
1833 'note' => 'hello I am testing Note',
1834 'contact_id' => $cId,
1835 'modified_date' => date('Ymd'),
1836 'subject' => 'Test Note',
1839 return $this->callAPISuccess('Note', 'create', $params);
1843 * Enable CiviCampaign Component.
1845 * @param bool $reloadConfig
1846 * Force relaod config or not
1848 public function enableCiviCampaign($reloadConfig = TRUE) {
1849 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1850 if ($reloadConfig) {
1851 // force reload of config object
1852 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1854 //flush cache by calling with reset
1855 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1859 * Create custom field with Option Values.
1861 * @param array $customGroup
1862 * @param string $name
1863 * Name of custom field.
1864 * @param array $extraParams
1865 * Additional parameters to pass through.
1869 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1870 $fieldParams = array(
1871 'custom_group_id' => $customGroup['id'],
1872 'name' => 'test_custom_group',
1873 'label' => 'Country',
1874 'html_type' => 'Select',
1875 'data_type' => 'String',
1878 'is_searchable' => 0,
1882 $optionGroup = array(
1884 'name' => 'option_group1',
1885 'label' => 'option_group_label1',
1888 $optionValue = array(
1889 'option_label' => array('Label1', 'Label2'),
1890 'option_value' => array('value1', 'value2'),
1891 'option_name' => array($name . '_1', $name . '_2'),
1892 'option_weight' => array(1, 2),
1893 'option_status' => 1,
1896 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1898 return $this->callAPISuccess('custom_field', 'create', $params);
1906 public function confirmEntitiesDeleted($entities) {
1907 foreach ($entities as $entity) {
1909 $result = $this->callAPISuccess($entity, 'Get', array());
1910 if ($result['error'] == 1 ||
$result['count'] > 0) {
1911 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1919 * Quick clean by emptying tables created for the test.
1921 * @param array $tablesToTruncate
1922 * @param bool $dropCustomValueTables
1923 * @throws \Exception
1925 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1927 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1929 if ($dropCustomValueTables) {
1930 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1931 while ($optionGroupResult->fetch()) {
1932 if (!empty($optionGroupResult->option_group_id
)) {
1933 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1936 $tablesToTruncate[] = 'civicrm_custom_group';
1937 $tablesToTruncate[] = 'civicrm_custom_field';
1940 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1942 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1943 foreach ($tablesToTruncate as $table) {
1944 $sql = "TRUNCATE TABLE $table";
1945 CRM_Core_DAO
::executeQuery($sql);
1947 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1949 if ($dropCustomValueTables) {
1950 $dbName = self
::getDBName();
1952 SELECT TABLE_NAME as tableName
1953 FROM INFORMATION_SCHEMA.TABLES
1954 WHERE TABLE_SCHEMA = '{$dbName}'
1955 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1958 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1959 while ($tableDAO->fetch()) {
1960 $sql = "DROP TABLE {$tableDAO->tableName}";
1961 CRM_Core_DAO
::executeQuery($sql);
1967 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1969 public function quickCleanUpFinancialEntities() {
1970 $tablesToTruncate = array(
1972 'civicrm_activity_contact',
1973 'civicrm_contribution',
1974 'civicrm_contribution_soft',
1975 'civicrm_contribution_product',
1976 'civicrm_financial_trxn',
1977 'civicrm_financial_item',
1978 'civicrm_contribution_recur',
1979 'civicrm_line_item',
1980 'civicrm_contribution_page',
1981 'civicrm_payment_processor',
1982 'civicrm_entity_financial_trxn',
1983 'civicrm_membership',
1984 'civicrm_membership_type',
1985 'civicrm_membership_payment',
1986 'civicrm_membership_log',
1987 'civicrm_membership_block',
1989 'civicrm_participant',
1990 'civicrm_participant_payment',
1992 'civicrm_pledge_payment',
1993 'civicrm_price_set_entity',
1994 'civicrm_price_field_value',
1995 'civicrm_price_field',
1997 $this->quickCleanup($tablesToTruncate);
1998 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1999 $this->restoreDefaultPriceSetConfig();
2001 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2002 $this->disableTaxAndInvoicing();
2003 $this->setCurrencySeparators(',');
2004 CRM_Core_PseudoConstant
::flush('taxRates');
2005 System
::singleton()->flushProcessors();
2008 public function restoreDefaultPriceSetConfig() {
2009 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2010 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2011 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)");
2012 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)");
2016 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2017 * Default behaviour is to also delete the entity
2018 * @param array $params
2019 * Params array to check against.
2021 * Id of the entity concerned.
2022 * @param string $entity
2023 * Name of entity concerned (e.g. membership).
2024 * @param bool $delete
2025 * Should the entity be deleted as part of this check.
2026 * @param string $errorText
2027 * Text to print on error.
2031 * @param array $params
2034 * @param int $delete
2035 * @param string $errorText
2039 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2041 $result = $this->callAPISuccessGetSingle($entity, array(
2046 $this->callAPISuccess($entity, 'Delete', array(
2050 $dateFields = $keys = $dateTimeFields = array();
2051 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2052 foreach ($fields['values'] as $field => $settings) {
2053 if (array_key_exists($field, $result)) {
2054 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2057 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2059 $type = CRM_Utils_Array
::value('type', $settings);
2060 if ($type == CRM_Utils_Type
::T_DATE
) {
2061 $dateFields[] = $settings['name'];
2062 // we should identify both real names & unique names as dates
2063 if ($field != $settings['name']) {
2064 $dateFields[] = $field;
2067 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2068 $dateTimeFields[] = $settings['name'];
2069 // we should identify both real names & unique names as dates
2070 if ($field != $settings['name']) {
2071 $dateTimeFields[] = $field;
2076 if (strtolower($entity) == 'contribution') {
2077 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2078 // this is not returned in id format
2079 unset($params['payment_instrument_id']);
2080 $params['contribution_source'] = $params['source'];
2081 unset($params['source']);
2084 foreach ($params as $key => $value) {
2085 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2088 if (in_array($key, $dateFields)) {
2089 $value = date('Y-m-d', strtotime($value));
2090 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2092 if (in_array($key, $dateTimeFields)) {
2093 $value = date('Y-m-d H:i:s', strtotime($value));
2094 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2096 $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);
2101 * Get formatted values in the actual and expected result.
2102 * @param array $actual
2103 * Actual calculated values.
2104 * @param array $expected
2107 public function checkArrayEquals(&$actual, &$expected) {
2108 self
::unsetId($actual);
2109 self
::unsetId($expected);
2110 $this->assertEquals($actual, $expected);
2114 * Unset the key 'id' from the array
2115 * @param array $unformattedArray
2116 * The array from which the 'id' has to be unset.
2118 public static function unsetId(&$unformattedArray) {
2119 $formattedArray = array();
2120 if (array_key_exists('id', $unformattedArray)) {
2121 unset($unformattedArray['id']);
2123 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2124 foreach ($unformattedArray['values'] as $key => $value) {
2125 if (is_array($value)) {
2126 foreach ($value as $k => $v) {
2132 elseif ($key == 'id') {
2133 $unformattedArray[$key];
2135 $formattedArray = array($value);
2137 $unformattedArray['values'] = $formattedArray;
2142 * Helper to enable/disable custom directory support
2144 * @param array $customDirs
2146 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2147 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2149 public function customDirectories($customDirs) {
2150 $config = CRM_Core_Config
::singleton();
2152 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2153 unset($config->customPHPPathDir
);
2155 elseif ($customDirs['php_path'] === TRUE) {
2156 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2159 $config->customPHPPathDir
= $php_path;
2162 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2163 unset($config->customTemplateDir
);
2165 elseif ($customDirs['template_path'] === TRUE) {
2166 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2169 $config->customTemplateDir
= $template_path;
2174 * Generate a temporary folder.
2176 * @param string $prefix
2179 public function createTempDir($prefix = 'test-') {
2180 $tempDir = CRM_Utils_File
::tempdir($prefix);
2181 $this->tempDirs
[] = $tempDir;
2185 public function cleanTempDirs() {
2186 if (!is_array($this->tempDirs
)) {
2187 // fix test errors where this is not set
2190 foreach ($this->tempDirs
as $tempDir) {
2191 if (is_dir($tempDir)) {
2192 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2198 * Temporarily replace the singleton extension with a different one.
2199 * @param \CRM_Extension_System $system
2201 public function setExtensionSystem(CRM_Extension_System
$system) {
2202 if ($this->origExtensionSystem
== NULL) {
2203 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2205 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2208 public function unsetExtensionSystem() {
2209 if ($this->origExtensionSystem
!== NULL) {
2210 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2211 $this->origExtensionSystem
= NULL;
2216 * Temporarily alter the settings-metadata to add a mock setting.
2218 * WARNING: The setting metadata will disappear on the next cache-clear.
2223 public function setMockSettingsMetaData($extras) {
2224 Civi
::service('settings_manager')->flush();
2226 CRM_Utils_Hook
::singleton()
2227 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2228 $metadata = array_merge($metadata, $extras);
2231 $fields = $this->callAPISuccess('setting', 'getfields', array());
2232 foreach ($extras as $key => $spec) {
2233 $this->assertNotEmpty($spec['title']);
2234 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2239 * @param string $name
2241 public function financialAccountDelete($name) {
2242 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2243 $financialAccount->name
= $name;
2244 if ($financialAccount->find(TRUE)) {
2245 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2246 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2247 $entityFinancialType->delete();
2248 $financialAccount->delete();
2253 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2254 * (NB unclear if this is still required)
2256 public function _sethtmlGlobals() {
2257 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2258 'required' => array(
2259 'html_quickform_rule_required',
2260 'HTML/QuickForm/Rule/Required.php',
2262 'maxlength' => array(
2263 'html_quickform_rule_range',
2264 'HTML/QuickForm/Rule/Range.php',
2266 'minlength' => array(
2267 'html_quickform_rule_range',
2268 'HTML/QuickForm/Rule/Range.php',
2270 'rangelength' => array(
2271 'html_quickform_rule_range',
2272 'HTML/QuickForm/Rule/Range.php',
2275 'html_quickform_rule_email',
2276 'HTML/QuickForm/Rule/Email.php',
2279 'html_quickform_rule_regex',
2280 'HTML/QuickForm/Rule/Regex.php',
2282 'lettersonly' => array(
2283 'html_quickform_rule_regex',
2284 'HTML/QuickForm/Rule/Regex.php',
2286 'alphanumeric' => array(
2287 'html_quickform_rule_regex',
2288 'HTML/QuickForm/Rule/Regex.php',
2291 'html_quickform_rule_regex',
2292 'HTML/QuickForm/Rule/Regex.php',
2294 'nopunctuation' => array(
2295 'html_quickform_rule_regex',
2296 'HTML/QuickForm/Rule/Regex.php',
2299 'html_quickform_rule_regex',
2300 'HTML/QuickForm/Rule/Regex.php',
2302 'callback' => array(
2303 'html_quickform_rule_callback',
2304 'HTML/QuickForm/Rule/Callback.php',
2307 'html_quickform_rule_compare',
2308 'HTML/QuickForm/Rule/Compare.php',
2311 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2312 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2314 'HTML/QuickForm/group.php',
2315 'HTML_QuickForm_group',
2318 'HTML/QuickForm/hidden.php',
2319 'HTML_QuickForm_hidden',
2322 'HTML/QuickForm/reset.php',
2323 'HTML_QuickForm_reset',
2325 'checkbox' => array(
2326 'HTML/QuickForm/checkbox.php',
2327 'HTML_QuickForm_checkbox',
2330 'HTML/QuickForm/file.php',
2331 'HTML_QuickForm_file',
2334 'HTML/QuickForm/image.php',
2335 'HTML_QuickForm_image',
2337 'password' => array(
2338 'HTML/QuickForm/password.php',
2339 'HTML_QuickForm_password',
2342 'HTML/QuickForm/radio.php',
2343 'HTML_QuickForm_radio',
2346 'HTML/QuickForm/button.php',
2347 'HTML_QuickForm_button',
2350 'HTML/QuickForm/submit.php',
2351 'HTML_QuickForm_submit',
2354 'HTML/QuickForm/select.php',
2355 'HTML_QuickForm_select',
2357 'hiddenselect' => array(
2358 'HTML/QuickForm/hiddenselect.php',
2359 'HTML_QuickForm_hiddenselect',
2362 'HTML/QuickForm/text.php',
2363 'HTML_QuickForm_text',
2365 'textarea' => array(
2366 'HTML/QuickForm/textarea.php',
2367 'HTML_QuickForm_textarea',
2369 'fckeditor' => array(
2370 'HTML/QuickForm/fckeditor.php',
2371 'HTML_QuickForm_FCKEditor',
2374 'HTML/QuickForm/tinymce.php',
2375 'HTML_QuickForm_TinyMCE',
2377 'dojoeditor' => array(
2378 'HTML/QuickForm/dojoeditor.php',
2379 'HTML_QuickForm_dojoeditor',
2382 'HTML/QuickForm/link.php',
2383 'HTML_QuickForm_link',
2385 'advcheckbox' => array(
2386 'HTML/QuickForm/advcheckbox.php',
2387 'HTML_QuickForm_advcheckbox',
2390 'HTML/QuickForm/date.php',
2391 'HTML_QuickForm_date',
2394 'HTML/QuickForm/static.php',
2395 'HTML_QuickForm_static',
2398 'HTML/QuickForm/header.php',
2399 'HTML_QuickForm_header',
2402 'HTML/QuickForm/html.php',
2403 'HTML_QuickForm_html',
2405 'hierselect' => array(
2406 'HTML/QuickForm/hierselect.php',
2407 'HTML_QuickForm_hierselect',
2409 'autocomplete' => array(
2410 'HTML/QuickForm/autocomplete.php',
2411 'HTML_QuickForm_autocomplete',
2414 'HTML/QuickForm/xbutton.php',
2415 'HTML_QuickForm_xbutton',
2417 'advmultiselect' => array(
2418 'HTML/QuickForm/advmultiselect.php',
2419 'HTML_QuickForm_advmultiselect',
2425 * Set up an acl allowing contact to see 2 specified groups
2426 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2428 * You need to have pre-created these groups & created the user e.g
2429 * $this->createLoggedInUser();
2430 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2431 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2433 * @param bool $isProfile
2435 public function setupACL($isProfile = FALSE) {
2437 $_REQUEST = $this->_params
;
2439 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2440 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2441 $ov = new CRM_Core_DAO_OptionValue();
2442 $ov->option_group_id
= $optionGroupID;
2444 if ($ov->find(TRUE)) {
2445 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2447 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2448 'option_group_id' => $optionGroupID,
2449 'label' => 'pick me',
2453 CRM_Core_DAO
::executeQuery("
2454 TRUNCATE civicrm_acl_cache
2457 CRM_Core_DAO
::executeQuery("
2458 TRUNCATE civicrm_acl_contact_cache
2461 CRM_Core_DAO
::executeQuery("
2462 INSERT INTO civicrm_acl_entity_role (
2463 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2464 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2468 CRM_Core_DAO
::executeQuery("
2469 INSERT INTO civicrm_acl (
2470 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2473 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2478 CRM_Core_DAO
::executeQuery("
2479 INSERT INTO civicrm_acl (
2480 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2483 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2487 CRM_Core_DAO
::executeQuery("
2488 INSERT INTO civicrm_acl (
2489 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2492 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2497 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2498 $this->callAPISuccess('group_contact', 'create', array(
2499 'group_id' => $this->_permissionedGroup
,
2500 'contact_id' => $this->_loggedInUser
,
2505 CRM_ACL_BAO_Cache
::resetCache();
2506 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2511 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2513 public function offsetDefaultPriceSet() {
2514 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2515 $firstID = $contributionPriceSet['id'];
2516 $this->callAPISuccess('price_set', 'create', array(
2517 'id' => $contributionPriceSet['id'],
2521 unset($contributionPriceSet['id']);
2522 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2523 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2524 'price_set_id' => $firstID,
2525 'options' => array('limit' => 1),
2527 unset($priceField['id']);
2528 $priceField['price_set_id'] = $newPriceSet['id'];
2529 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2530 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2531 'price_set_id' => $firstID,
2533 'options' => array('limit' => 1),
2536 unset($priceFieldValue['id']);
2537 //create some padding to use up ids
2538 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2539 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2540 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2544 * Create an instance of the paypal processor.
2545 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2546 * this parent class & we don't have a structure for that yet
2547 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2548 * & the best protection against that is the functions this class affords
2549 * @param array $params
2550 * @return int $result['id'] payment processor id
2552 public function paymentProcessorCreate($params = array()) {
2553 $params = array_merge(array(
2555 'domain_id' => CRM_Core_Config
::domainID(),
2556 'payment_processor_type_id' => 'PayPal',
2560 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2561 'password' => '1183377788',
2562 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2563 'url_site' => 'https://www.sandbox.paypal.com/',
2564 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2565 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2566 'class_name' => 'Payment_PayPalImpl',
2567 'billing_mode' => 3,
2568 'financial_type_id' => 1,
2569 'financial_account_id' => 12,
2570 // Credit card = 1 so can pass 'by accident'.
2571 'payment_instrument_id' => 'Debit Card',
2573 if (!is_numeric($params['payment_processor_type_id'])) {
2574 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2576 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2577 'name' => $params['payment_processor_type_id'],
2581 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2582 return $result['id'];
2586 * Set up initial recurring payment allowing subsequent IPN payments.
2588 * @param array $recurParams (Optional)
2589 * @param array $contributionParams (Optional)
2591 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2592 $contributionParams = array_merge([
2593 'total_amount' => '200',
2594 'invoice_id' => $this->_invoiceID
,
2595 'financial_type_id' => 'Donation',
2596 'contribution_status_id' => 'Pending',
2597 'contact_id' => $this->_contactID
,
2598 'contribution_page_id' => $this->_contributionPageID
,
2599 'payment_processor_id' => $this->_paymentProcessorID
,
2601 'skipCleanMoney' => TRUE,
2602 ], $contributionParams);
2603 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2604 'contact_id' => $this->_contactID
,
2607 'installments' => 5,
2608 'frequency_unit' => 'Month',
2609 'frequency_interval' => 1,
2610 'invoice_id' => $this->_invoiceID
,
2611 'contribution_status_id' => 2,
2612 'payment_processor_id' => $this->_paymentProcessorID
,
2613 // processor provided ID - use contact ID as proxy.
2614 'processor_id' => $this->_contactID
,
2615 'api.contribution.create' => $contributionParams,
2617 $this->_contributionRecurID
= $contributionRecur['id'];
2618 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2622 * 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
2624 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2626 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2627 $membershipParams = $recurParams = array();
2628 if (!empty($params['duration_unit'])) {
2629 $membershipParams['duration_unit'] = $params['duration_unit'];
2631 if (!empty($params['frequency_unit'])) {
2632 $recurParams['frequency_unit'] = $params['frequency_unit'];
2635 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2636 //create a contribution so our membership & contribution don't both have id = 1
2637 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2638 $this->contributionCreate(array(
2639 'contact_id' => $this->_contactID
,
2641 'financial_type_id' => 1,
2642 'invoice_id' => 'abcd',
2646 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2648 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2649 'contact_id' => $this->_contactID
,
2650 'membership_type_id' => $this->ids
['membership_type'],
2651 'contribution_recur_id' => $this->_contributionRecurID
,
2652 'format.only_id' => TRUE,
2654 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2655 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2657 $this->callAPISuccess('line_item', 'create', array(
2658 'entity_table' => 'civicrm_membership',
2659 'entity_id' => $this->ids
['membership'],
2660 'contribution_id' => $this->_contributionID
,
2661 'label' => 'General',
2663 'unit_price' => 200,
2664 'line_total' => 200,
2665 'financial_type_id' => 1,
2666 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2668 'label' => 'Membership Amount',
2669 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2671 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2673 'label' => 'General',
2674 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2677 $this->callAPISuccess('membership_payment', 'create', array(
2678 'contribution_id' => $this->_contributionID
,
2679 'membership_id' => $this->ids
['membership'],
2688 public function CiviUnitTestCase_fatalErrorHandler($message) {
2689 throw new Exception("{$message['message']}: {$message['code']}");
2693 * Helper function to create new mailing.
2695 * @param array $params
2699 public function createMailing($params = array()) {
2700 $params = array_merge(array(
2701 'subject' => 'maild' . rand(),
2702 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2703 'name' => 'mailing name' . rand(),
2707 $result = $this->callAPISuccess('Mailing', 'create', $params);
2708 return $result['id'];
2712 * Helper function to delete mailing.
2715 public function deleteMailing($id) {
2720 $this->callAPISuccess('Mailing', 'delete', $params);
2724 * Wrap the entire test case in a transaction.
2726 * Only subsequent DB statements will be wrapped in TX -- this cannot
2727 * retroactively wrap old DB statements. Therefore, it makes sense to
2728 * call this at the beginning of setUp().
2730 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2731 * this option does not work with, e.g., custom-data.
2733 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2734 * if TRUNCATE or ALTER is called while using a transaction.
2737 * Whether to use nesting or reference-counting.
2739 public function useTransaction($nest = TRUE) {
2741 $this->tx
= new CRM_Core_Transaction($nest);
2742 $this->tx
->rollback();
2747 * Assert the attachment exists.
2749 * @param bool $exists
2750 * @param array $apiResult
2752 protected function assertAttachmentExistence($exists, $apiResult) {
2753 $fileId = $apiResult['id'];
2754 $this->assertTrue(is_numeric($fileId));
2755 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2756 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2757 1 => array($fileId, 'Int'),
2759 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2760 1 => array($fileId, 'Int'),
2765 * Create a price set for an event.
2767 * @param int $feeTotal
2768 * @param int $minAmt
2769 * @param string $type
2774 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2775 // creating price set, price field
2776 $paramsSet['title'] = 'Price Set';
2777 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2778 $paramsSet['is_active'] = FALSE;
2779 $paramsSet['extends'] = 1;
2780 $paramsSet['min_amount'] = $minAmt;
2782 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2783 $this->_ids
['price_set'] = $priceSet->id
;
2785 $paramsField = array(
2786 'label' => 'Price Field',
2787 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2788 'html_type' => $type,
2789 'price' => $feeTotal,
2790 'option_label' => array('1' => 'Price Field'),
2791 'option_value' => array('1' => $feeTotal),
2792 'option_name' => array('1' => $feeTotal),
2793 'option_weight' => array('1' => 1),
2794 'option_amount' => array('1' => 1),
2795 'is_display_amounts' => 1,
2797 'options_per_line' => 1,
2798 'is_active' => array('1' => 1),
2799 'price_set_id' => $this->_ids
['price_set'],
2800 'is_enter_qty' => 1,
2801 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2803 if ($type === 'Radio') {
2804 $paramsField['is_enter_qty'] = 0;
2805 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2806 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2808 CRM_Price_BAO_PriceField
::create($paramsField);
2809 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2810 $this->_ids
['price_field'] = array_keys($fields['values']);
2811 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2812 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2814 return $this->_ids
['price_set'];
2818 * Add a profile to a contribution page.
2820 * @param string $name
2821 * @param int $contributionPageID
2822 * @param string $module
2824 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2826 'uf_group_id' => $name,
2827 'module' => $module,
2828 'entity_table' => 'civicrm_contribution_page',
2829 'entity_id' => $contributionPageID,
2832 if ($module !== 'CiviContribute') {
2833 $params['module_data'] = [$module => []];
2835 $this->callAPISuccess('UFJoin', 'create', $params);
2839 * Add participant with contribution
2843 protected function createParticipantWithContribution() {
2844 // creating price set, price field
2845 $this->_contactId
= $this->individualCreate();
2846 $event = $this->eventCreate();
2847 $this->_eventId
= $event['id'];
2848 $eventParams = array(
2849 'id' => $this->_eventId
,
2850 'financial_type_id' => 4,
2853 $this->callAPISuccess('event', 'create', $eventParams);
2854 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2855 $participantParams = array(
2856 'financial_type_id' => 4,
2857 'event_id' => $this->_eventId
,
2860 'fee_currency' => 'USD',
2861 'contact_id' => $this->_contactId
,
2863 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2864 $contributionParams = array(
2865 'total_amount' => 150,
2866 'currency' => 'USD',
2867 'contact_id' => $this->_contactId
,
2868 'financial_type_id' => 4,
2869 'contribution_status_id' => 1,
2870 'partial_payment_total' => 300.00,
2871 'partial_amount_to_pay' => 150,
2872 'contribution_mode' => 'participant',
2873 'participant_id' => $participant['id'],
2875 foreach ($priceFields['values'] as $key => $priceField) {
2876 $lineItems[1][$key] = array(
2877 'price_field_id' => $priceField['price_field_id'],
2878 'price_field_value_id' => $priceField['id'],
2879 'label' => $priceField['label'],
2880 'field_title' => $priceField['label'],
2882 'unit_price' => $priceField['amount'],
2883 'line_total' => $priceField['amount'],
2884 'financial_type_id' => $priceField['financial_type_id'],
2887 $contributionParams['line_item'] = $lineItems;
2888 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2889 $paymentParticipant = array(
2890 'participant_id' => $participant['id'],
2891 'contribution_id' => $contribution['id'],
2893 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2894 return array($lineItems, $contribution);
2900 * @param string $component
2901 * @param int $componentId
2902 * @param array $priceFieldOptions
2906 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2907 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2908 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2909 $paramsSet['is_active'] = TRUE;
2910 $paramsSet['financial_type_id'] = 'Event Fee';
2911 $paramsSet['extends'] = 1;
2912 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2913 $priceSetId = $priceSet['id'];
2914 //Checking for priceset added in the table.
2915 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2916 'id', $paramsSet['title'], 'Check DB for created priceset'
2918 $paramsField = array_merge(array(
2919 'label' => 'Price Field',
2920 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2921 'html_type' => 'CheckBox',
2922 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2923 'option_value' => array('1' => 100, '2' => 200),
2924 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2925 'option_weight' => array('1' => 1, '2' => 2),
2926 'option_amount' => array('1' => 100, '2' => 200),
2927 'is_display_amounts' => 1,
2929 'options_per_line' => 1,
2930 'is_active' => array('1' => 1, '2' => 1),
2931 'price_set_id' => $priceSet['id'],
2932 'is_enter_qty' => 1,
2933 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2934 ), $priceFieldOptions);
2936 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2938 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2940 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2944 * Replace the template with a test-oriented template designed to show all the variables.
2946 * @param string $templateName
2948 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2949 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2950 CRM_Core_DAO
::executeQuery(
2951 "UPDATE civicrm_option_group og
2952 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2953 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2954 SET m.msg_html = '{$testTemplate}'
2955 WHERE og.name = 'msg_tpl_workflow_contribution'
2956 AND ov.name = '{$templateName}'
2957 AND m.is_default = 1"
2962 * Reinstate the default template.
2964 * @param string $templateName
2966 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2967 CRM_Core_DAO
::executeQuery(
2968 "UPDATE civicrm_option_group og
2969 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2970 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2971 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2972 SET m.msg_html = m2.msg_html
2973 WHERE og.name = 'msg_tpl_workflow_contribution'
2974 AND ov.name = '{$templateName}'
2975 AND m.is_default = 1"
2980 * Flush statics relating to financial type.
2982 protected function flushFinancialTypeStatics() {
2983 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2984 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2986 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2987 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2989 CRM_Contribute_PseudoConstant
::flush('financialType');
2990 CRM_Contribute_PseudoConstant
::flush('membershipType');
2991 // Pseudoconstants may be saved to the cache table.
2992 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2993 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2994 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2998 * Set the permissions to the supplied array.
3000 * @param array $permissions
3002 protected function setPermissions($permissions) {
3003 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3004 $this->flushFinancialTypeStatics();
3008 * @param array $params
3011 public function _checkFinancialRecords($params, $context) {
3012 $entityParams = array(
3013 'entity_id' => $params['id'],
3014 'entity_table' => 'civicrm_contribution',
3016 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3017 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3018 if ($context == 'pending') {
3019 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3020 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3023 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3024 $trxnParams = array(
3025 'id' => $trxn['financial_trxn_id'],
3027 if ($context != 'online' && $context != 'payLater') {
3028 $compareParams = array(
3029 'to_financial_account_id' => 6,
3030 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3034 if ($context == 'feeAmount') {
3035 $compareParams['fee_amount'] = 50;
3037 elseif ($context == 'online') {
3038 $compareParams = array(
3039 'to_financial_account_id' => 12,
3040 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3042 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3045 elseif ($context == 'payLater') {
3046 $compareParams = array(
3047 'to_financial_account_id' => 7,
3048 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3052 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3053 $entityParams = array(
3054 'financial_trxn_id' => $trxn['financial_trxn_id'],
3055 'entity_table' => 'civicrm_financial_item',
3057 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3058 $fitemParams = array(
3059 'id' => $entityTrxn['entity_id'],
3061 $compareParams = array(
3062 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3064 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3066 if ($context == 'payLater') {
3067 $compareParams = array(
3068 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3070 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3073 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3074 if ($context == 'feeAmount') {
3076 'entity_id' => $params['id'],
3077 'entity_table' => 'civicrm_contribution',
3079 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3080 $trxnParams = array(
3081 'id' => $maxTrxn['financial_trxn_id'],
3083 $compareParams = array(
3084 'to_financial_account_id' => 5,
3085 'from_financial_account_id' => 6,
3086 'total_amount' => 50,
3089 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3090 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3091 $fitemParams = array(
3092 'entity_id' => $trxnId['financialTrxnId'],
3093 'entity_table' => 'civicrm_financial_trxn',
3095 $compareParams = array(
3098 'financial_account_id' => 5,
3100 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3102 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3103 // line should be copied into all the functions that call this function & evaluated there
3104 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3105 // when calling completeTransaction or repeatTransaction.
3106 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3110 * Return financial type id on basis of name
3112 * @param string $name Financial type m/c name
3116 public function getFinancialTypeId($name) {
3117 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3121 * Cleanup function for contents of $this->ids.
3123 * This is a best effort cleanup to use in tear downs etc.
3125 * It will not fail if the data has already been removed (some tests may do
3126 * their own cleanup).
3128 protected function cleanUpSetUpIDs() {
3129 foreach ($this->setupIDs
as $entity => $id) {
3131 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3133 catch (CiviCRM_API3_Exception
$e) {
3134 // This is a best-effort cleanup function, ignore.
3140 * Create Financial Type.
3142 * @param array $params
3146 protected function createFinancialType($params = array()) {
3147 $params = array_merge($params,
3149 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3153 return $this->callAPISuccess('FinancialType', 'create', $params);
3157 * Create Payment Instrument.
3159 * @param array $params
3160 * @param string $financialAccountName
3164 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
3165 $params = array_merge(array(
3166 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
3167 'option_group_id' => 'payment_instrument',
3170 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
3172 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3174 $financialAccountParams = [
3175 'entity_table' => 'civicrm_option_value',
3176 'entity_id' => $newPaymentInstrument,
3177 'account_relationship' => $relationTypeID,
3178 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
3180 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
3182 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
3186 * Enable Tax and Invoicing
3188 protected function enableTaxAndInvoicing($params = array()) {
3189 // Enable component contribute setting
3190 $contributeSetting = array_merge($params,
3193 'invoice_prefix' => 'INV_',
3194 'credit_notes_prefix' => 'CN_',
3196 'due_date_period' => 'days',
3198 'is_email_pdf' => 1,
3199 'tax_term' => 'Sales Tax',
3200 'tax_display_settings' => 'Inclusive',
3203 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3207 * Enable Tax and Invoicing
3209 protected function disableTaxAndInvoicing($params = array()) {
3210 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3211 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3213 // Enable component contribute setting
3214 $contributeSetting = array_merge($params,
3219 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3223 * Add Sales Tax relation for financial type with financial account.
3225 * @param int $financialTypeId
3229 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3231 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3232 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3233 'is_deductible' => 1,
3238 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3239 $entityParams = array(
3240 'entity_table' => 'civicrm_financial_type',
3241 'entity_id' => $financialTypeId,
3242 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3245 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3246 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3248 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3249 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3250 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3251 $dao->copyValues($entityParams);
3253 if ($dao->fetch()) {
3254 $entityParams['id'] = $dao->id
;
3256 $entityParams['financial_account_id'] = $account->id
;
3258 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3262 * Create price set with contribution test for test setup.
3264 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3265 * on parent class at some point (fn is not in 4.4).
3268 * @param array $params
3270 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3271 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3272 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3273 'title' => "Test Contribution Page",
3274 'financial_type_id' => 1,
3275 'currency' => 'NZD',
3276 'goal_amount' => 50,
3277 'is_pay_later' => 1,
3278 'is_monetary' => TRUE,
3279 'is_email_receipt' => FALSE,
3281 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3282 'is_quick_config' => 0,
3283 'extends' => 'CiviMember',
3284 'financial_type_id' => 1,
3285 'title' => 'my Page',
3287 $priceSetID = $priceSet['id'];
3289 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3290 $priceField = $this->callAPISuccess('price_field', 'create', array(
3291 'price_set_id' => $priceSetID,
3292 'label' => 'Goat Breed',
3293 'html_type' => 'Radio',
3295 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3296 'price_set_id' => $priceSetID,
3297 'price_field_id' => $priceField['id'],
3298 'label' => 'Long Haired Goat',
3300 'financial_type_id' => 'Donation',
3301 'membership_type_id' => $membershipTypeID,
3302 'membership_num_terms' => 1,
3304 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3305 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3306 'price_set_id' => $priceSetID,
3307 'price_field_id' => $priceField['id'],
3308 'label' => 'Shoe-eating Goat',
3310 'financial_type_id' => 'Donation',
3311 'membership_type_id' => $membershipTypeID,
3312 'membership_num_terms' => 2,
3314 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3316 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3317 'price_set_id' => $priceSetID,
3318 'price_field_id' => $priceField['id'],
3319 'label' => 'Shoe-eating Goat',
3321 'financial_type_id' => 'Donation',
3323 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3325 $this->_ids
['price_set'] = $priceSetID;
3326 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3327 $this->_ids
['price_field'] = array($priceField['id']);
3329 $this->_ids
['membership_type'] = $membershipTypeID;
3333 * Only specified contact returned.
3334 * @implements CRM_Utils_Hook::aclWhereClause
3337 * @param $whereTables
3341 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3342 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3346 * @implements CRM_Utils_Hook::selectWhereClause
3348 * @param string $entity
3349 * @param array $clauses
3351 public function selectWhereClauseHook($entity, &$clauses) {
3352 if ($entity == 'Event') {
3353 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3358 * An implementation of hook_civicrm_post used with all our test cases.
3361 * @param string $objectName
3362 * @param int $objectId
3365 public function onPost($op, $objectName, $objectId, &$objectRef) {
3366 if ($op == 'create' && $objectName == 'Individual') {
3367 CRM_Core_DAO
::executeQuery(
3368 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3370 1 => array($objectId, 'Integer'),
3375 if ($op == 'edit' && $objectName == 'Participant') {
3377 1 => array($objectId, 'Integer'),
3379 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3380 CRM_Core_DAO
::executeQuery($query, $params);
3385 * Instantiate form object.
3387 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3389 * @param string $class
3390 * Name of form class.
3392 * @return \CRM_Core_Form
3394 public function getFormObject($class) {
3395 $form = new $class();
3396 $_SERVER['REQUEST_METHOD'] = 'GET';
3397 $form->controller
= new CRM_Core_Controller();
3402 * Get possible thousand separators.
3406 public function getThousandSeparators() {
3407 return array(array('.'), array(','));
3411 * Set the separators for thousands and decimal points.
3413 * @param string $thousandSeparator
3415 protected function setCurrencySeparators($thousandSeparator) {
3416 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3418 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3422 * Format money as it would be input.
3424 * @param string $amount
3428 protected function formatMoneyInput($amount) {
3429 return CRM_Utils_Money
::format($amount, NULL, '%a');
3433 * Get the contribution object.
3435 * @param int $contributionID
3437 * @return \CRM_Contribute_BAO_Contribution
3439 protected function getContributionObject($contributionID) {
3440 $contributionObj = new CRM_Contribute_BAO_Contribution();
3441 $contributionObj->id
= $contributionID;
3442 $contributionObj->find(TRUE);
3443 return $contributionObj;
3447 * Enable multilingual.
3449 public function enableMultilingual() {
3450 $this->callAPISuccess('Setting', 'create', array(
3451 'lcMessages' => 'en_US',
3452 'languageLimit' => array(
3457 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3460 $dbLocale = '_en_US';