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
{
57 * Api version - easier to override than just a define
59 protected $_apiversion = API_LATEST_VERSION
;
61 * Database has been initialized.
65 private static $dbInit = FALSE;
68 * Database connection.
70 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
79 static protected $_dbName;
82 * 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 * @var CRM_Utils_Hook_UnitTests hookClass
120 * example of setting a method for a hook
121 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
123 public $hookClass = NULL;
126 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
128 protected $_params = array();
131 * @var CRM_Extension_System
133 protected $origExtensionSystem;
138 * Because we are overriding the parent class constructor, we
139 * need to show the same arguments as exist in the constructor of
140 * PHPUnit_Framework_TestCase, since
141 * PHPUnit_Framework_TestSuite::createTest() creates a
142 * ReflectionClass of the Test class and checks the constructor
143 * of that class to decide how to set up the test.
145 * @param string $name
147 * @param string $dataName
149 public function __construct($name = NULL, array$data = array(), $dataName = '') {
150 parent
::__construct($name, $data, $dataName);
152 // we need full error reporting
153 error_reporting(E_ALL
& ~E_NOTICE
);
155 self
::$_dbName = self
::getDBName();
157 // also load the class loader
158 require_once 'CRM/Core/ClassLoader.php';
159 CRM_Core_ClassLoader
::singleton()->register();
160 if (function_exists('_civix_phpunit_setUp')) {
161 // FIXME: loosen coupling
162 _civix_phpunit_setUp();
167 * Override to run the test and assert its state.
170 * @throws \PHPUnit_Framework_IncompleteTest
171 * @throws \PHPUnit_Framework_SkippedTest
173 protected function runTest() {
175 return parent
::runTest();
177 catch (PEAR_Exception
$e) {
178 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
179 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
186 public function requireDBReset() {
187 return $this->DBResetRequired
;
193 public static function getDBName() {
194 static $dbName = NULL;
195 if ($dbName === NULL) {
196 require_once "DB.php";
197 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
198 $dbName = $dsninfo['database'];
204 * Create database connection for this instance.
206 * Initialize the test database if it hasn't been initialized
208 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
210 protected function getConnection() {
211 $dbName = self
::$_dbName;
212 if (!self
::$dbInit) {
213 $dbName = self
::getDBName();
215 // install test database
216 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
218 static::_populateDB(FALSE, $this);
220 self
::$dbInit = TRUE;
223 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
227 * Required implementation of abstract method.
229 protected function getDataSet() {
233 * @param bool $perClass
234 * @param null $object
236 * TRUE if the populate logic runs; FALSE if it is skipped
238 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
239 if (CIVICRM_UF
!== 'UnitTests') {
240 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
243 if ($perClass ||
$object == NULL) {
247 $dbreset = $object->requireDBReset();
250 if (self
::$populateOnce ||
!$dbreset) {
253 self
::$populateOnce = NULL;
255 Civi\Test
::data()->populate();
260 public static function setUpBeforeClass() {
261 static::_populateDB(TRUE);
263 // also set this global hack
264 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
268 * Common setup functions for all unit tests.
270 protected function setUp() {
271 $session = CRM_Core_Session
::singleton();
272 $session->set('userID', NULL);
274 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
275 // Use a temporary file for STDIN
276 $GLOBALS['stdin'] = tmpfile();
277 if ($GLOBALS['stdin'] === FALSE) {
278 echo "Couldn't open temporary file\n";
282 // Get and save a connection to the database
283 $this->_dbconn
= $this->getConnection();
285 // reload database before each test
286 // $this->_populateDB();
288 // "initialize" CiviCRM to avoid problems when running single tests
289 // FIXME: look at it closer in second stage
291 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
292 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
294 // disable any left-over test extensions
295 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
297 // reset all the caches
298 CRM_Utils_System
::flushCache();
300 // initialize the object once db is loaded
302 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
304 // when running unit tests, use mockup user framework
305 $this->hookClass
= CRM_Utils_Hook
::singleton();
307 // Make sure the DB connection is setup properly
308 $config->userSystem
->setMySQLTimeZone();
309 $env = new CRM_Utils_Check_Component_Env();
310 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
312 // clear permissions stub to not check permissions
313 $config->userPermissionClass
->permissions
= NULL;
315 //flush component settings
316 CRM_Core_Component
::getEnabledComponents(TRUE);
318 error_reporting(E_ALL
);
320 $this->_sethtmlGlobals();
324 * Read everything from the datasets directory and insert into the db.
326 public function loadAllFixtures() {
327 $fixturesDir = __DIR__
. '/../../fixtures';
329 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
331 $xmlFiles = glob($fixturesDir . '/*.xml');
332 foreach ($xmlFiles as $xmlFixture) {
333 $op = new PHPUnit_Extensions_Database_Operation_Insert();
334 $dataset = $this->createXMLDataSet($xmlFixture);
335 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
336 $op->execute($this->_dbconn
, $dataset);
339 $yamlFiles = glob($fixturesDir . '/*.yaml');
340 foreach ($yamlFiles as $yamlFixture) {
341 $op = new PHPUnit_Extensions_Database_Operation_Insert();
342 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
343 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
344 $op->execute($this->_dbconn
, $dataset);
347 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
351 * Emulate a logged in user since certain functions use that.
352 * value to store a record in the DB (like activity)
356 * Contact ID of the created user.
358 public function createLoggedInUser() {
360 'first_name' => 'Logged In',
361 'last_name' => 'User ' . rand(),
362 'contact_type' => 'Individual',
364 $contactID = $this->individualCreate($params);
365 $this->callAPISuccess('UFMatch', 'create', array(
366 'contact_id' => $contactID,
367 'uf_name' => 'superman',
371 $session = CRM_Core_Session
::singleton();
372 $session->set('userID', $contactID);
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 $this->hookClass
->reset();
392 $session = CRM_Core_Session
::singleton();
393 $session->set('userID', NULL);
396 $this->tx
->rollback()->commit();
399 CRM_Core_Transaction
::forceRollbackIfEnabled();
400 \Civi\Core\Transaction\Manager
::singleton(TRUE);
403 CRM_Core_Transaction
::forceRollbackIfEnabled();
404 \Civi\Core\Transaction\Manager
::singleton(TRUE);
406 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
407 $this->quickCleanup($tablesToTruncate);
408 $this->createDomainContacts();
411 $this->cleanTempDirs();
412 $this->unsetExtensionSystem();
416 * Generic function to compare expected values after an api call to retrieved.
419 * @daoName string DAO Name of object we're evaluating.
420 * @id int Id of object
421 * @match array Associative array of field name => expected value. Empty if asserting
422 * that a DELETE occurred
423 * @delete boolean True if we're checking that a DELETE action occurred.
427 * @param bool $delete
428 * @throws \PHPUnit_Framework_AssertionFailedError
430 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
432 // adding this here since developers forget to check for an id
433 // and hence we get the first value in the db
434 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
437 $object = new $daoName();
441 // If we're asserting successful record deletion, make sure object is NOT found.
443 if ($object->find(TRUE)) {
444 $this->fail("Object not deleted by delete operation: $daoName, $id");
449 // Otherwise check matches of DAO field values against expected values in $match.
450 if ($object->find(TRUE)) {
451 $fields = &$object->fields();
452 foreach ($fields as $name => $value) {
453 $dbName = $value['name'];
454 if (isset($match[$name])) {
456 $this->assertEquals($object->$dbName, $match[$name]);
458 elseif (isset($match[$dbName])) {
460 $this->assertEquals($object->$dbName, $match[$dbName]);
465 $this->fail("Could not retrieve object: $daoName, $id");
468 $matchSize = count($match);
469 if ($verifiedCount != $matchSize) {
470 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
475 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
476 * @param string $daoName
477 * @param $searchValue
478 * @param $returnColumn
479 * @param $searchColumn
482 * @return null|string
483 * @throws PHPUnit_Framework_AssertionFailedError
485 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
486 if (empty($searchValue)) {
487 $this->fail("empty value passed to assertDBNotNull");
489 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
490 $this->assertNotNull($value, $message);
496 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
497 * @param string $daoName
498 * @param $searchValue
499 * @param $returnColumn
500 * @param $searchColumn
503 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
504 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
505 $this->assertNull($value, $message);
509 * Request a record from the DB by id. Success if row not found.
510 * @param string $daoName
512 * @param null $message
514 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
515 $message = $message ?
$message : "$daoName (#$id) should not exist";
516 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
517 $this->assertNull($value, $message);
521 * Request a record from the DB by id. Success if row not found.
522 * @param string $daoName
524 * @param null $message
526 public function assertDBRowExist($daoName, $id, $message = NULL) {
527 $message = $message ?
$message : "$daoName (#$id) should exist";
528 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
529 $this->assertEquals($id, $value, $message);
533 * Compare a single column value in a retrieved DB record to an expected value.
534 * @param string $daoName
535 * @param $searchValue
536 * @param $returnColumn
537 * @param $searchColumn
538 * @param $expectedValue
541 public function assertDBCompareValue(
542 $daoName, $searchValue, $returnColumn, $searchColumn,
543 $expectedValue, $message
545 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
546 $this->assertEquals($value, $expectedValue, $message);
550 * Compare all values in a single retrieved DB record to an array of expected values.
551 * @param string $daoName
552 * @param array $searchParams
553 * @param $expectedValues
555 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
556 //get the values from db
558 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
560 // compare db values with expected values
561 self
::assertAttributesEquals($expectedValues, $dbValues);
565 * Assert that a SQL query returns a given value.
567 * The first argument is an expected value. The remaining arguments are passed
568 * to CRM_Core_DAO::singleValueQuery
570 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
571 * array(1 => array("Whiz", "String")));
574 * @param array $params
575 * @param string $message
577 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
581 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
582 $this->assertEquals($expected, $actual,
583 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
584 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
590 * Assert that two array-trees are exactly equal, notwithstanding
591 * the sorting of keys
593 * @param array $expected
594 * @param array $actual
596 public function assertTreeEquals($expected, $actual) {
599 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
600 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
604 $this->assertEquals($e, $a);
608 * Assert that two numbers are approximately equal.
610 * @param int|float $expected
611 * @param int|float $actual
612 * @param int|float $tolerance
613 * @param string $message
615 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
616 if ($message === NULL) {
617 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
619 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
623 * Assert attributes are equal.
625 * @param $expectedValues
626 * @param $actualValues
627 * @param string $message
629 * @throws PHPUnit_Framework_AssertionFailedError
631 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
632 foreach ($expectedValues as $paramName => $paramValue) {
633 if (isset($actualValues[$paramName])) {
634 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
637 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
646 public function assertArrayKeyExists($key, &$list) {
647 $result = isset($list[$key]) ?
TRUE : FALSE;
648 $this->assertTrue($result, ts("%1 element exists?",
657 public function assertArrayValueNotNull($key, &$list) {
658 $this->assertArrayKeyExists($key, $list);
660 $value = isset($list[$key]) ?
$list[$key] : NULL;
661 $this->assertTrue($value,
662 ts("%1 element not null?",
669 * Check that api returned 'is_error' => 0.
671 * @param array $apiResult
673 * @param string $prefix
674 * Extra test to add to message.
676 public function assertAPISuccess($apiResult, $prefix = '') {
677 if (!empty($prefix)) {
680 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
682 if (!empty($apiResult['debug_information'])) {
683 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
685 if (!empty($apiResult['trace'])) {
686 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
688 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
692 * Check that api returned 'is_error' => 1.
694 * @param array $apiResult
696 * @param string $prefix
697 * Extra test to add to message.
698 * @param null $expectedError
700 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
701 if (!empty($prefix)) {
704 if ($expectedError && !empty($apiResult['is_error'])) {
705 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
707 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
708 $this->assertNotEmpty($apiResult['error_message']);
714 * @param string $message
716 public function assertType($expected, $actual, $message = '') {
717 return $this->assertInternalType($expected, $actual, $message);
721 * Check that a deleted item has been deleted.
726 public function assertAPIDeleted($entity, $id) {
727 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
732 * Check that api returned 'is_error' => 1
733 * else provide full message
734 * @param array $result
736 * @param array $valuesToExclude
737 * @param string $prefix
738 * Extra test to add to message.
740 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
741 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
742 foreach ($valuesToExclude as $value) {
743 if (isset($result[$value])) {
744 unset($result[$value]);
746 if (isset($expected[$value])) {
747 unset($expected[$value]);
750 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
754 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
758 * @param array $params
761 public function civicrm_api($entity, $action, $params) {
762 return civicrm_api($entity, $action, $params);
766 * Create a batch of external API calls which can
767 * be executed concurrently.
770 * $calls = $this->createExternalAPI()
771 * ->addCall('Contact', 'get', ...)
772 * ->addCall('Contact', 'get', ...)
778 * @return \Civi\API\ExternalBatch
779 * @throws PHPUnit_Framework_SkippedTestError
781 public function createExternalAPI() {
782 global $civicrm_root;
783 $defaultParams = array(
784 'version' => $this->_apiversion
,
788 $calls = new \Civi\API\
ExternalBatch($defaultParams);
790 if (!$calls->isSupported()) {
791 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
798 * wrap api functions.
799 * so we can ensure they succeed & throw exceptions without litterering the test with checks
801 * @param string $entity
802 * @param string $action
803 * @param array $params
804 * @param mixed $checkAgainst
805 * Optional value to check result against, implemented for getvalue,.
806 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
807 * for getsingle the array is compared against an array passed in - the id is not compared (for
812 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
813 $params = array_merge(array(
814 'version' => $this->_apiversion
,
819 switch (strtolower($action)) {
821 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
824 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
827 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
829 $result = $this->civicrm_api($entity, $action, $params);
830 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
835 * This function exists to wrap api getValue function & check the result
836 * so we can ensure they succeed & throw exceptions without litterering the test with checks
837 * There is a type check in this
839 * @param string $entity
840 * @param array $params
841 * @param string $type
842 * Per http://php.net/manual/en/function.gettype.php possible types.
852 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
854 'version' => $this->_apiversion
,
857 $result = $this->civicrm_api($entity, 'getvalue', $params);
859 if ($type == 'integer') {
860 // api seems to return integers as strings
861 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
864 $this->assertType($type, $result, "returned result should have been of type $type but was ");
871 * This function exists to wrap api getsingle function & check the result
872 * so we can ensure they succeed & throw exceptions without litterering the test with checks
874 * @param string $entity
875 * @param array $params
876 * @param array $checkAgainst
877 * Array to compare result against.
888 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
890 'version' => $this->_apiversion
,
893 $result = $this->civicrm_api($entity, 'getsingle', $params);
894 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
895 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
898 // @todo - have gone with the fn that unsets id? should we check id?
899 $this->checkArrayEquals($result, $checkAgainst);
905 * This function exists to wrap api getValue function & check the result
906 * so we can ensure they succeed & throw exceptions without litterering the test with checks
907 * There is a type check in this
908 * @param string $entity
909 * @param array $params
914 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
916 'version' => $this->_apiversion
,
919 $result = $this->civicrm_api($entity, 'getcount', $params);
920 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
921 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
923 if (is_int($count)) {
924 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
930 * This function exists to wrap api functions.
931 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
933 * @param string $entity
934 * @param string $action
935 * @param array $params
936 * @param string $function
937 * Pass this in to create a generated example.
938 * @param string $file
939 * Pass this in to create a generated example.
940 * @param string $description
941 * @param string|null $exampleName
945 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
946 $params['version'] = $this->_apiversion
;
947 $result = $this->callAPISuccess($entity, $action, $params);
948 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
953 * This function exists to wrap api functions.
954 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
955 * @param string $entity
956 * @param string $action
957 * @param array $params
958 * @param string $expectedErrorMessage
960 * @param null $extraOutput
963 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
964 if (is_array($params)) {
966 'version' => $this->_apiversion
,
969 $result = $this->civicrm_api($entity, $action, $params);
970 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
975 * Create required data based on $this->entity & $this->params
976 * This is just a way to set up the test data for delete & get functions
977 * so the distinction between set
978 * up & tested functions is clearer
983 public function createTestEntity() {
984 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
988 * Generic function to create Organisation, to be used in test cases
990 * @param array $params
991 * parameters for civicrm_contact_add api function call
993 * sequence number if creating multiple organizations
996 * id of Organisation created
998 public function organizationCreate($params = array(), $seq = 0) {
1002 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1003 return $this->_contactCreate($params);
1007 * Generic function to create Individual, to be used in test cases
1009 * @param array $params
1010 * parameters for civicrm_contact_add api function call
1012 * sequence number if creating multiple individuals
1015 * id of Individual created
1017 public function individualCreate($params = array(), $seq = 0) {
1018 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1019 return $this->_contactCreate($params);
1023 * Generic function to create Household, to be used in test cases
1025 * @param array $params
1026 * parameters for civicrm_contact_add api function call
1028 * sequence number if creating multiple households
1031 * id of Household created
1033 public function householdCreate($params = array(), $seq = 0) {
1034 $params = array_merge($this->sampleContact('Household', $seq), $params);
1035 return $this->_contactCreate($params);
1039 * Helper function for getting sample contact properties.
1041 * @param string $contact_type
1042 * enum contact type: Individual, Organization
1044 * sequence number for the values of this type
1047 * properties of sample contact (ie. $params for API call)
1049 public function sampleContact($contact_type, $seq = 0) {
1051 'Individual' => array(
1052 // The number of values in each list need to be coprime numbers to not have duplicates
1053 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1054 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1055 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1057 'Organization' => array(
1058 'organization_name' => array(
1059 'Unit Test Organization',
1066 'Household' => array(
1067 'household_name' => array('Unit Test household'),
1070 $params = array('contact_type' => $contact_type);
1071 foreach ($samples[$contact_type] as $key => $values) {
1072 $params[$key] = $values[$seq %
count($values)];
1074 if ($contact_type == 'Individual') {
1075 $params['email'] = strtolower(
1076 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1078 $params['prefix_id'] = 3;
1079 $params['suffix_id'] = 3;
1085 * Private helper function for calling civicrm_contact_add.
1087 * @param array $params
1088 * For civicrm_contact_add api function call.
1093 * id of Household created
1095 private function _contactCreate($params) {
1096 $result = $this->callAPISuccess('contact', 'create', $params);
1097 if (!empty($result['is_error']) ||
empty($result['id'])) {
1098 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1100 return $result['id'];
1104 * Delete contact, ensuring it is not the domain contact
1106 * @param int $contactID
1107 * Contact ID to delete
1109 public function contactDelete($contactID) {
1110 $domain = new CRM_Core_BAO_Domain();
1111 $domain->contact_id
= $contactID;
1112 if (!$domain->find(TRUE)) {
1113 $this->callAPISuccess('contact', 'delete', array(
1115 'skip_undelete' => 1,
1121 * @param int $contactTypeId
1125 public function contactTypeDelete($contactTypeId) {
1126 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1128 throw new Exception('Could not delete contact type');
1133 * @param array $params
1137 public function membershipTypeCreate($params = array()) {
1138 CRM_Member_PseudoConstant
::flush('membershipType');
1139 CRM_Core_Config
::clearDBCache();
1140 $memberOfOrganization = $this->organizationCreate();
1141 $params = array_merge(array(
1142 'name' => 'General',
1143 'duration_unit' => 'year',
1144 'duration_interval' => 1,
1145 'period_type' => 'rolling',
1146 'member_of_contact_id' => $memberOfOrganization,
1148 'financial_type_id' => 1,
1151 'visibility' => 'Public',
1154 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1156 CRM_Member_PseudoConstant
::flush('membershipType');
1157 CRM_Utils_Cache
::singleton()->flush();
1159 return $result['id'];
1163 * @param array $params
1167 public function contactMembershipCreate($params) {
1169 'join_date' => '2007-01-21',
1170 'start_date' => '2007-01-21',
1171 'end_date' => '2007-12-21',
1172 'source' => 'Payment',
1175 foreach ($pre as $key => $val) {
1176 if (!isset($params[$key])) {
1177 $params[$key] = $val;
1181 $result = $this->callAPISuccess('Membership', 'create', $params);
1182 return $result['id'];
1186 * Delete Membership Type.
1188 * @param array $params
1190 public function membershipTypeDelete($params) {
1191 $this->callAPISuccess('MembershipType', 'Delete', $params);
1195 * @param int $membershipID
1197 public function membershipDelete($membershipID) {
1198 $deleteParams = array('id' => $membershipID);
1199 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1203 * @param string $name
1207 public function membershipStatusCreate($name = 'test member status') {
1208 $params['name'] = $name;
1209 $params['start_event'] = 'start_date';
1210 $params['end_event'] = 'end_date';
1211 $params['is_current_member'] = 1;
1212 $params['is_active'] = 1;
1214 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1215 CRM_Member_PseudoConstant
::flush('membershipStatus');
1216 return $result['id'];
1220 * @param int $membershipStatusID
1222 public function membershipStatusDelete($membershipStatusID) {
1223 if (!$membershipStatusID) {
1226 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1230 * @param array $params
1234 public function relationshipTypeCreate($params = array()) {
1235 $params = array_merge(array(
1236 'name_a_b' => 'Relation 1 for relationship type create',
1237 'name_b_a' => 'Relation 2 for relationship type create',
1238 'contact_type_a' => 'Individual',
1239 'contact_type_b' => 'Organization',
1246 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1247 CRM_Core_PseudoConstant
::flush('relationshipType');
1249 return $result['id'];
1253 * Delete Relatinship Type.
1255 * @param int $relationshipTypeID
1257 public function relationshipTypeDelete($relationshipTypeID) {
1258 $params['id'] = $relationshipTypeID;
1259 $this->callAPISuccess('relationship_type', 'delete', $params);
1263 * @param array $params
1267 public function paymentProcessorTypeCreate($params = NULL) {
1268 if (is_null($params)) {
1270 'name' => 'API_Test_PP',
1271 'title' => 'API Test Payment Processor',
1272 'class_name' => 'CRM_Core_Payment_APITest',
1273 'billing_mode' => 'form',
1279 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1281 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1283 return $result['id'];
1287 * Create test Authorize.net instance.
1289 * @param array $params
1293 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1294 $params = array_merge(array(
1295 'name' => 'Authorize',
1296 'domain_id' => CRM_Core_Config
::domainID(),
1297 'payment_processor_type_id' => 'AuthNet',
1298 'title' => 'AuthNet',
1303 'user_name' => '4y5BfuW7jm',
1304 'password' => '4cAmW927n8uLf5J8',
1305 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1306 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1307 'class_name' => 'Payment_AuthorizeNet',
1308 'billing_mode' => 1,
1311 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1312 return $result['id'];
1316 * Create Participant.
1318 * @param array $params
1319 * Array of contact id and event id values.
1322 * $id of participant created
1324 public function participantCreate($params) {
1325 if (empty($params['contact_id'])) {
1326 $params['contact_id'] = $this->individualCreate();
1328 if (empty($params['event_id'])) {
1329 $event = $this->eventCreate();
1330 $params['event_id'] = $event['id'];
1335 'register_date' => 20070219,
1336 'source' => 'Wimbeldon',
1337 'event_level' => 'Payment',
1341 $params = array_merge($defaults, $params);
1342 $result = $this->callAPISuccess('Participant', 'create', $params);
1343 return $result['id'];
1347 * Create Payment Processor.
1350 * Id Payment Processor
1352 public function processorCreate() {
1353 $processorParams = array(
1356 'payment_processor_type_id' => 'Dummy',
1357 'financial_account_id' => 12,
1361 'url_site' => 'http://dummy.com',
1362 'url_recur' => 'http://dummy.com',
1363 'billing_mode' => 1,
1366 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1367 return $processor['id'];
1371 * Create Payment Processor.
1373 * @param array $processorParams
1375 * @return \CRM_Core_Payment_Dummy
1376 * Instance of Dummy Payment Processor
1378 public function dummyProcessorCreate($processorParams = array()) {
1379 $paymentProcessorID = $this->processorCreate($processorParams);
1380 return System
::singleton()->getById($paymentProcessorID);
1384 * Create contribution page.
1386 * @param array $params
1388 * Array of contribution page
1390 public function contributionPageCreate($params = array()) {
1391 $this->_pageParams
= array_merge(array(
1392 'title' => 'Test Contribution Page',
1393 'financial_type_id' => 1,
1394 'currency' => 'USD',
1395 'financial_account_id' => 1,
1397 'is_allow_other_amount' => 1,
1399 'max_amount' => 1000,
1401 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1405 * Create a sample batch.
1407 public function batchCreate() {
1408 $params = $this->_params
;
1409 $params['name'] = $params['title'] = 'Batch_433397';
1410 $params['status_id'] = 1;
1411 $result = $this->callAPISuccess('batch', 'create', $params);
1412 return $result['id'];
1418 * @param array $params
1420 * result of created tag
1422 public function tagCreate($params = array()) {
1424 'name' => 'New Tag3',
1425 'description' => 'This is description for Our New Tag ',
1428 $params = array_merge($defaults, $params);
1429 $result = $this->callAPISuccess('Tag', 'create', $params);
1430 return $result['values'][$result['id']];
1437 * Id of the tag to be deleted.
1441 public function tagDelete($tagId) {
1442 require_once 'api/api.php';
1446 $result = $this->callAPISuccess('Tag', 'delete', $params);
1447 return $result['id'];
1451 * Add entity(s) to the tag
1453 * @param array $params
1457 public function entityTagAdd($params) {
1458 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1465 * @param array $params
1469 * id of created pledge
1471 public function pledgeCreate($params) {
1472 $params = array_merge(array(
1473 'pledge_create_date' => date('Ymd'),
1474 'start_date' => date('Ymd'),
1475 'scheduled_date' => date('Ymd'),
1477 'pledge_status_id' => '2',
1478 'financial_type_id' => '1',
1479 'pledge_original_installment_amount' => 20,
1480 'frequency_interval' => 5,
1481 'frequency_unit' => 'year',
1482 'frequency_day' => 15,
1483 'installments' => 5,
1487 $result = $this->callAPISuccess('Pledge', 'create', $params);
1488 return $result['id'];
1492 * Delete contribution.
1494 * @param int $pledgeId
1496 public function pledgeDelete($pledgeId) {
1498 'pledge_id' => $pledgeId,
1500 $this->callAPISuccess('Pledge', 'delete', $params);
1504 * Create contribution.
1506 * @param array $params
1507 * Array of parameters.
1510 * id of created contribution
1512 public function contributionCreate($params) {
1514 $params = array_merge(array(
1516 'receive_date' => date('Ymd'),
1517 'total_amount' => 100.00,
1518 'fee_amount' => 5.00,
1519 'net_ammount' => 95.00,
1520 'financial_type_id' => 1,
1521 'payment_instrument_id' => 1,
1522 'non_deductible_amount' => 10.00,
1524 'invoice_id' => 67890,
1526 'contribution_status_id' => 1,
1529 $result = $this->callAPISuccess('contribution', 'create', $params);
1530 return $result['id'];
1534 * Delete contribution.
1536 * @param int $contributionId
1540 public function contributionDelete($contributionId) {
1542 'contribution_id' => $contributionId,
1544 $result = $this->callAPISuccess('contribution', 'delete', $params);
1551 * @param array $params
1552 * Name-value pair for an event.
1556 public function eventCreate($params = array()) {
1557 // if no contact was passed, make up a dummy event creator
1558 if (!isset($params['contact_id'])) {
1559 $params['contact_id'] = $this->_contactCreate(array(
1560 'contact_type' => 'Individual',
1561 'first_name' => 'Event',
1562 'last_name' => 'Creator',
1566 // set defaults for missing params
1567 $params = array_merge(array(
1568 'title' => 'Annual CiviCRM meet',
1569 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1570 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1571 'event_type_id' => 1,
1573 'start_date' => 20081021,
1574 'end_date' => 20081023,
1575 'is_online_registration' => 1,
1576 'registration_start_date' => 20080601,
1577 'registration_end_date' => 20081015,
1578 'max_participants' => 100,
1579 'event_full_text' => 'Sorry! We are already full',
1582 'is_show_location' => 0,
1585 return $this->callAPISuccess('Event', 'create', $params);
1596 public function eventDelete($id) {
1600 return $this->callAPISuccess('event', 'delete', $params);
1604 * Delete participant.
1606 * @param int $participantID
1610 public function participantDelete($participantID) {
1612 'id' => $participantID,
1614 return $this->callAPISuccess('Participant', 'delete', $params);
1618 * Create participant payment.
1620 * @param int $participantID
1621 * @param int $contributionID
1623 * $id of created payment
1625 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1626 //Create Participant Payment record With Values
1628 'participant_id' => $participantID,
1629 'contribution_id' => $contributionID,
1632 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1633 return $result['id'];
1637 * Delete participant payment.
1639 * @param int $paymentID
1641 public function participantPaymentDelete($paymentID) {
1645 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1651 * @param int $contactID
1653 * location id of created location
1655 public function locationAdd($contactID) {
1658 'location_type' => 'New Location Type',
1660 'name' => 'Saint Helier St',
1661 'county' => 'Marin',
1662 'country' => 'UNITED STATES',
1663 'state_province' => 'Michigan',
1664 'supplemental_address_1' => 'Hallmark Ct',
1665 'supplemental_address_2' => 'Jersey Village',
1670 'contact_id' => $contactID,
1671 'address' => $address,
1672 'location_format' => '2.0',
1673 'location_type' => 'New Location Type',
1676 $result = $this->callAPISuccess('Location', 'create', $params);
1681 * Delete Locations of contact.
1683 * @param array $params
1686 public function locationDelete($params) {
1687 $this->callAPISuccess('Location', 'delete', $params);
1691 * Add a Location Type.
1693 * @param array $params
1694 * @return CRM_Core_DAO_LocationType
1695 * location id of created location
1697 public function locationTypeCreate($params = NULL) {
1698 if ($params === NULL) {
1700 'name' => 'New Location Type',
1701 'vcard_name' => 'New Location Type',
1702 'description' => 'Location Type for Delete',
1707 $locationType = new CRM_Core_DAO_LocationType();
1708 $locationType->copyValues($params);
1709 $locationType->save();
1710 // clear getfields cache
1711 CRM_Core_PseudoConstant
::flush();
1712 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1713 return $locationType;
1717 * Delete a Location Type.
1719 * @param int $locationTypeId
1721 public function locationTypeDelete($locationTypeId) {
1722 $locationType = new CRM_Core_DAO_LocationType();
1723 $locationType->id
= $locationTypeId;
1724 $locationType->delete();
1730 * @param array $params
1731 * @return CRM_Core_DAO_Mapping
1732 * Mapping id of created mapping
1734 public function mappingCreate($params = NULL) {
1735 if ($params === NULL) {
1737 'name' => 'Mapping name',
1738 'description' => 'Mapping description',
1739 // 'Export Contact' mapping.
1740 'mapping_type_id' => 7,
1744 $mapping = new CRM_Core_DAO_Mapping();
1745 $mapping->copyValues($params);
1747 // clear getfields cache
1748 CRM_Core_PseudoConstant
::flush();
1749 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1756 * @param int $mappingId
1758 public function mappingDelete($mappingId) {
1759 $mapping = new CRM_Core_DAO_Mapping();
1760 $mapping->id
= $mappingId;
1767 * @param array $params
1769 * groupId of created group
1771 public function groupCreate($params = array()) {
1772 $params = array_merge(array(
1773 'name' => 'Test Group 1',
1775 'title' => 'New Test Group Created',
1776 'description' => 'New Test Group Created',
1778 'visibility' => 'Public Pages',
1779 'group_type' => array(
1785 $result = $this->callAPISuccess('Group', 'create', $params);
1786 return $result['id'];
1791 * Function to add a Group.
1793 * @params array to add group
1795 * @param int $groupID
1796 * @param int $totalCount
1798 * groupId of created group
1800 public function groupContactCreate($groupID, $totalCount = 10) {
1801 $params = array('group_id' => $groupID);
1802 for ($i = 1; $i <= $totalCount; $i++
) {
1803 $contactID = $this->individualCreate();
1805 $params +
= array('contact_id' => $contactID);
1808 $params +
= array("contact_id.$i" => $contactID);
1811 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1821 public function groupDelete($gid) {
1827 $this->callAPISuccess('Group', 'delete', $params);
1832 * @param array $params
1834 public function uFFieldCreate($params = array()) {
1835 $params = array_merge(array(
1837 'field_name' => 'first_name',
1840 'visibility' => 'Public Pages and Listings',
1841 'is_searchable' => '1',
1842 'label' => 'first_name',
1843 'field_type' => 'Individual',
1846 $this->callAPISuccess('uf_field', 'create', $params);
1850 * Add a UF Join Entry.
1852 * @param array $params
1854 * $id of created UF Join
1856 public function ufjoinCreate($params = NULL) {
1857 if ($params === NULL) {
1860 'module' => 'CiviEvent',
1861 'entity_table' => 'civicrm_event',
1867 $result = $this->callAPISuccess('uf_join', 'create', $params);
1872 * Delete a UF Join Entry.
1874 * @param array $params
1875 * with missing uf_group_id
1877 public function ufjoinDelete($params = NULL) {
1878 if ($params === NULL) {
1881 'module' => 'CiviEvent',
1882 'entity_table' => 'civicrm_event',
1885 'uf_group_id' => '',
1889 crm_add_uf_join($params);
1893 * @param array $params
1894 * Optional parameters.
1899 public function campaignCreate($params = array()) {
1900 $this->enableCiviCampaign();
1901 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1902 'name' => 'big_campaign',
1903 'title' => 'Campaign',
1905 return $campaign['id'];
1909 * Create Group for a contact.
1911 * @param int $contactId
1913 public function contactGroupCreate($contactId) {
1915 'contact_id.1' => $contactId,
1919 $this->callAPISuccess('GroupContact', 'Create', $params);
1923 * Delete Group for a contact.
1925 * @param int $contactId
1927 public function contactGroupDelete($contactId) {
1929 'contact_id.1' => $contactId,
1932 $this->civicrm_api('GroupContact', 'Delete', $params);
1938 * @param array $params
1941 public function activityCreate($params = NULL) {
1943 if ($params === NULL) {
1944 $individualSourceID = $this->individualCreate();
1946 $contactParams = array(
1947 'first_name' => 'Julia',
1948 'Last_name' => 'Anderson',
1950 'email' => 'julia_anderson@civicrm.org',
1951 'contact_type' => 'Individual',
1954 $individualTargetID = $this->individualCreate($contactParams);
1957 'source_contact_id' => $individualSourceID,
1958 'target_contact_id' => array($individualTargetID),
1959 'assignee_contact_id' => array($individualTargetID),
1960 'subject' => 'Discussion on warm beer',
1961 'activity_date_time' => date('Ymd'),
1962 'duration_hours' => 30,
1963 'duration_minutes' => 20,
1964 'location' => 'Baker Street',
1965 'details' => 'Lets schedule a meeting',
1967 'activity_name' => 'Meeting',
1971 $result = $this->callAPISuccess('Activity', 'create', $params);
1973 $result['target_contact_id'] = $individualTargetID;
1974 $result['assignee_contact_id'] = $individualTargetID;
1979 * Create an activity type.
1981 * @param array $params
1985 public function activityTypeCreate($params) {
1986 return $this->callAPISuccess('ActivityType', 'create', $params);
1990 * Delete activity type.
1992 * @param int $activityTypeId
1993 * Id of the activity type.
1996 public function activityTypeDelete($activityTypeId) {
1997 $params['activity_type_id'] = $activityTypeId;
1998 return $this->callAPISuccess('ActivityType', 'delete', $params);
2002 * Create custom group.
2004 * @param array $params
2007 public function customGroupCreate($params = array()) {
2009 'title' => 'new custom group',
2010 'extends' => 'Contact',
2012 'style' => 'Inline',
2016 $params = array_merge($defaults, $params);
2018 if (strlen($params['title']) > 13) {
2019 $params['title'] = substr($params['title'], 0, 13);
2022 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2023 $this->callAPISuccess('custom_group', 'get', array(
2024 'title' => $params['title'],
2025 array('api.custom_group.delete' => 1),
2028 return $this->callAPISuccess('custom_group', 'create', $params);
2032 * Existing function doesn't allow params to be over-ridden so need a new one
2033 * this one allows you to only pass in the params you want to change
2034 * @param array $params
2037 public function CustomGroupCreateByParams($params = array()) {
2039 'title' => "API Custom Group",
2040 'extends' => 'Contact',
2042 'style' => 'Inline',
2045 $params = array_merge($defaults, $params);
2046 return $this->callAPISuccess('custom_group', 'create', $params);
2050 * Create custom group with multi fields.
2051 * @param array $params
2054 public function CustomGroupMultipleCreateByParams($params = array()) {
2059 $params = array_merge($defaults, $params);
2060 return $this->CustomGroupCreateByParams($params);
2064 * Create custom group with multi fields.
2065 * @param array $params
2068 public function CustomGroupMultipleCreateWithFields($params = array()) {
2069 // also need to pass on $params['custom_field'] if not set but not in place yet
2071 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2072 $ids['custom_group_id'] = $customGroup['id'];
2074 $customField = $this->customFieldCreate(array(
2075 'custom_group_id' => $ids['custom_group_id'],
2076 'label' => 'field_1' . $ids['custom_group_id'],
2080 $ids['custom_field_id'][] = $customField['id'];
2082 $customField = $this->customFieldCreate(array(
2083 'custom_group_id' => $ids['custom_group_id'],
2084 'default_value' => '',
2085 'label' => 'field_2' . $ids['custom_group_id'],
2088 $ids['custom_field_id'][] = $customField['id'];
2090 $customField = $this->customFieldCreate(array(
2091 'custom_group_id' => $ids['custom_group_id'],
2092 'default_value' => '',
2093 'label' => 'field_3' . $ids['custom_group_id'],
2096 $ids['custom_field_id'][] = $customField['id'];
2102 * Create a custom group with a single text custom field. See
2103 * participant:testCreateWithCustom for how to use this
2105 * @param string $function
2107 * @param string $filename
2111 * ids of created objects
2113 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2114 $params = array('title' => $function);
2115 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2116 $params['extends'] = $entity ?
$entity : 'Contact';
2117 $customGroup = $this->CustomGroupCreate($params);
2118 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2119 CRM_Core_PseudoConstant
::flush();
2121 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2125 * Delete custom group.
2127 * @param int $customGroupID
2131 public function customGroupDelete($customGroupID) {
2132 $params['id'] = $customGroupID;
2133 return $this->callAPISuccess('custom_group', 'delete', $params);
2137 * Create custom field.
2139 * @param array $params
2140 * (custom_group_id) is required.
2143 public function customFieldCreate($params) {
2144 $params = array_merge(array(
2145 'label' => 'Custom Field',
2146 'data_type' => 'String',
2147 'html_type' => 'Text',
2148 'is_searchable' => 1,
2150 'default_value' => 'defaultValue',
2153 $result = $this->callAPISuccess('custom_field', 'create', $params);
2154 // these 2 functions are called with force to flush static caches
2155 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2156 CRM_Core_Component
::getEnabledComponents(1);
2161 * Delete custom field.
2163 * @param int $customFieldID
2167 public function customFieldDelete($customFieldID) {
2169 $params['id'] = $customFieldID;
2170 return $this->callAPISuccess('custom_field', 'delete', $params);
2179 public function noteCreate($cId) {
2181 'entity_table' => 'civicrm_contact',
2182 'entity_id' => $cId,
2183 'note' => 'hello I am testing Note',
2184 'contact_id' => $cId,
2185 'modified_date' => date('Ymd'),
2186 'subject' => 'Test Note',
2189 return $this->callAPISuccess('Note', 'create', $params);
2193 * Enable CiviCampaign Component.
2195 public function enableCiviCampaign() {
2196 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2197 // force reload of config object
2198 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2199 //flush cache by calling with reset
2200 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2204 * Create test generated example in api/v3/examples.
2206 * To turn this off (e.g. on the server) set
2207 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2208 * in your settings file
2210 * @param string $entity
2211 * @param string $action
2212 * @param array $params
2213 * Array as passed to civicrm_api function.
2214 * @param array $result
2215 * Array as received from the civicrm_api function.
2216 * @param string $testFunction
2217 * Calling function - generally __FUNCTION__.
2218 * @param string $testFile
2219 * Called from file - generally __FILE__.
2220 * @param string $description
2221 * Descriptive text for the example file.
2222 * @param string $exampleName
2223 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2225 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2226 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2229 $entity = _civicrm_api_get_camel_name($entity);
2230 $action = strtolower($action);
2232 if (empty($exampleName)) {
2233 // Attempt to convert lowercase action name to CamelCase.
2234 // This is clunky/imperfect due to the convention of all lowercase actions.
2235 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2236 $knownPrefixes = array(
2243 foreach ($knownPrefixes as $prefix) {
2244 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2245 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2250 $this->tidyExampleResult($result);
2251 if (isset($params['version'])) {
2252 unset($params['version']);
2254 // Format multiline description as array
2256 if (is_string($description) && strlen($description)) {
2257 foreach (explode("\n", $description) as $line) {
2258 $desc[] = trim($line);
2261 $smarty = CRM_Core_Smarty
::singleton();
2262 $smarty->assign('testFunction', $testFunction);
2263 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2264 $smarty->assign('params', $params);
2265 $smarty->assign('entity', $entity);
2266 $smarty->assign('testFile', basename($testFile));
2267 $smarty->assign('description', $desc);
2268 $smarty->assign('result', $result);
2269 $smarty->assign('action', $action);
2271 global $civicrm_root;
2272 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2273 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2274 mkdir($civicrm_root . "/api/v3/examples/$entity");
2276 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2277 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2283 * Tidy up examples array so that fields that change often ..don't
2284 * and debug related fields are unset
2286 * @param array $result
2288 public function tidyExampleResult(&$result) {
2289 if (!is_array($result)) {
2292 $fieldsToChange = array(
2293 'hash' => '67eac7789eaee00',
2294 'modified_date' => '2012-11-14 16:02:35',
2295 'created_date' => '2013-07-28 08:49:19',
2296 'create_date' => '20120130621222105',
2297 'application_received_date' => '20130728084957',
2298 'in_date' => '2013-07-28 08:50:19',
2299 'scheduled_date' => '20130728085413',
2300 'approval_date' => '20130728085413',
2301 'pledge_start_date_high' => '20130726090416',
2302 'start_date' => '2013-07-29 00:00:00',
2303 'event_start_date' => '2013-07-29 00:00:00',
2304 'end_date' => '2013-08-04 00:00:00',
2305 'event_end_date' => '2013-08-04 00:00:00',
2306 'decision_date' => '20130805000000',
2309 $keysToUnset = array('xdebug', 'undefined_fields');
2310 foreach ($keysToUnset as $unwantedKey) {
2311 if (isset($result[$unwantedKey])) {
2312 unset($result[$unwantedKey]);
2315 if (isset($result['values'])) {
2316 if (!is_array($result['values'])) {
2319 $resultArray = &$result['values'];
2321 elseif (is_array($result)) {
2322 $resultArray = &$result;
2328 foreach ($resultArray as $index => &$values) {
2329 if (!is_array($values)) {
2332 foreach ($values as $key => &$value) {
2333 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2334 if (isset($value['is_error'])) {
2335 // we have a std nested result format
2336 $this->tidyExampleResult($value);
2339 foreach ($value as &$nestedResult) {
2340 // this is an alternative syntax for nested results a keyed array of results
2341 $this->tidyExampleResult($nestedResult);
2345 if (in_array($key, $keysToUnset)) {
2346 unset($values[$key]);
2349 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2350 $value = $fieldsToChange[$key];
2352 if (is_string($value)) {
2353 $value = addslashes($value);
2362 * @param array $params
2366 public function noteDelete($params) {
2367 return $this->callAPISuccess('Note', 'delete', $params);
2371 * Create custom field with Option Values.
2373 * @param array $customGroup
2374 * @param string $name
2375 * Name of custom field.
2379 public function customFieldOptionValueCreate($customGroup, $name) {
2380 $fieldParams = array(
2381 'custom_group_id' => $customGroup['id'],
2382 'name' => 'test_custom_group',
2383 'label' => 'Country',
2384 'html_type' => 'Select',
2385 'data_type' => 'String',
2388 'is_searchable' => 0,
2392 $optionGroup = array(
2394 'name' => 'option_group1',
2395 'label' => 'option_group_label1',
2398 $optionValue = array(
2399 'option_label' => array('Label1', 'Label2'),
2400 'option_value' => array('value1', 'value2'),
2401 'option_name' => array($name . '_1', $name . '_2'),
2402 'option_weight' => array(1, 2),
2403 'option_status' => 1,
2406 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2408 return $this->callAPISuccess('custom_field', 'create', $params);
2416 public function confirmEntitiesDeleted($entities) {
2417 foreach ($entities as $entity) {
2419 $result = $this->callAPISuccess($entity, 'Get', array());
2420 if ($result['error'] == 1 ||
$result['count'] > 0) {
2421 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2429 * Quick clean by emptying tables created for the test.
2431 * @param array $tablesToTruncate
2432 * @param bool $dropCustomValueTables
2433 * @throws \Exception
2435 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2437 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2439 if ($dropCustomValueTables) {
2440 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2441 while ($optionGroupResult->fetch()) {
2442 if (!empty($optionGroupResult->option_group_id
)) {
2443 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2446 $tablesToTruncate[] = 'civicrm_custom_group';
2447 $tablesToTruncate[] = 'civicrm_custom_field';
2450 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2452 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2453 foreach ($tablesToTruncate as $table) {
2454 $sql = "TRUNCATE TABLE $table";
2455 CRM_Core_DAO
::executeQuery($sql);
2457 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2459 if ($dropCustomValueTables) {
2460 $dbName = self
::getDBName();
2462 SELECT TABLE_NAME as tableName
2463 FROM INFORMATION_SCHEMA.TABLES
2464 WHERE TABLE_SCHEMA = '{$dbName}'
2465 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2468 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2469 while ($tableDAO->fetch()) {
2470 $sql = "DROP TABLE {$tableDAO->tableName}";
2471 CRM_Core_DAO
::executeQuery($sql);
2477 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2479 public function quickCleanUpFinancialEntities() {
2480 $tablesToTruncate = array(
2482 'civicrm_activity_contact',
2483 'civicrm_contribution',
2484 'civicrm_contribution_soft',
2485 'civicrm_contribution_product',
2486 'civicrm_financial_trxn',
2487 'civicrm_financial_item',
2488 'civicrm_contribution_recur',
2489 'civicrm_line_item',
2490 'civicrm_contribution_page',
2491 'civicrm_payment_processor',
2492 'civicrm_entity_financial_trxn',
2493 'civicrm_membership',
2494 'civicrm_membership_type',
2495 'civicrm_membership_payment',
2496 'civicrm_membership_log',
2497 'civicrm_membership_block',
2499 'civicrm_participant',
2500 'civicrm_participant_payment',
2502 'civicrm_pledge_payment',
2503 'civicrm_price_set_entity',
2504 'civicrm_price_field_value',
2505 'civicrm_price_field',
2507 $this->quickCleanup($tablesToTruncate);
2508 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2509 $this->restoreDefaultPriceSetConfig();
2511 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2512 System
::singleton()->flushProcessors();
2515 public function restoreDefaultPriceSetConfig() {
2516 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2517 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)");
2518 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`, `deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2521 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2522 * Default behaviour is to also delete the entity
2523 * @param array $params
2524 * Params array to check against.
2526 * Id of the entity concerned.
2527 * @param string $entity
2528 * Name of entity concerned (e.g. membership).
2529 * @param bool $delete
2530 * Should the entity be deleted as part of this check.
2531 * @param string $errorText
2532 * Text to print on error.
2535 * @param array $params
2538 * @param int $delete
2539 * @param string $errorText
2543 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2545 $result = $this->callAPISuccessGetSingle($entity, array(
2550 $this->callAPISuccess($entity, 'Delete', array(
2554 $dateFields = $keys = $dateTimeFields = array();
2555 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2556 foreach ($fields['values'] as $field => $settings) {
2557 if (array_key_exists($field, $result)) {
2558 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2561 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2563 $type = CRM_Utils_Array
::value('type', $settings);
2564 if ($type == CRM_Utils_Type
::T_DATE
) {
2565 $dateFields[] = $settings['name'];
2566 // we should identify both real names & unique names as dates
2567 if ($field != $settings['name']) {
2568 $dateFields[] = $field;
2571 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2572 $dateTimeFields[] = $settings['name'];
2573 // we should identify both real names & unique names as dates
2574 if ($field != $settings['name']) {
2575 $dateTimeFields[] = $field;
2580 if (strtolower($entity) == 'contribution') {
2581 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2582 // this is not returned in id format
2583 unset($params['payment_instrument_id']);
2584 $params['contribution_source'] = $params['source'];
2585 unset($params['source']);
2588 foreach ($params as $key => $value) {
2589 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2592 if (in_array($key, $dateFields)) {
2593 $value = date('Y-m-d', strtotime($value));
2594 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2596 if (in_array($key, $dateTimeFields)) {
2597 $value = date('Y-m-d H:i:s', strtotime($value));
2598 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2600 $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);
2605 * Get formatted values in the actual and expected result.
2606 * @param array $actual
2607 * Actual calculated values.
2608 * @param array $expected
2611 public function checkArrayEquals(&$actual, &$expected) {
2612 self
::unsetId($actual);
2613 self
::unsetId($expected);
2614 $this->assertEquals($actual, $expected);
2618 * Unset the key 'id' from the array
2619 * @param array $unformattedArray
2620 * The array from which the 'id' has to be unset.
2622 public static function unsetId(&$unformattedArray) {
2623 $formattedArray = array();
2624 if (array_key_exists('id', $unformattedArray)) {
2625 unset($unformattedArray['id']);
2627 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2628 foreach ($unformattedArray['values'] as $key => $value) {
2629 if (is_array($value)) {
2630 foreach ($value as $k => $v) {
2636 elseif ($key == 'id') {
2637 $unformattedArray[$key];
2639 $formattedArray = array($value);
2641 $unformattedArray['values'] = $formattedArray;
2646 * Helper to enable/disable custom directory support
2648 * @param array $customDirs
2650 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2651 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2653 public function customDirectories($customDirs) {
2654 $config = CRM_Core_Config
::singleton();
2656 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2657 unset($config->customPHPPathDir
);
2659 elseif ($customDirs['php_path'] === TRUE) {
2660 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2663 $config->customPHPPathDir
= $php_path;
2666 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2667 unset($config->customTemplateDir
);
2669 elseif ($customDirs['template_path'] === TRUE) {
2670 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2673 $config->customTemplateDir
= $template_path;
2678 * Generate a temporary folder.
2680 * @param string $prefix
2683 public function createTempDir($prefix = 'test-') {
2684 $tempDir = CRM_Utils_File
::tempdir($prefix);
2685 $this->tempDirs
[] = $tempDir;
2689 public function cleanTempDirs() {
2690 if (!is_array($this->tempDirs
)) {
2691 // fix test errors where this is not set
2694 foreach ($this->tempDirs
as $tempDir) {
2695 if (is_dir($tempDir)) {
2696 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2702 * Temporarily replace the singleton extension with a different one.
2703 * @param \CRM_Extension_System $system
2705 public function setExtensionSystem(CRM_Extension_System
$system) {
2706 if ($this->origExtensionSystem
== NULL) {
2707 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2709 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2712 public function unsetExtensionSystem() {
2713 if ($this->origExtensionSystem
!== NULL) {
2714 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2715 $this->origExtensionSystem
= NULL;
2720 * Temporarily alter the settings-metadata to add a mock setting.
2722 * WARNING: The setting metadata will disappear on the next cache-clear.
2727 public function setMockSettingsMetaData($extras) {
2728 Civi
::service('settings_manager')->flush();
2730 CRM_Utils_Hook
::singleton()
2731 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2732 $metadata = array_merge($metadata, $extras);
2735 $fields = $this->callAPISuccess('setting', 'getfields', array());
2736 foreach ($extras as $key => $spec) {
2737 $this->assertNotEmpty($spec['title']);
2738 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2743 * @param string $name
2745 public function financialAccountDelete($name) {
2746 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2747 $financialAccount->name
= $name;
2748 if ($financialAccount->find(TRUE)) {
2749 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2750 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2751 $entityFinancialType->delete();
2752 $financialAccount->delete();
2757 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2758 * (NB unclear if this is still required)
2760 public function _sethtmlGlobals() {
2761 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2762 'required' => array(
2763 'html_quickform_rule_required',
2764 'HTML/QuickForm/Rule/Required.php',
2766 'maxlength' => array(
2767 'html_quickform_rule_range',
2768 'HTML/QuickForm/Rule/Range.php',
2770 'minlength' => array(
2771 'html_quickform_rule_range',
2772 'HTML/QuickForm/Rule/Range.php',
2774 'rangelength' => array(
2775 'html_quickform_rule_range',
2776 'HTML/QuickForm/Rule/Range.php',
2779 'html_quickform_rule_email',
2780 'HTML/QuickForm/Rule/Email.php',
2783 'html_quickform_rule_regex',
2784 'HTML/QuickForm/Rule/Regex.php',
2786 'lettersonly' => array(
2787 'html_quickform_rule_regex',
2788 'HTML/QuickForm/Rule/Regex.php',
2790 'alphanumeric' => array(
2791 'html_quickform_rule_regex',
2792 'HTML/QuickForm/Rule/Regex.php',
2795 'html_quickform_rule_regex',
2796 'HTML/QuickForm/Rule/Regex.php',
2798 'nopunctuation' => array(
2799 'html_quickform_rule_regex',
2800 'HTML/QuickForm/Rule/Regex.php',
2803 'html_quickform_rule_regex',
2804 'HTML/QuickForm/Rule/Regex.php',
2806 'callback' => array(
2807 'html_quickform_rule_callback',
2808 'HTML/QuickForm/Rule/Callback.php',
2811 'html_quickform_rule_compare',
2812 'HTML/QuickForm/Rule/Compare.php',
2815 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2816 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2818 'HTML/QuickForm/group.php',
2819 'HTML_QuickForm_group',
2822 'HTML/QuickForm/hidden.php',
2823 'HTML_QuickForm_hidden',
2826 'HTML/QuickForm/reset.php',
2827 'HTML_QuickForm_reset',
2829 'checkbox' => array(
2830 'HTML/QuickForm/checkbox.php',
2831 'HTML_QuickForm_checkbox',
2834 'HTML/QuickForm/file.php',
2835 'HTML_QuickForm_file',
2838 'HTML/QuickForm/image.php',
2839 'HTML_QuickForm_image',
2841 'password' => array(
2842 'HTML/QuickForm/password.php',
2843 'HTML_QuickForm_password',
2846 'HTML/QuickForm/radio.php',
2847 'HTML_QuickForm_radio',
2850 'HTML/QuickForm/button.php',
2851 'HTML_QuickForm_button',
2854 'HTML/QuickForm/submit.php',
2855 'HTML_QuickForm_submit',
2858 'HTML/QuickForm/select.php',
2859 'HTML_QuickForm_select',
2861 'hiddenselect' => array(
2862 'HTML/QuickForm/hiddenselect.php',
2863 'HTML_QuickForm_hiddenselect',
2866 'HTML/QuickForm/text.php',
2867 'HTML_QuickForm_text',
2869 'textarea' => array(
2870 'HTML/QuickForm/textarea.php',
2871 'HTML_QuickForm_textarea',
2873 'fckeditor' => array(
2874 'HTML/QuickForm/fckeditor.php',
2875 'HTML_QuickForm_FCKEditor',
2878 'HTML/QuickForm/tinymce.php',
2879 'HTML_QuickForm_TinyMCE',
2881 'dojoeditor' => array(
2882 'HTML/QuickForm/dojoeditor.php',
2883 'HTML_QuickForm_dojoeditor',
2886 'HTML/QuickForm/link.php',
2887 'HTML_QuickForm_link',
2889 'advcheckbox' => array(
2890 'HTML/QuickForm/advcheckbox.php',
2891 'HTML_QuickForm_advcheckbox',
2894 'HTML/QuickForm/date.php',
2895 'HTML_QuickForm_date',
2898 'HTML/QuickForm/static.php',
2899 'HTML_QuickForm_static',
2902 'HTML/QuickForm/header.php',
2903 'HTML_QuickForm_header',
2906 'HTML/QuickForm/html.php',
2907 'HTML_QuickForm_html',
2909 'hierselect' => array(
2910 'HTML/QuickForm/hierselect.php',
2911 'HTML_QuickForm_hierselect',
2913 'autocomplete' => array(
2914 'HTML/QuickForm/autocomplete.php',
2915 'HTML_QuickForm_autocomplete',
2918 'HTML/QuickForm/xbutton.php',
2919 'HTML_QuickForm_xbutton',
2921 'advmultiselect' => array(
2922 'HTML/QuickForm/advmultiselect.php',
2923 'HTML_QuickForm_advmultiselect',
2929 * Set up an acl allowing contact to see 2 specified groups
2930 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2932 * You need to have pre-created these groups & created the user e.g
2933 * $this->createLoggedInUser();
2934 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2935 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2937 * @param bool $isProfile
2939 public function setupACL($isProfile = FALSE) {
2941 $_REQUEST = $this->_params
;
2943 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2944 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2945 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2946 'option_group_id' => $optionGroupID,
2947 'label' => 'pick me',
2951 CRM_Core_DAO
::executeQuery("
2952 TRUNCATE civicrm_acl_cache
2955 CRM_Core_DAO
::executeQuery("
2956 TRUNCATE civicrm_acl_contact_cache
2959 CRM_Core_DAO
::executeQuery("
2960 INSERT INTO civicrm_acl_entity_role (
2961 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2962 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2966 CRM_Core_DAO
::executeQuery("
2967 INSERT INTO civicrm_acl (
2968 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2971 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2976 CRM_Core_DAO
::executeQuery("
2977 INSERT INTO civicrm_acl (
2978 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2981 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2985 CRM_Core_DAO
::executeQuery("
2986 INSERT INTO civicrm_acl (
2987 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2990 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2995 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2996 $this->callAPISuccess('group_contact', 'create', array(
2997 'group_id' => $this->_permissionedGroup
,
2998 'contact_id' => $this->_loggedInUser
,
3003 CRM_ACL_BAO_Cache
::resetCache();
3004 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3005 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3010 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3012 public function offsetDefaultPriceSet() {
3013 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3014 $firstID = $contributionPriceSet['id'];
3015 $this->callAPISuccess('price_set', 'create', array(
3016 'id' => $contributionPriceSet['id'],
3020 unset($contributionPriceSet['id']);
3021 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3022 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3023 'price_set_id' => $firstID,
3024 'options' => array('limit' => 1),
3026 unset($priceField['id']);
3027 $priceField['price_set_id'] = $newPriceSet['id'];
3028 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3029 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3030 'price_set_id' => $firstID,
3032 'options' => array('limit' => 1),
3035 unset($priceFieldValue['id']);
3036 //create some padding to use up ids
3037 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3038 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3039 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3043 * Create an instance of the paypal processor.
3044 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3045 * this parent class & we don't have a structure for that yet
3046 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3047 * & the best protection against that is the functions this class affords
3048 * @param array $params
3049 * @return int $result['id'] payment processor id
3051 public function paymentProcessorCreate($params = array()) {
3052 $params = array_merge(array(
3054 'domain_id' => CRM_Core_Config
::domainID(),
3055 'payment_processor_type_id' => 'PayPal',
3059 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3060 'password' => '1183377788',
3061 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3062 'url_site' => 'https://www.sandbox.paypal.com/',
3063 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3064 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3065 'class_name' => 'Payment_PayPalImpl',
3066 'billing_mode' => 3,
3067 'financial_type_id' => 1,
3068 'financial_account_id' => 12,
3071 if (!is_numeric($params['payment_processor_type_id'])) {
3072 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3074 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3075 'name' => $params['payment_processor_type_id'],
3079 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3080 return $result['id'];
3084 * Set up initial recurring payment allowing subsequent IPN payments.
3086 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3087 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3088 'contact_id' => $this->_contactID
,
3091 'installments' => 5,
3092 'frequency_unit' => 'Month',
3093 'frequency_interval' => 1,
3094 'invoice_id' => $this->_invoiceID
,
3095 'contribution_status_id' => 2,
3096 'payment_processor_id' => $this->_paymentProcessorID
,
3097 // processor provided ID - use contact ID as proxy.
3098 'processor_id' => $this->_contactID
,
3099 'api.contribution.create' => array(
3100 'total_amount' => '200',
3101 'invoice_id' => $this->_invoiceID
,
3102 'financial_type_id' => 1,
3103 'contribution_status_id' => 'Pending',
3104 'contact_id' => $this->_contactID
,
3105 'contribution_page_id' => $this->_contributionPageID
,
3106 'payment_processor_id' => $this->_paymentProcessorID
,
3110 $this->_contributionRecurID
= $contributionRecur['id'];
3111 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3115 * 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
3117 public function setupMembershipRecurringPaymentProcessorTransaction() {
3118 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3119 //create a contribution so our membership & contribution don't both have id = 1
3120 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3121 $this->contributionCreate(array(
3122 'contact_id' => $this->_contactID
,
3124 'financial_type_id' => 1,
3125 'invoice_id' => 'abcd',
3129 $this->setupRecurringPaymentProcessorTransaction();
3131 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3132 'contact_id' => $this->_contactID
,
3133 'membership_type_id' => $this->ids
['membership_type'],
3134 'contribution_recur_id' => $this->_contributionRecurID
,
3135 'format.only_id' => TRUE,
3137 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3138 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3140 $this->callAPISuccess('line_item', 'create', array(
3141 'entity_table' => 'civicrm_membership',
3142 'entity_id' => $this->ids
['membership'],
3143 'contribution_id' => $this->_contributionID
,
3144 'label' => 'General',
3146 'unit_price' => 200,
3147 'line_total' => 200,
3148 'financial_type_id' => 1,
3149 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3151 'label' => 'Membership Amount',
3152 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3154 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3156 'label' => 'General',
3157 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3160 $this->callAPISuccess('membership_payment', 'create', array(
3161 'contribution_id' => $this->_contributionID
,
3162 'membership_id' => $this->ids
['membership'],
3171 public function CiviUnitTestCase_fatalErrorHandler($message) {
3172 throw new Exception("{$message['message']}: {$message['code']}");
3176 * Helper function to create new mailing.
3179 public function createMailing() {
3181 'subject' => 'maild' . rand(),
3182 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3183 'name' => 'mailing name' . rand(),
3187 $result = $this->callAPISuccess('Mailing', 'create', $params);
3188 return $result['id'];
3192 * Helper function to delete mailing.
3195 public function deleteMailing($id) {
3200 $this->callAPISuccess('Mailing', 'delete', $params);
3204 * Wrap the entire test case in a transaction.
3206 * Only subsequent DB statements will be wrapped in TX -- this cannot
3207 * retroactively wrap old DB statements. Therefore, it makes sense to
3208 * call this at the beginning of setUp().
3210 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3211 * this option does not work with, e.g., custom-data.
3213 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3214 * if TRUNCATE or ALTER is called while using a transaction.
3217 * Whether to use nesting or reference-counting.
3219 public function useTransaction($nest = TRUE) {
3221 $this->tx
= new CRM_Core_Transaction($nest);
3222 $this->tx
->rollback();
3227 * Assert the attachment exists.
3229 * @param bool $exists
3230 * @param array $apiResult
3232 protected function assertAttachmentExistence($exists, $apiResult) {
3233 $fileId = $apiResult['id'];
3234 $this->assertTrue(is_numeric($fileId));
3235 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3236 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3237 1 => array($fileId, 'Int'),
3239 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3240 1 => array($fileId, 'Int'),
3245 * Create a price set for an event.
3247 * @param int $feeTotal
3252 protected function eventPriceSetCreate($feeTotal) {
3253 // creating price set, price field
3254 $paramsSet['title'] = 'Price Set';
3255 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3256 $paramsSet['is_active'] = FALSE;
3257 $paramsSet['extends'] = 1;
3259 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3260 $priceSetId = $priceset->id
;
3262 //Checking for priceset added in the table.
3263 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3264 'id', $paramsSet['title'], 'Check DB for created priceset'
3266 $paramsField = array(
3267 'label' => 'Price Field',
3268 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3269 'html_type' => 'Text',
3270 'price' => $feeTotal,
3271 'option_label' => array('1' => 'Price Field'),
3272 'option_value' => array('1' => $feeTotal),
3273 'option_name' => array('1' => $feeTotal),
3274 'option_weight' => array('1' => 1),
3275 'option_amount' => array('1' => 1),
3276 'is_display_amounts' => 1,
3278 'options_per_line' => 1,
3279 'is_active' => array('1' => 1),
3280 'price_set_id' => $priceset->id
,
3281 'is_enter_qty' => 1,
3282 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3284 CRM_Price_BAO_PriceField
::create($paramsField);
3290 * Add a profile to a contribution page.
3292 * @param string $name
3293 * @param int $contributionPageID
3295 protected function addProfile($name, $contributionPageID) {
3296 $this->callAPISuccess('UFJoin', 'create', array(
3297 'uf_group_id' => $name,
3298 'module' => 'CiviContribute',
3299 'entity_table' => 'civicrm_contribution_page',
3300 'entity_id' => $contributionPageID,
3306 * Add participant with contribution
3310 protected function createParticipantWithContribution() {
3311 // creating price set, price field
3312 $this->_contactId
= $this->individualCreate();
3313 $event = $this->eventCreate();
3314 $this->_eventId
= $event['id'];
3315 $eventParams = array(
3316 'id' => $this->_eventId
,
3317 'financial_type_id' => 4,
3320 $this->callAPISuccess('event', 'create', $eventParams);
3321 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3322 $participantParams = array(
3323 'financial_type_id' => 4,
3324 'event_id' => $this->_eventId
,
3327 'fee_currency' => 'USD',
3328 'contact_id' => $this->_contactId
,
3330 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3331 $contributionParams = array(
3332 'total_amount' => 150,
3333 'currency' => 'USD',
3334 'contact_id' => $this->_contactId
,
3335 'financial_type_id' => 4,
3336 'contribution_status_id' => 1,
3337 'partial_payment_total' => 300.00,
3338 'partial_amount_pay' => 150,
3339 'contribution_mode' => 'participant',
3340 'participant_id' => $participant['id'],
3342 foreach ($priceFields['values'] as $key => $priceField) {
3343 $lineItems[1][$key] = array(
3344 'price_field_id' => $priceField['price_field_id'],
3345 'price_field_value_id' => $priceField['id'],
3346 'label' => $priceField['label'],
3347 'field_title' => $priceField['label'],
3349 'unit_price' => $priceField['amount'],
3350 'line_total' => $priceField['amount'],
3351 'financial_type_id' => $priceField['financial_type_id'],
3354 $contributionParams['line_item'] = $lineItems;
3355 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3356 $paymentParticipant = array(
3357 'participant_id' => $participant['id'],
3358 'contribution_id' => $contribution['id'],
3361 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3362 return array($lineItems, $contribution);
3368 * @param string $component
3369 * @param int $componentId
3373 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3374 $paramsSet['title'] = 'Price Set';
3375 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3376 $paramsSet['is_active'] = TRUE;
3377 $paramsSet['financial_type_id'] = 4;
3378 $paramsSet['extends'] = 1;
3379 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3380 $priceSetId = $priceSet['id'];
3381 //Checking for priceset added in the table.
3382 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3383 'id', $paramsSet['title'], 'Check DB for created priceset'
3385 $paramsField = array(
3386 'label' => 'Price Field',
3387 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3388 'html_type' => 'CheckBox',
3389 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3390 'option_value' => array('1' => 100, '2' => 200),
3391 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3392 'option_weight' => array('1' => 1, '2' => 2),
3393 'option_amount' => array('1' => 100, '2' => 200),
3394 'is_display_amounts' => 1,
3396 'options_per_line' => 1,
3397 'is_active' => array('1' => 1, '2' => 1),
3398 'price_set_id' => $priceSet['id'],
3399 'is_enter_qty' => 1,
3400 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3402 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3404 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3406 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3410 * Replace the template with a test-oriented template designed to show all the variables.
3412 * @param string $templateName
3414 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3415 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3416 CRM_Core_DAO
::executeQuery(
3417 "UPDATE civicrm_option_group og
3418 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3419 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3420 SET m.msg_html = '{$testTemplate}'
3421 WHERE og.name = 'msg_tpl_workflow_contribution'
3422 AND ov.name = '{$templateName}'
3423 AND m.is_default = 1"
3428 * Reinstate the default template.
3430 * @param string $templateName
3432 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3433 CRM_Core_DAO
::executeQuery(
3434 "UPDATE civicrm_option_group og
3435 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3436 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3437 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3438 SET m.msg_html = m2.msg_html
3439 WHERE og.name = 'msg_tpl_workflow_contribution'
3440 AND ov.name = '{$templateName}'
3441 AND m.is_default = 1"
3446 * Flush statics relating to financial type.
3448 protected function flushFinancialTypeStatics() {
3449 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3450 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3452 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3453 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3455 CRM_Contribute_PseudoConstant
::flush('financialType');
3456 CRM_Contribute_PseudoConstant
::flush('membershipType');
3457 // Pseudoconstants may be saved to the cache table.
3458 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3459 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3460 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3464 * Set the permissions to the supplied array.
3466 * @param array $permissions
3468 protected function setPermissions($permissions) {
3469 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3470 $this->flushFinancialTypeStatics();
3471 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3475 * @param array $params
3478 public function _checkFinancialRecords($params, $context) {
3479 $entityParams = array(
3480 'entity_id' => $params['id'],
3481 'entity_table' => 'civicrm_contribution',
3483 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3484 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3485 if ($context == 'pending') {
3486 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3487 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3490 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3491 $trxnParams = array(
3492 'id' => $trxn['financial_trxn_id'],
3494 if ($context != 'online' && $context != 'payLater') {
3495 $compareParams = array(
3496 'to_financial_account_id' => 6,
3497 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3501 if ($context == 'feeAmount') {
3502 $compareParams['fee_amount'] = 50;
3504 elseif ($context == 'online') {
3505 $compareParams = array(
3506 'to_financial_account_id' => 12,
3507 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3509 'payment_instrument_id' => 1,
3512 elseif ($context == 'payLater') {
3513 $compareParams = array(
3514 'to_financial_account_id' => 7,
3515 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3519 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3520 $entityParams = array(
3521 'financial_trxn_id' => $trxn['financial_trxn_id'],
3522 'entity_table' => 'civicrm_financial_item',
3524 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3525 $fitemParams = array(
3526 'id' => $entityTrxn['entity_id'],
3528 $compareParams = array(
3529 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3531 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3533 if ($context == 'payLater') {
3534 $compareParams = array(
3535 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3537 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3540 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3541 if ($context == 'feeAmount') {
3543 'entity_id' => $params['id'],
3544 'entity_table' => 'civicrm_contribution',
3546 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3547 $trxnParams = array(
3548 'id' => $maxTrxn['financial_trxn_id'],
3550 $compareParams = array(
3551 'to_financial_account_id' => 5,
3552 'from_financial_account_id' => 6,
3553 'total_amount' => 50,
3556 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3557 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3558 $fitemParams = array(
3559 'entity_id' => $trxnId['financialTrxnId'],
3560 'entity_table' => 'civicrm_financial_trxn',
3562 $compareParams = array(
3565 'financial_account_id' => 5,
3567 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3569 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3570 // line should be copied into all the functions that call this function & evaluated there
3571 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3572 // when calling completeTransaction or repeatTransaction.
3573 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);