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) {
1391 $this->_pageParams
= array(
1392 'title' => 'Test Contribution Page',
1393 'financial_type_id' => 1,
1394 'currency' => 'USD',
1395 'financial_account_id' => 1,
1396 'payment_processor' => $params['processor_id'],
1398 'is_allow_other_amount' => 1,
1400 'max_amount' => 1000,
1402 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1403 return $contributionPage;
1407 * Create a sample batch.
1409 public function batchCreate() {
1410 $params = $this->_params
;
1411 $params['name'] = $params['title'] = 'Batch_433397';
1412 $params['status_id'] = 1;
1413 $result = $this->callAPISuccess('batch', 'create', $params);
1414 return $result['id'];
1420 * @param array $params
1422 * result of created tag
1424 public function tagCreate($params = array()) {
1426 'name' => 'New Tag3',
1427 'description' => 'This is description for Our New Tag ',
1430 $params = array_merge($defaults, $params);
1431 $result = $this->callAPISuccess('Tag', 'create', $params);
1432 return $result['values'][$result['id']];
1439 * Id of the tag to be deleted.
1443 public function tagDelete($tagId) {
1444 require_once 'api/api.php';
1448 $result = $this->callAPISuccess('Tag', 'delete', $params);
1449 return $result['id'];
1453 * Add entity(s) to the tag
1455 * @param array $params
1459 public function entityTagAdd($params) {
1460 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1467 * @param array $params
1471 * id of created pledge
1473 public function pledgeCreate($params) {
1474 $params = array_merge(array(
1475 'pledge_create_date' => date('Ymd'),
1476 'start_date' => date('Ymd'),
1477 'scheduled_date' => date('Ymd'),
1479 'pledge_status_id' => '2',
1480 'financial_type_id' => '1',
1481 'pledge_original_installment_amount' => 20,
1482 'frequency_interval' => 5,
1483 'frequency_unit' => 'year',
1484 'frequency_day' => 15,
1485 'installments' => 5,
1489 $result = $this->callAPISuccess('Pledge', 'create', $params);
1490 return $result['id'];
1494 * Delete contribution.
1496 * @param int $pledgeId
1498 public function pledgeDelete($pledgeId) {
1500 'pledge_id' => $pledgeId,
1502 $this->callAPISuccess('Pledge', 'delete', $params);
1506 * Create contribution.
1508 * @param array $params
1509 * Array of parameters.
1512 * id of created contribution
1514 public function contributionCreate($params) {
1516 $params = array_merge(array(
1518 'receive_date' => date('Ymd'),
1519 'total_amount' => 100.00,
1520 'fee_amount' => 5.00,
1521 'net_ammount' => 95.00,
1522 'financial_type_id' => 1,
1523 'payment_instrument_id' => 1,
1524 'non_deductible_amount' => 10.00,
1526 'invoice_id' => 67890,
1528 'contribution_status_id' => 1,
1531 $result = $this->callAPISuccess('contribution', 'create', $params);
1532 return $result['id'];
1536 * Delete contribution.
1538 * @param int $contributionId
1542 public function contributionDelete($contributionId) {
1544 'contribution_id' => $contributionId,
1546 $result = $this->callAPISuccess('contribution', 'delete', $params);
1553 * @param array $params
1554 * Name-value pair for an event.
1558 public function eventCreate($params = array()) {
1559 // if no contact was passed, make up a dummy event creator
1560 if (!isset($params['contact_id'])) {
1561 $params['contact_id'] = $this->_contactCreate(array(
1562 'contact_type' => 'Individual',
1563 'first_name' => 'Event',
1564 'last_name' => 'Creator',
1568 // set defaults for missing params
1569 $params = array_merge(array(
1570 'title' => 'Annual CiviCRM meet',
1571 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1572 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1573 'event_type_id' => 1,
1575 'start_date' => 20081021,
1576 'end_date' => 20081023,
1577 'is_online_registration' => 1,
1578 'registration_start_date' => 20080601,
1579 'registration_end_date' => 20081015,
1580 'max_participants' => 100,
1581 'event_full_text' => 'Sorry! We are already full',
1584 'is_show_location' => 0,
1587 return $this->callAPISuccess('Event', 'create', $params);
1598 public function eventDelete($id) {
1602 return $this->callAPISuccess('event', 'delete', $params);
1606 * Delete participant.
1608 * @param int $participantID
1612 public function participantDelete($participantID) {
1614 'id' => $participantID,
1616 return $this->callAPISuccess('Participant', 'delete', $params);
1620 * Create participant payment.
1622 * @param int $participantID
1623 * @param int $contributionID
1625 * $id of created payment
1627 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1628 //Create Participant Payment record With Values
1630 'participant_id' => $participantID,
1631 'contribution_id' => $contributionID,
1634 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1635 return $result['id'];
1639 * Delete participant payment.
1641 * @param int $paymentID
1643 public function participantPaymentDelete($paymentID) {
1647 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1653 * @param int $contactID
1655 * location id of created location
1657 public function locationAdd($contactID) {
1660 'location_type' => 'New Location Type',
1662 'name' => 'Saint Helier St',
1663 'county' => 'Marin',
1664 'country' => 'UNITED STATES',
1665 'state_province' => 'Michigan',
1666 'supplemental_address_1' => 'Hallmark Ct',
1667 'supplemental_address_2' => 'Jersey Village',
1672 'contact_id' => $contactID,
1673 'address' => $address,
1674 'location_format' => '2.0',
1675 'location_type' => 'New Location Type',
1678 $result = $this->callAPISuccess('Location', 'create', $params);
1683 * Delete Locations of contact.
1685 * @param array $params
1688 public function locationDelete($params) {
1689 $this->callAPISuccess('Location', 'delete', $params);
1693 * Add a Location Type.
1695 * @param array $params
1696 * @return CRM_Core_DAO_LocationType
1697 * location id of created location
1699 public function locationTypeCreate($params = NULL) {
1700 if ($params === NULL) {
1702 'name' => 'New Location Type',
1703 'vcard_name' => 'New Location Type',
1704 'description' => 'Location Type for Delete',
1709 $locationType = new CRM_Core_DAO_LocationType();
1710 $locationType->copyValues($params);
1711 $locationType->save();
1712 // clear getfields cache
1713 CRM_Core_PseudoConstant
::flush();
1714 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1715 return $locationType;
1719 * Delete a Location Type.
1721 * @param int $locationTypeId
1723 public function locationTypeDelete($locationTypeId) {
1724 $locationType = new CRM_Core_DAO_LocationType();
1725 $locationType->id
= $locationTypeId;
1726 $locationType->delete();
1732 * @param array $params
1733 * @return CRM_Core_DAO_Mapping
1734 * Mapping id of created mapping
1736 public function mappingCreate($params = NULL) {
1737 if ($params === NULL) {
1739 'name' => 'Mapping name',
1740 'description' => 'Mapping description',
1741 // 'Export Contact' mapping.
1742 'mapping_type_id' => 7,
1746 $mapping = new CRM_Core_DAO_Mapping();
1747 $mapping->copyValues($params);
1749 // clear getfields cache
1750 CRM_Core_PseudoConstant
::flush();
1751 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1758 * @param int $mappingId
1760 public function mappingDelete($mappingId) {
1761 $mapping = new CRM_Core_DAO_Mapping();
1762 $mapping->id
= $mappingId;
1769 * @param array $params
1771 * groupId of created group
1773 public function groupCreate($params = array()) {
1774 $params = array_merge(array(
1775 'name' => 'Test Group 1',
1777 'title' => 'New Test Group Created',
1778 'description' => 'New Test Group Created',
1780 'visibility' => 'Public Pages',
1781 'group_type' => array(
1787 $result = $this->callAPISuccess('Group', 'create', $params);
1788 return $result['id'];
1792 * Create a smart group.
1794 * By default it will be a group of households.
1796 * @param array $smartGroupParams
1797 * @param array $groupParams
1800 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1801 $smartGroupParams = array_merge(array(
1802 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1805 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1807 $groupParams['saved_search_id'] = $savedSearch->id
;
1808 return $this->groupCreate($groupParams);
1812 * Function to add a Group.
1814 * @params array to add group
1816 * @param int $groupID
1817 * @param int $totalCount
1819 * groupId of created group
1821 public function groupContactCreate($groupID, $totalCount = 10) {
1822 $params = array('group_id' => $groupID);
1823 for ($i = 1; $i <= $totalCount; $i++
) {
1824 $contactID = $this->individualCreate();
1826 $params +
= array('contact_id' => $contactID);
1829 $params +
= array("contact_id.$i" => $contactID);
1832 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1842 public function groupDelete($gid) {
1848 $this->callAPISuccess('Group', 'delete', $params);
1853 * @param array $params
1855 public function uFFieldCreate($params = array()) {
1856 $params = array_merge(array(
1858 'field_name' => 'first_name',
1861 'visibility' => 'Public Pages and Listings',
1862 'is_searchable' => '1',
1863 'label' => 'first_name',
1864 'field_type' => 'Individual',
1867 $this->callAPISuccess('uf_field', 'create', $params);
1871 * Add a UF Join Entry.
1873 * @param array $params
1875 * $id of created UF Join
1877 public function ufjoinCreate($params = NULL) {
1878 if ($params === NULL) {
1881 'module' => 'CiviEvent',
1882 'entity_table' => 'civicrm_event',
1888 $result = $this->callAPISuccess('uf_join', 'create', $params);
1893 * Delete a UF Join Entry.
1895 * @param array $params
1896 * with missing uf_group_id
1898 public function ufjoinDelete($params = NULL) {
1899 if ($params === NULL) {
1902 'module' => 'CiviEvent',
1903 'entity_table' => 'civicrm_event',
1906 'uf_group_id' => '',
1910 crm_add_uf_join($params);
1914 * @param array $params
1915 * Optional parameters.
1920 public function campaignCreate($params = array()) {
1921 $this->enableCiviCampaign();
1922 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1923 'name' => 'big_campaign',
1924 'title' => 'Campaign',
1926 return $campaign['id'];
1930 * Create Group for a contact.
1932 * @param int $contactId
1934 public function contactGroupCreate($contactId) {
1936 'contact_id.1' => $contactId,
1940 $this->callAPISuccess('GroupContact', 'Create', $params);
1944 * Delete Group for a contact.
1946 * @param int $contactId
1948 public function contactGroupDelete($contactId) {
1950 'contact_id.1' => $contactId,
1953 $this->civicrm_api('GroupContact', 'Delete', $params);
1959 * @param array $params
1962 public function activityCreate($params = NULL) {
1964 if ($params === NULL) {
1965 $individualSourceID = $this->individualCreate();
1967 $contactParams = array(
1968 'first_name' => 'Julia',
1969 'Last_name' => 'Anderson',
1971 'email' => 'julia_anderson@civicrm.org',
1972 'contact_type' => 'Individual',
1975 $individualTargetID = $this->individualCreate($contactParams);
1978 'source_contact_id' => $individualSourceID,
1979 'target_contact_id' => array($individualTargetID),
1980 'assignee_contact_id' => array($individualTargetID),
1981 'subject' => 'Discussion on warm beer',
1982 'activity_date_time' => date('Ymd'),
1983 'duration_hours' => 30,
1984 'duration_minutes' => 20,
1985 'location' => 'Baker Street',
1986 'details' => 'Lets schedule a meeting',
1988 'activity_name' => 'Meeting',
1992 $result = $this->callAPISuccess('Activity', 'create', $params);
1994 $result['target_contact_id'] = $individualTargetID;
1995 $result['assignee_contact_id'] = $individualTargetID;
2000 * Create an activity type.
2002 * @param array $params
2006 public function activityTypeCreate($params) {
2007 return $this->callAPISuccess('ActivityType', 'create', $params);
2011 * Delete activity type.
2013 * @param int $activityTypeId
2014 * Id of the activity type.
2017 public function activityTypeDelete($activityTypeId) {
2018 $params['activity_type_id'] = $activityTypeId;
2019 return $this->callAPISuccess('ActivityType', 'delete', $params);
2023 * Create custom group.
2025 * @param array $params
2028 public function customGroupCreate($params = array()) {
2030 'title' => 'new custom group',
2031 'extends' => 'Contact',
2033 'style' => 'Inline',
2037 $params = array_merge($defaults, $params);
2039 if (strlen($params['title']) > 13) {
2040 $params['title'] = substr($params['title'], 0, 13);
2043 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2044 $this->callAPISuccess('custom_group', 'get', array(
2045 'title' => $params['title'],
2046 array('api.custom_group.delete' => 1),
2049 return $this->callAPISuccess('custom_group', 'create', $params);
2053 * Existing function doesn't allow params to be over-ridden so need a new one
2054 * this one allows you to only pass in the params you want to change
2055 * @param array $params
2058 public function CustomGroupCreateByParams($params = array()) {
2060 'title' => "API Custom Group",
2061 'extends' => 'Contact',
2063 'style' => 'Inline',
2066 $params = array_merge($defaults, $params);
2067 return $this->callAPISuccess('custom_group', 'create', $params);
2071 * Create custom group with multi fields.
2072 * @param array $params
2075 public function CustomGroupMultipleCreateByParams($params = array()) {
2080 $params = array_merge($defaults, $params);
2081 return $this->CustomGroupCreateByParams($params);
2085 * Create custom group with multi fields.
2086 * @param array $params
2089 public function CustomGroupMultipleCreateWithFields($params = array()) {
2090 // also need to pass on $params['custom_field'] if not set but not in place yet
2092 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2093 $ids['custom_group_id'] = $customGroup['id'];
2095 $customField = $this->customFieldCreate(array(
2096 'custom_group_id' => $ids['custom_group_id'],
2097 'label' => 'field_1' . $ids['custom_group_id'],
2100 $ids['custom_field_id'][] = $customField['id'];
2102 $customField = $this->customFieldCreate(array(
2103 'custom_group_id' => $ids['custom_group_id'],
2104 'default_value' => '',
2105 'label' => 'field_2' . $ids['custom_group_id'],
2107 $ids['custom_field_id'][] = $customField['id'];
2109 $customField = $this->customFieldCreate(array(
2110 'custom_group_id' => $ids['custom_group_id'],
2111 'default_value' => '',
2112 'label' => 'field_3' . $ids['custom_group_id'],
2114 $ids['custom_field_id'][] = $customField['id'];
2120 * Create a custom group with a single text custom field. See
2121 * participant:testCreateWithCustom for how to use this
2123 * @param string $function
2125 * @param string $filename
2129 * ids of created objects
2131 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2132 $params = array('title' => $function);
2133 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2134 $params['extends'] = $entity ?
$entity : 'Contact';
2135 $customGroup = $this->CustomGroupCreate($params);
2136 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2137 CRM_Core_PseudoConstant
::flush();
2139 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2143 * Delete custom group.
2145 * @param int $customGroupID
2149 public function customGroupDelete($customGroupID) {
2150 $params['id'] = $customGroupID;
2151 return $this->callAPISuccess('custom_group', 'delete', $params);
2155 * Create custom field.
2157 * @param array $params
2158 * (custom_group_id) is required.
2161 public function customFieldCreate($params) {
2162 $params = array_merge(array(
2163 'label' => 'Custom Field',
2164 'data_type' => 'String',
2165 'html_type' => 'Text',
2166 'is_searchable' => 1,
2168 'default_value' => 'defaultValue',
2171 $result = $this->callAPISuccess('custom_field', 'create', $params);
2172 // these 2 functions are called with force to flush static caches
2173 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2174 CRM_Core_Component
::getEnabledComponents(1);
2179 * Delete custom field.
2181 * @param int $customFieldID
2185 public function customFieldDelete($customFieldID) {
2187 $params['id'] = $customFieldID;
2188 return $this->callAPISuccess('custom_field', 'delete', $params);
2197 public function noteCreate($cId) {
2199 'entity_table' => 'civicrm_contact',
2200 'entity_id' => $cId,
2201 'note' => 'hello I am testing Note',
2202 'contact_id' => $cId,
2203 'modified_date' => date('Ymd'),
2204 'subject' => 'Test Note',
2207 return $this->callAPISuccess('Note', 'create', $params);
2211 * Enable CiviCampaign Component.
2213 public function enableCiviCampaign() {
2214 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2215 // force reload of config object
2216 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2217 //flush cache by calling with reset
2218 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2222 * Create test generated example in api/v3/examples.
2224 * To turn this off (e.g. on the server) set
2225 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2226 * in your settings file
2228 * @param string $entity
2229 * @param string $action
2230 * @param array $params
2231 * Array as passed to civicrm_api function.
2232 * @param array $result
2233 * Array as received from the civicrm_api function.
2234 * @param string $testFunction
2235 * Calling function - generally __FUNCTION__.
2236 * @param string $testFile
2237 * Called from file - generally __FILE__.
2238 * @param string $description
2239 * Descriptive text for the example file.
2240 * @param string $exampleName
2241 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2243 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2244 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2247 $entity = _civicrm_api_get_camel_name($entity);
2248 $action = strtolower($action);
2250 if (empty($exampleName)) {
2251 // Attempt to convert lowercase action name to CamelCase.
2252 // This is clunky/imperfect due to the convention of all lowercase actions.
2253 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2254 $knownPrefixes = array(
2261 foreach ($knownPrefixes as $prefix) {
2262 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2263 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2268 $this->tidyExampleResult($result);
2269 if (isset($params['version'])) {
2270 unset($params['version']);
2272 // Format multiline description as array
2274 if (is_string($description) && strlen($description)) {
2275 foreach (explode("\n", $description) as $line) {
2276 $desc[] = trim($line);
2279 $smarty = CRM_Core_Smarty
::singleton();
2280 $smarty->assign('testFunction', $testFunction);
2281 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2282 $smarty->assign('params', $params);
2283 $smarty->assign('entity', $entity);
2284 $smarty->assign('testFile', basename($testFile));
2285 $smarty->assign('description', $desc);
2286 $smarty->assign('result', $result);
2287 $smarty->assign('action', $action);
2289 global $civicrm_root;
2290 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2291 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2292 mkdir($civicrm_root . "/api/v3/examples/$entity");
2294 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2295 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2301 * Tidy up examples array so that fields that change often ..don't
2302 * and debug related fields are unset
2304 * @param array $result
2306 public function tidyExampleResult(&$result) {
2307 if (!is_array($result)) {
2310 $fieldsToChange = array(
2311 'hash' => '67eac7789eaee00',
2312 'modified_date' => '2012-11-14 16:02:35',
2313 'created_date' => '2013-07-28 08:49:19',
2314 'create_date' => '20120130621222105',
2315 'application_received_date' => '20130728084957',
2316 'in_date' => '2013-07-28 08:50:19',
2317 'scheduled_date' => '20130728085413',
2318 'approval_date' => '20130728085413',
2319 'pledge_start_date_high' => '20130726090416',
2320 'start_date' => '2013-07-29 00:00:00',
2321 'event_start_date' => '2013-07-29 00:00:00',
2322 'end_date' => '2013-08-04 00:00:00',
2323 'event_end_date' => '2013-08-04 00:00:00',
2324 'decision_date' => '20130805000000',
2327 $keysToUnset = array('xdebug', 'undefined_fields');
2328 foreach ($keysToUnset as $unwantedKey) {
2329 if (isset($result[$unwantedKey])) {
2330 unset($result[$unwantedKey]);
2333 if (isset($result['values'])) {
2334 if (!is_array($result['values'])) {
2337 $resultArray = &$result['values'];
2339 elseif (is_array($result)) {
2340 $resultArray = &$result;
2346 foreach ($resultArray as $index => &$values) {
2347 if (!is_array($values)) {
2350 foreach ($values as $key => &$value) {
2351 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2352 if (isset($value['is_error'])) {
2353 // we have a std nested result format
2354 $this->tidyExampleResult($value);
2357 foreach ($value as &$nestedResult) {
2358 // this is an alternative syntax for nested results a keyed array of results
2359 $this->tidyExampleResult($nestedResult);
2363 if (in_array($key, $keysToUnset)) {
2364 unset($values[$key]);
2367 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2368 $value = $fieldsToChange[$key];
2370 if (is_string($value)) {
2371 $value = addslashes($value);
2380 * @param array $params
2384 public function noteDelete($params) {
2385 return $this->callAPISuccess('Note', 'delete', $params);
2389 * Create custom field with Option Values.
2391 * @param array $customGroup
2392 * @param string $name
2393 * Name of custom field.
2397 public function customFieldOptionValueCreate($customGroup, $name) {
2398 $fieldParams = array(
2399 'custom_group_id' => $customGroup['id'],
2400 'name' => 'test_custom_group',
2401 'label' => 'Country',
2402 'html_type' => 'Select',
2403 'data_type' => 'String',
2406 'is_searchable' => 0,
2410 $optionGroup = array(
2412 'name' => 'option_group1',
2413 'label' => 'option_group_label1',
2416 $optionValue = array(
2417 'option_label' => array('Label1', 'Label2'),
2418 'option_value' => array('value1', 'value2'),
2419 'option_name' => array($name . '_1', $name . '_2'),
2420 'option_weight' => array(1, 2),
2421 'option_status' => 1,
2424 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2426 return $this->callAPISuccess('custom_field', 'create', $params);
2434 public function confirmEntitiesDeleted($entities) {
2435 foreach ($entities as $entity) {
2437 $result = $this->callAPISuccess($entity, 'Get', array());
2438 if ($result['error'] == 1 ||
$result['count'] > 0) {
2439 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2447 * Quick clean by emptying tables created for the test.
2449 * @param array $tablesToTruncate
2450 * @param bool $dropCustomValueTables
2451 * @throws \Exception
2453 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2455 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2457 if ($dropCustomValueTables) {
2458 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2459 while ($optionGroupResult->fetch()) {
2460 if (!empty($optionGroupResult->option_group_id
)) {
2461 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2464 $tablesToTruncate[] = 'civicrm_custom_group';
2465 $tablesToTruncate[] = 'civicrm_custom_field';
2468 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2470 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2471 foreach ($tablesToTruncate as $table) {
2472 $sql = "TRUNCATE TABLE $table";
2473 CRM_Core_DAO
::executeQuery($sql);
2475 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2477 if ($dropCustomValueTables) {
2478 $dbName = self
::getDBName();
2480 SELECT TABLE_NAME as tableName
2481 FROM INFORMATION_SCHEMA.TABLES
2482 WHERE TABLE_SCHEMA = '{$dbName}'
2483 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2486 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2487 while ($tableDAO->fetch()) {
2488 $sql = "DROP TABLE {$tableDAO->tableName}";
2489 CRM_Core_DAO
::executeQuery($sql);
2495 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2497 public function quickCleanUpFinancialEntities() {
2498 $tablesToTruncate = array(
2500 'civicrm_activity_contact',
2501 'civicrm_contribution',
2502 'civicrm_contribution_soft',
2503 'civicrm_contribution_product',
2504 'civicrm_financial_trxn',
2505 'civicrm_financial_item',
2506 'civicrm_contribution_recur',
2507 'civicrm_line_item',
2508 'civicrm_contribution_page',
2509 'civicrm_payment_processor',
2510 'civicrm_entity_financial_trxn',
2511 'civicrm_membership',
2512 'civicrm_membership_type',
2513 'civicrm_membership_payment',
2514 'civicrm_membership_log',
2515 'civicrm_membership_block',
2517 'civicrm_participant',
2518 'civicrm_participant_payment',
2520 'civicrm_pledge_payment',
2521 'civicrm_price_set_entity',
2522 'civicrm_price_field_value',
2523 'civicrm_price_field',
2525 $this->quickCleanup($tablesToTruncate);
2526 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2527 $this->restoreDefaultPriceSetConfig();
2529 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2530 System
::singleton()->flushProcessors();
2533 public function restoreDefaultPriceSetConfig() {
2534 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2535 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)");
2536 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)");
2539 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2540 * Default behaviour is to also delete the entity
2541 * @param array $params
2542 * Params array to check against.
2544 * Id of the entity concerned.
2545 * @param string $entity
2546 * Name of entity concerned (e.g. membership).
2547 * @param bool $delete
2548 * Should the entity be deleted as part of this check.
2549 * @param string $errorText
2550 * Text to print on error.
2553 * @param array $params
2556 * @param int $delete
2557 * @param string $errorText
2561 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2563 $result = $this->callAPISuccessGetSingle($entity, array(
2568 $this->callAPISuccess($entity, 'Delete', array(
2572 $dateFields = $keys = $dateTimeFields = array();
2573 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2574 foreach ($fields['values'] as $field => $settings) {
2575 if (array_key_exists($field, $result)) {
2576 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2579 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2581 $type = CRM_Utils_Array
::value('type', $settings);
2582 if ($type == CRM_Utils_Type
::T_DATE
) {
2583 $dateFields[] = $settings['name'];
2584 // we should identify both real names & unique names as dates
2585 if ($field != $settings['name']) {
2586 $dateFields[] = $field;
2589 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2590 $dateTimeFields[] = $settings['name'];
2591 // we should identify both real names & unique names as dates
2592 if ($field != $settings['name']) {
2593 $dateTimeFields[] = $field;
2598 if (strtolower($entity) == 'contribution') {
2599 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2600 // this is not returned in id format
2601 unset($params['payment_instrument_id']);
2602 $params['contribution_source'] = $params['source'];
2603 unset($params['source']);
2606 foreach ($params as $key => $value) {
2607 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2610 if (in_array($key, $dateFields)) {
2611 $value = date('Y-m-d', strtotime($value));
2612 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2614 if (in_array($key, $dateTimeFields)) {
2615 $value = date('Y-m-d H:i:s', strtotime($value));
2616 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2618 $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);
2623 * Get formatted values in the actual and expected result.
2624 * @param array $actual
2625 * Actual calculated values.
2626 * @param array $expected
2629 public function checkArrayEquals(&$actual, &$expected) {
2630 self
::unsetId($actual);
2631 self
::unsetId($expected);
2632 $this->assertEquals($actual, $expected);
2636 * Unset the key 'id' from the array
2637 * @param array $unformattedArray
2638 * The array from which the 'id' has to be unset.
2640 public static function unsetId(&$unformattedArray) {
2641 $formattedArray = array();
2642 if (array_key_exists('id', $unformattedArray)) {
2643 unset($unformattedArray['id']);
2645 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2646 foreach ($unformattedArray['values'] as $key => $value) {
2647 if (is_array($value)) {
2648 foreach ($value as $k => $v) {
2654 elseif ($key == 'id') {
2655 $unformattedArray[$key];
2657 $formattedArray = array($value);
2659 $unformattedArray['values'] = $formattedArray;
2664 * Helper to enable/disable custom directory support
2666 * @param array $customDirs
2668 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2669 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2671 public function customDirectories($customDirs) {
2672 $config = CRM_Core_Config
::singleton();
2674 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2675 unset($config->customPHPPathDir
);
2677 elseif ($customDirs['php_path'] === TRUE) {
2678 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2681 $config->customPHPPathDir
= $php_path;
2684 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2685 unset($config->customTemplateDir
);
2687 elseif ($customDirs['template_path'] === TRUE) {
2688 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2691 $config->customTemplateDir
= $template_path;
2696 * Generate a temporary folder.
2698 * @param string $prefix
2701 public function createTempDir($prefix = 'test-') {
2702 $tempDir = CRM_Utils_File
::tempdir($prefix);
2703 $this->tempDirs
[] = $tempDir;
2707 public function cleanTempDirs() {
2708 if (!is_array($this->tempDirs
)) {
2709 // fix test errors where this is not set
2712 foreach ($this->tempDirs
as $tempDir) {
2713 if (is_dir($tempDir)) {
2714 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2720 * Temporarily replace the singleton extension with a different one.
2721 * @param \CRM_Extension_System $system
2723 public function setExtensionSystem(CRM_Extension_System
$system) {
2724 if ($this->origExtensionSystem
== NULL) {
2725 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2727 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2730 public function unsetExtensionSystem() {
2731 if ($this->origExtensionSystem
!== NULL) {
2732 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2733 $this->origExtensionSystem
= NULL;
2738 * Temporarily alter the settings-metadata to add a mock setting.
2740 * WARNING: The setting metadata will disappear on the next cache-clear.
2745 public function setMockSettingsMetaData($extras) {
2746 Civi
::service('settings_manager')->flush();
2748 CRM_Utils_Hook
::singleton()
2749 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2750 $metadata = array_merge($metadata, $extras);
2753 $fields = $this->callAPISuccess('setting', 'getfields', array());
2754 foreach ($extras as $key => $spec) {
2755 $this->assertNotEmpty($spec['title']);
2756 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2761 * @param string $name
2763 public function financialAccountDelete($name) {
2764 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2765 $financialAccount->name
= $name;
2766 if ($financialAccount->find(TRUE)) {
2767 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2768 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2769 $entityFinancialType->delete();
2770 $financialAccount->delete();
2775 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2776 * (NB unclear if this is still required)
2778 public function _sethtmlGlobals() {
2779 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2780 'required' => array(
2781 'html_quickform_rule_required',
2782 'HTML/QuickForm/Rule/Required.php',
2784 'maxlength' => array(
2785 'html_quickform_rule_range',
2786 'HTML/QuickForm/Rule/Range.php',
2788 'minlength' => array(
2789 'html_quickform_rule_range',
2790 'HTML/QuickForm/Rule/Range.php',
2792 'rangelength' => array(
2793 'html_quickform_rule_range',
2794 'HTML/QuickForm/Rule/Range.php',
2797 'html_quickform_rule_email',
2798 'HTML/QuickForm/Rule/Email.php',
2801 'html_quickform_rule_regex',
2802 'HTML/QuickForm/Rule/Regex.php',
2804 'lettersonly' => array(
2805 'html_quickform_rule_regex',
2806 'HTML/QuickForm/Rule/Regex.php',
2808 'alphanumeric' => array(
2809 'html_quickform_rule_regex',
2810 'HTML/QuickForm/Rule/Regex.php',
2813 'html_quickform_rule_regex',
2814 'HTML/QuickForm/Rule/Regex.php',
2816 'nopunctuation' => array(
2817 'html_quickform_rule_regex',
2818 'HTML/QuickForm/Rule/Regex.php',
2821 'html_quickform_rule_regex',
2822 'HTML/QuickForm/Rule/Regex.php',
2824 'callback' => array(
2825 'html_quickform_rule_callback',
2826 'HTML/QuickForm/Rule/Callback.php',
2829 'html_quickform_rule_compare',
2830 'HTML/QuickForm/Rule/Compare.php',
2833 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2834 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2836 'HTML/QuickForm/group.php',
2837 'HTML_QuickForm_group',
2840 'HTML/QuickForm/hidden.php',
2841 'HTML_QuickForm_hidden',
2844 'HTML/QuickForm/reset.php',
2845 'HTML_QuickForm_reset',
2847 'checkbox' => array(
2848 'HTML/QuickForm/checkbox.php',
2849 'HTML_QuickForm_checkbox',
2852 'HTML/QuickForm/file.php',
2853 'HTML_QuickForm_file',
2856 'HTML/QuickForm/image.php',
2857 'HTML_QuickForm_image',
2859 'password' => array(
2860 'HTML/QuickForm/password.php',
2861 'HTML_QuickForm_password',
2864 'HTML/QuickForm/radio.php',
2865 'HTML_QuickForm_radio',
2868 'HTML/QuickForm/button.php',
2869 'HTML_QuickForm_button',
2872 'HTML/QuickForm/submit.php',
2873 'HTML_QuickForm_submit',
2876 'HTML/QuickForm/select.php',
2877 'HTML_QuickForm_select',
2879 'hiddenselect' => array(
2880 'HTML/QuickForm/hiddenselect.php',
2881 'HTML_QuickForm_hiddenselect',
2884 'HTML/QuickForm/text.php',
2885 'HTML_QuickForm_text',
2887 'textarea' => array(
2888 'HTML/QuickForm/textarea.php',
2889 'HTML_QuickForm_textarea',
2891 'fckeditor' => array(
2892 'HTML/QuickForm/fckeditor.php',
2893 'HTML_QuickForm_FCKEditor',
2896 'HTML/QuickForm/tinymce.php',
2897 'HTML_QuickForm_TinyMCE',
2899 'dojoeditor' => array(
2900 'HTML/QuickForm/dojoeditor.php',
2901 'HTML_QuickForm_dojoeditor',
2904 'HTML/QuickForm/link.php',
2905 'HTML_QuickForm_link',
2907 'advcheckbox' => array(
2908 'HTML/QuickForm/advcheckbox.php',
2909 'HTML_QuickForm_advcheckbox',
2912 'HTML/QuickForm/date.php',
2913 'HTML_QuickForm_date',
2916 'HTML/QuickForm/static.php',
2917 'HTML_QuickForm_static',
2920 'HTML/QuickForm/header.php',
2921 'HTML_QuickForm_header',
2924 'HTML/QuickForm/html.php',
2925 'HTML_QuickForm_html',
2927 'hierselect' => array(
2928 'HTML/QuickForm/hierselect.php',
2929 'HTML_QuickForm_hierselect',
2931 'autocomplete' => array(
2932 'HTML/QuickForm/autocomplete.php',
2933 'HTML_QuickForm_autocomplete',
2936 'HTML/QuickForm/xbutton.php',
2937 'HTML_QuickForm_xbutton',
2939 'advmultiselect' => array(
2940 'HTML/QuickForm/advmultiselect.php',
2941 'HTML_QuickForm_advmultiselect',
2947 * Set up an acl allowing contact to see 2 specified groups
2948 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2950 * You need to have pre-created these groups & created the user e.g
2951 * $this->createLoggedInUser();
2952 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2953 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2955 * @param bool $isProfile
2957 public function setupACL($isProfile = FALSE) {
2959 $_REQUEST = $this->_params
;
2961 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2962 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2963 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2964 'option_group_id' => $optionGroupID,
2965 'label' => 'pick me',
2969 CRM_Core_DAO
::executeQuery("
2970 TRUNCATE civicrm_acl_cache
2973 CRM_Core_DAO
::executeQuery("
2974 TRUNCATE civicrm_acl_contact_cache
2977 CRM_Core_DAO
::executeQuery("
2978 INSERT INTO civicrm_acl_entity_role (
2979 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2980 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2984 CRM_Core_DAO
::executeQuery("
2985 INSERT INTO civicrm_acl (
2986 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2989 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2994 CRM_Core_DAO
::executeQuery("
2995 INSERT INTO civicrm_acl (
2996 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2999 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3003 CRM_Core_DAO
::executeQuery("
3004 INSERT INTO civicrm_acl (
3005 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3008 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3013 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3014 $this->callAPISuccess('group_contact', 'create', array(
3015 'group_id' => $this->_permissionedGroup
,
3016 'contact_id' => $this->_loggedInUser
,
3021 CRM_ACL_BAO_Cache
::resetCache();
3022 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3023 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3028 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3030 public function offsetDefaultPriceSet() {
3031 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3032 $firstID = $contributionPriceSet['id'];
3033 $this->callAPISuccess('price_set', 'create', array(
3034 'id' => $contributionPriceSet['id'],
3038 unset($contributionPriceSet['id']);
3039 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3040 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3041 'price_set_id' => $firstID,
3042 'options' => array('limit' => 1),
3044 unset($priceField['id']);
3045 $priceField['price_set_id'] = $newPriceSet['id'];
3046 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3047 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3048 'price_set_id' => $firstID,
3050 'options' => array('limit' => 1),
3053 unset($priceFieldValue['id']);
3054 //create some padding to use up ids
3055 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3056 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3057 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3061 * Create an instance of the paypal processor.
3062 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3063 * this parent class & we don't have a structure for that yet
3064 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3065 * & the best protection against that is the functions this class affords
3066 * @param array $params
3067 * @return int $result['id'] payment processor id
3069 public function paymentProcessorCreate($params = array()) {
3070 $params = array_merge(array(
3072 'domain_id' => CRM_Core_Config
::domainID(),
3073 'payment_processor_type_id' => 'PayPal',
3077 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3078 'password' => '1183377788',
3079 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3080 'url_site' => 'https://www.sandbox.paypal.com/',
3081 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3082 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3083 'class_name' => 'Payment_PayPalImpl',
3084 'billing_mode' => 3,
3085 'financial_type_id' => 1,
3086 'financial_account_id' => 12,
3089 if (!is_numeric($params['payment_processor_type_id'])) {
3090 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3092 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3093 'name' => $params['payment_processor_type_id'],
3097 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3098 return $result['id'];
3102 * Set up initial recurring payment allowing subsequent IPN payments.
3104 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3105 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3106 'contact_id' => $this->_contactID
,
3109 'installments' => 5,
3110 'frequency_unit' => 'Month',
3111 'frequency_interval' => 1,
3112 'invoice_id' => $this->_invoiceID
,
3113 'contribution_status_id' => 2,
3114 'payment_processor_id' => $this->_paymentProcessorID
,
3115 // processor provided ID - use contact ID as proxy.
3116 'processor_id' => $this->_contactID
,
3117 'api.contribution.create' => array(
3118 'total_amount' => '200',
3119 'invoice_id' => $this->_invoiceID
,
3120 'financial_type_id' => 1,
3121 'contribution_status_id' => 'Pending',
3122 'contact_id' => $this->_contactID
,
3123 'contribution_page_id' => $this->_contributionPageID
,
3124 'payment_processor_id' => $this->_paymentProcessorID
,
3128 $this->_contributionRecurID
= $contributionRecur['id'];
3129 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3133 * 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
3135 public function setupMembershipRecurringPaymentProcessorTransaction() {
3136 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3137 //create a contribution so our membership & contribution don't both have id = 1
3138 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3139 $this->contributionCreate(array(
3140 'contact_id' => $this->_contactID
,
3142 'financial_type_id' => 1,
3143 'invoice_id' => 'abcd',
3147 $this->setupRecurringPaymentProcessorTransaction();
3149 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3150 'contact_id' => $this->_contactID
,
3151 'membership_type_id' => $this->ids
['membership_type'],
3152 'contribution_recur_id' => $this->_contributionRecurID
,
3153 'format.only_id' => TRUE,
3155 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3156 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3158 $this->callAPISuccess('line_item', 'create', array(
3159 'entity_table' => 'civicrm_membership',
3160 'entity_id' => $this->ids
['membership'],
3161 'contribution_id' => $this->_contributionID
,
3162 'label' => 'General',
3164 'unit_price' => 200,
3165 'line_total' => 200,
3166 'financial_type_id' => 1,
3167 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3169 'label' => 'Membership Amount',
3170 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3172 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3174 'label' => 'General',
3175 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3178 $this->callAPISuccess('membership_payment', 'create', array(
3179 'contribution_id' => $this->_contributionID
,
3180 'membership_id' => $this->ids
['membership'],
3189 public function CiviUnitTestCase_fatalErrorHandler($message) {
3190 throw new Exception("{$message['message']}: {$message['code']}");
3194 * Helper function to create new mailing.
3197 public function createMailing() {
3199 'subject' => 'maild' . rand(),
3200 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3201 'name' => 'mailing name' . rand(),
3205 $result = $this->callAPISuccess('Mailing', 'create', $params);
3206 return $result['id'];
3210 * Helper function to delete mailing.
3213 public function deleteMailing($id) {
3218 $this->callAPISuccess('Mailing', 'delete', $params);
3222 * Wrap the entire test case in a transaction.
3224 * Only subsequent DB statements will be wrapped in TX -- this cannot
3225 * retroactively wrap old DB statements. Therefore, it makes sense to
3226 * call this at the beginning of setUp().
3228 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3229 * this option does not work with, e.g., custom-data.
3231 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3232 * if TRUNCATE or ALTER is called while using a transaction.
3235 * Whether to use nesting or reference-counting.
3237 public function useTransaction($nest = TRUE) {
3239 $this->tx
= new CRM_Core_Transaction($nest);
3240 $this->tx
->rollback();
3245 * Assert the attachment exists.
3247 * @param bool $exists
3248 * @param array $apiResult
3250 protected function assertAttachmentExistence($exists, $apiResult) {
3251 $fileId = $apiResult['id'];
3252 $this->assertTrue(is_numeric($fileId));
3253 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3254 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3255 1 => array($fileId, 'Int'),
3257 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3258 1 => array($fileId, 'Int'),
3263 * Create a price set for an event.
3265 * @param int $feeTotal
3270 protected function eventPriceSetCreate($feeTotal) {
3271 // creating price set, price field
3272 $paramsSet['title'] = 'Price Set';
3273 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3274 $paramsSet['is_active'] = FALSE;
3275 $paramsSet['extends'] = 1;
3277 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3278 $priceSetId = $priceset->id
;
3280 //Checking for priceset added in the table.
3281 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3282 'id', $paramsSet['title'], 'Check DB for created priceset'
3284 $paramsField = array(
3285 'label' => 'Price Field',
3286 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3287 'html_type' => 'Text',
3288 'price' => $feeTotal,
3289 'option_label' => array('1' => 'Price Field'),
3290 'option_value' => array('1' => $feeTotal),
3291 'option_name' => array('1' => $feeTotal),
3292 'option_weight' => array('1' => 1),
3293 'option_amount' => array('1' => 1),
3294 'is_display_amounts' => 1,
3296 'options_per_line' => 1,
3297 'is_active' => array('1' => 1),
3298 'price_set_id' => $priceset->id
,
3299 'is_enter_qty' => 1,
3300 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3302 CRM_Price_BAO_PriceField
::create($paramsField);
3308 * Add a profile to a contribution page.
3310 * @param string $name
3311 * @param int $contributionPageID
3313 protected function addProfile($name, $contributionPageID) {
3314 $this->callAPISuccess('UFJoin', 'create', array(
3315 'uf_group_id' => $name,
3316 'module' => 'CiviContribute',
3317 'entity_table' => 'civicrm_contribution_page',
3318 'entity_id' => $contributionPageID,
3324 * Add participant with contribution
3328 protected function createParticipantWithContribution() {
3329 // creating price set, price field
3330 $this->_contactId
= Contact
::createIndividual();
3331 $this->_eventId
= Event
::create($this->_contactId
);
3332 $eventParams = array(
3333 'id' => $this->_eventId
,
3334 'financial_type_id' => 4,
3337 $this->callAPISuccess('event', 'create', $eventParams);
3338 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3339 $participantParams = array(
3340 'financial_type_id' => 4,
3341 'event_id' => $this->_eventId
,
3344 'fee_currency' => 'USD',
3345 'contact_id' => $this->_contactId
,
3347 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3348 $contributionParams = array(
3349 'total_amount' => 150,
3350 'currency' => 'USD',
3351 'contact_id' => $this->_contactId
,
3352 'financial_type_id' => 4,
3353 'contribution_status_id' => 1,
3354 'partial_payment_total' => 300.00,
3355 'partial_amount_pay' => 150,
3356 'contribution_mode' => 'participant',
3357 'participant_id' => $participant['id'],
3359 foreach ($priceFields['values'] as $key => $priceField) {
3360 $lineItems[1][$key] = array(
3361 'price_field_id' => $priceField['price_field_id'],
3362 'price_field_value_id' => $priceField['id'],
3363 'label' => $priceField['label'],
3364 'field_title' => $priceField['label'],
3366 'unit_price' => $priceField['amount'],
3367 'line_total' => $priceField['amount'],
3368 'financial_type_id' => $priceField['financial_type_id'],
3371 $contributionParams['line_item'] = $lineItems;
3372 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3373 $paymentParticipant = array(
3374 'participant_id' => $participant['id'],
3375 'contribution_id' => $contribution['id'],
3378 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3379 return array($lineItems, $contribution);
3385 * @param string $component
3386 * @param int $componentId
3390 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3391 $paramsSet['title'] = 'Price Set';
3392 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3393 $paramsSet['is_active'] = TRUE;
3394 $paramsSet['financial_type_id'] = 4;
3395 $paramsSet['extends'] = 1;
3396 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3397 $priceSetId = $priceSet['id'];
3398 //Checking for priceset added in the table.
3399 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3400 'id', $paramsSet['title'], 'Check DB for created priceset'
3402 $paramsField = array(
3403 'label' => 'Price Field',
3404 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3405 'html_type' => 'CheckBox',
3406 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3407 'option_value' => array('1' => 100, '2' => 200),
3408 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3409 'option_weight' => array('1' => 1, '2' => 2),
3410 'option_amount' => array('1' => 100, '2' => 200),
3411 'is_display_amounts' => 1,
3413 'options_per_line' => 1,
3414 'is_active' => array('1' => 1, '2' => 1),
3415 'price_set_id' => $priceSet['id'],
3416 'is_enter_qty' => 1,
3417 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3419 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3421 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3423 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3427 * Replace the template with a test-oriented template designed to show all the variables.
3429 * @param string $templateName
3431 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3432 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
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 SET m.msg_html = '{$testTemplate}'
3438 WHERE og.name = 'msg_tpl_workflow_contribution'
3439 AND ov.name = '{$templateName}'
3440 AND m.is_default = 1"
3445 * Reinstate the default template.
3447 * @param string $templateName
3449 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3450 CRM_Core_DAO
::executeQuery(
3451 "UPDATE civicrm_option_group og
3452 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3453 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3454 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3455 SET m.msg_html = m2.msg_html
3456 WHERE og.name = 'msg_tpl_workflow_contribution'
3457 AND ov.name = '{$templateName}'
3458 AND m.is_default = 1"
3463 * Flush statics relating to financial type.
3465 protected function flushFinancialTypeStatics() {
3466 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3467 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3469 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3470 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3472 CRM_Contribute_PseudoConstant
::flush('financialType');
3473 CRM_Contribute_PseudoConstant
::flush('membershipType');
3474 // Pseudoconstants may be saved to the cache table.
3475 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3476 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3477 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3481 * Set the permissions to the supplied array.
3483 * @param array $permissions
3485 protected function setPermissions($permissions) {
3486 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3487 $this->flushFinancialTypeStatics();
3488 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3492 * @param array $params
3495 public function _checkFinancialRecords($params, $context) {
3496 $entityParams = array(
3497 'entity_id' => $params['id'],
3498 'entity_table' => 'civicrm_contribution',
3500 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3501 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3502 if ($context == 'pending') {
3503 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3504 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3507 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3508 $trxnParams = array(
3509 'id' => $trxn['financial_trxn_id'],
3511 if ($context != 'online' && $context != 'payLater') {
3512 $compareParams = array(
3513 'to_financial_account_id' => 6,
3514 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3518 if ($context == 'feeAmount') {
3519 $compareParams['fee_amount'] = 50;
3521 elseif ($context == 'online') {
3522 $compareParams = array(
3523 'to_financial_account_id' => 12,
3524 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3526 'payment_instrument_id' => 1,
3529 elseif ($context == 'payLater') {
3530 $compareParams = array(
3531 'to_financial_account_id' => 7,
3532 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3536 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3537 $entityParams = array(
3538 'financial_trxn_id' => $trxn['financial_trxn_id'],
3539 'entity_table' => 'civicrm_financial_item',
3541 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3542 $fitemParams = array(
3543 'id' => $entityTrxn['entity_id'],
3545 $compareParams = array(
3546 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3548 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3550 if ($context == 'payLater') {
3551 $compareParams = array(
3552 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3554 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3557 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3558 if ($context == 'feeAmount') {
3560 'entity_id' => $params['id'],
3561 'entity_table' => 'civicrm_contribution',
3563 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3564 $trxnParams = array(
3565 'id' => $maxTrxn['financial_trxn_id'],
3567 $compareParams = array(
3568 'to_financial_account_id' => 5,
3569 'from_financial_account_id' => 6,
3570 'total_amount' => 50,
3573 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3574 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3575 $fitemParams = array(
3576 'entity_id' => $trxnId['financialTrxnId'],
3577 'entity_table' => 'civicrm_financial_trxn',
3579 $compareParams = array(
3582 'financial_account_id' => 5,
3584 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3586 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3587 // line should be copied into all the functions that call this function & evaluated there
3588 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3589 // when calling completeTransaction or repeatTransaction.
3590 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);