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 * Does the current setup support ONLY_FULL_GROUP_BY mode
70 protected $_supportFullGroupBy;
73 * Database connection.
75 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
84 static protected $_dbName;
87 * Track tables we have modified during a test.
89 protected $_tablesToTruncate = array();
92 * @var array of temporary directory names
97 * @var boolean populateOnce allows to skip db resets in setUp
99 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
100 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
103 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
105 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
107 public static $populateOnce = FALSE;
110 * @var boolean DBResetRequired allows skipping DB reset
111 * in specific test case. If you still need
112 * to reset single test (method) of such case, call
113 * $this->cleanDB() in the first line of this
116 public $DBResetRequired = TRUE;
119 * @var CRM_Core_Transaction|NULL
124 * @var CRM_Utils_Hook_UnitTests hookClass
125 * example of setting a method for a hook
126 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
128 public $hookClass = NULL;
131 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
133 protected $_params = array();
136 * @var CRM_Extension_System
138 protected $origExtensionSystem;
141 * Array of IDs created during test setup routine.
143 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
147 public $setupIDs = array();
152 * Because we are overriding the parent class constructor, we
153 * need to show the same arguments as exist in the constructor of
154 * PHPUnit_Framework_TestCase, since
155 * PHPUnit_Framework_TestSuite::createTest() creates a
156 * ReflectionClass of the Test class and checks the constructor
157 * of that class to decide how to set up the test.
159 * @param string $name
161 * @param string $dataName
163 public function __construct($name = NULL, array$data = array(), $dataName = '') {
164 parent
::__construct($name, $data, $dataName);
166 // we need full error reporting
167 error_reporting(E_ALL
& ~E_NOTICE
);
169 self
::$_dbName = self
::getDBName();
171 // also load the class loader
172 require_once 'CRM/Core/ClassLoader.php';
173 CRM_Core_ClassLoader
::singleton()->register();
174 if (function_exists('_civix_phpunit_setUp')) {
175 // FIXME: loosen coupling
176 _civix_phpunit_setUp();
181 * Override to run the test and assert its state.
184 * @throws \PHPUnit_Framework_IncompleteTest
185 * @throws \PHPUnit_Framework_SkippedTest
187 protected function runTest() {
189 return parent
::runTest();
191 catch (PEAR_Exception
$e) {
192 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
193 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
200 public function requireDBReset() {
201 return $this->DBResetRequired
;
207 public static function getDBName() {
208 static $dbName = NULL;
209 if ($dbName === NULL) {
210 require_once "DB.php";
211 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
212 $dbName = $dsninfo['database'];
218 * Create database connection for this instance.
220 * Initialize the test database if it hasn't been initialized
222 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
224 protected function getConnection() {
225 $dbName = self
::$_dbName;
226 if (!self
::$dbInit) {
227 $dbName = self
::getDBName();
229 // install test database
230 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
232 static::_populateDB(FALSE, $this);
234 self
::$dbInit = TRUE;
237 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
241 * Required implementation of abstract method.
243 protected function getDataSet() {
247 * @param bool $perClass
248 * @param null $object
250 * TRUE if the populate logic runs; FALSE if it is skipped
252 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
253 if (CIVICRM_UF
!== 'UnitTests') {
254 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
257 if ($perClass ||
$object == NULL) {
261 $dbreset = $object->requireDBReset();
264 if (self
::$populateOnce ||
!$dbreset) {
267 self
::$populateOnce = NULL;
269 Civi\Test
::data()->populate();
274 public static function setUpBeforeClass() {
275 static::_populateDB(TRUE);
277 // also set this global hack
278 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
282 * Common setup functions for all unit tests.
284 protected function setUp() {
285 $session = CRM_Core_Session
::singleton();
286 $session->set('userID', NULL);
288 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
289 // Use a temporary file for STDIN
290 $GLOBALS['stdin'] = tmpfile();
291 if ($GLOBALS['stdin'] === FALSE) {
292 echo "Couldn't open temporary file\n";
296 // Get and save a connection to the database
297 $this->_dbconn
= $this->getConnection();
299 $this->_supportFullGroupBy
= CRM_Utils_SQL
::supportsFullGroupBy();
301 // reload database before each test
302 // $this->_populateDB();
304 // "initialize" CiviCRM to avoid problems when running single tests
305 // FIXME: look at it closer in second stage
307 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
308 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
310 // disable any left-over test extensions
311 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
313 // reset all the caches
314 CRM_Utils_System
::flushCache();
316 // initialize the object once db is loaded
318 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
320 // when running unit tests, use mockup user framework
321 $this->hookClass
= CRM_Utils_Hook
::singleton();
323 // Make sure the DB connection is setup properly
324 $config->userSystem
->setMySQLTimeZone();
325 $env = new CRM_Utils_Check_Component_Env();
326 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
328 // clear permissions stub to not check permissions
329 $config->userPermissionClass
->permissions
= NULL;
331 //flush component settings
332 CRM_Core_Component
::getEnabledComponents(TRUE);
334 error_reporting(E_ALL
);
336 $this->_sethtmlGlobals();
340 * Read everything from the datasets directory and insert into the db.
342 public function loadAllFixtures() {
343 $fixturesDir = __DIR__
. '/../../fixtures';
345 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
347 $xmlFiles = glob($fixturesDir . '/*.xml');
348 foreach ($xmlFiles as $xmlFixture) {
349 $op = new PHPUnit_Extensions_Database_Operation_Insert();
350 $dataset = $this->createXMLDataSet($xmlFixture);
351 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
352 $op->execute($this->_dbconn
, $dataset);
355 $yamlFiles = glob($fixturesDir . '/*.yaml');
356 foreach ($yamlFiles as $yamlFixture) {
357 $op = new PHPUnit_Extensions_Database_Operation_Insert();
358 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
359 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
360 $op->execute($this->_dbconn
, $dataset);
363 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
367 * Emulate a logged in user since certain functions use that.
368 * value to store a record in the DB (like activity)
372 * Contact ID of the created user.
374 public function createLoggedInUser() {
376 'first_name' => 'Logged In',
377 'last_name' => 'User ' . rand(),
378 'contact_type' => 'Individual',
380 $contactID = $this->individualCreate($params);
381 $this->callAPISuccess('UFMatch', 'create', array(
382 'contact_id' => $contactID,
383 'uf_name' => 'superman',
387 $session = CRM_Core_Session
::singleton();
388 $session->set('userID', $contactID);
393 * Create default domain contacts for the two domains added during test class.
394 * database population.
396 public function createDomainContacts() {
397 $this->organizationCreate();
398 $this->organizationCreate(array('organization_name' => 'Second Domain'));
402 * Common teardown functions for all unit tests.
404 protected function tearDown() {
405 error_reporting(E_ALL
& ~E_NOTICE
);
406 CRM_Utils_Hook
::singleton()->reset();
407 $this->hookClass
->reset();
408 $session = CRM_Core_Session
::singleton();
409 $session->set('userID', NULL);
412 $this->tx
->rollback()->commit();
415 CRM_Core_Transaction
::forceRollbackIfEnabled();
416 \Civi\Core\Transaction\Manager
::singleton(TRUE);
419 CRM_Core_Transaction
::forceRollbackIfEnabled();
420 \Civi\Core\Transaction\Manager
::singleton(TRUE);
422 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
423 $this->quickCleanup($tablesToTruncate);
424 $this->createDomainContacts();
427 $this->cleanTempDirs();
428 $this->unsetExtensionSystem();
432 * Generic function to compare expected values after an api call to retrieved.
435 * @daoName string DAO Name of object we're evaluating.
436 * @id int Id of object
437 * @match array Associative array of field name => expected value. Empty if asserting
438 * that a DELETE occurred
439 * @delete boolean True if we're checking that a DELETE action occurred.
443 * @param bool $delete
444 * @throws \PHPUnit_Framework_AssertionFailedError
446 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
448 // adding this here since developers forget to check for an id
449 // and hence we get the first value in the db
450 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
453 $object = new $daoName();
457 // If we're asserting successful record deletion, make sure object is NOT found.
459 if ($object->find(TRUE)) {
460 $this->fail("Object not deleted by delete operation: $daoName, $id");
465 // Otherwise check matches of DAO field values against expected values in $match.
466 if ($object->find(TRUE)) {
467 $fields = &$object->fields();
468 foreach ($fields as $name => $value) {
469 $dbName = $value['name'];
470 if (isset($match[$name])) {
472 $this->assertEquals($object->$dbName, $match[$name]);
474 elseif (isset($match[$dbName])) {
476 $this->assertEquals($object->$dbName, $match[$dbName]);
481 $this->fail("Could not retrieve object: $daoName, $id");
484 $matchSize = count($match);
485 if ($verifiedCount != $matchSize) {
486 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
491 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
492 * @param string $daoName
493 * @param $searchValue
494 * @param $returnColumn
495 * @param $searchColumn
498 * @return null|string
499 * @throws PHPUnit_Framework_AssertionFailedError
501 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
502 if (empty($searchValue)) {
503 $this->fail("empty value passed to assertDBNotNull");
505 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
506 $this->assertNotNull($value, $message);
512 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
513 * @param string $daoName
514 * @param $searchValue
515 * @param $returnColumn
516 * @param $searchColumn
519 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
520 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
521 $this->assertNull($value, $message);
525 * Request a record from the DB by id. Success if row not found.
526 * @param string $daoName
528 * @param null $message
530 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
531 $message = $message ?
$message : "$daoName (#$id) should not exist";
532 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
533 $this->assertNull($value, $message);
537 * Request a record from the DB by id. Success if row not found.
538 * @param string $daoName
540 * @param null $message
542 public function assertDBRowExist($daoName, $id, $message = NULL) {
543 $message = $message ?
$message : "$daoName (#$id) should exist";
544 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
545 $this->assertEquals($id, $value, $message);
549 * Compare a single column value in a retrieved DB record to an expected value.
550 * @param string $daoName
551 * @param $searchValue
552 * @param $returnColumn
553 * @param $searchColumn
554 * @param $expectedValue
557 public function assertDBCompareValue(
558 $daoName, $searchValue, $returnColumn, $searchColumn,
559 $expectedValue, $message
561 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
562 $this->assertEquals($value, $expectedValue, $message);
566 * Compare all values in a single retrieved DB record to an array of expected values.
567 * @param string $daoName
568 * @param array $searchParams
569 * @param $expectedValues
571 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
572 //get the values from db
574 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
576 // compare db values with expected values
577 self
::assertAttributesEquals($expectedValues, $dbValues);
581 * Assert that a SQL query returns a given value.
583 * The first argument is an expected value. The remaining arguments are passed
584 * to CRM_Core_DAO::singleValueQuery
586 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
587 * array(1 => array("Whiz", "String")));
590 * @param array $params
591 * @param string $message
593 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
597 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
598 $this->assertEquals($expected, $actual,
599 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
600 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
606 * Assert that two array-trees are exactly equal, notwithstanding
607 * the sorting of keys
609 * @param array $expected
610 * @param array $actual
612 public function assertTreeEquals($expected, $actual) {
615 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
616 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
620 $this->assertEquals($e, $a);
624 * Assert that two numbers are approximately equal.
626 * @param int|float $expected
627 * @param int|float $actual
628 * @param int|float $tolerance
629 * @param string $message
631 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
632 if ($message === NULL) {
633 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
635 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
639 * Assert attributes are equal.
641 * @param $expectedValues
642 * @param $actualValues
643 * @param string $message
645 * @throws PHPUnit_Framework_AssertionFailedError
647 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
648 foreach ($expectedValues as $paramName => $paramValue) {
649 if (isset($actualValues[$paramName])) {
650 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
653 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
662 public function assertArrayKeyExists($key, &$list) {
663 $result = isset($list[$key]) ?
TRUE : FALSE;
664 $this->assertTrue($result, ts("%1 element exists?",
673 public function assertArrayValueNotNull($key, &$list) {
674 $this->assertArrayKeyExists($key, $list);
676 $value = isset($list[$key]) ?
$list[$key] : NULL;
677 $this->assertTrue($value,
678 ts("%1 element not null?",
685 * Check that api returned 'is_error' => 0.
687 * @param array $apiResult
689 * @param string $prefix
690 * Extra test to add to message.
692 public function assertAPISuccess($apiResult, $prefix = '') {
693 if (!empty($prefix)) {
696 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
698 if (!empty($apiResult['debug_information'])) {
699 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
701 if (!empty($apiResult['trace'])) {
702 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
704 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
708 * Check that api returned 'is_error' => 1.
710 * @param array $apiResult
712 * @param string $prefix
713 * Extra test to add to message.
714 * @param null $expectedError
716 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
717 if (!empty($prefix)) {
720 if ($expectedError && !empty($apiResult['is_error'])) {
721 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
723 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
724 $this->assertNotEmpty($apiResult['error_message']);
730 * @param string $message
732 public function assertType($expected, $actual, $message = '') {
733 return $this->assertInternalType($expected, $actual, $message);
737 * Check that a deleted item has been deleted.
742 public function assertAPIDeleted($entity, $id) {
743 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
748 * Check that api returned 'is_error' => 1
749 * else provide full message
750 * @param array $result
752 * @param array $valuesToExclude
753 * @param string $prefix
754 * Extra test to add to message.
756 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
757 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
758 foreach ($valuesToExclude as $value) {
759 if (isset($result[$value])) {
760 unset($result[$value]);
762 if (isset($expected[$value])) {
763 unset($expected[$value]);
766 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
770 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
774 * @param array $params
777 public function civicrm_api($entity, $action, $params) {
778 return civicrm_api($entity, $action, $params);
782 * Create a batch of external API calls which can
783 * be executed concurrently.
786 * $calls = $this->createExternalAPI()
787 * ->addCall('Contact', 'get', ...)
788 * ->addCall('Contact', 'get', ...)
794 * @return \Civi\API\ExternalBatch
795 * @throws PHPUnit_Framework_SkippedTestError
797 public function createExternalAPI() {
798 global $civicrm_root;
799 $defaultParams = array(
800 'version' => $this->_apiversion
,
804 $calls = new \Civi\API\
ExternalBatch($defaultParams);
806 if (!$calls->isSupported()) {
807 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
814 * wrap api functions.
815 * so we can ensure they succeed & throw exceptions without litterering the test with checks
817 * @param string $entity
818 * @param string $action
819 * @param array $params
820 * @param mixed $checkAgainst
821 * Optional value to check result against, implemented for getvalue,.
822 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
823 * for getsingle the array is compared against an array passed in - the id is not compared (for
828 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
829 $params = array_merge(array(
830 'version' => $this->_apiversion
,
835 switch (strtolower($action)) {
837 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
840 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
843 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
845 $result = $this->civicrm_api($entity, $action, $params);
846 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
851 * This function exists to wrap api getValue function & check the result
852 * so we can ensure they succeed & throw exceptions without litterering the test with checks
853 * There is a type check in this
855 * @param string $entity
856 * @param array $params
857 * @param string $type
858 * Per http://php.net/manual/en/function.gettype.php possible types.
868 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
870 'version' => $this->_apiversion
,
873 $result = $this->civicrm_api($entity, 'getvalue', $params);
875 if ($type == 'integer') {
876 // api seems to return integers as strings
877 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
880 $this->assertType($type, $result, "returned result should have been of type $type but was ");
887 * This function exists to wrap api getsingle function & check the result
888 * so we can ensure they succeed & throw exceptions without litterering the test with checks
890 * @param string $entity
891 * @param array $params
892 * @param array $checkAgainst
893 * Array to compare result against.
904 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
906 'version' => $this->_apiversion
,
908 $result = $this->civicrm_api($entity, 'getsingle', $params);
909 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
910 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
913 // @todo - have gone with the fn that unsets id? should we check id?
914 $this->checkArrayEquals($result, $checkAgainst);
920 * This function exists to wrap api getValue function & check the result
921 * so we can ensure they succeed & throw exceptions without litterering the test with checks
922 * There is a type check in this
923 * @param string $entity
924 * @param array $params
929 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
931 'version' => $this->_apiversion
,
934 $result = $this->civicrm_api($entity, 'getcount', $params);
935 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
936 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
938 if (is_int($count)) {
939 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
945 * This function exists to wrap api functions.
946 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
948 * @param string $entity
949 * @param string $action
950 * @param array $params
951 * @param string $function
952 * Pass this in to create a generated example.
953 * @param string $file
954 * Pass this in to create a generated example.
955 * @param string $description
956 * @param string|null $exampleName
960 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
961 $params['version'] = $this->_apiversion
;
962 $result = $this->callAPISuccess($entity, $action, $params);
963 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
968 * This function exists to wrap api functions.
969 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
970 * @param string $entity
971 * @param string $action
972 * @param array $params
973 * @param string $expectedErrorMessage
975 * @param null $extraOutput
978 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
979 if (is_array($params)) {
981 'version' => $this->_apiversion
,
984 $result = $this->civicrm_api($entity, $action, $params);
985 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
990 * Create required data based on $this->entity & $this->params
991 * This is just a way to set up the test data for delete & get functions
992 * so the distinction between set
993 * up & tested functions is clearer
998 public function createTestEntity() {
999 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1003 * Generic function to create Organisation, to be used in test cases
1005 * @param array $params
1006 * parameters for civicrm_contact_add api function call
1008 * sequence number if creating multiple organizations
1011 * id of Organisation created
1013 public function organizationCreate($params = array(), $seq = 0) {
1017 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1018 return $this->_contactCreate($params);
1022 * Generic function to create Individual, to be used in test cases
1024 * @param array $params
1025 * parameters for civicrm_contact_add api function call
1027 * sequence number if creating multiple individuals
1030 * id of Individual created
1032 public function individualCreate($params = array(), $seq = 0) {
1033 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1034 return $this->_contactCreate($params);
1038 * Generic function to create Household, to be used in test cases
1040 * @param array $params
1041 * parameters for civicrm_contact_add api function call
1043 * sequence number if creating multiple households
1046 * id of Household created
1048 public function householdCreate($params = array(), $seq = 0) {
1049 $params = array_merge($this->sampleContact('Household', $seq), $params);
1050 return $this->_contactCreate($params);
1054 * Helper function for getting sample contact properties.
1056 * @param string $contact_type
1057 * enum contact type: Individual, Organization
1059 * sequence number for the values of this type
1062 * properties of sample contact (ie. $params for API call)
1064 public function sampleContact($contact_type, $seq = 0) {
1066 'Individual' => array(
1067 // The number of values in each list need to be coprime numbers to not have duplicates
1068 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1069 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1070 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1072 'Organization' => array(
1073 'organization_name' => array(
1074 'Unit Test Organization',
1081 'Household' => array(
1082 'household_name' => array('Unit Test household'),
1085 $params = array('contact_type' => $contact_type);
1086 foreach ($samples[$contact_type] as $key => $values) {
1087 $params[$key] = $values[$seq %
count($values)];
1089 if ($contact_type == 'Individual') {
1090 $params['email'] = strtolower(
1091 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1093 $params['prefix_id'] = 3;
1094 $params['suffix_id'] = 3;
1100 * Private helper function for calling civicrm_contact_add.
1102 * @param array $params
1103 * For civicrm_contact_add api function call.
1108 * id of Household created
1110 private function _contactCreate($params) {
1111 $result = $this->callAPISuccess('contact', 'create', $params);
1112 if (!empty($result['is_error']) ||
empty($result['id'])) {
1113 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1115 return $result['id'];
1119 * Delete contact, ensuring it is not the domain contact
1121 * @param int $contactID
1122 * Contact ID to delete
1124 public function contactDelete($contactID) {
1125 $domain = new CRM_Core_BAO_Domain();
1126 $domain->contact_id
= $contactID;
1127 if (!$domain->find(TRUE)) {
1128 $this->callAPISuccess('contact', 'delete', array(
1130 'skip_undelete' => 1,
1136 * @param int $contactTypeId
1140 public function contactTypeDelete($contactTypeId) {
1141 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1143 throw new Exception('Could not delete contact type');
1148 * @param array $params
1152 public function membershipTypeCreate($params = array()) {
1153 CRM_Member_PseudoConstant
::flush('membershipType');
1154 CRM_Core_Config
::clearDBCache();
1155 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
1156 $params = array_merge(array(
1157 'name' => 'General',
1158 'duration_unit' => 'year',
1159 'duration_interval' => 1,
1160 'period_type' => 'rolling',
1161 'member_of_contact_id' => $memberOfOrganization,
1163 'financial_type_id' => 2,
1166 'visibility' => 'Public',
1169 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1171 CRM_Member_PseudoConstant
::flush('membershipType');
1172 CRM_Utils_Cache
::singleton()->flush();
1174 return $result['id'];
1178 * @param array $params
1182 public function contactMembershipCreate($params) {
1183 $params = array_merge(array(
1184 'join_date' => '2007-01-21',
1185 'start_date' => '2007-01-21',
1186 'end_date' => '2007-12-21',
1187 'source' => 'Payment',
1188 'membership_type_id' => 'General',
1190 if (!is_numeric($params['membership_type_id'])) {
1191 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
1192 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
1193 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
1197 $result = $this->callAPISuccess('Membership', 'create', $params);
1198 return $result['id'];
1202 * Delete Membership Type.
1204 * @param array $params
1206 public function membershipTypeDelete($params) {
1207 $this->callAPISuccess('MembershipType', 'Delete', $params);
1211 * @param int $membershipID
1213 public function membershipDelete($membershipID) {
1214 $deleteParams = array('id' => $membershipID);
1215 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1219 * @param string $name
1223 public function membershipStatusCreate($name = 'test member status') {
1224 $params['name'] = $name;
1225 $params['start_event'] = 'start_date';
1226 $params['end_event'] = 'end_date';
1227 $params['is_current_member'] = 1;
1228 $params['is_active'] = 1;
1230 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1231 CRM_Member_PseudoConstant
::flush('membershipStatus');
1232 return $result['id'];
1236 * @param int $membershipStatusID
1238 public function membershipStatusDelete($membershipStatusID) {
1239 if (!$membershipStatusID) {
1242 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1246 * @param array $params
1250 public function relationshipTypeCreate($params = array()) {
1251 $params = array_merge(array(
1252 'name_a_b' => 'Relation 1 for relationship type create',
1253 'name_b_a' => 'Relation 2 for relationship type create',
1254 'contact_type_a' => 'Individual',
1255 'contact_type_b' => 'Organization',
1262 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1263 CRM_Core_PseudoConstant
::flush('relationshipType');
1265 return $result['id'];
1269 * Delete Relatinship Type.
1271 * @param int $relationshipTypeID
1273 public function relationshipTypeDelete($relationshipTypeID) {
1274 $params['id'] = $relationshipTypeID;
1275 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1276 if (!empty($check['count'])) {
1277 $this->callAPISuccess('relationship_type', 'delete', $params);
1282 * @param array $params
1286 public function paymentProcessorTypeCreate($params = NULL) {
1287 if (is_null($params)) {
1289 'name' => 'API_Test_PP',
1290 'title' => 'API Test Payment Processor',
1291 'class_name' => 'CRM_Core_Payment_APITest',
1292 'billing_mode' => 'form',
1298 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1300 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1302 return $result['id'];
1306 * Create test Authorize.net instance.
1308 * @param array $params
1312 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1313 $params = array_merge(array(
1314 'name' => 'Authorize',
1315 'domain_id' => CRM_Core_Config
::domainID(),
1316 'payment_processor_type_id' => 'AuthNet',
1317 'title' => 'AuthNet',
1322 'user_name' => '4y5BfuW7jm',
1323 'password' => '4cAmW927n8uLf5J8',
1324 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1325 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1326 'class_name' => 'Payment_AuthorizeNet',
1327 'billing_mode' => 1,
1330 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1331 return $result['id'];
1335 * Create Participant.
1337 * @param array $params
1338 * Array of contact id and event id values.
1341 * $id of participant created
1343 public function participantCreate($params) {
1344 if (empty($params['contact_id'])) {
1345 $params['contact_id'] = $this->individualCreate();
1347 if (empty($params['event_id'])) {
1348 $event = $this->eventCreate();
1349 $params['event_id'] = $event['id'];
1354 'register_date' => 20070219,
1355 'source' => 'Wimbeldon',
1356 'event_level' => 'Payment',
1360 $params = array_merge($defaults, $params);
1361 $result = $this->callAPISuccess('Participant', 'create', $params);
1362 return $result['id'];
1366 * Create Payment Processor.
1369 * Id Payment Processor
1371 public function processorCreate($params = array()) {
1372 $processorParams = array(
1375 'payment_processor_type_id' => 'Dummy',
1376 'financial_account_id' => 12,
1380 'url_site' => 'http://dummy.com',
1381 'url_recur' => 'http://dummy.com',
1382 'billing_mode' => 1,
1384 'payment_instrument_id' => 'Debit Card',
1386 $processorParams = array_merge($processorParams, $params);
1387 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1388 return $processor['id'];
1392 * Create Payment Processor.
1394 * @param array $processorParams
1396 * @return \CRM_Core_Payment_Dummy
1397 * Instance of Dummy Payment Processor
1399 public function dummyProcessorCreate($processorParams = array()) {
1400 $paymentProcessorID = $this->processorCreate($processorParams);
1401 return System
::singleton()->getById($paymentProcessorID);
1405 * Create contribution page.
1407 * @param array $params
1409 * Array of contribution page
1411 public function contributionPageCreate($params = array()) {
1412 $this->_pageParams
= array_merge(array(
1413 'title' => 'Test Contribution Page',
1414 'financial_type_id' => 1,
1415 'currency' => 'USD',
1416 'financial_account_id' => 1,
1418 'is_allow_other_amount' => 1,
1420 'max_amount' => 1000,
1422 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1426 * Create a sample batch.
1428 public function batchCreate() {
1429 $params = $this->_params
;
1430 $params['name'] = $params['title'] = 'Batch_433397';
1431 $params['status_id'] = 1;
1432 $result = $this->callAPISuccess('batch', 'create', $params);
1433 return $result['id'];
1439 * @param array $params
1441 * result of created tag
1443 public function tagCreate($params = array()) {
1445 'name' => 'New Tag3',
1446 'description' => 'This is description for Our New Tag ',
1449 $params = array_merge($defaults, $params);
1450 $result = $this->callAPISuccess('Tag', 'create', $params);
1451 return $result['values'][$result['id']];
1458 * Id of the tag to be deleted.
1462 public function tagDelete($tagId) {
1463 require_once 'api/api.php';
1467 $result = $this->callAPISuccess('Tag', 'delete', $params);
1468 return $result['id'];
1472 * Add entity(s) to the tag
1474 * @param array $params
1478 public function entityTagAdd($params) {
1479 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1486 * @param array $params
1490 * id of created pledge
1492 public function pledgeCreate($params) {
1493 $params = array_merge(array(
1494 'pledge_create_date' => date('Ymd'),
1495 'start_date' => date('Ymd'),
1496 'scheduled_date' => date('Ymd'),
1498 'pledge_status_id' => '2',
1499 'financial_type_id' => '1',
1500 'pledge_original_installment_amount' => 20,
1501 'frequency_interval' => 5,
1502 'frequency_unit' => 'year',
1503 'frequency_day' => 15,
1504 'installments' => 5,
1508 $result = $this->callAPISuccess('Pledge', 'create', $params);
1509 return $result['id'];
1513 * Delete contribution.
1515 * @param int $pledgeId
1517 public function pledgeDelete($pledgeId) {
1519 'pledge_id' => $pledgeId,
1521 $this->callAPISuccess('Pledge', 'delete', $params);
1525 * Create contribution.
1527 * @param array $params
1528 * Array of parameters.
1531 * id of created contribution
1533 public function contributionCreate($params) {
1535 $params = array_merge(array(
1537 'receive_date' => date('Ymd'),
1538 'total_amount' => 100.00,
1539 'fee_amount' => 5.00,
1540 'financial_type_id' => 1,
1541 'payment_instrument_id' => 1,
1542 'non_deductible_amount' => 10.00,
1544 'invoice_id' => 67890,
1546 'contribution_status_id' => 1,
1549 $result = $this->callAPISuccess('contribution', 'create', $params);
1550 return $result['id'];
1554 * Delete contribution.
1556 * @param int $contributionId
1560 public function contributionDelete($contributionId) {
1562 'contribution_id' => $contributionId,
1564 $result = $this->callAPISuccess('contribution', 'delete', $params);
1571 * @param array $params
1572 * Name-value pair for an event.
1576 public function eventCreate($params = array()) {
1577 // if no contact was passed, make up a dummy event creator
1578 if (!isset($params['contact_id'])) {
1579 $params['contact_id'] = $this->_contactCreate(array(
1580 'contact_type' => 'Individual',
1581 'first_name' => 'Event',
1582 'last_name' => 'Creator',
1586 // set defaults for missing params
1587 $params = array_merge(array(
1588 'title' => 'Annual CiviCRM meet',
1589 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1590 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1591 'event_type_id' => 1,
1593 'start_date' => 20081021,
1594 'end_date' => 20081023,
1595 'is_online_registration' => 1,
1596 'registration_start_date' => 20080601,
1597 'registration_end_date' => 20081015,
1598 'max_participants' => 100,
1599 'event_full_text' => 'Sorry! We are already full',
1602 'is_show_location' => 0,
1605 return $this->callAPISuccess('Event', 'create', $params);
1616 public function eventDelete($id) {
1620 return $this->callAPISuccess('event', 'delete', $params);
1624 * Delete participant.
1626 * @param int $participantID
1630 public function participantDelete($participantID) {
1632 'id' => $participantID,
1634 $check = $this->callAPISuccess('Participant', 'get', $params);
1635 if ($check['count'] > 0) {
1636 return $this->callAPISuccess('Participant', 'delete', $params);
1641 * Create participant payment.
1643 * @param int $participantID
1644 * @param int $contributionID
1646 * $id of created payment
1648 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1649 //Create Participant Payment record With Values
1651 'participant_id' => $participantID,
1652 'contribution_id' => $contributionID,
1655 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1656 return $result['id'];
1660 * Delete participant payment.
1662 * @param int $paymentID
1664 public function participantPaymentDelete($paymentID) {
1668 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1674 * @param int $contactID
1676 * location id of created location
1678 public function locationAdd($contactID) {
1681 'location_type' => 'New Location Type',
1683 'name' => 'Saint Helier St',
1684 'county' => 'Marin',
1685 'country' => 'UNITED STATES',
1686 'state_province' => 'Michigan',
1687 'supplemental_address_1' => 'Hallmark Ct',
1688 'supplemental_address_2' => 'Jersey Village',
1689 'supplemental_address_3' => 'My Town',
1694 'contact_id' => $contactID,
1695 'address' => $address,
1696 'location_format' => '2.0',
1697 'location_type' => 'New Location Type',
1700 $result = $this->callAPISuccess('Location', 'create', $params);
1705 * Delete Locations of contact.
1707 * @param array $params
1710 public function locationDelete($params) {
1711 $this->callAPISuccess('Location', 'delete', $params);
1715 * Add a Location Type.
1717 * @param array $params
1718 * @return CRM_Core_DAO_LocationType
1719 * location id of created location
1721 public function locationTypeCreate($params = NULL) {
1722 if ($params === NULL) {
1724 'name' => 'New Location Type',
1725 'vcard_name' => 'New Location Type',
1726 'description' => 'Location Type for Delete',
1731 $locationType = new CRM_Core_DAO_LocationType();
1732 $locationType->copyValues($params);
1733 $locationType->save();
1734 // clear getfields cache
1735 CRM_Core_PseudoConstant
::flush();
1736 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1737 return $locationType;
1741 * Delete a Location Type.
1743 * @param int $locationTypeId
1745 public function locationTypeDelete($locationTypeId) {
1746 $locationType = new CRM_Core_DAO_LocationType();
1747 $locationType->id
= $locationTypeId;
1748 $locationType->delete();
1754 * @param array $params
1755 * @return CRM_Core_DAO_Mapping
1756 * Mapping id of created mapping
1758 public function mappingCreate($params = NULL) {
1759 if ($params === NULL) {
1761 'name' => 'Mapping name',
1762 'description' => 'Mapping description',
1763 // 'Export Contact' mapping.
1764 'mapping_type_id' => 7,
1768 $mapping = new CRM_Core_DAO_Mapping();
1769 $mapping->copyValues($params);
1771 // clear getfields cache
1772 CRM_Core_PseudoConstant
::flush();
1773 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1780 * @param int $mappingId
1782 public function mappingDelete($mappingId) {
1783 $mapping = new CRM_Core_DAO_Mapping();
1784 $mapping->id
= $mappingId;
1791 * @param array $params
1793 * groupId of created group
1795 public function groupCreate($params = array()) {
1796 $params = array_merge(array(
1797 'name' => 'Test Group 1',
1799 'title' => 'New Test Group Created',
1800 'description' => 'New Test Group Created',
1802 'visibility' => 'Public Pages',
1803 'group_type' => array(
1809 $result = $this->callAPISuccess('Group', 'create', $params);
1810 return $result['id'];
1814 * Prepare class for ACLs.
1816 protected function prepareForACLs() {
1817 $config = CRM_Core_Config
::singleton();
1818 $config->userPermissionClass
->permissions
= array();
1824 protected function cleanUpAfterACLs() {
1825 CRM_Utils_Hook
::singleton()->reset();
1826 $tablesToTruncate = array(
1828 'civicrm_acl_cache',
1829 'civicrm_acl_entity_role',
1830 'civicrm_acl_contact_cache',
1832 $this->quickCleanup($tablesToTruncate);
1833 $config = CRM_Core_Config
::singleton();
1834 unset($config->userPermissionClass
->permissions
);
1837 * Create a smart group.
1839 * By default it will be a group of households.
1841 * @param array $smartGroupParams
1842 * @param array $groupParams
1845 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1846 $smartGroupParams = array_merge(array(
1847 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1850 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1852 $groupParams['saved_search_id'] = $savedSearch->id
;
1853 return $this->groupCreate($groupParams);
1857 * Function to add a Group.
1859 * @params array to add group
1861 * @param int $groupID
1862 * @param int $totalCount
1864 * groupId of created group
1866 public function groupContactCreate($groupID, $totalCount = 10) {
1867 $params = array('group_id' => $groupID);
1868 for ($i = 1; $i <= $totalCount; $i++
) {
1869 $contactID = $this->individualCreate();
1871 $params +
= array('contact_id' => $contactID);
1874 $params +
= array("contact_id.$i" => $contactID);
1877 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1887 public function groupDelete($gid) {
1893 $this->callAPISuccess('Group', 'delete', $params);
1898 * @param array $params
1900 public function uFFieldCreate($params = array()) {
1901 $params = array_merge(array(
1903 'field_name' => 'first_name',
1906 'visibility' => 'Public Pages and Listings',
1907 'is_searchable' => '1',
1908 'label' => 'first_name',
1909 'field_type' => 'Individual',
1912 $this->callAPISuccess('uf_field', 'create', $params);
1916 * Add a UF Join Entry.
1918 * @param array $params
1920 * $id of created UF Join
1922 public function ufjoinCreate($params = NULL) {
1923 if ($params === NULL) {
1926 'module' => 'CiviEvent',
1927 'entity_table' => 'civicrm_event',
1933 $result = $this->callAPISuccess('uf_join', 'create', $params);
1938 * Delete a UF Join Entry.
1940 * @param array $params
1941 * with missing uf_group_id
1943 public function ufjoinDelete($params = NULL) {
1944 if ($params === NULL) {
1947 'module' => 'CiviEvent',
1948 'entity_table' => 'civicrm_event',
1951 'uf_group_id' => '',
1955 crm_add_uf_join($params);
1959 * @param array $params
1960 * Optional parameters.
1961 * @param bool $reloadConfig
1962 * While enabling CiviCampaign component, we shouldn't always forcibly
1963 * reload config as this hinder hook call in test environment
1968 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1969 $this->enableCiviCampaign($reloadConfig);
1970 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1971 'name' => 'big_campaign',
1972 'title' => 'Campaign',
1974 return $campaign['id'];
1978 * Create Group for a contact.
1980 * @param int $contactId
1982 public function contactGroupCreate($contactId) {
1984 'contact_id.1' => $contactId,
1988 $this->callAPISuccess('GroupContact', 'Create', $params);
1992 * Delete Group for a contact.
1994 * @param int $contactId
1996 public function contactGroupDelete($contactId) {
1998 'contact_id.1' => $contactId,
2001 $this->civicrm_api('GroupContact', 'Delete', $params);
2007 * @param array $params
2010 public function activityCreate($params = array()) {
2011 $params = array_merge(array(
2012 'subject' => 'Discussion on warm beer',
2013 'activity_date_time' => date('Ymd'),
2014 'duration_hours' => 30,
2015 'duration_minutes' => 20,
2016 'location' => 'Baker Street',
2017 'details' => 'Lets schedule a meeting',
2019 'activity_name' => 'Meeting',
2021 if (!isset($params['source_contact_id'])) {
2022 $params['source_contact_id'] = $this->individualCreate();
2024 if (!isset($params['target_contact_id'])) {
2025 $params['target_contact_id'] = $this->individualCreate(array(
2026 'first_name' => 'Julia',
2027 'Last_name' => 'Anderson',
2029 'email' => 'julia_anderson@civicrm.org',
2030 'contact_type' => 'Individual',
2033 if (!isset($params['assignee_contact_id'])) {
2034 $params['assignee_contact_id'] = $params['target_contact_id'];
2037 $result = $this->callAPISuccess('Activity', 'create', $params);
2039 $result['target_contact_id'] = $params['target_contact_id'];
2040 $result['assignee_contact_id'] = $params['assignee_contact_id'];
2045 * Create an activity type.
2047 * @param array $params
2051 public function activityTypeCreate($params) {
2052 return $this->callAPISuccess('ActivityType', 'create', $params);
2056 * Delete activity type.
2058 * @param int $activityTypeId
2059 * Id of the activity type.
2062 public function activityTypeDelete($activityTypeId) {
2063 $params['activity_type_id'] = $activityTypeId;
2064 return $this->callAPISuccess('ActivityType', 'delete', $params);
2068 * Create custom group.
2070 * @param array $params
2073 public function customGroupCreate($params = array()) {
2075 'title' => 'new custom group',
2076 'extends' => 'Contact',
2078 'style' => 'Inline',
2082 $params = array_merge($defaults, $params);
2084 if (strlen($params['title']) > 13) {
2085 $params['title'] = substr($params['title'], 0, 13);
2088 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2089 $this->callAPISuccess('custom_group', 'get', array(
2090 'title' => $params['title'],
2091 array('api.custom_group.delete' => 1),
2094 return $this->callAPISuccess('custom_group', 'create', $params);
2098 * Existing function doesn't allow params to be over-ridden so need a new one
2099 * this one allows you to only pass in the params you want to change
2100 * @param array $params
2103 public function CustomGroupCreateByParams($params = array()) {
2105 'title' => "API Custom Group",
2106 'extends' => 'Contact',
2108 'style' => 'Inline',
2111 $params = array_merge($defaults, $params);
2112 return $this->callAPISuccess('custom_group', 'create', $params);
2116 * Create custom group with multi fields.
2117 * @param array $params
2120 public function CustomGroupMultipleCreateByParams($params = array()) {
2125 $params = array_merge($defaults, $params);
2126 return $this->CustomGroupCreateByParams($params);
2130 * Create custom group with multi fields.
2131 * @param array $params
2134 public function CustomGroupMultipleCreateWithFields($params = array()) {
2135 // also need to pass on $params['custom_field'] if not set but not in place yet
2137 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2138 $ids['custom_group_id'] = $customGroup['id'];
2140 $customField = $this->customFieldCreate(array(
2141 'custom_group_id' => $ids['custom_group_id'],
2142 'label' => 'field_1' . $ids['custom_group_id'],
2146 $ids['custom_field_id'][] = $customField['id'];
2148 $customField = $this->customFieldCreate(array(
2149 'custom_group_id' => $ids['custom_group_id'],
2150 'default_value' => '',
2151 'label' => 'field_2' . $ids['custom_group_id'],
2154 $ids['custom_field_id'][] = $customField['id'];
2156 $customField = $this->customFieldCreate(array(
2157 'custom_group_id' => $ids['custom_group_id'],
2158 'default_value' => '',
2159 'label' => 'field_3' . $ids['custom_group_id'],
2162 $ids['custom_field_id'][] = $customField['id'];
2168 * Create a custom group with a single text custom field. See
2169 * participant:testCreateWithCustom for how to use this
2171 * @param string $function
2173 * @param string $filename
2177 * ids of created objects
2179 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2180 $params = array('title' => $function);
2181 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2182 $params['extends'] = $entity ?
$entity : 'Contact';
2183 $customGroup = $this->CustomGroupCreate($params);
2184 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2185 CRM_Core_PseudoConstant
::flush();
2187 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2191 * Delete custom group.
2193 * @param int $customGroupID
2197 public function customGroupDelete($customGroupID) {
2198 $params['id'] = $customGroupID;
2199 return $this->callAPISuccess('custom_group', 'delete', $params);
2203 * Create custom field.
2205 * @param array $params
2206 * (custom_group_id) is required.
2209 public function customFieldCreate($params) {
2210 $params = array_merge(array(
2211 'label' => 'Custom Field',
2212 'data_type' => 'String',
2213 'html_type' => 'Text',
2214 'is_searchable' => 1,
2216 'default_value' => 'defaultValue',
2219 $result = $this->callAPISuccess('custom_field', 'create', $params);
2220 // these 2 functions are called with force to flush static caches
2221 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2222 CRM_Core_Component
::getEnabledComponents(1);
2227 * Delete custom field.
2229 * @param int $customFieldID
2233 public function customFieldDelete($customFieldID) {
2235 $params['id'] = $customFieldID;
2236 return $this->callAPISuccess('custom_field', 'delete', $params);
2245 public function noteCreate($cId) {
2247 'entity_table' => 'civicrm_contact',
2248 'entity_id' => $cId,
2249 'note' => 'hello I am testing Note',
2250 'contact_id' => $cId,
2251 'modified_date' => date('Ymd'),
2252 'subject' => 'Test Note',
2255 return $this->callAPISuccess('Note', 'create', $params);
2259 * Enable CiviCampaign Component.
2261 * @param bool $reloadConfig
2262 * Force relaod config or not
2264 public function enableCiviCampaign($reloadConfig = TRUE) {
2265 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2266 if ($reloadConfig) {
2267 // force reload of config object
2268 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2270 //flush cache by calling with reset
2271 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2275 * Create test generated example in api/v3/examples.
2277 * To turn this off (e.g. on the server) set
2278 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2279 * in your settings file
2281 * @param string $entity
2282 * @param string $action
2283 * @param array $params
2284 * Array as passed to civicrm_api function.
2285 * @param array $result
2286 * Array as received from the civicrm_api function.
2287 * @param string $testFunction
2288 * Calling function - generally __FUNCTION__.
2289 * @param string $testFile
2290 * Called from file - generally __FILE__.
2291 * @param string $description
2292 * Descriptive text for the example file.
2293 * @param string $exampleName
2294 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2296 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2297 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2300 $entity = _civicrm_api_get_camel_name($entity);
2301 $action = strtolower($action);
2303 if (empty($exampleName)) {
2304 // Attempt to convert lowercase action name to CamelCase.
2305 // This is clunky/imperfect due to the convention of all lowercase actions.
2306 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2307 $knownPrefixes = array(
2314 foreach ($knownPrefixes as $prefix) {
2315 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2316 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2321 $this->tidyExampleResult($result);
2322 if (isset($params['version'])) {
2323 unset($params['version']);
2325 // Format multiline description as array
2327 if (is_string($description) && strlen($description)) {
2328 foreach (explode("\n", $description) as $line) {
2329 $desc[] = trim($line);
2332 $smarty = CRM_Core_Smarty
::singleton();
2333 $smarty->assign('testFunction', $testFunction);
2334 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2335 foreach ($params as $index => $param) {
2336 if (is_string($param)) {
2337 $params[$index] = addslashes($param);
2340 $smarty->assign('params', $params);
2341 $smarty->assign('entity', $entity);
2342 $smarty->assign('testFile', basename($testFile));
2343 $smarty->assign('description', $desc);
2344 $smarty->assign('result', $result);
2345 $smarty->assign('action', $action);
2347 global $civicrm_root;
2348 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2349 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2350 mkdir($civicrm_root . "/api/v3/examples/$entity");
2352 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2353 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2359 * Tidy up examples array so that fields that change often ..don't
2360 * and debug related fields are unset
2362 * @param array $result
2364 public function tidyExampleResult(&$result) {
2365 if (!is_array($result)) {
2368 $fieldsToChange = array(
2369 'hash' => '67eac7789eaee00',
2370 'modified_date' => '2012-11-14 16:02:35',
2371 'created_date' => '2013-07-28 08:49:19',
2372 'create_date' => '20120130621222105',
2373 'application_received_date' => '20130728084957',
2374 'in_date' => '2013-07-28 08:50:19',
2375 'scheduled_date' => '20130728085413',
2376 'approval_date' => '20130728085413',
2377 'pledge_start_date_high' => '20130726090416',
2378 'start_date' => '2013-07-29 00:00:00',
2379 'event_start_date' => '2013-07-29 00:00:00',
2380 'end_date' => '2013-08-04 00:00:00',
2381 'event_end_date' => '2013-08-04 00:00:00',
2382 'decision_date' => '20130805000000',
2385 $keysToUnset = array('xdebug', 'undefined_fields');
2386 foreach ($keysToUnset as $unwantedKey) {
2387 if (isset($result[$unwantedKey])) {
2388 unset($result[$unwantedKey]);
2391 if (isset($result['values'])) {
2392 if (!is_array($result['values'])) {
2395 $resultArray = &$result['values'];
2397 elseif (is_array($result)) {
2398 $resultArray = &$result;
2404 foreach ($resultArray as $index => &$values) {
2405 if (!is_array($values)) {
2408 foreach ($values as $key => &$value) {
2409 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2410 if (isset($value['is_error'])) {
2411 // we have a std nested result format
2412 $this->tidyExampleResult($value);
2415 foreach ($value as &$nestedResult) {
2416 // this is an alternative syntax for nested results a keyed array of results
2417 $this->tidyExampleResult($nestedResult);
2421 if (in_array($key, $keysToUnset)) {
2422 unset($values[$key]);
2425 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2426 $value = $fieldsToChange[$key];
2428 if (is_string($value)) {
2429 $value = addslashes($value);
2436 * Create custom field with Option Values.
2438 * @param array $customGroup
2439 * @param string $name
2440 * Name of custom field.
2441 * @param array $extraParams
2442 * Additional parameters to pass through.
2446 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2447 $fieldParams = array(
2448 'custom_group_id' => $customGroup['id'],
2449 'name' => 'test_custom_group',
2450 'label' => 'Country',
2451 'html_type' => 'Select',
2452 'data_type' => 'String',
2455 'is_searchable' => 0,
2459 $optionGroup = array(
2461 'name' => 'option_group1',
2462 'label' => 'option_group_label1',
2465 $optionValue = array(
2466 'option_label' => array('Label1', 'Label2'),
2467 'option_value' => array('value1', 'value2'),
2468 'option_name' => array($name . '_1', $name . '_2'),
2469 'option_weight' => array(1, 2),
2470 'option_status' => 1,
2473 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2475 return $this->callAPISuccess('custom_field', 'create', $params);
2483 public function confirmEntitiesDeleted($entities) {
2484 foreach ($entities as $entity) {
2486 $result = $this->callAPISuccess($entity, 'Get', array());
2487 if ($result['error'] == 1 ||
$result['count'] > 0) {
2488 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2496 * Quick clean by emptying tables created for the test.
2498 * @param array $tablesToTruncate
2499 * @param bool $dropCustomValueTables
2500 * @throws \Exception
2502 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2504 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2506 if ($dropCustomValueTables) {
2507 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2508 while ($optionGroupResult->fetch()) {
2509 if (!empty($optionGroupResult->option_group_id
)) {
2510 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2513 $tablesToTruncate[] = 'civicrm_custom_group';
2514 $tablesToTruncate[] = 'civicrm_custom_field';
2517 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2519 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2520 foreach ($tablesToTruncate as $table) {
2521 $sql = "TRUNCATE TABLE $table";
2522 CRM_Core_DAO
::executeQuery($sql);
2524 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2526 if ($dropCustomValueTables) {
2527 $dbName = self
::getDBName();
2529 SELECT TABLE_NAME as tableName
2530 FROM INFORMATION_SCHEMA.TABLES
2531 WHERE TABLE_SCHEMA = '{$dbName}'
2532 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2535 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2536 while ($tableDAO->fetch()) {
2537 $sql = "DROP TABLE {$tableDAO->tableName}";
2538 CRM_Core_DAO
::executeQuery($sql);
2544 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2546 public function quickCleanUpFinancialEntities() {
2547 $tablesToTruncate = array(
2549 'civicrm_activity_contact',
2550 'civicrm_contribution',
2551 'civicrm_contribution_soft',
2552 'civicrm_contribution_product',
2553 'civicrm_financial_trxn',
2554 'civicrm_financial_item',
2555 'civicrm_contribution_recur',
2556 'civicrm_line_item',
2557 'civicrm_contribution_page',
2558 'civicrm_payment_processor',
2559 'civicrm_entity_financial_trxn',
2560 'civicrm_membership',
2561 'civicrm_membership_type',
2562 'civicrm_membership_payment',
2563 'civicrm_membership_log',
2564 'civicrm_membership_block',
2566 'civicrm_participant',
2567 'civicrm_participant_payment',
2569 'civicrm_pledge_payment',
2570 'civicrm_price_set_entity',
2571 'civicrm_price_field_value',
2572 'civicrm_price_field',
2574 $this->quickCleanup($tablesToTruncate);
2575 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2576 $this->restoreDefaultPriceSetConfig();
2578 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2579 $this->disableTaxAndInvoicing();
2580 System
::singleton()->flushProcessors();
2583 public function restoreDefaultPriceSetConfig() {
2584 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2585 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)");
2586 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)");
2589 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2590 * Default behaviour is to also delete the entity
2591 * @param array $params
2592 * Params array to check against.
2594 * Id of the entity concerned.
2595 * @param string $entity
2596 * Name of entity concerned (e.g. membership).
2597 * @param bool $delete
2598 * Should the entity be deleted as part of this check.
2599 * @param string $errorText
2600 * Text to print on error.
2603 * @param array $params
2606 * @param int $delete
2607 * @param string $errorText
2611 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2613 $result = $this->callAPISuccessGetSingle($entity, array(
2618 $this->callAPISuccess($entity, 'Delete', array(
2622 $dateFields = $keys = $dateTimeFields = array();
2623 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2624 foreach ($fields['values'] as $field => $settings) {
2625 if (array_key_exists($field, $result)) {
2626 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2629 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2631 $type = CRM_Utils_Array
::value('type', $settings);
2632 if ($type == CRM_Utils_Type
::T_DATE
) {
2633 $dateFields[] = $settings['name'];
2634 // we should identify both real names & unique names as dates
2635 if ($field != $settings['name']) {
2636 $dateFields[] = $field;
2639 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2640 $dateTimeFields[] = $settings['name'];
2641 // we should identify both real names & unique names as dates
2642 if ($field != $settings['name']) {
2643 $dateTimeFields[] = $field;
2648 if (strtolower($entity) == 'contribution') {
2649 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2650 // this is not returned in id format
2651 unset($params['payment_instrument_id']);
2652 $params['contribution_source'] = $params['source'];
2653 unset($params['source']);
2656 foreach ($params as $key => $value) {
2657 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2660 if (in_array($key, $dateFields)) {
2661 $value = date('Y-m-d', strtotime($value));
2662 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2664 if (in_array($key, $dateTimeFields)) {
2665 $value = date('Y-m-d H:i:s', strtotime($value));
2666 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2668 $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);
2673 * Get formatted values in the actual and expected result.
2674 * @param array $actual
2675 * Actual calculated values.
2676 * @param array $expected
2679 public function checkArrayEquals(&$actual, &$expected) {
2680 self
::unsetId($actual);
2681 self
::unsetId($expected);
2682 $this->assertEquals($actual, $expected);
2686 * Unset the key 'id' from the array
2687 * @param array $unformattedArray
2688 * The array from which the 'id' has to be unset.
2690 public static function unsetId(&$unformattedArray) {
2691 $formattedArray = array();
2692 if (array_key_exists('id', $unformattedArray)) {
2693 unset($unformattedArray['id']);
2695 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2696 foreach ($unformattedArray['values'] as $key => $value) {
2697 if (is_array($value)) {
2698 foreach ($value as $k => $v) {
2704 elseif ($key == 'id') {
2705 $unformattedArray[$key];
2707 $formattedArray = array($value);
2709 $unformattedArray['values'] = $formattedArray;
2714 * Helper to enable/disable custom directory support
2716 * @param array $customDirs
2718 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2719 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2721 public function customDirectories($customDirs) {
2722 $config = CRM_Core_Config
::singleton();
2724 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2725 unset($config->customPHPPathDir
);
2727 elseif ($customDirs['php_path'] === TRUE) {
2728 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2731 $config->customPHPPathDir
= $php_path;
2734 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2735 unset($config->customTemplateDir
);
2737 elseif ($customDirs['template_path'] === TRUE) {
2738 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2741 $config->customTemplateDir
= $template_path;
2746 * Generate a temporary folder.
2748 * @param string $prefix
2751 public function createTempDir($prefix = 'test-') {
2752 $tempDir = CRM_Utils_File
::tempdir($prefix);
2753 $this->tempDirs
[] = $tempDir;
2757 public function cleanTempDirs() {
2758 if (!is_array($this->tempDirs
)) {
2759 // fix test errors where this is not set
2762 foreach ($this->tempDirs
as $tempDir) {
2763 if (is_dir($tempDir)) {
2764 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2770 * Temporarily replace the singleton extension with a different one.
2771 * @param \CRM_Extension_System $system
2773 public function setExtensionSystem(CRM_Extension_System
$system) {
2774 if ($this->origExtensionSystem
== NULL) {
2775 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2777 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2780 public function unsetExtensionSystem() {
2781 if ($this->origExtensionSystem
!== NULL) {
2782 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2783 $this->origExtensionSystem
= NULL;
2788 * Temporarily alter the settings-metadata to add a mock setting.
2790 * WARNING: The setting metadata will disappear on the next cache-clear.
2795 public function setMockSettingsMetaData($extras) {
2796 Civi
::service('settings_manager')->flush();
2798 CRM_Utils_Hook
::singleton()
2799 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2800 $metadata = array_merge($metadata, $extras);
2803 $fields = $this->callAPISuccess('setting', 'getfields', array());
2804 foreach ($extras as $key => $spec) {
2805 $this->assertNotEmpty($spec['title']);
2806 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2811 * @param string $name
2813 public function financialAccountDelete($name) {
2814 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2815 $financialAccount->name
= $name;
2816 if ($financialAccount->find(TRUE)) {
2817 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2818 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2819 $entityFinancialType->delete();
2820 $financialAccount->delete();
2825 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2826 * (NB unclear if this is still required)
2828 public function _sethtmlGlobals() {
2829 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2830 'required' => array(
2831 'html_quickform_rule_required',
2832 'HTML/QuickForm/Rule/Required.php',
2834 'maxlength' => array(
2835 'html_quickform_rule_range',
2836 'HTML/QuickForm/Rule/Range.php',
2838 'minlength' => array(
2839 'html_quickform_rule_range',
2840 'HTML/QuickForm/Rule/Range.php',
2842 'rangelength' => array(
2843 'html_quickform_rule_range',
2844 'HTML/QuickForm/Rule/Range.php',
2847 'html_quickform_rule_email',
2848 'HTML/QuickForm/Rule/Email.php',
2851 'html_quickform_rule_regex',
2852 'HTML/QuickForm/Rule/Regex.php',
2854 'lettersonly' => array(
2855 'html_quickform_rule_regex',
2856 'HTML/QuickForm/Rule/Regex.php',
2858 'alphanumeric' => array(
2859 'html_quickform_rule_regex',
2860 'HTML/QuickForm/Rule/Regex.php',
2863 'html_quickform_rule_regex',
2864 'HTML/QuickForm/Rule/Regex.php',
2866 'nopunctuation' => array(
2867 'html_quickform_rule_regex',
2868 'HTML/QuickForm/Rule/Regex.php',
2871 'html_quickform_rule_regex',
2872 'HTML/QuickForm/Rule/Regex.php',
2874 'callback' => array(
2875 'html_quickform_rule_callback',
2876 'HTML/QuickForm/Rule/Callback.php',
2879 'html_quickform_rule_compare',
2880 'HTML/QuickForm/Rule/Compare.php',
2883 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2884 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2886 'HTML/QuickForm/group.php',
2887 'HTML_QuickForm_group',
2890 'HTML/QuickForm/hidden.php',
2891 'HTML_QuickForm_hidden',
2894 'HTML/QuickForm/reset.php',
2895 'HTML_QuickForm_reset',
2897 'checkbox' => array(
2898 'HTML/QuickForm/checkbox.php',
2899 'HTML_QuickForm_checkbox',
2902 'HTML/QuickForm/file.php',
2903 'HTML_QuickForm_file',
2906 'HTML/QuickForm/image.php',
2907 'HTML_QuickForm_image',
2909 'password' => array(
2910 'HTML/QuickForm/password.php',
2911 'HTML_QuickForm_password',
2914 'HTML/QuickForm/radio.php',
2915 'HTML_QuickForm_radio',
2918 'HTML/QuickForm/button.php',
2919 'HTML_QuickForm_button',
2922 'HTML/QuickForm/submit.php',
2923 'HTML_QuickForm_submit',
2926 'HTML/QuickForm/select.php',
2927 'HTML_QuickForm_select',
2929 'hiddenselect' => array(
2930 'HTML/QuickForm/hiddenselect.php',
2931 'HTML_QuickForm_hiddenselect',
2934 'HTML/QuickForm/text.php',
2935 'HTML_QuickForm_text',
2937 'textarea' => array(
2938 'HTML/QuickForm/textarea.php',
2939 'HTML_QuickForm_textarea',
2941 'fckeditor' => array(
2942 'HTML/QuickForm/fckeditor.php',
2943 'HTML_QuickForm_FCKEditor',
2946 'HTML/QuickForm/tinymce.php',
2947 'HTML_QuickForm_TinyMCE',
2949 'dojoeditor' => array(
2950 'HTML/QuickForm/dojoeditor.php',
2951 'HTML_QuickForm_dojoeditor',
2954 'HTML/QuickForm/link.php',
2955 'HTML_QuickForm_link',
2957 'advcheckbox' => array(
2958 'HTML/QuickForm/advcheckbox.php',
2959 'HTML_QuickForm_advcheckbox',
2962 'HTML/QuickForm/date.php',
2963 'HTML_QuickForm_date',
2966 'HTML/QuickForm/static.php',
2967 'HTML_QuickForm_static',
2970 'HTML/QuickForm/header.php',
2971 'HTML_QuickForm_header',
2974 'HTML/QuickForm/html.php',
2975 'HTML_QuickForm_html',
2977 'hierselect' => array(
2978 'HTML/QuickForm/hierselect.php',
2979 'HTML_QuickForm_hierselect',
2981 'autocomplete' => array(
2982 'HTML/QuickForm/autocomplete.php',
2983 'HTML_QuickForm_autocomplete',
2986 'HTML/QuickForm/xbutton.php',
2987 'HTML_QuickForm_xbutton',
2989 'advmultiselect' => array(
2990 'HTML/QuickForm/advmultiselect.php',
2991 'HTML_QuickForm_advmultiselect',
2997 * Set up an acl allowing contact to see 2 specified groups
2998 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3000 * You need to have pre-created these groups & created the user e.g
3001 * $this->createLoggedInUser();
3002 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3003 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3005 * @param bool $isProfile
3007 public function setupACL($isProfile = FALSE) {
3009 $_REQUEST = $this->_params
;
3011 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3012 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3013 $ov = new CRM_Core_DAO_OptionValue();
3014 $ov->option_group_id
= $optionGroupID;
3016 if ($ov->find(TRUE)) {
3017 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
3019 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3020 'option_group_id' => $optionGroupID,
3021 'label' => 'pick me',
3025 CRM_Core_DAO
::executeQuery("
3026 TRUNCATE civicrm_acl_cache
3029 CRM_Core_DAO
::executeQuery("
3030 TRUNCATE civicrm_acl_contact_cache
3033 CRM_Core_DAO
::executeQuery("
3034 INSERT INTO civicrm_acl_entity_role (
3035 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3036 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3040 CRM_Core_DAO
::executeQuery("
3041 INSERT INTO civicrm_acl (
3042 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3045 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3050 CRM_Core_DAO
::executeQuery("
3051 INSERT INTO civicrm_acl (
3052 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3055 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3059 CRM_Core_DAO
::executeQuery("
3060 INSERT INTO civicrm_acl (
3061 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3064 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3069 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3070 $this->callAPISuccess('group_contact', 'create', array(
3071 'group_id' => $this->_permissionedGroup
,
3072 'contact_id' => $this->_loggedInUser
,
3077 CRM_ACL_BAO_Cache
::resetCache();
3078 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3079 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3084 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3086 public function offsetDefaultPriceSet() {
3087 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3088 $firstID = $contributionPriceSet['id'];
3089 $this->callAPISuccess('price_set', 'create', array(
3090 'id' => $contributionPriceSet['id'],
3094 unset($contributionPriceSet['id']);
3095 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3096 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3097 'price_set_id' => $firstID,
3098 'options' => array('limit' => 1),
3100 unset($priceField['id']);
3101 $priceField['price_set_id'] = $newPriceSet['id'];
3102 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3103 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3104 'price_set_id' => $firstID,
3106 'options' => array('limit' => 1),
3109 unset($priceFieldValue['id']);
3110 //create some padding to use up ids
3111 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3112 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3113 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3117 * Create an instance of the paypal processor.
3118 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3119 * this parent class & we don't have a structure for that yet
3120 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3121 * & the best protection against that is the functions this class affords
3122 * @param array $params
3123 * @return int $result['id'] payment processor id
3125 public function paymentProcessorCreate($params = array()) {
3126 $params = array_merge(array(
3128 'domain_id' => CRM_Core_Config
::domainID(),
3129 'payment_processor_type_id' => 'PayPal',
3133 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3134 'password' => '1183377788',
3135 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3136 'url_site' => 'https://www.sandbox.paypal.com/',
3137 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3138 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3139 'class_name' => 'Payment_PayPalImpl',
3140 'billing_mode' => 3,
3141 'financial_type_id' => 1,
3142 'financial_account_id' => 12,
3143 // Credit card = 1 so can pass 'by accident'.
3144 'payment_instrument_id' => 'Debit Card',
3147 if (!is_numeric($params['payment_processor_type_id'])) {
3148 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3150 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3151 'name' => $params['payment_processor_type_id'],
3155 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3156 return $result['id'];
3160 * Set up initial recurring payment allowing subsequent IPN payments.
3162 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3163 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3164 'contact_id' => $this->_contactID
,
3167 'installments' => 5,
3168 'frequency_unit' => 'Month',
3169 'frequency_interval' => 1,
3170 'invoice_id' => $this->_invoiceID
,
3171 'contribution_status_id' => 2,
3172 'payment_processor_id' => $this->_paymentProcessorID
,
3173 // processor provided ID - use contact ID as proxy.
3174 'processor_id' => $this->_contactID
,
3175 'api.contribution.create' => array(
3176 'total_amount' => '200',
3177 'invoice_id' => $this->_invoiceID
,
3178 'financial_type_id' => 1,
3179 'contribution_status_id' => 'Pending',
3180 'contact_id' => $this->_contactID
,
3181 'contribution_page_id' => $this->_contributionPageID
,
3182 'payment_processor_id' => $this->_paymentProcessorID
,
3186 $this->_contributionRecurID
= $contributionRecur['id'];
3187 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3191 * 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
3193 public function setupMembershipRecurringPaymentProcessorTransaction() {
3194 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3195 //create a contribution so our membership & contribution don't both have id = 1
3196 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3197 $this->contributionCreate(array(
3198 'contact_id' => $this->_contactID
,
3200 'financial_type_id' => 1,
3201 'invoice_id' => 'abcd',
3205 $this->setupRecurringPaymentProcessorTransaction();
3207 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3208 'contact_id' => $this->_contactID
,
3209 'membership_type_id' => $this->ids
['membership_type'],
3210 'contribution_recur_id' => $this->_contributionRecurID
,
3211 'format.only_id' => TRUE,
3213 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3214 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3216 $this->callAPISuccess('line_item', 'create', array(
3217 'entity_table' => 'civicrm_membership',
3218 'entity_id' => $this->ids
['membership'],
3219 'contribution_id' => $this->_contributionID
,
3220 'label' => 'General',
3222 'unit_price' => 200,
3223 'line_total' => 200,
3224 'financial_type_id' => 1,
3225 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3227 'label' => 'Membership Amount',
3228 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3230 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3232 'label' => 'General',
3233 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3236 $this->callAPISuccess('membership_payment', 'create', array(
3237 'contribution_id' => $this->_contributionID
,
3238 'membership_id' => $this->ids
['membership'],
3247 public function CiviUnitTestCase_fatalErrorHandler($message) {
3248 throw new Exception("{$message['message']}: {$message['code']}");
3252 * Helper function to create new mailing.
3254 * @param array $params
3258 public function createMailing($params = array()) {
3259 $params = array_merge(array(
3260 'subject' => 'maild' . rand(),
3261 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3262 'name' => 'mailing name' . rand(),
3266 $result = $this->callAPISuccess('Mailing', 'create', $params);
3267 return $result['id'];
3271 * Helper function to delete mailing.
3274 public function deleteMailing($id) {
3279 $this->callAPISuccess('Mailing', 'delete', $params);
3283 * Wrap the entire test case in a transaction.
3285 * Only subsequent DB statements will be wrapped in TX -- this cannot
3286 * retroactively wrap old DB statements. Therefore, it makes sense to
3287 * call this at the beginning of setUp().
3289 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3290 * this option does not work with, e.g., custom-data.
3292 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3293 * if TRUNCATE or ALTER is called while using a transaction.
3296 * Whether to use nesting or reference-counting.
3298 public function useTransaction($nest = TRUE) {
3300 $this->tx
= new CRM_Core_Transaction($nest);
3301 $this->tx
->rollback();
3306 * Assert the attachment exists.
3308 * @param bool $exists
3309 * @param array $apiResult
3311 protected function assertAttachmentExistence($exists, $apiResult) {
3312 $fileId = $apiResult['id'];
3313 $this->assertTrue(is_numeric($fileId));
3314 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3315 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3316 1 => array($fileId, 'Int'),
3318 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3319 1 => array($fileId, 'Int'),
3324 * Create a price set for an event.
3326 * @param int $feeTotal
3327 * @param int $minAmt
3332 protected function eventPriceSetCreate($feeTotal, $minAmt = 0) {
3333 // creating price set, price field
3334 $paramsSet['title'] = 'Price Set';
3335 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3336 $paramsSet['is_active'] = FALSE;
3337 $paramsSet['extends'] = 1;
3338 $paramsSet['min_amount'] = $minAmt;
3340 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3341 $priceSetId = $priceset->id
;
3343 //Checking for priceset added in the table.
3344 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3345 'id', $paramsSet['title'], 'Check DB for created priceset'
3347 $paramsField = array(
3348 'label' => 'Price Field',
3349 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3350 'html_type' => 'Text',
3351 'price' => $feeTotal,
3352 'option_label' => array('1' => 'Price Field'),
3353 'option_value' => array('1' => $feeTotal),
3354 'option_name' => array('1' => $feeTotal),
3355 'option_weight' => array('1' => 1),
3356 'option_amount' => array('1' => 1),
3357 'is_display_amounts' => 1,
3359 'options_per_line' => 1,
3360 'is_active' => array('1' => 1),
3361 'price_set_id' => $priceset->id
,
3362 'is_enter_qty' => 1,
3363 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3365 CRM_Price_BAO_PriceField
::create($paramsField);
3371 * Add a profile to a contribution page.
3373 * @param string $name
3374 * @param int $contributionPageID
3376 protected function addProfile($name, $contributionPageID) {
3377 $this->callAPISuccess('UFJoin', 'create', array(
3378 'uf_group_id' => $name,
3379 'module' => 'CiviContribute',
3380 'entity_table' => 'civicrm_contribution_page',
3381 'entity_id' => $contributionPageID,
3387 * Add participant with contribution
3391 protected function createParticipantWithContribution() {
3392 // creating price set, price field
3393 $this->_contactId
= $this->individualCreate();
3394 $event = $this->eventCreate();
3395 $this->_eventId
= $event['id'];
3396 $eventParams = array(
3397 'id' => $this->_eventId
,
3398 'financial_type_id' => 4,
3401 $this->callAPISuccess('event', 'create', $eventParams);
3402 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3403 $participantParams = array(
3404 'financial_type_id' => 4,
3405 'event_id' => $this->_eventId
,
3408 'fee_currency' => 'USD',
3409 'contact_id' => $this->_contactId
,
3411 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3412 $contributionParams = array(
3413 'total_amount' => 150,
3414 'currency' => 'USD',
3415 'contact_id' => $this->_contactId
,
3416 'financial_type_id' => 4,
3417 'contribution_status_id' => 1,
3418 'partial_payment_total' => 300.00,
3419 'partial_amount_to_pay' => 150,
3420 'contribution_mode' => 'participant',
3421 'participant_id' => $participant['id'],
3423 foreach ($priceFields['values'] as $key => $priceField) {
3424 $lineItems[1][$key] = array(
3425 'price_field_id' => $priceField['price_field_id'],
3426 'price_field_value_id' => $priceField['id'],
3427 'label' => $priceField['label'],
3428 'field_title' => $priceField['label'],
3430 'unit_price' => $priceField['amount'],
3431 'line_total' => $priceField['amount'],
3432 'financial_type_id' => $priceField['financial_type_id'],
3435 $contributionParams['line_item'] = $lineItems;
3436 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3437 $paymentParticipant = array(
3438 'participant_id' => $participant['id'],
3439 'contribution_id' => $contribution['id'],
3441 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3442 return array($lineItems, $contribution);
3448 * @param string $component
3449 * @param int $componentId
3453 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3454 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3455 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3456 $paramsSet['is_active'] = TRUE;
3457 $paramsSet['financial_type_id'] = 4;
3458 $paramsSet['extends'] = 1;
3459 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3460 $priceSetId = $priceSet['id'];
3461 //Checking for priceset added in the table.
3462 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3463 'id', $paramsSet['title'], 'Check DB for created priceset'
3465 $paramsField = array_merge(array(
3466 'label' => 'Price Field',
3467 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3468 'html_type' => 'CheckBox',
3469 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3470 'option_value' => array('1' => 100, '2' => 200),
3471 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3472 'option_weight' => array('1' => 1, '2' => 2),
3473 'option_amount' => array('1' => 100, '2' => 200),
3474 'is_display_amounts' => 1,
3476 'options_per_line' => 1,
3477 'is_active' => array('1' => 1, '2' => 1),
3478 'price_set_id' => $priceSet['id'],
3479 'is_enter_qty' => 1,
3480 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3481 ), $priceFieldOptions);
3483 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3485 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3487 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3491 * Replace the template with a test-oriented template designed to show all the variables.
3493 * @param string $templateName
3495 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3496 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3497 CRM_Core_DAO
::executeQuery(
3498 "UPDATE civicrm_option_group og
3499 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3500 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3501 SET m.msg_html = '{$testTemplate}'
3502 WHERE og.name = 'msg_tpl_workflow_contribution'
3503 AND ov.name = '{$templateName}'
3504 AND m.is_default = 1"
3509 * Reinstate the default template.
3511 * @param string $templateName
3513 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3514 CRM_Core_DAO
::executeQuery(
3515 "UPDATE civicrm_option_group og
3516 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3517 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3518 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3519 SET m.msg_html = m2.msg_html
3520 WHERE og.name = 'msg_tpl_workflow_contribution'
3521 AND ov.name = '{$templateName}'
3522 AND m.is_default = 1"
3527 * Flush statics relating to financial type.
3529 protected function flushFinancialTypeStatics() {
3530 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3531 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3533 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3534 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3536 CRM_Contribute_PseudoConstant
::flush('financialType');
3537 CRM_Contribute_PseudoConstant
::flush('membershipType');
3538 // Pseudoconstants may be saved to the cache table.
3539 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3540 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3541 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3545 * Set the permissions to the supplied array.
3547 * @param array $permissions
3549 protected function setPermissions($permissions) {
3550 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3551 $this->flushFinancialTypeStatics();
3552 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3556 * @param array $params
3559 public function _checkFinancialRecords($params, $context) {
3560 $entityParams = array(
3561 'entity_id' => $params['id'],
3562 'entity_table' => 'civicrm_contribution',
3564 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3565 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3566 if ($context == 'pending') {
3567 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3568 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3571 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3572 $trxnParams = array(
3573 'id' => $trxn['financial_trxn_id'],
3575 if ($context != 'online' && $context != 'payLater') {
3576 $compareParams = array(
3577 'to_financial_account_id' => 6,
3578 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3582 if ($context == 'feeAmount') {
3583 $compareParams['fee_amount'] = 50;
3585 elseif ($context == 'online') {
3586 $compareParams = array(
3587 'to_financial_account_id' => 12,
3588 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3590 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3593 elseif ($context == 'payLater') {
3594 $compareParams = array(
3595 'to_financial_account_id' => 7,
3596 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3600 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3601 $entityParams = array(
3602 'financial_trxn_id' => $trxn['financial_trxn_id'],
3603 'entity_table' => 'civicrm_financial_item',
3605 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3606 $fitemParams = array(
3607 'id' => $entityTrxn['entity_id'],
3609 $compareParams = array(
3610 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3612 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3614 if ($context == 'payLater') {
3615 $compareParams = array(
3616 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3618 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3621 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3622 if ($context == 'feeAmount') {
3624 'entity_id' => $params['id'],
3625 'entity_table' => 'civicrm_contribution',
3627 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3628 $trxnParams = array(
3629 'id' => $maxTrxn['financial_trxn_id'],
3631 $compareParams = array(
3632 'to_financial_account_id' => 5,
3633 'from_financial_account_id' => 6,
3634 'total_amount' => 50,
3637 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3638 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3639 $fitemParams = array(
3640 'entity_id' => $trxnId['financialTrxnId'],
3641 'entity_table' => 'civicrm_financial_trxn',
3643 $compareParams = array(
3646 'financial_account_id' => 5,
3648 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3650 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3651 // line should be copied into all the functions that call this function & evaluated there
3652 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3653 // when calling completeTransaction or repeatTransaction.
3654 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3658 * Return financial type id on basis of name
3660 * @param string $name Financial type m/c name
3664 public function getFinancialTypeId($name) {
3665 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3669 * Cleanup function for contents of $this->ids.
3671 * This is a best effort cleanup to use in tear downs etc.
3673 * It will not fail if the data has already been removed (some tests may do
3674 * their own cleanup).
3676 protected function cleanUpSetUpIDs() {
3677 foreach ($this->setupIDs
as $entity => $id) {
3679 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3681 catch (CiviCRM_API3_Exception
$e) {
3682 // This is a best-effort cleanup function, ignore.
3688 * Create Financial Type.
3690 * @param array $params
3694 protected function createFinancialType($params = array()) {
3695 $params = array_merge($params,
3697 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3701 return $this->callAPISuccess('FinancialType', 'create', $params);
3705 * Enable Tax and Invoicing
3707 protected function enableTaxAndInvoicing($params = array()) {
3708 // Enable component contribute setting
3709 $contributeSetting = array_merge($params,
3712 'invoice_prefix' => 'INV_',
3713 'credit_notes_prefix' => 'CN_',
3715 'due_date_period' => 'days',
3717 'is_email_pdf' => 1,
3718 'tax_term' => 'Sales Tax',
3719 'tax_display_settings' => 'Inclusive',
3722 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3726 * Enable Tax and Invoicing
3728 protected function disableTaxAndInvoicing($params = array()) {
3729 // Enable component contribute setting
3730 $contributeSetting = array_merge($params,
3735 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3739 * Add Sales Tax relation for financial type with financial account.
3741 * @param int $financialTypeId
3745 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3747 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3748 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3749 'is_deductible' => 1,
3754 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3755 $entityParams = array(
3756 'entity_table' => 'civicrm_financial_type',
3757 'entity_id' => $financialTypeId,
3758 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3761 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3762 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3763 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3764 $dao->copyValues($entityParams);
3766 if ($dao->fetch()) {
3767 $entityParams['id'] = $dao->id
;
3769 $entityParams['financial_account_id'] = $account->id
;
3771 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3775 * Create price set with contribution test for test setup.
3777 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3778 * on parent class at some point (fn is not in 4.4).
3781 * @param array $params
3783 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3784 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3785 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3786 'title' => "Test Contribution Page",
3787 'financial_type_id' => 1,
3788 'currency' => 'NZD',
3789 'goal_amount' => 50,
3790 'is_pay_later' => 1,
3791 'is_monetary' => TRUE,
3792 'is_email_receipt' => FALSE,
3794 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3795 'is_quick_config' => 0,
3796 'extends' => 'CiviMember',
3797 'financial_type_id' => 1,
3798 'title' => 'my Page',
3800 $priceSetID = $priceSet['id'];
3802 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3803 $priceField = $this->callAPISuccess('price_field', 'create', array(
3804 'price_set_id' => $priceSetID,
3805 'label' => 'Goat Breed',
3806 'html_type' => 'Radio',
3808 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3809 'price_set_id' => $priceSetID,
3810 'price_field_id' => $priceField['id'],
3811 'label' => 'Long Haired Goat',
3813 'financial_type_id' => 'Donation',
3814 'membership_type_id' => $membershipTypeID,
3815 'membership_num_terms' => 1,
3818 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3819 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3820 'price_set_id' => $priceSetID,
3821 'price_field_id' => $priceField['id'],
3822 'label' => 'Shoe-eating Goat',
3824 'financial_type_id' => 'Donation',
3825 'membership_type_id' => $membershipTypeID,
3826 'membership_num_terms' => 2,
3829 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3831 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3832 'price_set_id' => $priceSetID,
3833 'price_field_id' => $priceField['id'],
3834 'label' => 'Shoe-eating Goat',
3836 'financial_type_id' => 'Donation',
3839 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3841 $this->_ids
['price_set'] = $priceSetID;
3842 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3843 $this->_ids
['price_field'] = array($priceField['id']);
3845 $this->_ids
['membership_type'] = $membershipTypeID;
3849 * No results returned.
3851 * @implements CRM_Utils_Hook::aclWhereClause
3853 * @param string $type
3854 * @param array $tables
3855 * @param array $whereTables
3856 * @param int $contactID
3857 * @param string $where
3859 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3863 * Only specified contact returned.
3864 * @implements CRM_Utils_Hook::aclWhereClause
3867 * @param $whereTables
3871 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3872 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3876 * @implements CRM_Utils_Hook::selectWhereClause
3878 * @param string $entity
3879 * @param array $clauses
3881 public function selectWhereClauseHook($entity, &$clauses) {
3882 if ($entity == 'Event') {
3883 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3888 * An implementation of hook_civicrm_post used with all our test cases.
3891 * @param string $objectName
3892 * @param int $objectId
3895 public function onPost($op, $objectName, $objectId, &$objectRef) {
3896 if ($op == 'create' && $objectName == 'Individual') {
3897 CRM_Core_DAO
::executeQuery(
3898 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3900 1 => array($objectId, 'Integer'),
3905 if ($op == 'edit' && $objectName == 'Participant') {
3907 1 => array($objectId, 'Integer'),
3909 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3910 CRM_Core_DAO
::executeQuery($query, $params);
3916 * Instantiate form object.
3918 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3920 * @param string $class
3921 * Name of form class.
3923 * @return \CRM_Core_Form
3925 public function getFormObject($class) {
3926 $form = new $class();
3927 $_SERVER['REQUEST_METHOD'] = 'GET';
3928 $form->controller
= new CRM_Core_Controller();