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;
136 * Array of IDs created during test setup routine.
138 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
142 public $setupIDs = array();
147 * Because we are overriding the parent class constructor, we
148 * need to show the same arguments as exist in the constructor of
149 * PHPUnit_Framework_TestCase, since
150 * PHPUnit_Framework_TestSuite::createTest() creates a
151 * ReflectionClass of the Test class and checks the constructor
152 * of that class to decide how to set up the test.
154 * @param string $name
156 * @param string $dataName
158 public function __construct($name = NULL, array$data = array(), $dataName = '') {
159 parent
::__construct($name, $data, $dataName);
161 // we need full error reporting
162 error_reporting(E_ALL
& ~E_NOTICE
);
164 self
::$_dbName = self
::getDBName();
166 // also load the class loader
167 require_once 'CRM/Core/ClassLoader.php';
168 CRM_Core_ClassLoader
::singleton()->register();
169 if (function_exists('_civix_phpunit_setUp')) {
170 // FIXME: loosen coupling
171 _civix_phpunit_setUp();
176 * Override to run the test and assert its state.
179 * @throws \PHPUnit_Framework_IncompleteTest
180 * @throws \PHPUnit_Framework_SkippedTest
182 protected function runTest() {
184 return parent
::runTest();
186 catch (PEAR_Exception
$e) {
187 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
188 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
195 public function requireDBReset() {
196 return $this->DBResetRequired
;
202 public static function getDBName() {
203 static $dbName = NULL;
204 if ($dbName === NULL) {
205 require_once "DB.php";
206 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
207 $dbName = $dsninfo['database'];
213 * Create database connection for this instance.
215 * Initialize the test database if it hasn't been initialized
217 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
219 protected function getConnection() {
220 $dbName = self
::$_dbName;
221 if (!self
::$dbInit) {
222 $dbName = self
::getDBName();
224 // install test database
225 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
227 static::_populateDB(FALSE, $this);
229 self
::$dbInit = TRUE;
232 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
236 * Required implementation of abstract method.
238 protected function getDataSet() {
242 * @param bool $perClass
243 * @param null $object
245 * TRUE if the populate logic runs; FALSE if it is skipped
247 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
248 if (CIVICRM_UF
!== 'UnitTests') {
249 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
252 if ($perClass ||
$object == NULL) {
256 $dbreset = $object->requireDBReset();
259 if (self
::$populateOnce ||
!$dbreset) {
262 self
::$populateOnce = NULL;
264 Civi\Test
::data()->populate();
269 public static function setUpBeforeClass() {
270 static::_populateDB(TRUE);
272 // also set this global hack
273 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
277 * Common setup functions for all unit tests.
279 protected function setUp() {
280 $session = CRM_Core_Session
::singleton();
281 $session->set('userID', NULL);
283 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
284 // Use a temporary file for STDIN
285 $GLOBALS['stdin'] = tmpfile();
286 if ($GLOBALS['stdin'] === FALSE) {
287 echo "Couldn't open temporary file\n";
291 // Get and save a connection to the database
292 $this->_dbconn
= $this->getConnection();
294 // reload database before each test
295 // $this->_populateDB();
297 // "initialize" CiviCRM to avoid problems when running single tests
298 // FIXME: look at it closer in second stage
300 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
301 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
303 // disable any left-over test extensions
304 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
306 // reset all the caches
307 CRM_Utils_System
::flushCache();
309 // initialize the object once db is loaded
311 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
313 // when running unit tests, use mockup user framework
314 $this->hookClass
= CRM_Utils_Hook
::singleton();
316 // Make sure the DB connection is setup properly
317 $config->userSystem
->setMySQLTimeZone();
318 $env = new CRM_Utils_Check_Component_Env();
319 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
321 // clear permissions stub to not check permissions
322 $config->userPermissionClass
->permissions
= NULL;
324 //flush component settings
325 CRM_Core_Component
::getEnabledComponents(TRUE);
327 error_reporting(E_ALL
);
329 $this->_sethtmlGlobals();
333 * Read everything from the datasets directory and insert into the db.
335 public function loadAllFixtures() {
336 $fixturesDir = __DIR__
. '/../../fixtures';
338 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
340 $xmlFiles = glob($fixturesDir . '/*.xml');
341 foreach ($xmlFiles as $xmlFixture) {
342 $op = new PHPUnit_Extensions_Database_Operation_Insert();
343 $dataset = $this->createXMLDataSet($xmlFixture);
344 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
345 $op->execute($this->_dbconn
, $dataset);
348 $yamlFiles = glob($fixturesDir . '/*.yaml');
349 foreach ($yamlFiles as $yamlFixture) {
350 $op = new PHPUnit_Extensions_Database_Operation_Insert();
351 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
352 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
353 $op->execute($this->_dbconn
, $dataset);
356 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
360 * Emulate a logged in user since certain functions use that.
361 * value to store a record in the DB (like activity)
365 * Contact ID of the created user.
367 public function createLoggedInUser() {
369 'first_name' => 'Logged In',
370 'last_name' => 'User ' . rand(),
371 'contact_type' => 'Individual',
373 $contactID = $this->individualCreate($params);
374 $this->callAPISuccess('UFMatch', 'create', array(
375 'contact_id' => $contactID,
376 'uf_name' => 'superman',
380 $session = CRM_Core_Session
::singleton();
381 $session->set('userID', $contactID);
386 * Create default domain contacts for the two domains added during test class.
387 * database population.
389 public function createDomainContacts() {
390 $this->organizationCreate();
391 $this->organizationCreate(array('organization_name' => 'Second Domain'));
395 * Common teardown functions for all unit tests.
397 protected function tearDown() {
398 error_reporting(E_ALL
& ~E_NOTICE
);
399 CRM_Utils_Hook
::singleton()->reset();
400 $this->hookClass
->reset();
401 $session = CRM_Core_Session
::singleton();
402 $session->set('userID', NULL);
405 $this->tx
->rollback()->commit();
408 CRM_Core_Transaction
::forceRollbackIfEnabled();
409 \Civi\Core\Transaction\Manager
::singleton(TRUE);
412 CRM_Core_Transaction
::forceRollbackIfEnabled();
413 \Civi\Core\Transaction\Manager
::singleton(TRUE);
415 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
416 $this->quickCleanup($tablesToTruncate);
417 $this->createDomainContacts();
420 $this->cleanTempDirs();
421 $this->unsetExtensionSystem();
425 * Generic function to compare expected values after an api call to retrieved.
428 * @daoName string DAO Name of object we're evaluating.
429 * @id int Id of object
430 * @match array Associative array of field name => expected value. Empty if asserting
431 * that a DELETE occurred
432 * @delete boolean True if we're checking that a DELETE action occurred.
436 * @param bool $delete
437 * @throws \PHPUnit_Framework_AssertionFailedError
439 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
441 // adding this here since developers forget to check for an id
442 // and hence we get the first value in the db
443 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
446 $object = new $daoName();
450 // If we're asserting successful record deletion, make sure object is NOT found.
452 if ($object->find(TRUE)) {
453 $this->fail("Object not deleted by delete operation: $daoName, $id");
458 // Otherwise check matches of DAO field values against expected values in $match.
459 if ($object->find(TRUE)) {
460 $fields = &$object->fields();
461 foreach ($fields as $name => $value) {
462 $dbName = $value['name'];
463 if (isset($match[$name])) {
465 $this->assertEquals($object->$dbName, $match[$name]);
467 elseif (isset($match[$dbName])) {
469 $this->assertEquals($object->$dbName, $match[$dbName]);
474 $this->fail("Could not retrieve object: $daoName, $id");
477 $matchSize = count($match);
478 if ($verifiedCount != $matchSize) {
479 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
484 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
485 * @param string $daoName
486 * @param $searchValue
487 * @param $returnColumn
488 * @param $searchColumn
491 * @return null|string
492 * @throws PHPUnit_Framework_AssertionFailedError
494 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
495 if (empty($searchValue)) {
496 $this->fail("empty value passed to assertDBNotNull");
498 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
499 $this->assertNotNull($value, $message);
505 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
506 * @param string $daoName
507 * @param $searchValue
508 * @param $returnColumn
509 * @param $searchColumn
512 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
513 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
514 $this->assertNull($value, $message);
518 * Request a record from the DB by id. Success if row not found.
519 * @param string $daoName
521 * @param null $message
523 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
524 $message = $message ?
$message : "$daoName (#$id) should not exist";
525 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
526 $this->assertNull($value, $message);
530 * Request a record from the DB by id. Success if row not found.
531 * @param string $daoName
533 * @param null $message
535 public function assertDBRowExist($daoName, $id, $message = NULL) {
536 $message = $message ?
$message : "$daoName (#$id) should exist";
537 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
538 $this->assertEquals($id, $value, $message);
542 * Compare a single column value in a retrieved DB record to an expected value.
543 * @param string $daoName
544 * @param $searchValue
545 * @param $returnColumn
546 * @param $searchColumn
547 * @param $expectedValue
550 public function assertDBCompareValue(
551 $daoName, $searchValue, $returnColumn, $searchColumn,
552 $expectedValue, $message
554 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
555 $this->assertEquals($value, $expectedValue, $message);
559 * Compare all values in a single retrieved DB record to an array of expected values.
560 * @param string $daoName
561 * @param array $searchParams
562 * @param $expectedValues
564 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
565 //get the values from db
567 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
569 // compare db values with expected values
570 self
::assertAttributesEquals($expectedValues, $dbValues);
574 * Assert that a SQL query returns a given value.
576 * The first argument is an expected value. The remaining arguments are passed
577 * to CRM_Core_DAO::singleValueQuery
579 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
580 * array(1 => array("Whiz", "String")));
583 * @param array $params
584 * @param string $message
586 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
590 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
591 $this->assertEquals($expected, $actual,
592 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
593 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
599 * Assert that two array-trees are exactly equal, notwithstanding
600 * the sorting of keys
602 * @param array $expected
603 * @param array $actual
605 public function assertTreeEquals($expected, $actual) {
608 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
609 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
613 $this->assertEquals($e, $a);
617 * Assert that two numbers are approximately equal.
619 * @param int|float $expected
620 * @param int|float $actual
621 * @param int|float $tolerance
622 * @param string $message
624 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
625 if ($message === NULL) {
626 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
628 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
632 * Assert attributes are equal.
634 * @param $expectedValues
635 * @param $actualValues
636 * @param string $message
638 * @throws PHPUnit_Framework_AssertionFailedError
640 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
641 foreach ($expectedValues as $paramName => $paramValue) {
642 if (isset($actualValues[$paramName])) {
643 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
646 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
655 public function assertArrayKeyExists($key, &$list) {
656 $result = isset($list[$key]) ?
TRUE : FALSE;
657 $this->assertTrue($result, ts("%1 element exists?",
666 public function assertArrayValueNotNull($key, &$list) {
667 $this->assertArrayKeyExists($key, $list);
669 $value = isset($list[$key]) ?
$list[$key] : NULL;
670 $this->assertTrue($value,
671 ts("%1 element not null?",
678 * Check that api returned 'is_error' => 0.
680 * @param array $apiResult
682 * @param string $prefix
683 * Extra test to add to message.
685 public function assertAPISuccess($apiResult, $prefix = '') {
686 if (!empty($prefix)) {
689 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
691 if (!empty($apiResult['debug_information'])) {
692 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
694 if (!empty($apiResult['trace'])) {
695 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
697 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
701 * Check that api returned 'is_error' => 1.
703 * @param array $apiResult
705 * @param string $prefix
706 * Extra test to add to message.
707 * @param null $expectedError
709 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
710 if (!empty($prefix)) {
713 if ($expectedError && !empty($apiResult['is_error'])) {
714 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
716 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
717 $this->assertNotEmpty($apiResult['error_message']);
723 * @param string $message
725 public function assertType($expected, $actual, $message = '') {
726 return $this->assertInternalType($expected, $actual, $message);
730 * Check that a deleted item has been deleted.
735 public function assertAPIDeleted($entity, $id) {
736 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
741 * Check that api returned 'is_error' => 1
742 * else provide full message
743 * @param array $result
745 * @param array $valuesToExclude
746 * @param string $prefix
747 * Extra test to add to message.
749 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
750 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
751 foreach ($valuesToExclude as $value) {
752 if (isset($result[$value])) {
753 unset($result[$value]);
755 if (isset($expected[$value])) {
756 unset($expected[$value]);
759 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
763 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
767 * @param array $params
770 public function civicrm_api($entity, $action, $params) {
771 return civicrm_api($entity, $action, $params);
775 * Create a batch of external API calls which can
776 * be executed concurrently.
779 * $calls = $this->createExternalAPI()
780 * ->addCall('Contact', 'get', ...)
781 * ->addCall('Contact', 'get', ...)
787 * @return \Civi\API\ExternalBatch
788 * @throws PHPUnit_Framework_SkippedTestError
790 public function createExternalAPI() {
791 global $civicrm_root;
792 $defaultParams = array(
793 'version' => $this->_apiversion
,
797 $calls = new \Civi\API\
ExternalBatch($defaultParams);
799 if (!$calls->isSupported()) {
800 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
807 * wrap api functions.
808 * so we can ensure they succeed & throw exceptions without litterering the test with checks
810 * @param string $entity
811 * @param string $action
812 * @param array $params
813 * @param mixed $checkAgainst
814 * Optional value to check result against, implemented for getvalue,.
815 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
816 * for getsingle the array is compared against an array passed in - the id is not compared (for
821 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
822 $params = array_merge(array(
823 'version' => $this->_apiversion
,
828 switch (strtolower($action)) {
830 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
833 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
836 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
838 $result = $this->civicrm_api($entity, $action, $params);
839 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
844 * This function exists to wrap api getValue function & check the result
845 * so we can ensure they succeed & throw exceptions without litterering the test with checks
846 * There is a type check in this
848 * @param string $entity
849 * @param array $params
850 * @param string $type
851 * Per http://php.net/manual/en/function.gettype.php possible types.
861 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
863 'version' => $this->_apiversion
,
866 $result = $this->civicrm_api($entity, 'getvalue', $params);
868 if ($type == 'integer') {
869 // api seems to return integers as strings
870 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
873 $this->assertType($type, $result, "returned result should have been of type $type but was ");
880 * This function exists to wrap api getsingle function & check the result
881 * so we can ensure they succeed & throw exceptions without litterering the test with checks
883 * @param string $entity
884 * @param array $params
885 * @param array $checkAgainst
886 * Array to compare result against.
897 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
899 'version' => $this->_apiversion
,
902 $result = $this->civicrm_api($entity, 'getsingle', $params);
903 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
904 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
907 // @todo - have gone with the fn that unsets id? should we check id?
908 $this->checkArrayEquals($result, $checkAgainst);
914 * This function exists to wrap api getValue function & check the result
915 * so we can ensure they succeed & throw exceptions without litterering the test with checks
916 * There is a type check in this
917 * @param string $entity
918 * @param array $params
923 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
925 'version' => $this->_apiversion
,
928 $result = $this->civicrm_api($entity, 'getcount', $params);
929 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
930 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
932 if (is_int($count)) {
933 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
939 * This function exists to wrap api functions.
940 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
942 * @param string $entity
943 * @param string $action
944 * @param array $params
945 * @param string $function
946 * Pass this in to create a generated example.
947 * @param string $file
948 * Pass this in to create a generated example.
949 * @param string $description
950 * @param string|null $exampleName
954 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
955 $params['version'] = $this->_apiversion
;
956 $result = $this->callAPISuccess($entity, $action, $params);
957 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
962 * This function exists to wrap api functions.
963 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
964 * @param string $entity
965 * @param string $action
966 * @param array $params
967 * @param string $expectedErrorMessage
969 * @param null $extraOutput
972 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
973 if (is_array($params)) {
975 'version' => $this->_apiversion
,
978 $result = $this->civicrm_api($entity, $action, $params);
979 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
984 * Create required data based on $this->entity & $this->params
985 * This is just a way to set up the test data for delete & get functions
986 * so the distinction between set
987 * up & tested functions is clearer
992 public function createTestEntity() {
993 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
997 * Generic function to create Organisation, to be used in test cases
999 * @param array $params
1000 * parameters for civicrm_contact_add api function call
1002 * sequence number if creating multiple organizations
1005 * id of Organisation created
1007 public function organizationCreate($params = array(), $seq = 0) {
1011 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1012 return $this->_contactCreate($params);
1016 * Generic function to create Individual, to be used in test cases
1018 * @param array $params
1019 * parameters for civicrm_contact_add api function call
1021 * sequence number if creating multiple individuals
1024 * id of Individual created
1026 public function individualCreate($params = array(), $seq = 0) {
1027 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1028 return $this->_contactCreate($params);
1032 * Generic function to create Household, to be used in test cases
1034 * @param array $params
1035 * parameters for civicrm_contact_add api function call
1037 * sequence number if creating multiple households
1040 * id of Household created
1042 public function householdCreate($params = array(), $seq = 0) {
1043 $params = array_merge($this->sampleContact('Household', $seq), $params);
1044 return $this->_contactCreate($params);
1048 * Helper function for getting sample contact properties.
1050 * @param string $contact_type
1051 * enum contact type: Individual, Organization
1053 * sequence number for the values of this type
1056 * properties of sample contact (ie. $params for API call)
1058 public function sampleContact($contact_type, $seq = 0) {
1060 'Individual' => array(
1061 // The number of values in each list need to be coprime numbers to not have duplicates
1062 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1063 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1064 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1066 'Organization' => array(
1067 'organization_name' => array(
1068 'Unit Test Organization',
1075 'Household' => array(
1076 'household_name' => array('Unit Test household'),
1079 $params = array('contact_type' => $contact_type);
1080 foreach ($samples[$contact_type] as $key => $values) {
1081 $params[$key] = $values[$seq %
count($values)];
1083 if ($contact_type == 'Individual') {
1084 $params['email'] = strtolower(
1085 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1087 $params['prefix_id'] = 3;
1088 $params['suffix_id'] = 3;
1094 * Private helper function for calling civicrm_contact_add.
1096 * @param array $params
1097 * For civicrm_contact_add api function call.
1102 * id of Household created
1104 private function _contactCreate($params) {
1105 $result = $this->callAPISuccess('contact', 'create', $params);
1106 if (!empty($result['is_error']) ||
empty($result['id'])) {
1107 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1109 return $result['id'];
1113 * Delete contact, ensuring it is not the domain contact
1115 * @param int $contactID
1116 * Contact ID to delete
1118 public function contactDelete($contactID) {
1119 $domain = new CRM_Core_BAO_Domain();
1120 $domain->contact_id
= $contactID;
1121 if (!$domain->find(TRUE)) {
1122 $this->callAPISuccess('contact', 'delete', array(
1124 'skip_undelete' => 1,
1130 * @param int $contactTypeId
1134 public function contactTypeDelete($contactTypeId) {
1135 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1137 throw new Exception('Could not delete contact type');
1142 * @param array $params
1146 public function membershipTypeCreate($params = array()) {
1147 CRM_Member_PseudoConstant
::flush('membershipType');
1148 CRM_Core_Config
::clearDBCache();
1149 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
1150 $params = array_merge(array(
1151 'name' => 'General',
1152 'duration_unit' => 'year',
1153 'duration_interval' => 1,
1154 'period_type' => 'rolling',
1155 'member_of_contact_id' => $memberOfOrganization,
1157 'financial_type_id' => 2,
1160 'visibility' => 'Public',
1163 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1165 CRM_Member_PseudoConstant
::flush('membershipType');
1166 CRM_Utils_Cache
::singleton()->flush();
1168 return $result['id'];
1172 * @param array $params
1176 public function contactMembershipCreate($params) {
1177 $params = array_merge(array(
1178 'join_date' => '2007-01-21',
1179 'start_date' => '2007-01-21',
1180 'end_date' => '2007-12-21',
1181 'source' => 'Payment',
1182 'membership_type_id' => 'General',
1184 if (!is_numeric($params['membership_type_id'])) {
1185 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
1186 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
1187 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
1191 $result = $this->callAPISuccess('Membership', 'create', $params);
1192 return $result['id'];
1196 * Delete Membership Type.
1198 * @param array $params
1200 public function membershipTypeDelete($params) {
1201 $this->callAPISuccess('MembershipType', 'Delete', $params);
1205 * @param int $membershipID
1207 public function membershipDelete($membershipID) {
1208 $deleteParams = array('id' => $membershipID);
1209 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1213 * @param string $name
1217 public function membershipStatusCreate($name = 'test member status') {
1218 $params['name'] = $name;
1219 $params['start_event'] = 'start_date';
1220 $params['end_event'] = 'end_date';
1221 $params['is_current_member'] = 1;
1222 $params['is_active'] = 1;
1224 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1225 CRM_Member_PseudoConstant
::flush('membershipStatus');
1226 return $result['id'];
1230 * @param int $membershipStatusID
1232 public function membershipStatusDelete($membershipStatusID) {
1233 if (!$membershipStatusID) {
1236 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1240 * @param array $params
1244 public function relationshipTypeCreate($params = array()) {
1245 $params = array_merge(array(
1246 'name_a_b' => 'Relation 1 for relationship type create',
1247 'name_b_a' => 'Relation 2 for relationship type create',
1248 'contact_type_a' => 'Individual',
1249 'contact_type_b' => 'Organization',
1256 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1257 CRM_Core_PseudoConstant
::flush('relationshipType');
1259 return $result['id'];
1263 * Delete Relatinship Type.
1265 * @param int $relationshipTypeID
1267 public function relationshipTypeDelete($relationshipTypeID) {
1268 $params['id'] = $relationshipTypeID;
1269 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1270 if (!empty($check['count'])) {
1271 $this->callAPISuccess('relationship_type', 'delete', $params);
1276 * @param array $params
1280 public function paymentProcessorTypeCreate($params = NULL) {
1281 if (is_null($params)) {
1283 'name' => 'API_Test_PP',
1284 'title' => 'API Test Payment Processor',
1285 'class_name' => 'CRM_Core_Payment_APITest',
1286 'billing_mode' => 'form',
1292 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1294 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1296 return $result['id'];
1300 * Create test Authorize.net instance.
1302 * @param array $params
1306 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1307 $params = array_merge(array(
1308 'name' => 'Authorize',
1309 'domain_id' => CRM_Core_Config
::domainID(),
1310 'payment_processor_type_id' => 'AuthNet',
1311 'title' => 'AuthNet',
1316 'user_name' => '4y5BfuW7jm',
1317 'password' => '4cAmW927n8uLf5J8',
1318 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1319 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1320 'class_name' => 'Payment_AuthorizeNet',
1321 'billing_mode' => 1,
1324 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1325 return $result['id'];
1329 * Create Participant.
1331 * @param array $params
1332 * Array of contact id and event id values.
1335 * $id of participant created
1337 public function participantCreate($params) {
1338 if (empty($params['contact_id'])) {
1339 $params['contact_id'] = $this->individualCreate();
1341 if (empty($params['event_id'])) {
1342 $event = $this->eventCreate();
1343 $params['event_id'] = $event['id'];
1348 'register_date' => 20070219,
1349 'source' => 'Wimbeldon',
1350 'event_level' => 'Payment',
1354 $params = array_merge($defaults, $params);
1355 $result = $this->callAPISuccess('Participant', 'create', $params);
1356 return $result['id'];
1360 * Create Payment Processor.
1363 * Id Payment Processor
1365 public function processorCreate($params = array()) {
1366 $processorParams = array(
1369 'payment_processor_type_id' => 'Dummy',
1370 'financial_account_id' => 12,
1374 'url_site' => 'http://dummy.com',
1375 'url_recur' => 'http://dummy.com',
1376 'billing_mode' => 1,
1378 'payment_instrument_id' => 'Debit Card',
1380 $processorParams = array_merge($processorParams, $params);
1381 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1382 return $processor['id'];
1386 * Create Payment Processor.
1388 * @param array $processorParams
1390 * @return \CRM_Core_Payment_Dummy
1391 * Instance of Dummy Payment Processor
1393 public function dummyProcessorCreate($processorParams = array()) {
1394 $paymentProcessorID = $this->processorCreate($processorParams);
1395 return System
::singleton()->getById($paymentProcessorID);
1399 * Create contribution page.
1401 * @param array $params
1403 * Array of contribution page
1405 public function contributionPageCreate($params = array()) {
1406 $this->_pageParams
= array_merge(array(
1407 'title' => 'Test Contribution Page',
1408 'financial_type_id' => 1,
1409 'currency' => 'USD',
1410 'financial_account_id' => 1,
1412 'is_allow_other_amount' => 1,
1414 'max_amount' => 1000,
1416 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1420 * Create a sample batch.
1422 public function batchCreate() {
1423 $params = $this->_params
;
1424 $params['name'] = $params['title'] = 'Batch_433397';
1425 $params['status_id'] = 1;
1426 $result = $this->callAPISuccess('batch', 'create', $params);
1427 return $result['id'];
1433 * @param array $params
1435 * result of created tag
1437 public function tagCreate($params = array()) {
1439 'name' => 'New Tag3',
1440 'description' => 'This is description for Our New Tag ',
1443 $params = array_merge($defaults, $params);
1444 $result = $this->callAPISuccess('Tag', 'create', $params);
1445 return $result['values'][$result['id']];
1452 * Id of the tag to be deleted.
1456 public function tagDelete($tagId) {
1457 require_once 'api/api.php';
1461 $result = $this->callAPISuccess('Tag', 'delete', $params);
1462 return $result['id'];
1466 * Add entity(s) to the tag
1468 * @param array $params
1472 public function entityTagAdd($params) {
1473 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1480 * @param array $params
1484 * id of created pledge
1486 public function pledgeCreate($params) {
1487 $params = array_merge(array(
1488 'pledge_create_date' => date('Ymd'),
1489 'start_date' => date('Ymd'),
1490 'scheduled_date' => date('Ymd'),
1492 'pledge_status_id' => '2',
1493 'financial_type_id' => '1',
1494 'pledge_original_installment_amount' => 20,
1495 'frequency_interval' => 5,
1496 'frequency_unit' => 'year',
1497 'frequency_day' => 15,
1498 'installments' => 5,
1502 $result = $this->callAPISuccess('Pledge', 'create', $params);
1503 return $result['id'];
1507 * Delete contribution.
1509 * @param int $pledgeId
1511 public function pledgeDelete($pledgeId) {
1513 'pledge_id' => $pledgeId,
1515 $this->callAPISuccess('Pledge', 'delete', $params);
1519 * Create contribution.
1521 * @param array $params
1522 * Array of parameters.
1525 * id of created contribution
1527 public function contributionCreate($params) {
1529 $params = array_merge(array(
1531 'receive_date' => date('Ymd'),
1532 'total_amount' => 100.00,
1533 'fee_amount' => 5.00,
1534 'net_ammount' => 95.00,
1535 'financial_type_id' => 1,
1536 'payment_instrument_id' => 1,
1537 'non_deductible_amount' => 10.00,
1539 'invoice_id' => 67890,
1541 'contribution_status_id' => 1,
1544 $result = $this->callAPISuccess('contribution', 'create', $params);
1545 return $result['id'];
1549 * Delete contribution.
1551 * @param int $contributionId
1555 public function contributionDelete($contributionId) {
1557 'contribution_id' => $contributionId,
1559 $result = $this->callAPISuccess('contribution', 'delete', $params);
1566 * @param array $params
1567 * Name-value pair for an event.
1571 public function eventCreate($params = array()) {
1572 // if no contact was passed, make up a dummy event creator
1573 if (!isset($params['contact_id'])) {
1574 $params['contact_id'] = $this->_contactCreate(array(
1575 'contact_type' => 'Individual',
1576 'first_name' => 'Event',
1577 'last_name' => 'Creator',
1581 // set defaults for missing params
1582 $params = array_merge(array(
1583 'title' => 'Annual CiviCRM meet',
1584 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1585 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1586 'event_type_id' => 1,
1588 'start_date' => 20081021,
1589 'end_date' => 20081023,
1590 'is_online_registration' => 1,
1591 'registration_start_date' => 20080601,
1592 'registration_end_date' => 20081015,
1593 'max_participants' => 100,
1594 'event_full_text' => 'Sorry! We are already full',
1597 'is_show_location' => 0,
1600 return $this->callAPISuccess('Event', 'create', $params);
1611 public function eventDelete($id) {
1615 return $this->callAPISuccess('event', 'delete', $params);
1619 * Delete participant.
1621 * @param int $participantID
1625 public function participantDelete($participantID) {
1627 'id' => $participantID,
1629 $check = $this->callAPISuccess('Participant', 'get', $params);
1630 if ($check['count'] > 0) {
1631 return $this->callAPISuccess('Participant', 'delete', $params);
1636 * Create participant payment.
1638 * @param int $participantID
1639 * @param int $contributionID
1641 * $id of created payment
1643 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1644 //Create Participant Payment record With Values
1646 'participant_id' => $participantID,
1647 'contribution_id' => $contributionID,
1650 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1651 return $result['id'];
1655 * Delete participant payment.
1657 * @param int $paymentID
1659 public function participantPaymentDelete($paymentID) {
1663 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1669 * @param int $contactID
1671 * location id of created location
1673 public function locationAdd($contactID) {
1676 'location_type' => 'New Location Type',
1678 'name' => 'Saint Helier St',
1679 'county' => 'Marin',
1680 'country' => 'UNITED STATES',
1681 'state_province' => 'Michigan',
1682 'supplemental_address_1' => 'Hallmark Ct',
1683 'supplemental_address_2' => 'Jersey Village',
1688 'contact_id' => $contactID,
1689 'address' => $address,
1690 'location_format' => '2.0',
1691 'location_type' => 'New Location Type',
1694 $result = $this->callAPISuccess('Location', 'create', $params);
1699 * Delete Locations of contact.
1701 * @param array $params
1704 public function locationDelete($params) {
1705 $this->callAPISuccess('Location', 'delete', $params);
1709 * Add a Location Type.
1711 * @param array $params
1712 * @return CRM_Core_DAO_LocationType
1713 * location id of created location
1715 public function locationTypeCreate($params = NULL) {
1716 if ($params === NULL) {
1718 'name' => 'New Location Type',
1719 'vcard_name' => 'New Location Type',
1720 'description' => 'Location Type for Delete',
1725 $locationType = new CRM_Core_DAO_LocationType();
1726 $locationType->copyValues($params);
1727 $locationType->save();
1728 // clear getfields cache
1729 CRM_Core_PseudoConstant
::flush();
1730 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1731 return $locationType;
1735 * Delete a Location Type.
1737 * @param int $locationTypeId
1739 public function locationTypeDelete($locationTypeId) {
1740 $locationType = new CRM_Core_DAO_LocationType();
1741 $locationType->id
= $locationTypeId;
1742 $locationType->delete();
1748 * @param array $params
1749 * @return CRM_Core_DAO_Mapping
1750 * Mapping id of created mapping
1752 public function mappingCreate($params = NULL) {
1753 if ($params === NULL) {
1755 'name' => 'Mapping name',
1756 'description' => 'Mapping description',
1757 // 'Export Contact' mapping.
1758 'mapping_type_id' => 7,
1762 $mapping = new CRM_Core_DAO_Mapping();
1763 $mapping->copyValues($params);
1765 // clear getfields cache
1766 CRM_Core_PseudoConstant
::flush();
1767 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1774 * @param int $mappingId
1776 public function mappingDelete($mappingId) {
1777 $mapping = new CRM_Core_DAO_Mapping();
1778 $mapping->id
= $mappingId;
1785 * @param array $params
1787 * groupId of created group
1789 public function groupCreate($params = array()) {
1790 $params = array_merge(array(
1791 'name' => 'Test Group 1',
1793 'title' => 'New Test Group Created',
1794 'description' => 'New Test Group Created',
1796 'visibility' => 'Public Pages',
1797 'group_type' => array(
1803 $result = $this->callAPISuccess('Group', 'create', $params);
1804 return $result['id'];
1808 * Create a smart group.
1810 * By default it will be a group of households.
1812 * @param array $smartGroupParams
1813 * @param array $groupParams
1816 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1817 $smartGroupParams = array_merge(array(
1818 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1821 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1823 $groupParams['saved_search_id'] = $savedSearch->id
;
1824 return $this->groupCreate($groupParams);
1828 * Function to add a Group.
1830 * @params array to add group
1832 * @param int $groupID
1833 * @param int $totalCount
1835 * groupId of created group
1837 public function groupContactCreate($groupID, $totalCount = 10) {
1838 $params = array('group_id' => $groupID);
1839 for ($i = 1; $i <= $totalCount; $i++
) {
1840 $contactID = $this->individualCreate();
1842 $params +
= array('contact_id' => $contactID);
1845 $params +
= array("contact_id.$i" => $contactID);
1848 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1858 public function groupDelete($gid) {
1864 $this->callAPISuccess('Group', 'delete', $params);
1869 * @param array $params
1871 public function uFFieldCreate($params = array()) {
1872 $params = array_merge(array(
1874 'field_name' => 'first_name',
1877 'visibility' => 'Public Pages and Listings',
1878 'is_searchable' => '1',
1879 'label' => 'first_name',
1880 'field_type' => 'Individual',
1883 $this->callAPISuccess('uf_field', 'create', $params);
1887 * Add a UF Join Entry.
1889 * @param array $params
1891 * $id of created UF Join
1893 public function ufjoinCreate($params = NULL) {
1894 if ($params === NULL) {
1897 'module' => 'CiviEvent',
1898 'entity_table' => 'civicrm_event',
1904 $result = $this->callAPISuccess('uf_join', 'create', $params);
1909 * Delete a UF Join Entry.
1911 * @param array $params
1912 * with missing uf_group_id
1914 public function ufjoinDelete($params = NULL) {
1915 if ($params === NULL) {
1918 'module' => 'CiviEvent',
1919 'entity_table' => 'civicrm_event',
1922 'uf_group_id' => '',
1926 crm_add_uf_join($params);
1930 * @param array $params
1931 * Optional parameters.
1936 public function campaignCreate($params = array()) {
1937 $this->enableCiviCampaign();
1938 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1939 'name' => 'big_campaign',
1940 'title' => 'Campaign',
1942 return $campaign['id'];
1946 * Create Group for a contact.
1948 * @param int $contactId
1950 public function contactGroupCreate($contactId) {
1952 'contact_id.1' => $contactId,
1956 $this->callAPISuccess('GroupContact', 'Create', $params);
1960 * Delete Group for a contact.
1962 * @param int $contactId
1964 public function contactGroupDelete($contactId) {
1966 'contact_id.1' => $contactId,
1969 $this->civicrm_api('GroupContact', 'Delete', $params);
1975 * @param array $params
1978 public function activityCreate($params = array()) {
1979 $params = array_merge(array(
1980 'subject' => 'Discussion on warm beer',
1981 'activity_date_time' => date('Ymd'),
1982 'duration_hours' => 30,
1983 'duration_minutes' => 20,
1984 'location' => 'Baker Street',
1985 'details' => 'Lets schedule a meeting',
1987 'activity_name' => 'Meeting',
1989 if (!isset($params['source_contact_id'])) {
1990 $params['source_contact_id'] = $this->individualCreate();
1992 if (!isset($params['target_contact_id'])) {
1993 $params['target_contact_id'] = $this->individualCreate(array(
1994 'first_name' => 'Julia',
1995 'Last_name' => 'Anderson',
1997 'email' => 'julia_anderson@civicrm.org',
1998 'contact_type' => 'Individual',
2001 if (!isset($params['assignee_contact_id'])) {
2002 $params['assignee_contact_id'] = $params['target_contact_id'];
2005 $result = $this->callAPISuccess('Activity', 'create', $params);
2007 $result['target_contact_id'] = $params['target_contact_id'];
2008 $result['assignee_contact_id'] = $params['assignee_contact_id'];
2013 * Create an activity type.
2015 * @param array $params
2019 public function activityTypeCreate($params) {
2020 return $this->callAPISuccess('ActivityType', 'create', $params);
2024 * Delete activity type.
2026 * @param int $activityTypeId
2027 * Id of the activity type.
2030 public function activityTypeDelete($activityTypeId) {
2031 $params['activity_type_id'] = $activityTypeId;
2032 return $this->callAPISuccess('ActivityType', 'delete', $params);
2036 * Create custom group.
2038 * @param array $params
2041 public function customGroupCreate($params = array()) {
2043 'title' => 'new custom group',
2044 'extends' => 'Contact',
2046 'style' => 'Inline',
2050 $params = array_merge($defaults, $params);
2052 if (strlen($params['title']) > 13) {
2053 $params['title'] = substr($params['title'], 0, 13);
2056 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2057 $this->callAPISuccess('custom_group', 'get', array(
2058 'title' => $params['title'],
2059 array('api.custom_group.delete' => 1),
2062 return $this->callAPISuccess('custom_group', 'create', $params);
2066 * Existing function doesn't allow params to be over-ridden so need a new one
2067 * this one allows you to only pass in the params you want to change
2068 * @param array $params
2071 public function CustomGroupCreateByParams($params = array()) {
2073 'title' => "API Custom Group",
2074 'extends' => 'Contact',
2076 'style' => 'Inline',
2079 $params = array_merge($defaults, $params);
2080 return $this->callAPISuccess('custom_group', 'create', $params);
2084 * Create custom group with multi fields.
2085 * @param array $params
2088 public function CustomGroupMultipleCreateByParams($params = array()) {
2093 $params = array_merge($defaults, $params);
2094 return $this->CustomGroupCreateByParams($params);
2098 * Create custom group with multi fields.
2099 * @param array $params
2102 public function CustomGroupMultipleCreateWithFields($params = array()) {
2103 // also need to pass on $params['custom_field'] if not set but not in place yet
2105 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2106 $ids['custom_group_id'] = $customGroup['id'];
2108 $customField = $this->customFieldCreate(array(
2109 'custom_group_id' => $ids['custom_group_id'],
2110 'label' => 'field_1' . $ids['custom_group_id'],
2114 $ids['custom_field_id'][] = $customField['id'];
2116 $customField = $this->customFieldCreate(array(
2117 'custom_group_id' => $ids['custom_group_id'],
2118 'default_value' => '',
2119 'label' => 'field_2' . $ids['custom_group_id'],
2122 $ids['custom_field_id'][] = $customField['id'];
2124 $customField = $this->customFieldCreate(array(
2125 'custom_group_id' => $ids['custom_group_id'],
2126 'default_value' => '',
2127 'label' => 'field_3' . $ids['custom_group_id'],
2130 $ids['custom_field_id'][] = $customField['id'];
2136 * Create a custom group with a single text custom field. See
2137 * participant:testCreateWithCustom for how to use this
2139 * @param string $function
2141 * @param string $filename
2145 * ids of created objects
2147 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2148 $params = array('title' => $function);
2149 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2150 $params['extends'] = $entity ?
$entity : 'Contact';
2151 $customGroup = $this->CustomGroupCreate($params);
2152 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2153 CRM_Core_PseudoConstant
::flush();
2155 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2159 * Delete custom group.
2161 * @param int $customGroupID
2165 public function customGroupDelete($customGroupID) {
2166 $params['id'] = $customGroupID;
2167 return $this->callAPISuccess('custom_group', 'delete', $params);
2171 * Create custom field.
2173 * @param array $params
2174 * (custom_group_id) is required.
2177 public function customFieldCreate($params) {
2178 $params = array_merge(array(
2179 'label' => 'Custom Field',
2180 'data_type' => 'String',
2181 'html_type' => 'Text',
2182 'is_searchable' => 1,
2184 'default_value' => 'defaultValue',
2187 $result = $this->callAPISuccess('custom_field', 'create', $params);
2188 // these 2 functions are called with force to flush static caches
2189 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2190 CRM_Core_Component
::getEnabledComponents(1);
2195 * Delete custom field.
2197 * @param int $customFieldID
2201 public function customFieldDelete($customFieldID) {
2203 $params['id'] = $customFieldID;
2204 return $this->callAPISuccess('custom_field', 'delete', $params);
2213 public function noteCreate($cId) {
2215 'entity_table' => 'civicrm_contact',
2216 'entity_id' => $cId,
2217 'note' => 'hello I am testing Note',
2218 'contact_id' => $cId,
2219 'modified_date' => date('Ymd'),
2220 'subject' => 'Test Note',
2223 return $this->callAPISuccess('Note', 'create', $params);
2227 * Enable CiviCampaign Component.
2229 public function enableCiviCampaign() {
2230 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2231 // force reload of config object
2232 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2233 //flush cache by calling with reset
2234 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2238 * Create test generated example in api/v3/examples.
2240 * To turn this off (e.g. on the server) set
2241 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2242 * in your settings file
2244 * @param string $entity
2245 * @param string $action
2246 * @param array $params
2247 * Array as passed to civicrm_api function.
2248 * @param array $result
2249 * Array as received from the civicrm_api function.
2250 * @param string $testFunction
2251 * Calling function - generally __FUNCTION__.
2252 * @param string $testFile
2253 * Called from file - generally __FILE__.
2254 * @param string $description
2255 * Descriptive text for the example file.
2256 * @param string $exampleName
2257 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2259 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2260 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2263 $entity = _civicrm_api_get_camel_name($entity);
2264 $action = strtolower($action);
2266 if (empty($exampleName)) {
2267 // Attempt to convert lowercase action name to CamelCase.
2268 // This is clunky/imperfect due to the convention of all lowercase actions.
2269 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2270 $knownPrefixes = array(
2277 foreach ($knownPrefixes as $prefix) {
2278 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2279 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2284 $this->tidyExampleResult($result);
2285 if (isset($params['version'])) {
2286 unset($params['version']);
2288 // Format multiline description as array
2290 if (is_string($description) && strlen($description)) {
2291 foreach (explode("\n", $description) as $line) {
2292 $desc[] = trim($line);
2295 $smarty = CRM_Core_Smarty
::singleton();
2296 $smarty->assign('testFunction', $testFunction);
2297 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2298 $smarty->assign('params', $params);
2299 $smarty->assign('entity', $entity);
2300 $smarty->assign('testFile', basename($testFile));
2301 $smarty->assign('description', $desc);
2302 $smarty->assign('result', $result);
2303 $smarty->assign('action', $action);
2305 global $civicrm_root;
2306 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2307 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2308 mkdir($civicrm_root . "/api/v3/examples/$entity");
2310 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2311 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2317 * Tidy up examples array so that fields that change often ..don't
2318 * and debug related fields are unset
2320 * @param array $result
2322 public function tidyExampleResult(&$result) {
2323 if (!is_array($result)) {
2326 $fieldsToChange = array(
2327 'hash' => '67eac7789eaee00',
2328 'modified_date' => '2012-11-14 16:02:35',
2329 'created_date' => '2013-07-28 08:49:19',
2330 'create_date' => '20120130621222105',
2331 'application_received_date' => '20130728084957',
2332 'in_date' => '2013-07-28 08:50:19',
2333 'scheduled_date' => '20130728085413',
2334 'approval_date' => '20130728085413',
2335 'pledge_start_date_high' => '20130726090416',
2336 'start_date' => '2013-07-29 00:00:00',
2337 'event_start_date' => '2013-07-29 00:00:00',
2338 'end_date' => '2013-08-04 00:00:00',
2339 'event_end_date' => '2013-08-04 00:00:00',
2340 'decision_date' => '20130805000000',
2343 $keysToUnset = array('xdebug', 'undefined_fields');
2344 foreach ($keysToUnset as $unwantedKey) {
2345 if (isset($result[$unwantedKey])) {
2346 unset($result[$unwantedKey]);
2349 if (isset($result['values'])) {
2350 if (!is_array($result['values'])) {
2353 $resultArray = &$result['values'];
2355 elseif (is_array($result)) {
2356 $resultArray = &$result;
2362 foreach ($resultArray as $index => &$values) {
2363 if (!is_array($values)) {
2366 foreach ($values as $key => &$value) {
2367 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2368 if (isset($value['is_error'])) {
2369 // we have a std nested result format
2370 $this->tidyExampleResult($value);
2373 foreach ($value as &$nestedResult) {
2374 // this is an alternative syntax for nested results a keyed array of results
2375 $this->tidyExampleResult($nestedResult);
2379 if (in_array($key, $keysToUnset)) {
2380 unset($values[$key]);
2383 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2384 $value = $fieldsToChange[$key];
2386 if (is_string($value)) {
2387 $value = addslashes($value);
2394 * Create custom field with Option Values.
2396 * @param array $customGroup
2397 * @param string $name
2398 * Name of custom field.
2402 public function customFieldOptionValueCreate($customGroup, $name) {
2403 $fieldParams = array(
2404 'custom_group_id' => $customGroup['id'],
2405 'name' => 'test_custom_group',
2406 'label' => 'Country',
2407 'html_type' => 'Select',
2408 'data_type' => 'String',
2411 'is_searchable' => 0,
2415 $optionGroup = array(
2417 'name' => 'option_group1',
2418 'label' => 'option_group_label1',
2421 $optionValue = array(
2422 'option_label' => array('Label1', 'Label2'),
2423 'option_value' => array('value1', 'value2'),
2424 'option_name' => array($name . '_1', $name . '_2'),
2425 'option_weight' => array(1, 2),
2426 'option_status' => 1,
2429 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2431 return $this->callAPISuccess('custom_field', 'create', $params);
2439 public function confirmEntitiesDeleted($entities) {
2440 foreach ($entities as $entity) {
2442 $result = $this->callAPISuccess($entity, 'Get', array());
2443 if ($result['error'] == 1 ||
$result['count'] > 0) {
2444 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2452 * Quick clean by emptying tables created for the test.
2454 * @param array $tablesToTruncate
2455 * @param bool $dropCustomValueTables
2456 * @throws \Exception
2458 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2460 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2462 if ($dropCustomValueTables) {
2463 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2464 while ($optionGroupResult->fetch()) {
2465 if (!empty($optionGroupResult->option_group_id
)) {
2466 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2469 $tablesToTruncate[] = 'civicrm_custom_group';
2470 $tablesToTruncate[] = 'civicrm_custom_field';
2473 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2475 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2476 foreach ($tablesToTruncate as $table) {
2477 $sql = "TRUNCATE TABLE $table";
2478 CRM_Core_DAO
::executeQuery($sql);
2480 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2482 if ($dropCustomValueTables) {
2483 $dbName = self
::getDBName();
2485 SELECT TABLE_NAME as tableName
2486 FROM INFORMATION_SCHEMA.TABLES
2487 WHERE TABLE_SCHEMA = '{$dbName}'
2488 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2491 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2492 while ($tableDAO->fetch()) {
2493 $sql = "DROP TABLE {$tableDAO->tableName}";
2494 CRM_Core_DAO
::executeQuery($sql);
2500 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2502 public function quickCleanUpFinancialEntities() {
2503 $tablesToTruncate = array(
2505 'civicrm_activity_contact',
2506 'civicrm_contribution',
2507 'civicrm_contribution_soft',
2508 'civicrm_contribution_product',
2509 'civicrm_financial_trxn',
2510 'civicrm_financial_item',
2511 'civicrm_contribution_recur',
2512 'civicrm_line_item',
2513 'civicrm_contribution_page',
2514 'civicrm_payment_processor',
2515 'civicrm_entity_financial_trxn',
2516 'civicrm_membership',
2517 'civicrm_membership_type',
2518 'civicrm_membership_payment',
2519 'civicrm_membership_log',
2520 'civicrm_membership_block',
2522 'civicrm_participant',
2523 'civicrm_participant_payment',
2525 'civicrm_pledge_payment',
2526 'civicrm_price_set_entity',
2527 'civicrm_price_field_value',
2528 'civicrm_price_field',
2530 $this->quickCleanup($tablesToTruncate);
2531 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2532 $this->restoreDefaultPriceSetConfig();
2534 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2535 System
::singleton()->flushProcessors();
2538 public function restoreDefaultPriceSetConfig() {
2539 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2540 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)");
2541 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `non_deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2544 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2545 * Default behaviour is to also delete the entity
2546 * @param array $params
2547 * Params array to check against.
2549 * Id of the entity concerned.
2550 * @param string $entity
2551 * Name of entity concerned (e.g. membership).
2552 * @param bool $delete
2553 * Should the entity be deleted as part of this check.
2554 * @param string $errorText
2555 * Text to print on error.
2558 * @param array $params
2561 * @param int $delete
2562 * @param string $errorText
2566 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2568 $result = $this->callAPISuccessGetSingle($entity, array(
2573 $this->callAPISuccess($entity, 'Delete', array(
2577 $dateFields = $keys = $dateTimeFields = array();
2578 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2579 foreach ($fields['values'] as $field => $settings) {
2580 if (array_key_exists($field, $result)) {
2581 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2584 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2586 $type = CRM_Utils_Array
::value('type', $settings);
2587 if ($type == CRM_Utils_Type
::T_DATE
) {
2588 $dateFields[] = $settings['name'];
2589 // we should identify both real names & unique names as dates
2590 if ($field != $settings['name']) {
2591 $dateFields[] = $field;
2594 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2595 $dateTimeFields[] = $settings['name'];
2596 // we should identify both real names & unique names as dates
2597 if ($field != $settings['name']) {
2598 $dateTimeFields[] = $field;
2603 if (strtolower($entity) == 'contribution') {
2604 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2605 // this is not returned in id format
2606 unset($params['payment_instrument_id']);
2607 $params['contribution_source'] = $params['source'];
2608 unset($params['source']);
2611 foreach ($params as $key => $value) {
2612 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2615 if (in_array($key, $dateFields)) {
2616 $value = date('Y-m-d', strtotime($value));
2617 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2619 if (in_array($key, $dateTimeFields)) {
2620 $value = date('Y-m-d H:i:s', strtotime($value));
2621 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2623 $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);
2628 * Get formatted values in the actual and expected result.
2629 * @param array $actual
2630 * Actual calculated values.
2631 * @param array $expected
2634 public function checkArrayEquals(&$actual, &$expected) {
2635 self
::unsetId($actual);
2636 self
::unsetId($expected);
2637 $this->assertEquals($actual, $expected);
2641 * Unset the key 'id' from the array
2642 * @param array $unformattedArray
2643 * The array from which the 'id' has to be unset.
2645 public static function unsetId(&$unformattedArray) {
2646 $formattedArray = array();
2647 if (array_key_exists('id', $unformattedArray)) {
2648 unset($unformattedArray['id']);
2650 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2651 foreach ($unformattedArray['values'] as $key => $value) {
2652 if (is_array($value)) {
2653 foreach ($value as $k => $v) {
2659 elseif ($key == 'id') {
2660 $unformattedArray[$key];
2662 $formattedArray = array($value);
2664 $unformattedArray['values'] = $formattedArray;
2669 * Helper to enable/disable custom directory support
2671 * @param array $customDirs
2673 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2674 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2676 public function customDirectories($customDirs) {
2677 $config = CRM_Core_Config
::singleton();
2679 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2680 unset($config->customPHPPathDir
);
2682 elseif ($customDirs['php_path'] === TRUE) {
2683 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2686 $config->customPHPPathDir
= $php_path;
2689 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2690 unset($config->customTemplateDir
);
2692 elseif ($customDirs['template_path'] === TRUE) {
2693 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2696 $config->customTemplateDir
= $template_path;
2701 * Generate a temporary folder.
2703 * @param string $prefix
2706 public function createTempDir($prefix = 'test-') {
2707 $tempDir = CRM_Utils_File
::tempdir($prefix);
2708 $this->tempDirs
[] = $tempDir;
2712 public function cleanTempDirs() {
2713 if (!is_array($this->tempDirs
)) {
2714 // fix test errors where this is not set
2717 foreach ($this->tempDirs
as $tempDir) {
2718 if (is_dir($tempDir)) {
2719 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2725 * Temporarily replace the singleton extension with a different one.
2726 * @param \CRM_Extension_System $system
2728 public function setExtensionSystem(CRM_Extension_System
$system) {
2729 if ($this->origExtensionSystem
== NULL) {
2730 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2732 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2735 public function unsetExtensionSystem() {
2736 if ($this->origExtensionSystem
!== NULL) {
2737 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2738 $this->origExtensionSystem
= NULL;
2743 * Temporarily alter the settings-metadata to add a mock setting.
2745 * WARNING: The setting metadata will disappear on the next cache-clear.
2750 public function setMockSettingsMetaData($extras) {
2751 Civi
::service('settings_manager')->flush();
2753 CRM_Utils_Hook
::singleton()
2754 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2755 $metadata = array_merge($metadata, $extras);
2758 $fields = $this->callAPISuccess('setting', 'getfields', array());
2759 foreach ($extras as $key => $spec) {
2760 $this->assertNotEmpty($spec['title']);
2761 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2766 * @param string $name
2768 public function financialAccountDelete($name) {
2769 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2770 $financialAccount->name
= $name;
2771 if ($financialAccount->find(TRUE)) {
2772 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2773 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2774 $entityFinancialType->delete();
2775 $financialAccount->delete();
2780 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2781 * (NB unclear if this is still required)
2783 public function _sethtmlGlobals() {
2784 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2785 'required' => array(
2786 'html_quickform_rule_required',
2787 'HTML/QuickForm/Rule/Required.php',
2789 'maxlength' => array(
2790 'html_quickform_rule_range',
2791 'HTML/QuickForm/Rule/Range.php',
2793 'minlength' => array(
2794 'html_quickform_rule_range',
2795 'HTML/QuickForm/Rule/Range.php',
2797 'rangelength' => array(
2798 'html_quickform_rule_range',
2799 'HTML/QuickForm/Rule/Range.php',
2802 'html_quickform_rule_email',
2803 'HTML/QuickForm/Rule/Email.php',
2806 'html_quickform_rule_regex',
2807 'HTML/QuickForm/Rule/Regex.php',
2809 'lettersonly' => array(
2810 'html_quickform_rule_regex',
2811 'HTML/QuickForm/Rule/Regex.php',
2813 'alphanumeric' => array(
2814 'html_quickform_rule_regex',
2815 'HTML/QuickForm/Rule/Regex.php',
2818 'html_quickform_rule_regex',
2819 'HTML/QuickForm/Rule/Regex.php',
2821 'nopunctuation' => array(
2822 'html_quickform_rule_regex',
2823 'HTML/QuickForm/Rule/Regex.php',
2826 'html_quickform_rule_regex',
2827 'HTML/QuickForm/Rule/Regex.php',
2829 'callback' => array(
2830 'html_quickform_rule_callback',
2831 'HTML/QuickForm/Rule/Callback.php',
2834 'html_quickform_rule_compare',
2835 'HTML/QuickForm/Rule/Compare.php',
2838 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2839 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2841 'HTML/QuickForm/group.php',
2842 'HTML_QuickForm_group',
2845 'HTML/QuickForm/hidden.php',
2846 'HTML_QuickForm_hidden',
2849 'HTML/QuickForm/reset.php',
2850 'HTML_QuickForm_reset',
2852 'checkbox' => array(
2853 'HTML/QuickForm/checkbox.php',
2854 'HTML_QuickForm_checkbox',
2857 'HTML/QuickForm/file.php',
2858 'HTML_QuickForm_file',
2861 'HTML/QuickForm/image.php',
2862 'HTML_QuickForm_image',
2864 'password' => array(
2865 'HTML/QuickForm/password.php',
2866 'HTML_QuickForm_password',
2869 'HTML/QuickForm/radio.php',
2870 'HTML_QuickForm_radio',
2873 'HTML/QuickForm/button.php',
2874 'HTML_QuickForm_button',
2877 'HTML/QuickForm/submit.php',
2878 'HTML_QuickForm_submit',
2881 'HTML/QuickForm/select.php',
2882 'HTML_QuickForm_select',
2884 'hiddenselect' => array(
2885 'HTML/QuickForm/hiddenselect.php',
2886 'HTML_QuickForm_hiddenselect',
2889 'HTML/QuickForm/text.php',
2890 'HTML_QuickForm_text',
2892 'textarea' => array(
2893 'HTML/QuickForm/textarea.php',
2894 'HTML_QuickForm_textarea',
2896 'fckeditor' => array(
2897 'HTML/QuickForm/fckeditor.php',
2898 'HTML_QuickForm_FCKEditor',
2901 'HTML/QuickForm/tinymce.php',
2902 'HTML_QuickForm_TinyMCE',
2904 'dojoeditor' => array(
2905 'HTML/QuickForm/dojoeditor.php',
2906 'HTML_QuickForm_dojoeditor',
2909 'HTML/QuickForm/link.php',
2910 'HTML_QuickForm_link',
2912 'advcheckbox' => array(
2913 'HTML/QuickForm/advcheckbox.php',
2914 'HTML_QuickForm_advcheckbox',
2917 'HTML/QuickForm/date.php',
2918 'HTML_QuickForm_date',
2921 'HTML/QuickForm/static.php',
2922 'HTML_QuickForm_static',
2925 'HTML/QuickForm/header.php',
2926 'HTML_QuickForm_header',
2929 'HTML/QuickForm/html.php',
2930 'HTML_QuickForm_html',
2932 'hierselect' => array(
2933 'HTML/QuickForm/hierselect.php',
2934 'HTML_QuickForm_hierselect',
2936 'autocomplete' => array(
2937 'HTML/QuickForm/autocomplete.php',
2938 'HTML_QuickForm_autocomplete',
2941 'HTML/QuickForm/xbutton.php',
2942 'HTML_QuickForm_xbutton',
2944 'advmultiselect' => array(
2945 'HTML/QuickForm/advmultiselect.php',
2946 'HTML_QuickForm_advmultiselect',
2952 * Set up an acl allowing contact to see 2 specified groups
2953 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2955 * You need to have pre-created these groups & created the user e.g
2956 * $this->createLoggedInUser();
2957 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2958 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2960 * @param bool $isProfile
2962 public function setupACL($isProfile = FALSE) {
2964 $_REQUEST = $this->_params
;
2966 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2967 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2968 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2969 'option_group_id' => $optionGroupID,
2970 'label' => 'pick me',
2974 CRM_Core_DAO
::executeQuery("
2975 TRUNCATE civicrm_acl_cache
2978 CRM_Core_DAO
::executeQuery("
2979 TRUNCATE civicrm_acl_contact_cache
2982 CRM_Core_DAO
::executeQuery("
2983 INSERT INTO civicrm_acl_entity_role (
2984 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2985 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2989 CRM_Core_DAO
::executeQuery("
2990 INSERT INTO civicrm_acl (
2991 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2994 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2999 CRM_Core_DAO
::executeQuery("
3000 INSERT INTO civicrm_acl (
3001 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3004 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3008 CRM_Core_DAO
::executeQuery("
3009 INSERT INTO civicrm_acl (
3010 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3013 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3018 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3019 $this->callAPISuccess('group_contact', 'create', array(
3020 'group_id' => $this->_permissionedGroup
,
3021 'contact_id' => $this->_loggedInUser
,
3026 CRM_ACL_BAO_Cache
::resetCache();
3027 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3028 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3033 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3035 public function offsetDefaultPriceSet() {
3036 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3037 $firstID = $contributionPriceSet['id'];
3038 $this->callAPISuccess('price_set', 'create', array(
3039 'id' => $contributionPriceSet['id'],
3043 unset($contributionPriceSet['id']);
3044 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3045 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3046 'price_set_id' => $firstID,
3047 'options' => array('limit' => 1),
3049 unset($priceField['id']);
3050 $priceField['price_set_id'] = $newPriceSet['id'];
3051 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3052 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3053 'price_set_id' => $firstID,
3055 'options' => array('limit' => 1),
3058 unset($priceFieldValue['id']);
3059 //create some padding to use up ids
3060 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3061 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3062 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3066 * Create an instance of the paypal processor.
3067 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3068 * this parent class & we don't have a structure for that yet
3069 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3070 * & the best protection against that is the functions this class affords
3071 * @param array $params
3072 * @return int $result['id'] payment processor id
3074 public function paymentProcessorCreate($params = array()) {
3075 $params = array_merge(array(
3077 'domain_id' => CRM_Core_Config
::domainID(),
3078 'payment_processor_type_id' => 'PayPal',
3082 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3083 'password' => '1183377788',
3084 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3085 'url_site' => 'https://www.sandbox.paypal.com/',
3086 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3087 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3088 'class_name' => 'Payment_PayPalImpl',
3089 'billing_mode' => 3,
3090 'financial_type_id' => 1,
3091 'financial_account_id' => 12,
3092 // Credit card = 1 so can pass 'by accident'.
3093 'payment_instrument_id' => 'Debit Card',
3096 if (!is_numeric($params['payment_processor_type_id'])) {
3097 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3099 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3100 'name' => $params['payment_processor_type_id'],
3104 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3105 return $result['id'];
3109 * Set up initial recurring payment allowing subsequent IPN payments.
3111 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3112 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3113 'contact_id' => $this->_contactID
,
3116 'installments' => 5,
3117 'frequency_unit' => 'Month',
3118 'frequency_interval' => 1,
3119 'invoice_id' => $this->_invoiceID
,
3120 'contribution_status_id' => 2,
3121 'payment_processor_id' => $this->_paymentProcessorID
,
3122 // processor provided ID - use contact ID as proxy.
3123 'processor_id' => $this->_contactID
,
3124 'api.contribution.create' => array(
3125 'total_amount' => '200',
3126 'invoice_id' => $this->_invoiceID
,
3127 'financial_type_id' => 1,
3128 'contribution_status_id' => 'Pending',
3129 'contact_id' => $this->_contactID
,
3130 'contribution_page_id' => $this->_contributionPageID
,
3131 'payment_processor_id' => $this->_paymentProcessorID
,
3135 $this->_contributionRecurID
= $contributionRecur['id'];
3136 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3140 * 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
3142 public function setupMembershipRecurringPaymentProcessorTransaction() {
3143 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3144 //create a contribution so our membership & contribution don't both have id = 1
3145 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3146 $this->contributionCreate(array(
3147 'contact_id' => $this->_contactID
,
3149 'financial_type_id' => 1,
3150 'invoice_id' => 'abcd',
3154 $this->setupRecurringPaymentProcessorTransaction();
3156 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3157 'contact_id' => $this->_contactID
,
3158 'membership_type_id' => $this->ids
['membership_type'],
3159 'contribution_recur_id' => $this->_contributionRecurID
,
3160 'format.only_id' => TRUE,
3162 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3163 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3165 $this->callAPISuccess('line_item', 'create', array(
3166 'entity_table' => 'civicrm_membership',
3167 'entity_id' => $this->ids
['membership'],
3168 'contribution_id' => $this->_contributionID
,
3169 'label' => 'General',
3171 'unit_price' => 200,
3172 'line_total' => 200,
3173 'financial_type_id' => 1,
3174 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3176 'label' => 'Membership Amount',
3177 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3179 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3181 'label' => 'General',
3182 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3185 $this->callAPISuccess('membership_payment', 'create', array(
3186 'contribution_id' => $this->_contributionID
,
3187 'membership_id' => $this->ids
['membership'],
3196 public function CiviUnitTestCase_fatalErrorHandler($message) {
3197 throw new Exception("{$message['message']}: {$message['code']}");
3201 * Helper function to create new mailing.
3203 * @param array $params
3207 public function createMailing($params) {
3208 $params = array_merge(array(
3209 'subject' => 'maild' . rand(),
3210 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3211 'name' => 'mailing name' . rand(),
3215 $result = $this->callAPISuccess('Mailing', 'create', $params);
3216 return $result['id'];
3220 * Helper function to delete mailing.
3223 public function deleteMailing($id) {
3228 $this->callAPISuccess('Mailing', 'delete', $params);
3232 * Wrap the entire test case in a transaction.
3234 * Only subsequent DB statements will be wrapped in TX -- this cannot
3235 * retroactively wrap old DB statements. Therefore, it makes sense to
3236 * call this at the beginning of setUp().
3238 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3239 * this option does not work with, e.g., custom-data.
3241 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3242 * if TRUNCATE or ALTER is called while using a transaction.
3245 * Whether to use nesting or reference-counting.
3247 public function useTransaction($nest = TRUE) {
3249 $this->tx
= new CRM_Core_Transaction($nest);
3250 $this->tx
->rollback();
3255 * Assert the attachment exists.
3257 * @param bool $exists
3258 * @param array $apiResult
3260 protected function assertAttachmentExistence($exists, $apiResult) {
3261 $fileId = $apiResult['id'];
3262 $this->assertTrue(is_numeric($fileId));
3263 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3264 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3265 1 => array($fileId, 'Int'),
3267 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3268 1 => array($fileId, 'Int'),
3273 * Create a price set for an event.
3275 * @param int $feeTotal
3276 * @param int $minAmt
3281 protected function eventPriceSetCreate($feeTotal, $minAmt = 0) {
3282 // creating price set, price field
3283 $paramsSet['title'] = 'Price Set';
3284 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3285 $paramsSet['is_active'] = FALSE;
3286 $paramsSet['extends'] = 1;
3287 $paramsSet['min_amount'] = $minAmt;
3289 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3290 $priceSetId = $priceset->id
;
3292 //Checking for priceset added in the table.
3293 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3294 'id', $paramsSet['title'], 'Check DB for created priceset'
3296 $paramsField = array(
3297 'label' => 'Price Field',
3298 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3299 'html_type' => 'Text',
3300 'price' => $feeTotal,
3301 'option_label' => array('1' => 'Price Field'),
3302 'option_value' => array('1' => $feeTotal),
3303 'option_name' => array('1' => $feeTotal),
3304 'option_weight' => array('1' => 1),
3305 'option_amount' => array('1' => 1),
3306 'is_display_amounts' => 1,
3308 'options_per_line' => 1,
3309 'is_active' => array('1' => 1),
3310 'price_set_id' => $priceset->id
,
3311 'is_enter_qty' => 1,
3312 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3314 CRM_Price_BAO_PriceField
::create($paramsField);
3320 * Add a profile to a contribution page.
3322 * @param string $name
3323 * @param int $contributionPageID
3325 protected function addProfile($name, $contributionPageID) {
3326 $this->callAPISuccess('UFJoin', 'create', array(
3327 'uf_group_id' => $name,
3328 'module' => 'CiviContribute',
3329 'entity_table' => 'civicrm_contribution_page',
3330 'entity_id' => $contributionPageID,
3336 * Add participant with contribution
3340 protected function createParticipantWithContribution() {
3341 // creating price set, price field
3342 $this->_contactId
= $this->individualCreate();
3343 $event = $this->eventCreate();
3344 $this->_eventId
= $event['id'];
3345 $eventParams = array(
3346 'id' => $this->_eventId
,
3347 'financial_type_id' => 4,
3350 $this->callAPISuccess('event', 'create', $eventParams);
3351 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3352 $participantParams = array(
3353 'financial_type_id' => 4,
3354 'event_id' => $this->_eventId
,
3357 'fee_currency' => 'USD',
3358 'contact_id' => $this->_contactId
,
3360 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3361 $contributionParams = array(
3362 'total_amount' => 150,
3363 'currency' => 'USD',
3364 'contact_id' => $this->_contactId
,
3365 'financial_type_id' => 4,
3366 'contribution_status_id' => 1,
3367 'partial_payment_total' => 300.00,
3368 'partial_amount_pay' => 150,
3369 'contribution_mode' => 'participant',
3370 'participant_id' => $participant['id'],
3372 foreach ($priceFields['values'] as $key => $priceField) {
3373 $lineItems[1][$key] = array(
3374 'price_field_id' => $priceField['price_field_id'],
3375 'price_field_value_id' => $priceField['id'],
3376 'label' => $priceField['label'],
3377 'field_title' => $priceField['label'],
3379 'unit_price' => $priceField['amount'],
3380 'line_total' => $priceField['amount'],
3381 'financial_type_id' => $priceField['financial_type_id'],
3384 $contributionParams['line_item'] = $lineItems;
3385 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3386 $paymentParticipant = array(
3387 'participant_id' => $participant['id'],
3388 'contribution_id' => $contribution['id'],
3390 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3391 return array($lineItems, $contribution);
3397 * @param string $component
3398 * @param int $componentId
3402 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3403 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3404 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3405 $paramsSet['is_active'] = TRUE;
3406 $paramsSet['financial_type_id'] = 4;
3407 $paramsSet['extends'] = 1;
3408 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3409 $priceSetId = $priceSet['id'];
3410 //Checking for priceset added in the table.
3411 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3412 'id', $paramsSet['title'], 'Check DB for created priceset'
3414 $paramsField = array_merge(array(
3415 'label' => 'Price Field',
3416 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3417 'html_type' => 'CheckBox',
3418 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3419 'option_value' => array('1' => 100, '2' => 200),
3420 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3421 'option_weight' => array('1' => 1, '2' => 2),
3422 'option_amount' => array('1' => 100, '2' => 200),
3423 'is_display_amounts' => 1,
3425 'options_per_line' => 1,
3426 'is_active' => array('1' => 1, '2' => 1),
3427 'price_set_id' => $priceSet['id'],
3428 'is_enter_qty' => 1,
3429 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3430 ), $priceFieldOptions);
3432 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3434 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3436 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3440 * Replace the template with a test-oriented template designed to show all the variables.
3442 * @param string $templateName
3444 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3445 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3446 CRM_Core_DAO
::executeQuery(
3447 "UPDATE civicrm_option_group og
3448 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3449 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3450 SET m.msg_html = '{$testTemplate}'
3451 WHERE og.name = 'msg_tpl_workflow_contribution'
3452 AND ov.name = '{$templateName}'
3453 AND m.is_default = 1"
3458 * Reinstate the default template.
3460 * @param string $templateName
3462 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3463 CRM_Core_DAO
::executeQuery(
3464 "UPDATE civicrm_option_group og
3465 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3466 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3467 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3468 SET m.msg_html = m2.msg_html
3469 WHERE og.name = 'msg_tpl_workflow_contribution'
3470 AND ov.name = '{$templateName}'
3471 AND m.is_default = 1"
3476 * Flush statics relating to financial type.
3478 protected function flushFinancialTypeStatics() {
3479 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3480 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3482 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3483 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3485 CRM_Contribute_PseudoConstant
::flush('financialType');
3486 CRM_Contribute_PseudoConstant
::flush('membershipType');
3487 // Pseudoconstants may be saved to the cache table.
3488 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3489 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3490 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3494 * Set the permissions to the supplied array.
3496 * @param array $permissions
3498 protected function setPermissions($permissions) {
3499 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3500 $this->flushFinancialTypeStatics();
3501 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3505 * @param array $params
3508 public function _checkFinancialRecords($params, $context) {
3509 $entityParams = array(
3510 'entity_id' => $params['id'],
3511 'entity_table' => 'civicrm_contribution',
3513 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3514 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3515 if ($context == 'pending') {
3516 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3517 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3520 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3521 $trxnParams = array(
3522 'id' => $trxn['financial_trxn_id'],
3524 if ($context != 'online' && $context != 'payLater') {
3525 $compareParams = array(
3526 'to_financial_account_id' => 6,
3527 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3531 if ($context == 'feeAmount') {
3532 $compareParams['fee_amount'] = 50;
3534 elseif ($context == 'online') {
3535 $compareParams = array(
3536 'to_financial_account_id' => 12,
3537 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3539 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3542 elseif ($context == 'payLater') {
3543 $compareParams = array(
3544 'to_financial_account_id' => 7,
3545 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3549 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3550 $entityParams = array(
3551 'financial_trxn_id' => $trxn['financial_trxn_id'],
3552 'entity_table' => 'civicrm_financial_item',
3554 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3555 $fitemParams = array(
3556 'id' => $entityTrxn['entity_id'],
3558 $compareParams = array(
3559 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3561 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3563 if ($context == 'payLater') {
3564 $compareParams = array(
3565 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3567 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3570 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3571 if ($context == 'feeAmount') {
3573 'entity_id' => $params['id'],
3574 'entity_table' => 'civicrm_contribution',
3576 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3577 $trxnParams = array(
3578 'id' => $maxTrxn['financial_trxn_id'],
3580 $compareParams = array(
3581 'to_financial_account_id' => 5,
3582 'from_financial_account_id' => 6,
3583 'total_amount' => 50,
3586 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3587 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3588 $fitemParams = array(
3589 'entity_id' => $trxnId['financialTrxnId'],
3590 'entity_table' => 'civicrm_financial_trxn',
3592 $compareParams = array(
3595 'financial_account_id' => 5,
3597 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3599 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3600 // line should be copied into all the functions that call this function & evaluated there
3601 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3602 // when calling completeTransaction or repeatTransaction.
3603 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3607 * Return financial type id on basis of name
3609 * @param string $name Financial type m/c name
3613 public function getFinancialTypeId($name) {
3614 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3618 * Cleanup function for contents of $this->ids.
3620 * This is a best effort cleanup to use in tear downs etc.
3622 * It will not fail if the data has already been removed (some tests may do
3623 * their own cleanup).
3625 protected function cleanUpSetUpIDs() {
3626 foreach ($this->setupIDs
as $entity => $id) {
3628 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3630 catch (CiviCRM_API3_Exception
$e) {
3631 // This is a best-effort cleanup function, ignore.
3637 * Create Financial Type.
3639 * @param array $params
3643 protected function createFinancialType($params = array()) {
3644 $params = array_merge($params,
3646 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3650 return $this->callAPISuccess('FinancialType', 'create', $params);
3654 * Enable Tax and Invoicing
3656 protected function enableTaxAndInvoicing($params = array()) {
3657 // Enable component contribute setting
3658 $contributeSetting = array_merge($params,
3661 'invoice_prefix' => 'INV_',
3662 'credit_notes_prefix' => 'CN_',
3664 'due_date_period' => 'days',
3666 'is_email_pdf' => 1,
3667 'tax_term' => 'Sales Tax',
3668 'tax_display_settings' => 'Inclusive',
3671 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3675 * Add Sales Tax relation for financial type with financial account.
3677 * @param int $financialTypeId
3681 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3683 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3684 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3685 'is_deductible' => 1,
3690 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3691 $entityParams = array(
3692 'entity_table' => 'civicrm_financial_type',
3693 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3694 'entity_id' => $financialTypeId,
3695 'financial_account_id' => $account->id
,
3697 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3701 * Create price set with contribution test for test setup.
3703 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3704 * on parent class at some point (fn is not in 4.4).
3707 * @param array $params
3709 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3710 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3711 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3712 'title' => "Test Contribution Page",
3713 'financial_type_id' => 1,
3714 'currency' => 'NZD',
3715 'goal_amount' => 50,
3716 'is_pay_later' => 1,
3717 'is_monetary' => TRUE,
3718 'is_email_receipt' => FALSE,
3720 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3721 'is_quick_config' => 0,
3722 'extends' => 'CiviMember',
3723 'financial_type_id' => 1,
3724 'title' => 'my Page',
3726 $priceSetID = $priceSet['id'];
3728 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3729 $priceField = $this->callAPISuccess('price_field', 'create', array(
3730 'price_set_id' => $priceSetID,
3731 'label' => 'Goat Breed',
3732 'html_type' => 'Radio',
3734 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3735 'price_set_id' => $priceSetID,
3736 'price_field_id' => $priceField['id'],
3737 'label' => 'Long Haired Goat',
3739 'financial_type_id' => 'Donation',
3740 'membership_type_id' => $membershipTypeID,
3741 'membership_num_terms' => 1,
3744 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3745 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3746 'price_set_id' => $priceSetID,
3747 'price_field_id' => $priceField['id'],
3748 'label' => 'Shoe-eating Goat',
3750 'financial_type_id' => 'Donation',
3751 'membership_type_id' => $membershipTypeID,
3752 'membership_num_terms' => 2,
3755 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3757 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3758 'price_set_id' => $priceSetID,
3759 'price_field_id' => $priceField['id'],
3760 'label' => 'Shoe-eating Goat',
3762 'financial_type_id' => 'Donation',
3765 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3767 $this->_ids
['price_set'] = $priceSetID;
3768 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3769 $this->_ids
['price_field'] = array($priceField['id']);
3771 $this->_ids
['membership_type'] = $membershipTypeID;