3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
32 * Include class definitions
34 require_once 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
57 * Api version - easier to override than just a define
59 protected $_apiversion = API_LATEST_VERSION
;
61 * Database has been initialized.
65 private static $dbInit = FALSE;
68 * Database connection.
70 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
79 static protected $_dbName;
82 * Track tables we have modified during a test.
84 protected $_tablesToTruncate = array();
87 * @var array of temporary directory names
92 * @var boolean populateOnce allows to skip db resets in setUp
94 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
95 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
98 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
100 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
102 public static $populateOnce = FALSE;
105 * @var boolean DBResetRequired allows skipping DB reset
106 * in specific test case. If you still need
107 * to reset single test (method) of such case, call
108 * $this->cleanDB() in the first line of this
111 public $DBResetRequired = TRUE;
114 * @var CRM_Core_Transaction|NULL
119 * @var CRM_Utils_Hook_UnitTests hookClass
120 * example of setting a method for a hook
121 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
123 public $hookClass = NULL;
126 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
128 protected $_params = array();
131 * @var CRM_Extension_System
133 protected $origExtensionSystem;
136 * Array of IDs created during test setup routine.
138 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
142 public $setupIDs = array();
147 * Because we are overriding the parent class constructor, we
148 * need to show the same arguments as exist in the constructor of
149 * PHPUnit_Framework_TestCase, since
150 * PHPUnit_Framework_TestSuite::createTest() creates a
151 * ReflectionClass of the Test class and checks the constructor
152 * of that class to decide how to set up the test.
154 * @param string $name
156 * @param string $dataName
158 public function __construct($name = NULL, array$data = array(), $dataName = '') {
159 parent
::__construct($name, $data, $dataName);
161 // we need full error reporting
162 error_reporting(E_ALL
& ~E_NOTICE
);
164 self
::$_dbName = self
::getDBName();
166 // also load the class loader
167 require_once 'CRM/Core/ClassLoader.php';
168 CRM_Core_ClassLoader
::singleton()->register();
169 if (function_exists('_civix_phpunit_setUp')) {
170 // FIXME: loosen coupling
171 _civix_phpunit_setUp();
176 * Override to run the test and assert its state.
179 * @throws \PHPUnit_Framework_IncompleteTest
180 * @throws \PHPUnit_Framework_SkippedTest
182 protected function runTest() {
184 return parent
::runTest();
186 catch (PEAR_Exception
$e) {
187 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
188 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
195 public function requireDBReset() {
196 return $this->DBResetRequired
;
202 public static function getDBName() {
203 static $dbName = NULL;
204 if ($dbName === NULL) {
205 require_once "DB.php";
206 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
207 $dbName = $dsninfo['database'];
213 * Create database connection for this instance.
215 * Initialize the test database if it hasn't been initialized
217 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
219 protected function getConnection() {
220 $dbName = self
::$_dbName;
221 if (!self
::$dbInit) {
222 $dbName = self
::getDBName();
224 // install test database
225 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
227 static::_populateDB(FALSE, $this);
229 self
::$dbInit = TRUE;
232 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
236 * Required implementation of abstract method.
238 protected function getDataSet() {
242 * @param bool $perClass
243 * @param null $object
245 * TRUE if the populate logic runs; FALSE if it is skipped
247 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
248 if (CIVICRM_UF
!== 'UnitTests') {
249 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
252 if ($perClass ||
$object == NULL) {
256 $dbreset = $object->requireDBReset();
259 if (self
::$populateOnce ||
!$dbreset) {
262 self
::$populateOnce = NULL;
264 Civi\Test
::data()->populate();
269 public static function setUpBeforeClass() {
270 static::_populateDB(TRUE);
272 // also set this global hack
273 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
277 * Common setup functions for all unit tests.
279 protected function setUp() {
280 $session = CRM_Core_Session
::singleton();
281 $session->set('userID', NULL);
283 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
284 // Use a temporary file for STDIN
285 $GLOBALS['stdin'] = tmpfile();
286 if ($GLOBALS['stdin'] === FALSE) {
287 echo "Couldn't open temporary file\n";
291 // Get and save a connection to the database
292 $this->_dbconn
= $this->getConnection();
294 // reload database before each test
295 // $this->_populateDB();
297 // "initialize" CiviCRM to avoid problems when running single tests
298 // FIXME: look at it closer in second stage
300 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
301 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
303 // disable any left-over test extensions
304 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
306 // reset all the caches
307 CRM_Utils_System
::flushCache();
309 // initialize the object once db is loaded
311 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
313 // when running unit tests, use mockup user framework
314 $this->hookClass
= CRM_Utils_Hook
::singleton();
316 // Make sure the DB connection is setup properly
317 $config->userSystem
->setMySQLTimeZone();
318 $env = new CRM_Utils_Check_Component_Env();
319 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
321 // clear permissions stub to not check permissions
322 $config->userPermissionClass
->permissions
= NULL;
324 //flush component settings
325 CRM_Core_Component
::getEnabledComponents(TRUE);
327 error_reporting(E_ALL
);
329 $this->_sethtmlGlobals();
333 * Read everything from the datasets directory and insert into the db.
335 public function loadAllFixtures() {
336 $fixturesDir = __DIR__
. '/../../fixtures';
338 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
340 $xmlFiles = glob($fixturesDir . '/*.xml');
341 foreach ($xmlFiles as $xmlFixture) {
342 $op = new PHPUnit_Extensions_Database_Operation_Insert();
343 $dataset = $this->createXMLDataSet($xmlFixture);
344 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
345 $op->execute($this->_dbconn
, $dataset);
348 $yamlFiles = glob($fixturesDir . '/*.yaml');
349 foreach ($yamlFiles as $yamlFixture) {
350 $op = new PHPUnit_Extensions_Database_Operation_Insert();
351 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
352 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
353 $op->execute($this->_dbconn
, $dataset);
356 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
360 * Emulate a logged in user since certain functions use that.
361 * value to store a record in the DB (like activity)
365 * Contact ID of the created user.
367 public function createLoggedInUser() {
369 'first_name' => 'Logged In',
370 'last_name' => 'User ' . rand(),
371 'contact_type' => 'Individual',
373 $contactID = $this->individualCreate($params);
374 $this->callAPISuccess('UFMatch', 'create', array(
375 'contact_id' => $contactID,
376 'uf_name' => 'superman',
380 $session = CRM_Core_Session
::singleton();
381 $session->set('userID', $contactID);
386 * Create default domain contacts for the two domains added during test class.
387 * database population.
389 public function createDomainContacts() {
390 $this->organizationCreate();
391 $this->organizationCreate(array('organization_name' => 'Second Domain'));
395 * Common teardown functions for all unit tests.
397 protected function tearDown() {
398 error_reporting(E_ALL
& ~E_NOTICE
);
399 CRM_Utils_Hook
::singleton()->reset();
400 $this->hookClass
->reset();
401 $session = CRM_Core_Session
::singleton();
402 $session->set('userID', NULL);
405 $this->tx
->rollback()->commit();
408 CRM_Core_Transaction
::forceRollbackIfEnabled();
409 \Civi\Core\Transaction\Manager
::singleton(TRUE);
412 CRM_Core_Transaction
::forceRollbackIfEnabled();
413 \Civi\Core\Transaction\Manager
::singleton(TRUE);
415 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
416 $this->quickCleanup($tablesToTruncate);
417 $this->createDomainContacts();
420 $this->cleanTempDirs();
421 $this->unsetExtensionSystem();
425 * Generic function to compare expected values after an api call to retrieved.
428 * @daoName string DAO Name of object we're evaluating.
429 * @id int Id of object
430 * @match array Associative array of field name => expected value. Empty if asserting
431 * that a DELETE occurred
432 * @delete boolean True if we're checking that a DELETE action occurred.
436 * @param bool $delete
437 * @throws \PHPUnit_Framework_AssertionFailedError
439 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
441 // adding this here since developers forget to check for an id
442 // and hence we get the first value in the db
443 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
446 $object = new $daoName();
450 // If we're asserting successful record deletion, make sure object is NOT found.
452 if ($object->find(TRUE)) {
453 $this->fail("Object not deleted by delete operation: $daoName, $id");
458 // Otherwise check matches of DAO field values against expected values in $match.
459 if ($object->find(TRUE)) {
460 $fields = &$object->fields();
461 foreach ($fields as $name => $value) {
462 $dbName = $value['name'];
463 if (isset($match[$name])) {
465 $this->assertEquals($object->$dbName, $match[$name]);
467 elseif (isset($match[$dbName])) {
469 $this->assertEquals($object->$dbName, $match[$dbName]);
474 $this->fail("Could not retrieve object: $daoName, $id");
477 $matchSize = count($match);
478 if ($verifiedCount != $matchSize) {
479 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
484 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
485 * @param string $daoName
486 * @param $searchValue
487 * @param $returnColumn
488 * @param $searchColumn
491 * @return null|string
492 * @throws PHPUnit_Framework_AssertionFailedError
494 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
495 if (empty($searchValue)) {
496 $this->fail("empty value passed to assertDBNotNull");
498 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
499 $this->assertNotNull($value, $message);
505 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
506 * @param string $daoName
507 * @param $searchValue
508 * @param $returnColumn
509 * @param $searchColumn
512 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
513 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
514 $this->assertNull($value, $message);
518 * Request a record from the DB by id. Success if row not found.
519 * @param string $daoName
521 * @param null $message
523 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
524 $message = $message ?
$message : "$daoName (#$id) should not exist";
525 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
526 $this->assertNull($value, $message);
530 * Request a record from the DB by id. Success if row not found.
531 * @param string $daoName
533 * @param null $message
535 public function assertDBRowExist($daoName, $id, $message = NULL) {
536 $message = $message ?
$message : "$daoName (#$id) should exist";
537 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
538 $this->assertEquals($id, $value, $message);
542 * Compare a single column value in a retrieved DB record to an expected value.
543 * @param string $daoName
544 * @param $searchValue
545 * @param $returnColumn
546 * @param $searchColumn
547 * @param $expectedValue
550 public function assertDBCompareValue(
551 $daoName, $searchValue, $returnColumn, $searchColumn,
552 $expectedValue, $message
554 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
555 $this->assertEquals($value, $expectedValue, $message);
559 * Compare all values in a single retrieved DB record to an array of expected values.
560 * @param string $daoName
561 * @param array $searchParams
562 * @param $expectedValues
564 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
565 //get the values from db
567 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
569 // compare db values with expected values
570 self
::assertAttributesEquals($expectedValues, $dbValues);
574 * Assert that a SQL query returns a given value.
576 * The first argument is an expected value. The remaining arguments are passed
577 * to CRM_Core_DAO::singleValueQuery
579 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
580 * array(1 => array("Whiz", "String")));
583 * @param array $params
584 * @param string $message
586 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
590 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
591 $this->assertEquals($expected, $actual,
592 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
593 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
599 * Assert that two array-trees are exactly equal, notwithstanding
600 * the sorting of keys
602 * @param array $expected
603 * @param array $actual
605 public function assertTreeEquals($expected, $actual) {
608 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
609 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
613 $this->assertEquals($e, $a);
617 * Assert that two numbers are approximately equal.
619 * @param int|float $expected
620 * @param int|float $actual
621 * @param int|float $tolerance
622 * @param string $message
624 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
625 if ($message === NULL) {
626 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
628 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
632 * Assert attributes are equal.
634 * @param $expectedValues
635 * @param $actualValues
636 * @param string $message
638 * @throws PHPUnit_Framework_AssertionFailedError
640 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
641 foreach ($expectedValues as $paramName => $paramValue) {
642 if (isset($actualValues[$paramName])) {
643 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
646 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
655 public function assertArrayKeyExists($key, &$list) {
656 $result = isset($list[$key]) ?
TRUE : FALSE;
657 $this->assertTrue($result, ts("%1 element exists?",
666 public function assertArrayValueNotNull($key, &$list) {
667 $this->assertArrayKeyExists($key, $list);
669 $value = isset($list[$key]) ?
$list[$key] : NULL;
670 $this->assertTrue($value,
671 ts("%1 element not null?",
678 * Check that api returned 'is_error' => 0.
680 * @param array $apiResult
682 * @param string $prefix
683 * Extra test to add to message.
685 public function assertAPISuccess($apiResult, $prefix = '') {
686 if (!empty($prefix)) {
689 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
691 if (!empty($apiResult['debug_information'])) {
692 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
694 if (!empty($apiResult['trace'])) {
695 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
697 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
701 * Check that api returned 'is_error' => 1.
703 * @param array $apiResult
705 * @param string $prefix
706 * Extra test to add to message.
707 * @param null $expectedError
709 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
710 if (!empty($prefix)) {
713 if ($expectedError && !empty($apiResult['is_error'])) {
714 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
716 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
717 $this->assertNotEmpty($apiResult['error_message']);
723 * @param string $message
725 public function assertType($expected, $actual, $message = '') {
726 return $this->assertInternalType($expected, $actual, $message);
730 * Check that a deleted item has been deleted.
735 public function assertAPIDeleted($entity, $id) {
736 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
741 * Check that api returned 'is_error' => 1
742 * else provide full message
743 * @param array $result
745 * @param array $valuesToExclude
746 * @param string $prefix
747 * Extra test to add to message.
749 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
750 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
751 foreach ($valuesToExclude as $value) {
752 if (isset($result[$value])) {
753 unset($result[$value]);
755 if (isset($expected[$value])) {
756 unset($expected[$value]);
759 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
763 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
767 * @param array $params
770 public function civicrm_api($entity, $action, $params) {
771 return civicrm_api($entity, $action, $params);
775 * Create a batch of external API calls which can
776 * be executed concurrently.
779 * $calls = $this->createExternalAPI()
780 * ->addCall('Contact', 'get', ...)
781 * ->addCall('Contact', 'get', ...)
787 * @return \Civi\API\ExternalBatch
788 * @throws PHPUnit_Framework_SkippedTestError
790 public function createExternalAPI() {
791 global $civicrm_root;
792 $defaultParams = array(
793 'version' => $this->_apiversion
,
797 $calls = new \Civi\API\
ExternalBatch($defaultParams);
799 if (!$calls->isSupported()) {
800 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
807 * wrap api functions.
808 * so we can ensure they succeed & throw exceptions without litterering the test with checks
810 * @param string $entity
811 * @param string $action
812 * @param array $params
813 * @param mixed $checkAgainst
814 * Optional value to check result against, implemented for getvalue,.
815 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
816 * for getsingle the array is compared against an array passed in - the id is not compared (for
821 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
822 $params = array_merge(array(
823 'version' => $this->_apiversion
,
828 switch (strtolower($action)) {
830 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
833 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
836 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
838 $result = $this->civicrm_api($entity, $action, $params);
839 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
844 * This function exists to wrap api getValue function & check the result
845 * so we can ensure they succeed & throw exceptions without litterering the test with checks
846 * There is a type check in this
848 * @param string $entity
849 * @param array $params
850 * @param string $type
851 * Per http://php.net/manual/en/function.gettype.php possible types.
861 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
863 'version' => $this->_apiversion
,
866 $result = $this->civicrm_api($entity, 'getvalue', $params);
868 if ($type == 'integer') {
869 // api seems to return integers as strings
870 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
873 $this->assertType($type, $result, "returned result should have been of type $type but was ");
880 * This function exists to wrap api getsingle function & check the result
881 * so we can ensure they succeed & throw exceptions without litterering the test with checks
883 * @param string $entity
884 * @param array $params
885 * @param array $checkAgainst
886 * Array to compare result against.
897 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
899 'version' => $this->_apiversion
,
901 $result = $this->civicrm_api($entity, 'getsingle', $params);
902 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
903 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
906 // @todo - have gone with the fn that unsets id? should we check id?
907 $this->checkArrayEquals($result, $checkAgainst);
913 * This function exists to wrap api getValue function & check the result
914 * so we can ensure they succeed & throw exceptions without litterering the test with checks
915 * There is a type check in this
916 * @param string $entity
917 * @param array $params
922 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
924 'version' => $this->_apiversion
,
927 $result = $this->civicrm_api($entity, 'getcount', $params);
928 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
929 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
931 if (is_int($count)) {
932 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
938 * This function exists to wrap api functions.
939 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
941 * @param string $entity
942 * @param string $action
943 * @param array $params
944 * @param string $function
945 * Pass this in to create a generated example.
946 * @param string $file
947 * Pass this in to create a generated example.
948 * @param string $description
949 * @param string|null $exampleName
953 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
954 $params['version'] = $this->_apiversion
;
955 $result = $this->callAPISuccess($entity, $action, $params);
956 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
961 * This function exists to wrap api functions.
962 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
963 * @param string $entity
964 * @param string $action
965 * @param array $params
966 * @param string $expectedErrorMessage
968 * @param null $extraOutput
971 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
972 if (is_array($params)) {
974 'version' => $this->_apiversion
,
977 $result = $this->civicrm_api($entity, $action, $params);
978 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
983 * Create required data based on $this->entity & $this->params
984 * This is just a way to set up the test data for delete & get functions
985 * so the distinction between set
986 * up & tested functions is clearer
991 public function createTestEntity() {
992 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
996 * Generic function to create Organisation, to be used in test cases
998 * @param array $params
999 * parameters for civicrm_contact_add api function call
1001 * sequence number if creating multiple organizations
1004 * id of Organisation created
1006 public function organizationCreate($params = array(), $seq = 0) {
1010 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1011 return $this->_contactCreate($params);
1015 * Generic function to create Individual, to be used in test cases
1017 * @param array $params
1018 * parameters for civicrm_contact_add api function call
1020 * sequence number if creating multiple individuals
1023 * id of Individual created
1025 public function individualCreate($params = array(), $seq = 0) {
1026 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1027 return $this->_contactCreate($params);
1031 * Generic function to create Household, to be used in test cases
1033 * @param array $params
1034 * parameters for civicrm_contact_add api function call
1036 * sequence number if creating multiple households
1039 * id of Household created
1041 public function householdCreate($params = array(), $seq = 0) {
1042 $params = array_merge($this->sampleContact('Household', $seq), $params);
1043 return $this->_contactCreate($params);
1047 * Helper function for getting sample contact properties.
1049 * @param string $contact_type
1050 * enum contact type: Individual, Organization
1052 * sequence number for the values of this type
1055 * properties of sample contact (ie. $params for API call)
1057 public function sampleContact($contact_type, $seq = 0) {
1059 'Individual' => array(
1060 // The number of values in each list need to be coprime numbers to not have duplicates
1061 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1062 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1063 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1065 'Organization' => array(
1066 'organization_name' => array(
1067 'Unit Test Organization',
1074 'Household' => array(
1075 'household_name' => array('Unit Test household'),
1078 $params = array('contact_type' => $contact_type);
1079 foreach ($samples[$contact_type] as $key => $values) {
1080 $params[$key] = $values[$seq %
count($values)];
1082 if ($contact_type == 'Individual') {
1083 $params['email'] = strtolower(
1084 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1086 $params['prefix_id'] = 3;
1087 $params['suffix_id'] = 3;
1093 * Private helper function for calling civicrm_contact_add.
1095 * @param array $params
1096 * For civicrm_contact_add api function call.
1101 * id of Household created
1103 private function _contactCreate($params) {
1104 $result = $this->callAPISuccess('contact', 'create', $params);
1105 if (!empty($result['is_error']) ||
empty($result['id'])) {
1106 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1108 return $result['id'];
1112 * Delete contact, ensuring it is not the domain contact
1114 * @param int $contactID
1115 * Contact ID to delete
1117 public function contactDelete($contactID) {
1118 $domain = new CRM_Core_BAO_Domain();
1119 $domain->contact_id
= $contactID;
1120 if (!$domain->find(TRUE)) {
1121 $this->callAPISuccess('contact', 'delete', array(
1123 'skip_undelete' => 1,
1129 * @param int $contactTypeId
1133 public function contactTypeDelete($contactTypeId) {
1134 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1136 throw new Exception('Could not delete contact type');
1141 * @param array $params
1145 public function membershipTypeCreate($params = array()) {
1146 CRM_Member_PseudoConstant
::flush('membershipType');
1147 CRM_Core_Config
::clearDBCache();
1148 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
1149 $params = array_merge(array(
1150 'name' => 'General',
1151 'duration_unit' => 'year',
1152 'duration_interval' => 1,
1153 'period_type' => 'rolling',
1154 'member_of_contact_id' => $memberOfOrganization,
1156 'financial_type_id' => 2,
1159 'visibility' => 'Public',
1162 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1164 CRM_Member_PseudoConstant
::flush('membershipType');
1165 CRM_Utils_Cache
::singleton()->flush();
1167 return $result['id'];
1171 * @param array $params
1175 public function contactMembershipCreate($params) {
1176 $params = array_merge(array(
1177 'join_date' => '2007-01-21',
1178 'start_date' => '2007-01-21',
1179 'end_date' => '2007-12-21',
1180 'source' => 'Payment',
1181 'membership_type_id' => 'General',
1183 if (!is_numeric($params['membership_type_id'])) {
1184 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
1185 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
1186 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
1190 $result = $this->callAPISuccess('Membership', 'create', $params);
1191 return $result['id'];
1195 * Delete Membership Type.
1197 * @param array $params
1199 public function membershipTypeDelete($params) {
1200 $this->callAPISuccess('MembershipType', 'Delete', $params);
1204 * @param int $membershipID
1206 public function membershipDelete($membershipID) {
1207 $deleteParams = array('id' => $membershipID);
1208 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1212 * @param string $name
1216 public function membershipStatusCreate($name = 'test member status') {
1217 $params['name'] = $name;
1218 $params['start_event'] = 'start_date';
1219 $params['end_event'] = 'end_date';
1220 $params['is_current_member'] = 1;
1221 $params['is_active'] = 1;
1223 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1224 CRM_Member_PseudoConstant
::flush('membershipStatus');
1225 return $result['id'];
1229 * @param int $membershipStatusID
1231 public function membershipStatusDelete($membershipStatusID) {
1232 if (!$membershipStatusID) {
1235 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1239 * @param array $params
1243 public function relationshipTypeCreate($params = array()) {
1244 $params = array_merge(array(
1245 'name_a_b' => 'Relation 1 for relationship type create',
1246 'name_b_a' => 'Relation 2 for relationship type create',
1247 'contact_type_a' => 'Individual',
1248 'contact_type_b' => 'Organization',
1255 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1256 CRM_Core_PseudoConstant
::flush('relationshipType');
1258 return $result['id'];
1262 * Delete Relatinship Type.
1264 * @param int $relationshipTypeID
1266 public function relationshipTypeDelete($relationshipTypeID) {
1267 $params['id'] = $relationshipTypeID;
1268 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1269 if (!empty($check['count'])) {
1270 $this->callAPISuccess('relationship_type', 'delete', $params);
1275 * @param array $params
1279 public function paymentProcessorTypeCreate($params = NULL) {
1280 if (is_null($params)) {
1282 'name' => 'API_Test_PP',
1283 'title' => 'API Test Payment Processor',
1284 'class_name' => 'CRM_Core_Payment_APITest',
1285 'billing_mode' => 'form',
1291 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1293 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1295 return $result['id'];
1299 * Create test Authorize.net instance.
1301 * @param array $params
1305 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1306 $params = array_merge(array(
1307 'name' => 'Authorize',
1308 'domain_id' => CRM_Core_Config
::domainID(),
1309 'payment_processor_type_id' => 'AuthNet',
1310 'title' => 'AuthNet',
1315 'user_name' => '4y5BfuW7jm',
1316 'password' => '4cAmW927n8uLf5J8',
1317 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1318 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1319 'class_name' => 'Payment_AuthorizeNet',
1320 'billing_mode' => 1,
1323 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1324 return $result['id'];
1328 * Create Participant.
1330 * @param array $params
1331 * Array of contact id and event id values.
1334 * $id of participant created
1336 public function participantCreate($params) {
1337 if (empty($params['contact_id'])) {
1338 $params['contact_id'] = $this->individualCreate();
1340 if (empty($params['event_id'])) {
1341 $event = $this->eventCreate();
1342 $params['event_id'] = $event['id'];
1347 'register_date' => 20070219,
1348 'source' => 'Wimbeldon',
1349 'event_level' => 'Payment',
1353 $params = array_merge($defaults, $params);
1354 $result = $this->callAPISuccess('Participant', 'create', $params);
1355 return $result['id'];
1359 * Create Payment Processor.
1362 * Id Payment Processor
1364 public function processorCreate($params = array()) {
1365 $processorParams = array(
1368 'payment_processor_type_id' => 'Dummy',
1369 'financial_account_id' => 12,
1373 'url_site' => 'http://dummy.com',
1374 'url_recur' => 'http://dummy.com',
1375 'billing_mode' => 1,
1377 'payment_instrument_id' => 'Debit Card',
1379 $processorParams = array_merge($processorParams, $params);
1380 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1381 return $processor['id'];
1385 * Create Payment Processor.
1387 * @param array $processorParams
1389 * @return \CRM_Core_Payment_Dummy
1390 * Instance of Dummy Payment Processor
1392 public function dummyProcessorCreate($processorParams = array()) {
1393 $paymentProcessorID = $this->processorCreate($processorParams);
1394 return System
::singleton()->getById($paymentProcessorID);
1398 * Create contribution page.
1400 * @param array $params
1402 * Array of contribution page
1404 public function contributionPageCreate($params = array()) {
1405 $this->_pageParams
= array_merge(array(
1406 'title' => 'Test Contribution Page',
1407 'financial_type_id' => 1,
1408 'currency' => 'USD',
1409 'financial_account_id' => 1,
1411 'is_allow_other_amount' => 1,
1413 'max_amount' => 1000,
1415 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1419 * Create a sample batch.
1421 public function batchCreate() {
1422 $params = $this->_params
;
1423 $params['name'] = $params['title'] = 'Batch_433397';
1424 $params['status_id'] = 1;
1425 $result = $this->callAPISuccess('batch', 'create', $params);
1426 return $result['id'];
1432 * @param array $params
1434 * result of created tag
1436 public function tagCreate($params = array()) {
1438 'name' => 'New Tag3',
1439 'description' => 'This is description for Our New Tag ',
1442 $params = array_merge($defaults, $params);
1443 $result = $this->callAPISuccess('Tag', 'create', $params);
1444 return $result['values'][$result['id']];
1451 * Id of the tag to be deleted.
1455 public function tagDelete($tagId) {
1456 require_once 'api/api.php';
1460 $result = $this->callAPISuccess('Tag', 'delete', $params);
1461 return $result['id'];
1465 * Add entity(s) to the tag
1467 * @param array $params
1471 public function entityTagAdd($params) {
1472 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1479 * @param array $params
1483 * id of created pledge
1485 public function pledgeCreate($params) {
1486 $params = array_merge(array(
1487 'pledge_create_date' => date('Ymd'),
1488 'start_date' => date('Ymd'),
1489 'scheduled_date' => date('Ymd'),
1491 'pledge_status_id' => '2',
1492 'financial_type_id' => '1',
1493 'pledge_original_installment_amount' => 20,
1494 'frequency_interval' => 5,
1495 'frequency_unit' => 'year',
1496 'frequency_day' => 15,
1497 'installments' => 5,
1501 $result = $this->callAPISuccess('Pledge', 'create', $params);
1502 return $result['id'];
1506 * Delete contribution.
1508 * @param int $pledgeId
1510 public function pledgeDelete($pledgeId) {
1512 'pledge_id' => $pledgeId,
1514 $this->callAPISuccess('Pledge', 'delete', $params);
1518 * Create contribution.
1520 * @param array $params
1521 * Array of parameters.
1524 * id of created contribution
1526 public function contributionCreate($params) {
1528 $params = array_merge(array(
1530 'receive_date' => date('Ymd'),
1531 'total_amount' => 100.00,
1532 'fee_amount' => 5.00,
1533 'financial_type_id' => 1,
1534 'payment_instrument_id' => 1,
1535 'non_deductible_amount' => 10.00,
1537 'invoice_id' => 67890,
1539 'contribution_status_id' => 1,
1542 $result = $this->callAPISuccess('contribution', 'create', $params);
1543 return $result['id'];
1547 * Delete contribution.
1549 * @param int $contributionId
1553 public function contributionDelete($contributionId) {
1555 'contribution_id' => $contributionId,
1557 $result = $this->callAPISuccess('contribution', 'delete', $params);
1564 * @param array $params
1565 * Name-value pair for an event.
1569 public function eventCreate($params = array()) {
1570 // if no contact was passed, make up a dummy event creator
1571 if (!isset($params['contact_id'])) {
1572 $params['contact_id'] = $this->_contactCreate(array(
1573 'contact_type' => 'Individual',
1574 'first_name' => 'Event',
1575 'last_name' => 'Creator',
1579 // set defaults for missing params
1580 $params = array_merge(array(
1581 'title' => 'Annual CiviCRM meet',
1582 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1583 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1584 'event_type_id' => 1,
1586 'start_date' => 20081021,
1587 'end_date' => 20081023,
1588 'is_online_registration' => 1,
1589 'registration_start_date' => 20080601,
1590 'registration_end_date' => 20081015,
1591 'max_participants' => 100,
1592 'event_full_text' => 'Sorry! We are already full',
1595 'is_show_location' => 0,
1598 return $this->callAPISuccess('Event', 'create', $params);
1602 * Create a paid event.
1604 * @param array $params
1608 protected function eventCreatePaid($params) {
1609 $event = $this->eventCreate($params);
1610 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1611 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1612 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1613 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1614 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1626 public function eventDelete($id) {
1630 return $this->callAPISuccess('event', 'delete', $params);
1634 * Delete participant.
1636 * @param int $participantID
1640 public function participantDelete($participantID) {
1642 'id' => $participantID,
1644 $check = $this->callAPISuccess('Participant', 'get', $params);
1645 if ($check['count'] > 0) {
1646 return $this->callAPISuccess('Participant', 'delete', $params);
1651 * Create participant payment.
1653 * @param int $participantID
1654 * @param int $contributionID
1656 * $id of created payment
1658 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1659 //Create Participant Payment record With Values
1661 'participant_id' => $participantID,
1662 'contribution_id' => $contributionID,
1665 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1666 return $result['id'];
1670 * Delete participant payment.
1672 * @param int $paymentID
1674 public function participantPaymentDelete($paymentID) {
1678 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1684 * @param int $contactID
1686 * location id of created location
1688 public function locationAdd($contactID) {
1691 'location_type' => 'New Location Type',
1693 'name' => 'Saint Helier St',
1694 'county' => 'Marin',
1695 'country' => 'UNITED STATES',
1696 'state_province' => 'Michigan',
1697 'supplemental_address_1' => 'Hallmark Ct',
1698 'supplemental_address_2' => 'Jersey Village',
1699 'supplemental_address_3' => 'My Town',
1704 'contact_id' => $contactID,
1705 'address' => $address,
1706 'location_format' => '2.0',
1707 'location_type' => 'New Location Type',
1710 $result = $this->callAPISuccess('Location', 'create', $params);
1715 * Delete Locations of contact.
1717 * @param array $params
1720 public function locationDelete($params) {
1721 $this->callAPISuccess('Location', 'delete', $params);
1725 * Add a Location Type.
1727 * @param array $params
1728 * @return CRM_Core_DAO_LocationType
1729 * location id of created location
1731 public function locationTypeCreate($params = NULL) {
1732 if ($params === NULL) {
1734 'name' => 'New Location Type',
1735 'vcard_name' => 'New Location Type',
1736 'description' => 'Location Type for Delete',
1741 $locationType = new CRM_Core_DAO_LocationType();
1742 $locationType->copyValues($params);
1743 $locationType->save();
1744 // clear getfields cache
1745 CRM_Core_PseudoConstant
::flush();
1746 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1747 return $locationType;
1751 * Delete a Location Type.
1753 * @param int $locationTypeId
1755 public function locationTypeDelete($locationTypeId) {
1756 $locationType = new CRM_Core_DAO_LocationType();
1757 $locationType->id
= $locationTypeId;
1758 $locationType->delete();
1764 * @param array $params
1765 * @return CRM_Core_DAO_Mapping
1766 * Mapping id of created mapping
1768 public function mappingCreate($params = NULL) {
1769 if ($params === NULL) {
1771 'name' => 'Mapping name',
1772 'description' => 'Mapping description',
1773 // 'Export Contact' mapping.
1774 'mapping_type_id' => 7,
1778 $mapping = new CRM_Core_DAO_Mapping();
1779 $mapping->copyValues($params);
1781 // clear getfields cache
1782 CRM_Core_PseudoConstant
::flush();
1783 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1790 * @param int $mappingId
1792 public function mappingDelete($mappingId) {
1793 $mapping = new CRM_Core_DAO_Mapping();
1794 $mapping->id
= $mappingId;
1801 * @param array $params
1803 * groupId of created group
1805 public function groupCreate($params = array()) {
1806 $params = array_merge(array(
1807 'name' => 'Test Group 1',
1809 'title' => 'New Test Group Created',
1810 'description' => 'New Test Group Created',
1812 'visibility' => 'Public Pages',
1813 'group_type' => array(
1819 $result = $this->callAPISuccess('Group', 'create', $params);
1820 return $result['id'];
1824 * Prepare class for ACLs.
1826 protected function prepareForACLs() {
1827 $config = CRM_Core_Config
::singleton();
1828 $config->userPermissionClass
->permissions
= array();
1834 protected function cleanUpAfterACLs() {
1835 CRM_Utils_Hook
::singleton()->reset();
1836 $tablesToTruncate = array(
1838 'civicrm_acl_cache',
1839 'civicrm_acl_entity_role',
1840 'civicrm_acl_contact_cache',
1842 $this->quickCleanup($tablesToTruncate);
1843 $config = CRM_Core_Config
::singleton();
1844 unset($config->userPermissionClass
->permissions
);
1847 * Create a smart group.
1849 * By default it will be a group of households.
1851 * @param array $smartGroupParams
1852 * @param array $groupParams
1855 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1856 $smartGroupParams = array_merge(array(
1857 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1860 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1862 $groupParams['saved_search_id'] = $savedSearch->id
;
1863 return $this->groupCreate($groupParams);
1867 * Function to add a Group.
1869 * @params array to add group
1871 * @param int $groupID
1872 * @param int $totalCount
1874 * groupId of created group
1876 public function groupContactCreate($groupID, $totalCount = 10) {
1877 $params = array('group_id' => $groupID);
1878 for ($i = 1; $i <= $totalCount; $i++
) {
1879 $contactID = $this->individualCreate();
1881 $params +
= array('contact_id' => $contactID);
1884 $params +
= array("contact_id.$i" => $contactID);
1887 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1897 public function groupDelete($gid) {
1903 $this->callAPISuccess('Group', 'delete', $params);
1908 * @param array $params
1910 public function uFFieldCreate($params = array()) {
1911 $params = array_merge(array(
1913 'field_name' => 'first_name',
1916 'visibility' => 'Public Pages and Listings',
1917 'is_searchable' => '1',
1918 'label' => 'first_name',
1919 'field_type' => 'Individual',
1922 $this->callAPISuccess('uf_field', 'create', $params);
1926 * Add a UF Join Entry.
1928 * @param array $params
1930 * $id of created UF Join
1932 public function ufjoinCreate($params = NULL) {
1933 if ($params === NULL) {
1936 'module' => 'CiviEvent',
1937 'entity_table' => 'civicrm_event',
1943 $result = $this->callAPISuccess('uf_join', 'create', $params);
1948 * Delete a UF Join Entry.
1950 * @param array $params
1951 * with missing uf_group_id
1953 public function ufjoinDelete($params = NULL) {
1954 if ($params === NULL) {
1957 'module' => 'CiviEvent',
1958 'entity_table' => 'civicrm_event',
1961 'uf_group_id' => '',
1965 crm_add_uf_join($params);
1969 * @param array $params
1970 * Optional parameters.
1971 * @param bool $reloadConfig
1972 * While enabling CiviCampaign component, we shouldn't always forcibly
1973 * reload config as this hinder hook call in test environment
1978 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1979 $this->enableCiviCampaign($reloadConfig);
1980 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1981 'name' => 'big_campaign',
1982 'title' => 'Campaign',
1984 return $campaign['id'];
1988 * Create Group for a contact.
1990 * @param int $contactId
1992 public function contactGroupCreate($contactId) {
1994 'contact_id.1' => $contactId,
1998 $this->callAPISuccess('GroupContact', 'Create', $params);
2002 * Delete Group for a contact.
2004 * @param int $contactId
2006 public function contactGroupDelete($contactId) {
2008 'contact_id.1' => $contactId,
2011 $this->civicrm_api('GroupContact', 'Delete', $params);
2017 * @param array $params
2020 public function activityCreate($params = array()) {
2021 $params = array_merge(array(
2022 'subject' => 'Discussion on warm beer',
2023 'activity_date_time' => date('Ymd'),
2024 'duration_hours' => 30,
2025 'duration_minutes' => 20,
2026 'location' => 'Baker Street',
2027 'details' => 'Lets schedule a meeting',
2029 'activity_name' => 'Meeting',
2031 if (!isset($params['source_contact_id'])) {
2032 $params['source_contact_id'] = $this->individualCreate();
2034 if (!isset($params['target_contact_id'])) {
2035 $params['target_contact_id'] = $this->individualCreate(array(
2036 'first_name' => 'Julia',
2037 'Last_name' => 'Anderson',
2039 'email' => 'julia_anderson@civicrm.org',
2040 'contact_type' => 'Individual',
2043 if (!isset($params['assignee_contact_id'])) {
2044 $params['assignee_contact_id'] = $params['target_contact_id'];
2047 $result = $this->callAPISuccess('Activity', 'create', $params);
2049 $result['target_contact_id'] = $params['target_contact_id'];
2050 $result['assignee_contact_id'] = $params['assignee_contact_id'];
2055 * Create an activity type.
2057 * @param array $params
2061 public function activityTypeCreate($params) {
2062 return $this->callAPISuccess('ActivityType', 'create', $params);
2066 * Delete activity type.
2068 * @param int $activityTypeId
2069 * Id of the activity type.
2072 public function activityTypeDelete($activityTypeId) {
2073 $params['activity_type_id'] = $activityTypeId;
2074 return $this->callAPISuccess('ActivityType', 'delete', $params);
2078 * Create custom group.
2080 * @param array $params
2083 public function customGroupCreate($params = array()) {
2085 'title' => 'new custom group',
2086 'extends' => 'Contact',
2088 'style' => 'Inline',
2092 $params = array_merge($defaults, $params);
2094 if (strlen($params['title']) > 13) {
2095 $params['title'] = substr($params['title'], 0, 13);
2098 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2099 $this->callAPISuccess('custom_group', 'get', array(
2100 'title' => $params['title'],
2101 array('api.custom_group.delete' => 1),
2104 return $this->callAPISuccess('custom_group', 'create', $params);
2108 * Existing function doesn't allow params to be over-ridden so need a new one
2109 * this one allows you to only pass in the params you want to change
2110 * @param array $params
2113 public function CustomGroupCreateByParams($params = array()) {
2115 'title' => "API Custom Group",
2116 'extends' => 'Contact',
2118 'style' => 'Inline',
2121 $params = array_merge($defaults, $params);
2122 return $this->callAPISuccess('custom_group', 'create', $params);
2126 * Create custom group with multi fields.
2127 * @param array $params
2130 public function CustomGroupMultipleCreateByParams($params = array()) {
2135 $params = array_merge($defaults, $params);
2136 return $this->CustomGroupCreateByParams($params);
2140 * Create custom group with multi fields.
2141 * @param array $params
2144 public function CustomGroupMultipleCreateWithFields($params = array()) {
2145 // also need to pass on $params['custom_field'] if not set but not in place yet
2147 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2148 $ids['custom_group_id'] = $customGroup['id'];
2150 $customField = $this->customFieldCreate(array(
2151 'custom_group_id' => $ids['custom_group_id'],
2152 'label' => 'field_1' . $ids['custom_group_id'],
2156 $ids['custom_field_id'][] = $customField['id'];
2158 $customField = $this->customFieldCreate(array(
2159 'custom_group_id' => $ids['custom_group_id'],
2160 'default_value' => '',
2161 'label' => 'field_2' . $ids['custom_group_id'],
2164 $ids['custom_field_id'][] = $customField['id'];
2166 $customField = $this->customFieldCreate(array(
2167 'custom_group_id' => $ids['custom_group_id'],
2168 'default_value' => '',
2169 'label' => 'field_3' . $ids['custom_group_id'],
2172 $ids['custom_field_id'][] = $customField['id'];
2178 * Create a custom group with a single text custom field. See
2179 * participant:testCreateWithCustom for how to use this
2181 * @param string $function
2183 * @param string $filename
2187 * ids of created objects
2189 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2190 $params = array('title' => $function);
2191 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2192 $params['extends'] = $entity ?
$entity : 'Contact';
2193 $customGroup = $this->CustomGroupCreate($params);
2194 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2195 CRM_Core_PseudoConstant
::flush();
2197 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2201 * Delete custom group.
2203 * @param int $customGroupID
2207 public function customGroupDelete($customGroupID) {
2208 $params['id'] = $customGroupID;
2209 return $this->callAPISuccess('custom_group', 'delete', $params);
2213 * Create custom field.
2215 * @param array $params
2216 * (custom_group_id) is required.
2219 public function customFieldCreate($params) {
2220 $params = array_merge(array(
2221 'label' => 'Custom Field',
2222 'data_type' => 'String',
2223 'html_type' => 'Text',
2224 'is_searchable' => 1,
2226 'default_value' => 'defaultValue',
2229 $result = $this->callAPISuccess('custom_field', 'create', $params);
2230 // these 2 functions are called with force to flush static caches
2231 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2232 CRM_Core_Component
::getEnabledComponents(1);
2237 * Delete custom field.
2239 * @param int $customFieldID
2243 public function customFieldDelete($customFieldID) {
2245 $params['id'] = $customFieldID;
2246 return $this->callAPISuccess('custom_field', 'delete', $params);
2255 public function noteCreate($cId) {
2257 'entity_table' => 'civicrm_contact',
2258 'entity_id' => $cId,
2259 'note' => 'hello I am testing Note',
2260 'contact_id' => $cId,
2261 'modified_date' => date('Ymd'),
2262 'subject' => 'Test Note',
2265 return $this->callAPISuccess('Note', 'create', $params);
2269 * Enable CiviCampaign Component.
2271 * @param bool $reloadConfig
2272 * Force relaod config or not
2274 public function enableCiviCampaign($reloadConfig = TRUE) {
2275 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2276 if ($reloadConfig) {
2277 // force reload of config object
2278 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2280 //flush cache by calling with reset
2281 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2285 * Create test generated example in api/v3/examples.
2287 * To turn this off (e.g. on the server) set
2288 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2289 * in your settings file
2291 * @param string $entity
2292 * @param string $action
2293 * @param array $params
2294 * Array as passed to civicrm_api function.
2295 * @param array $result
2296 * Array as received from the civicrm_api function.
2297 * @param string $testFunction
2298 * Calling function - generally __FUNCTION__.
2299 * @param string $testFile
2300 * Called from file - generally __FILE__.
2301 * @param string $description
2302 * Descriptive text for the example file.
2303 * @param string $exampleName
2304 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2306 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2307 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2310 $entity = _civicrm_api_get_camel_name($entity);
2311 $action = strtolower($action);
2313 if (empty($exampleName)) {
2314 // Attempt to convert lowercase action name to CamelCase.
2315 // This is clunky/imperfect due to the convention of all lowercase actions.
2316 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2317 $knownPrefixes = array(
2324 foreach ($knownPrefixes as $prefix) {
2325 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2326 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2331 $this->tidyExampleResult($result);
2332 if (isset($params['version'])) {
2333 unset($params['version']);
2335 // Format multiline description as array
2337 if (is_string($description) && strlen($description)) {
2338 foreach (explode("\n", $description) as $line) {
2339 $desc[] = trim($line);
2342 $smarty = CRM_Core_Smarty
::singleton();
2343 $smarty->assign('testFunction', $testFunction);
2344 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2345 foreach ($params as $index => $param) {
2346 if (is_string($param)) {
2347 $params[$index] = addslashes($param);
2350 $smarty->assign('params', $params);
2351 $smarty->assign('entity', $entity);
2352 $smarty->assign('testFile', basename($testFile));
2353 $smarty->assign('description', $desc);
2354 $smarty->assign('result', $result);
2355 $smarty->assign('action', $action);
2357 global $civicrm_root;
2358 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2359 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2360 mkdir($civicrm_root . "/api/v3/examples/$entity");
2362 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2363 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2369 * Tidy up examples array so that fields that change often ..don't
2370 * and debug related fields are unset
2372 * @param array $result
2374 public function tidyExampleResult(&$result) {
2375 if (!is_array($result)) {
2378 $fieldsToChange = array(
2379 'hash' => '67eac7789eaee00',
2380 'modified_date' => '2012-11-14 16:02:35',
2381 'created_date' => '2013-07-28 08:49:19',
2382 'create_date' => '20120130621222105',
2383 'application_received_date' => '20130728084957',
2384 'in_date' => '2013-07-28 08:50:19',
2385 'scheduled_date' => '20130728085413',
2386 'approval_date' => '20130728085413',
2387 'pledge_start_date_high' => '20130726090416',
2388 'start_date' => '2013-07-29 00:00:00',
2389 'event_start_date' => '2013-07-29 00:00:00',
2390 'end_date' => '2013-08-04 00:00:00',
2391 'event_end_date' => '2013-08-04 00:00:00',
2392 'decision_date' => '20130805000000',
2395 $keysToUnset = array('xdebug', 'undefined_fields');
2396 foreach ($keysToUnset as $unwantedKey) {
2397 if (isset($result[$unwantedKey])) {
2398 unset($result[$unwantedKey]);
2401 if (isset($result['values'])) {
2402 if (!is_array($result['values'])) {
2405 $resultArray = &$result['values'];
2407 elseif (is_array($result)) {
2408 $resultArray = &$result;
2414 foreach ($resultArray as $index => &$values) {
2415 if (!is_array($values)) {
2418 foreach ($values as $key => &$value) {
2419 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2420 if (isset($value['is_error'])) {
2421 // we have a std nested result format
2422 $this->tidyExampleResult($value);
2425 foreach ($value as &$nestedResult) {
2426 // this is an alternative syntax for nested results a keyed array of results
2427 $this->tidyExampleResult($nestedResult);
2431 if (in_array($key, $keysToUnset)) {
2432 unset($values[$key]);
2435 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2436 $value = $fieldsToChange[$key];
2438 if (is_string($value)) {
2439 $value = addslashes($value);
2446 * Create custom field with Option Values.
2448 * @param array $customGroup
2449 * @param string $name
2450 * Name of custom field.
2451 * @param array $extraParams
2452 * Additional parameters to pass through.
2456 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2457 $fieldParams = array(
2458 'custom_group_id' => $customGroup['id'],
2459 'name' => 'test_custom_group',
2460 'label' => 'Country',
2461 'html_type' => 'Select',
2462 'data_type' => 'String',
2465 'is_searchable' => 0,
2469 $optionGroup = array(
2471 'name' => 'option_group1',
2472 'label' => 'option_group_label1',
2475 $optionValue = array(
2476 'option_label' => array('Label1', 'Label2'),
2477 'option_value' => array('value1', 'value2'),
2478 'option_name' => array($name . '_1', $name . '_2'),
2479 'option_weight' => array(1, 2),
2480 'option_status' => 1,
2483 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2485 return $this->callAPISuccess('custom_field', 'create', $params);
2493 public function confirmEntitiesDeleted($entities) {
2494 foreach ($entities as $entity) {
2496 $result = $this->callAPISuccess($entity, 'Get', array());
2497 if ($result['error'] == 1 ||
$result['count'] > 0) {
2498 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2506 * Quick clean by emptying tables created for the test.
2508 * @param array $tablesToTruncate
2509 * @param bool $dropCustomValueTables
2510 * @throws \Exception
2512 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2514 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2516 if ($dropCustomValueTables) {
2517 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2518 while ($optionGroupResult->fetch()) {
2519 if (!empty($optionGroupResult->option_group_id
)) {
2520 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2523 $tablesToTruncate[] = 'civicrm_custom_group';
2524 $tablesToTruncate[] = 'civicrm_custom_field';
2527 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2529 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2530 foreach ($tablesToTruncate as $table) {
2531 $sql = "TRUNCATE TABLE $table";
2532 CRM_Core_DAO
::executeQuery($sql);
2534 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2536 if ($dropCustomValueTables) {
2537 $dbName = self
::getDBName();
2539 SELECT TABLE_NAME as tableName
2540 FROM INFORMATION_SCHEMA.TABLES
2541 WHERE TABLE_SCHEMA = '{$dbName}'
2542 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2545 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2546 while ($tableDAO->fetch()) {
2547 $sql = "DROP TABLE {$tableDAO->tableName}";
2548 CRM_Core_DAO
::executeQuery($sql);
2554 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2556 public function quickCleanUpFinancialEntities() {
2557 $tablesToTruncate = array(
2559 'civicrm_activity_contact',
2560 'civicrm_contribution',
2561 'civicrm_contribution_soft',
2562 'civicrm_contribution_product',
2563 'civicrm_financial_trxn',
2564 'civicrm_financial_item',
2565 'civicrm_contribution_recur',
2566 'civicrm_line_item',
2567 'civicrm_contribution_page',
2568 'civicrm_payment_processor',
2569 'civicrm_entity_financial_trxn',
2570 'civicrm_membership',
2571 'civicrm_membership_type',
2572 'civicrm_membership_payment',
2573 'civicrm_membership_log',
2574 'civicrm_membership_block',
2576 'civicrm_participant',
2577 'civicrm_participant_payment',
2579 'civicrm_pledge_payment',
2580 'civicrm_price_set_entity',
2581 'civicrm_price_field_value',
2582 'civicrm_price_field',
2584 $this->quickCleanup($tablesToTruncate);
2585 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2586 $this->restoreDefaultPriceSetConfig();
2588 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2589 $this->disableTaxAndInvoicing();
2590 System
::singleton()->flushProcessors();
2593 public function restoreDefaultPriceSetConfig() {
2594 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2595 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)");
2596 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)");
2599 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2600 * Default behaviour is to also delete the entity
2601 * @param array $params
2602 * Params array to check against.
2604 * Id of the entity concerned.
2605 * @param string $entity
2606 * Name of entity concerned (e.g. membership).
2607 * @param bool $delete
2608 * Should the entity be deleted as part of this check.
2609 * @param string $errorText
2610 * Text to print on error.
2613 * @param array $params
2616 * @param int $delete
2617 * @param string $errorText
2621 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2623 $result = $this->callAPISuccessGetSingle($entity, array(
2628 $this->callAPISuccess($entity, 'Delete', array(
2632 $dateFields = $keys = $dateTimeFields = array();
2633 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2634 foreach ($fields['values'] as $field => $settings) {
2635 if (array_key_exists($field, $result)) {
2636 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2639 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2641 $type = CRM_Utils_Array
::value('type', $settings);
2642 if ($type == CRM_Utils_Type
::T_DATE
) {
2643 $dateFields[] = $settings['name'];
2644 // we should identify both real names & unique names as dates
2645 if ($field != $settings['name']) {
2646 $dateFields[] = $field;
2649 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2650 $dateTimeFields[] = $settings['name'];
2651 // we should identify both real names & unique names as dates
2652 if ($field != $settings['name']) {
2653 $dateTimeFields[] = $field;
2658 if (strtolower($entity) == 'contribution') {
2659 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2660 // this is not returned in id format
2661 unset($params['payment_instrument_id']);
2662 $params['contribution_source'] = $params['source'];
2663 unset($params['source']);
2666 foreach ($params as $key => $value) {
2667 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2670 if (in_array($key, $dateFields)) {
2671 $value = date('Y-m-d', strtotime($value));
2672 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2674 if (in_array($key, $dateTimeFields)) {
2675 $value = date('Y-m-d H:i:s', strtotime($value));
2676 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2678 $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);
2683 * Get formatted values in the actual and expected result.
2684 * @param array $actual
2685 * Actual calculated values.
2686 * @param array $expected
2689 public function checkArrayEquals(&$actual, &$expected) {
2690 self
::unsetId($actual);
2691 self
::unsetId($expected);
2692 $this->assertEquals($actual, $expected);
2696 * Unset the key 'id' from the array
2697 * @param array $unformattedArray
2698 * The array from which the 'id' has to be unset.
2700 public static function unsetId(&$unformattedArray) {
2701 $formattedArray = array();
2702 if (array_key_exists('id', $unformattedArray)) {
2703 unset($unformattedArray['id']);
2705 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2706 foreach ($unformattedArray['values'] as $key => $value) {
2707 if (is_array($value)) {
2708 foreach ($value as $k => $v) {
2714 elseif ($key == 'id') {
2715 $unformattedArray[$key];
2717 $formattedArray = array($value);
2719 $unformattedArray['values'] = $formattedArray;
2724 * Helper to enable/disable custom directory support
2726 * @param array $customDirs
2728 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2729 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2731 public function customDirectories($customDirs) {
2732 $config = CRM_Core_Config
::singleton();
2734 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2735 unset($config->customPHPPathDir
);
2737 elseif ($customDirs['php_path'] === TRUE) {
2738 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2741 $config->customPHPPathDir
= $php_path;
2744 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2745 unset($config->customTemplateDir
);
2747 elseif ($customDirs['template_path'] === TRUE) {
2748 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2751 $config->customTemplateDir
= $template_path;
2756 * Generate a temporary folder.
2758 * @param string $prefix
2761 public function createTempDir($prefix = 'test-') {
2762 $tempDir = CRM_Utils_File
::tempdir($prefix);
2763 $this->tempDirs
[] = $tempDir;
2767 public function cleanTempDirs() {
2768 if (!is_array($this->tempDirs
)) {
2769 // fix test errors where this is not set
2772 foreach ($this->tempDirs
as $tempDir) {
2773 if (is_dir($tempDir)) {
2774 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2780 * Temporarily replace the singleton extension with a different one.
2781 * @param \CRM_Extension_System $system
2783 public function setExtensionSystem(CRM_Extension_System
$system) {
2784 if ($this->origExtensionSystem
== NULL) {
2785 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2787 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2790 public function unsetExtensionSystem() {
2791 if ($this->origExtensionSystem
!== NULL) {
2792 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2793 $this->origExtensionSystem
= NULL;
2798 * Temporarily alter the settings-metadata to add a mock setting.
2800 * WARNING: The setting metadata will disappear on the next cache-clear.
2805 public function setMockSettingsMetaData($extras) {
2806 Civi
::service('settings_manager')->flush();
2808 CRM_Utils_Hook
::singleton()
2809 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2810 $metadata = array_merge($metadata, $extras);
2813 $fields = $this->callAPISuccess('setting', 'getfields', array());
2814 foreach ($extras as $key => $spec) {
2815 $this->assertNotEmpty($spec['title']);
2816 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2821 * @param string $name
2823 public function financialAccountDelete($name) {
2824 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2825 $financialAccount->name
= $name;
2826 if ($financialAccount->find(TRUE)) {
2827 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2828 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2829 $entityFinancialType->delete();
2830 $financialAccount->delete();
2835 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2836 * (NB unclear if this is still required)
2838 public function _sethtmlGlobals() {
2839 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2840 'required' => array(
2841 'html_quickform_rule_required',
2842 'HTML/QuickForm/Rule/Required.php',
2844 'maxlength' => array(
2845 'html_quickform_rule_range',
2846 'HTML/QuickForm/Rule/Range.php',
2848 'minlength' => array(
2849 'html_quickform_rule_range',
2850 'HTML/QuickForm/Rule/Range.php',
2852 'rangelength' => array(
2853 'html_quickform_rule_range',
2854 'HTML/QuickForm/Rule/Range.php',
2857 'html_quickform_rule_email',
2858 'HTML/QuickForm/Rule/Email.php',
2861 'html_quickform_rule_regex',
2862 'HTML/QuickForm/Rule/Regex.php',
2864 'lettersonly' => array(
2865 'html_quickform_rule_regex',
2866 'HTML/QuickForm/Rule/Regex.php',
2868 'alphanumeric' => array(
2869 'html_quickform_rule_regex',
2870 'HTML/QuickForm/Rule/Regex.php',
2873 'html_quickform_rule_regex',
2874 'HTML/QuickForm/Rule/Regex.php',
2876 'nopunctuation' => array(
2877 'html_quickform_rule_regex',
2878 'HTML/QuickForm/Rule/Regex.php',
2881 'html_quickform_rule_regex',
2882 'HTML/QuickForm/Rule/Regex.php',
2884 'callback' => array(
2885 'html_quickform_rule_callback',
2886 'HTML/QuickForm/Rule/Callback.php',
2889 'html_quickform_rule_compare',
2890 'HTML/QuickForm/Rule/Compare.php',
2893 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2894 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2896 'HTML/QuickForm/group.php',
2897 'HTML_QuickForm_group',
2900 'HTML/QuickForm/hidden.php',
2901 'HTML_QuickForm_hidden',
2904 'HTML/QuickForm/reset.php',
2905 'HTML_QuickForm_reset',
2907 'checkbox' => array(
2908 'HTML/QuickForm/checkbox.php',
2909 'HTML_QuickForm_checkbox',
2912 'HTML/QuickForm/file.php',
2913 'HTML_QuickForm_file',
2916 'HTML/QuickForm/image.php',
2917 'HTML_QuickForm_image',
2919 'password' => array(
2920 'HTML/QuickForm/password.php',
2921 'HTML_QuickForm_password',
2924 'HTML/QuickForm/radio.php',
2925 'HTML_QuickForm_radio',
2928 'HTML/QuickForm/button.php',
2929 'HTML_QuickForm_button',
2932 'HTML/QuickForm/submit.php',
2933 'HTML_QuickForm_submit',
2936 'HTML/QuickForm/select.php',
2937 'HTML_QuickForm_select',
2939 'hiddenselect' => array(
2940 'HTML/QuickForm/hiddenselect.php',
2941 'HTML_QuickForm_hiddenselect',
2944 'HTML/QuickForm/text.php',
2945 'HTML_QuickForm_text',
2947 'textarea' => array(
2948 'HTML/QuickForm/textarea.php',
2949 'HTML_QuickForm_textarea',
2951 'fckeditor' => array(
2952 'HTML/QuickForm/fckeditor.php',
2953 'HTML_QuickForm_FCKEditor',
2956 'HTML/QuickForm/tinymce.php',
2957 'HTML_QuickForm_TinyMCE',
2959 'dojoeditor' => array(
2960 'HTML/QuickForm/dojoeditor.php',
2961 'HTML_QuickForm_dojoeditor',
2964 'HTML/QuickForm/link.php',
2965 'HTML_QuickForm_link',
2967 'advcheckbox' => array(
2968 'HTML/QuickForm/advcheckbox.php',
2969 'HTML_QuickForm_advcheckbox',
2972 'HTML/QuickForm/date.php',
2973 'HTML_QuickForm_date',
2976 'HTML/QuickForm/static.php',
2977 'HTML_QuickForm_static',
2980 'HTML/QuickForm/header.php',
2981 'HTML_QuickForm_header',
2984 'HTML/QuickForm/html.php',
2985 'HTML_QuickForm_html',
2987 'hierselect' => array(
2988 'HTML/QuickForm/hierselect.php',
2989 'HTML_QuickForm_hierselect',
2991 'autocomplete' => array(
2992 'HTML/QuickForm/autocomplete.php',
2993 'HTML_QuickForm_autocomplete',
2996 'HTML/QuickForm/xbutton.php',
2997 'HTML_QuickForm_xbutton',
2999 'advmultiselect' => array(
3000 'HTML/QuickForm/advmultiselect.php',
3001 'HTML_QuickForm_advmultiselect',
3007 * Set up an acl allowing contact to see 2 specified groups
3008 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3010 * You need to have pre-created these groups & created the user e.g
3011 * $this->createLoggedInUser();
3012 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3013 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3015 * @param bool $isProfile
3017 public function setupACL($isProfile = FALSE) {
3019 $_REQUEST = $this->_params
;
3021 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3022 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3023 $ov = new CRM_Core_DAO_OptionValue();
3024 $ov->option_group_id
= $optionGroupID;
3026 if ($ov->find(TRUE)) {
3027 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
3029 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3030 'option_group_id' => $optionGroupID,
3031 'label' => 'pick me',
3035 CRM_Core_DAO
::executeQuery("
3036 TRUNCATE civicrm_acl_cache
3039 CRM_Core_DAO
::executeQuery("
3040 TRUNCATE civicrm_acl_contact_cache
3043 CRM_Core_DAO
::executeQuery("
3044 INSERT INTO civicrm_acl_entity_role (
3045 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3046 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 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_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3060 CRM_Core_DAO
::executeQuery("
3061 INSERT INTO civicrm_acl (
3062 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3065 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3069 CRM_Core_DAO
::executeQuery("
3070 INSERT INTO civicrm_acl (
3071 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3074 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3079 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3080 $this->callAPISuccess('group_contact', 'create', array(
3081 'group_id' => $this->_permissionedGroup
,
3082 'contact_id' => $this->_loggedInUser
,
3087 CRM_ACL_BAO_Cache
::resetCache();
3088 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3089 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3094 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3096 public function offsetDefaultPriceSet() {
3097 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3098 $firstID = $contributionPriceSet['id'];
3099 $this->callAPISuccess('price_set', 'create', array(
3100 'id' => $contributionPriceSet['id'],
3104 unset($contributionPriceSet['id']);
3105 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3106 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3107 'price_set_id' => $firstID,
3108 'options' => array('limit' => 1),
3110 unset($priceField['id']);
3111 $priceField['price_set_id'] = $newPriceSet['id'];
3112 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3113 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3114 'price_set_id' => $firstID,
3116 'options' => array('limit' => 1),
3119 unset($priceFieldValue['id']);
3120 //create some padding to use up ids
3121 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3122 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3123 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3127 * Create an instance of the paypal processor.
3128 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3129 * this parent class & we don't have a structure for that yet
3130 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3131 * & the best protection against that is the functions this class affords
3132 * @param array $params
3133 * @return int $result['id'] payment processor id
3135 public function paymentProcessorCreate($params = array()) {
3136 $params = array_merge(array(
3138 'domain_id' => CRM_Core_Config
::domainID(),
3139 'payment_processor_type_id' => 'PayPal',
3143 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3144 'password' => '1183377788',
3145 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3146 'url_site' => 'https://www.sandbox.paypal.com/',
3147 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3148 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3149 'class_name' => 'Payment_PayPalImpl',
3150 'billing_mode' => 3,
3151 'financial_type_id' => 1,
3152 'financial_account_id' => 12,
3153 // Credit card = 1 so can pass 'by accident'.
3154 'payment_instrument_id' => 'Debit Card',
3157 if (!is_numeric($params['payment_processor_type_id'])) {
3158 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3160 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3161 'name' => $params['payment_processor_type_id'],
3165 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3166 return $result['id'];
3170 * Set up initial recurring payment allowing subsequent IPN payments.
3172 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3173 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3174 'contact_id' => $this->_contactID
,
3177 'installments' => 5,
3178 'frequency_unit' => 'Month',
3179 'frequency_interval' => 1,
3180 'invoice_id' => $this->_invoiceID
,
3181 'contribution_status_id' => 2,
3182 'payment_processor_id' => $this->_paymentProcessorID
,
3183 // processor provided ID - use contact ID as proxy.
3184 'processor_id' => $this->_contactID
,
3185 'api.contribution.create' => array(
3186 'total_amount' => '200',
3187 'invoice_id' => $this->_invoiceID
,
3188 'financial_type_id' => 1,
3189 'contribution_status_id' => 'Pending',
3190 'contact_id' => $this->_contactID
,
3191 'contribution_page_id' => $this->_contributionPageID
,
3192 'payment_processor_id' => $this->_paymentProcessorID
,
3196 $this->_contributionRecurID
= $contributionRecur['id'];
3197 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3201 * 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
3203 public function setupMembershipRecurringPaymentProcessorTransaction() {
3204 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3205 //create a contribution so our membership & contribution don't both have id = 1
3206 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3207 $this->contributionCreate(array(
3208 'contact_id' => $this->_contactID
,
3210 'financial_type_id' => 1,
3211 'invoice_id' => 'abcd',
3215 $this->setupRecurringPaymentProcessorTransaction();
3217 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3218 'contact_id' => $this->_contactID
,
3219 'membership_type_id' => $this->ids
['membership_type'],
3220 'contribution_recur_id' => $this->_contributionRecurID
,
3221 'format.only_id' => TRUE,
3223 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3224 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3226 $this->callAPISuccess('line_item', 'create', array(
3227 'entity_table' => 'civicrm_membership',
3228 'entity_id' => $this->ids
['membership'],
3229 'contribution_id' => $this->_contributionID
,
3230 'label' => 'General',
3232 'unit_price' => 200,
3233 'line_total' => 200,
3234 'financial_type_id' => 1,
3235 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3237 'label' => 'Membership Amount',
3238 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3240 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3242 'label' => 'General',
3243 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3246 $this->callAPISuccess('membership_payment', 'create', array(
3247 'contribution_id' => $this->_contributionID
,
3248 'membership_id' => $this->ids
['membership'],
3257 public function CiviUnitTestCase_fatalErrorHandler($message) {
3258 throw new Exception("{$message['message']}: {$message['code']}");
3262 * Helper function to create new mailing.
3264 * @param array $params
3268 public function createMailing($params = array()) {
3269 $params = array_merge(array(
3270 'subject' => 'maild' . rand(),
3271 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3272 'name' => 'mailing name' . rand(),
3276 $result = $this->callAPISuccess('Mailing', 'create', $params);
3277 return $result['id'];
3281 * Helper function to delete mailing.
3284 public function deleteMailing($id) {
3289 $this->callAPISuccess('Mailing', 'delete', $params);
3293 * Wrap the entire test case in a transaction.
3295 * Only subsequent DB statements will be wrapped in TX -- this cannot
3296 * retroactively wrap old DB statements. Therefore, it makes sense to
3297 * call this at the beginning of setUp().
3299 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3300 * this option does not work with, e.g., custom-data.
3302 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3303 * if TRUNCATE or ALTER is called while using a transaction.
3306 * Whether to use nesting or reference-counting.
3308 public function useTransaction($nest = TRUE) {
3310 $this->tx
= new CRM_Core_Transaction($nest);
3311 $this->tx
->rollback();
3316 * Assert the attachment exists.
3318 * @param bool $exists
3319 * @param array $apiResult
3321 protected function assertAttachmentExistence($exists, $apiResult) {
3322 $fileId = $apiResult['id'];
3323 $this->assertTrue(is_numeric($fileId));
3324 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3325 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3326 1 => array($fileId, 'Int'),
3328 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3329 1 => array($fileId, 'Int'),
3334 * Create a price set for an event.
3336 * @param int $feeTotal
3337 * @param int $minAmt
3338 * @param string $type
3343 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3344 // creating price set, price field
3345 $paramsSet['title'] = 'Price Set';
3346 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3347 $paramsSet['is_active'] = FALSE;
3348 $paramsSet['extends'] = 1;
3349 $paramsSet['min_amount'] = $minAmt;
3351 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
3352 $this->_ids
['price_set'] = $priceSet->id
;
3354 $paramsField = array(
3355 'label' => 'Price Field',
3356 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3357 'html_type' => $type,
3358 'price' => $feeTotal,
3359 'option_label' => array('1' => 'Price Field'),
3360 'option_value' => array('1' => $feeTotal),
3361 'option_name' => array('1' => $feeTotal),
3362 'option_weight' => array('1' => 1),
3363 'option_amount' => array('1' => 1),
3364 'is_display_amounts' => 1,
3366 'options_per_line' => 1,
3367 'is_active' => array('1' => 1),
3368 'price_set_id' => $this->_ids
['price_set'],
3369 'is_enter_qty' => 1,
3370 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3372 if ($type === 'Radio') {
3373 $paramsField['is_enter_qty'] = 0;
3374 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3375 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3377 CRM_Price_BAO_PriceField
::create($paramsField);
3378 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
3379 $this->_ids
['price_field'] = array_keys($fields['values']);
3380 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
3381 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
3383 return $this->_ids
['price_set'];
3387 * Add a profile to a contribution page.
3389 * @param string $name
3390 * @param int $contributionPageID
3392 protected function addProfile($name, $contributionPageID) {
3393 $this->callAPISuccess('UFJoin', 'create', array(
3394 'uf_group_id' => $name,
3395 'module' => 'CiviContribute',
3396 'entity_table' => 'civicrm_contribution_page',
3397 'entity_id' => $contributionPageID,
3403 * Add participant with contribution
3407 protected function createParticipantWithContribution() {
3408 // creating price set, price field
3409 $this->_contactId
= $this->individualCreate();
3410 $event = $this->eventCreate();
3411 $this->_eventId
= $event['id'];
3412 $eventParams = array(
3413 'id' => $this->_eventId
,
3414 'financial_type_id' => 4,
3417 $this->callAPISuccess('event', 'create', $eventParams);
3418 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3419 $participantParams = array(
3420 'financial_type_id' => 4,
3421 'event_id' => $this->_eventId
,
3424 'fee_currency' => 'USD',
3425 'contact_id' => $this->_contactId
,
3427 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3428 $contributionParams = array(
3429 'total_amount' => 150,
3430 'currency' => 'USD',
3431 'contact_id' => $this->_contactId
,
3432 'financial_type_id' => 4,
3433 'contribution_status_id' => 1,
3434 'partial_payment_total' => 300.00,
3435 'partial_amount_to_pay' => 150,
3436 'contribution_mode' => 'participant',
3437 'participant_id' => $participant['id'],
3439 foreach ($priceFields['values'] as $key => $priceField) {
3440 $lineItems[1][$key] = array(
3441 'price_field_id' => $priceField['price_field_id'],
3442 'price_field_value_id' => $priceField['id'],
3443 'label' => $priceField['label'],
3444 'field_title' => $priceField['label'],
3446 'unit_price' => $priceField['amount'],
3447 'line_total' => $priceField['amount'],
3448 'financial_type_id' => $priceField['financial_type_id'],
3451 $contributionParams['line_item'] = $lineItems;
3452 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3453 $paymentParticipant = array(
3454 'participant_id' => $participant['id'],
3455 'contribution_id' => $contribution['id'],
3457 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3458 return array($lineItems, $contribution);
3464 * @param string $component
3465 * @param int $componentId
3469 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3470 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3471 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3472 $paramsSet['is_active'] = TRUE;
3473 $paramsSet['financial_type_id'] = 4;
3474 $paramsSet['extends'] = 1;
3475 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3476 $priceSetId = $priceSet['id'];
3477 //Checking for priceset added in the table.
3478 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3479 'id', $paramsSet['title'], 'Check DB for created priceset'
3481 $paramsField = array_merge(array(
3482 'label' => 'Price Field',
3483 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3484 'html_type' => 'CheckBox',
3485 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3486 'option_value' => array('1' => 100, '2' => 200),
3487 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3488 'option_weight' => array('1' => 1, '2' => 2),
3489 'option_amount' => array('1' => 100, '2' => 200),
3490 'is_display_amounts' => 1,
3492 'options_per_line' => 1,
3493 'is_active' => array('1' => 1, '2' => 1),
3494 'price_set_id' => $priceSet['id'],
3495 'is_enter_qty' => 1,
3496 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3497 ), $priceFieldOptions);
3499 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3501 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3503 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3507 * Replace the template with a test-oriented template designed to show all the variables.
3509 * @param string $templateName
3511 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3512 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3513 CRM_Core_DAO
::executeQuery(
3514 "UPDATE civicrm_option_group og
3515 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3516 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3517 SET m.msg_html = '{$testTemplate}'
3518 WHERE og.name = 'msg_tpl_workflow_contribution'
3519 AND ov.name = '{$templateName}'
3520 AND m.is_default = 1"
3525 * Reinstate the default template.
3527 * @param string $templateName
3529 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3530 CRM_Core_DAO
::executeQuery(
3531 "UPDATE civicrm_option_group og
3532 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3533 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3534 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3535 SET m.msg_html = m2.msg_html
3536 WHERE og.name = 'msg_tpl_workflow_contribution'
3537 AND ov.name = '{$templateName}'
3538 AND m.is_default = 1"
3543 * Flush statics relating to financial type.
3545 protected function flushFinancialTypeStatics() {
3546 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3547 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3549 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3550 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3552 CRM_Contribute_PseudoConstant
::flush('financialType');
3553 CRM_Contribute_PseudoConstant
::flush('membershipType');
3554 // Pseudoconstants may be saved to the cache table.
3555 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3556 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3557 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3561 * Set the permissions to the supplied array.
3563 * @param array $permissions
3565 protected function setPermissions($permissions) {
3566 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3567 $this->flushFinancialTypeStatics();
3568 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3572 * @param array $params
3575 public function _checkFinancialRecords($params, $context) {
3576 $entityParams = array(
3577 'entity_id' => $params['id'],
3578 'entity_table' => 'civicrm_contribution',
3580 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3581 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3582 if ($context == 'pending') {
3583 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3584 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3587 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3588 $trxnParams = array(
3589 'id' => $trxn['financial_trxn_id'],
3591 if ($context != 'online' && $context != 'payLater') {
3592 $compareParams = array(
3593 'to_financial_account_id' => 6,
3594 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3598 if ($context == 'feeAmount') {
3599 $compareParams['fee_amount'] = 50;
3601 elseif ($context == 'online') {
3602 $compareParams = array(
3603 'to_financial_account_id' => 12,
3604 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3606 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3609 elseif ($context == 'payLater') {
3610 $compareParams = array(
3611 'to_financial_account_id' => 7,
3612 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3616 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3617 $entityParams = array(
3618 'financial_trxn_id' => $trxn['financial_trxn_id'],
3619 'entity_table' => 'civicrm_financial_item',
3621 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3622 $fitemParams = array(
3623 'id' => $entityTrxn['entity_id'],
3625 $compareParams = array(
3626 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3628 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3630 if ($context == 'payLater') {
3631 $compareParams = array(
3632 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3634 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3637 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3638 if ($context == 'feeAmount') {
3640 'entity_id' => $params['id'],
3641 'entity_table' => 'civicrm_contribution',
3643 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3644 $trxnParams = array(
3645 'id' => $maxTrxn['financial_trxn_id'],
3647 $compareParams = array(
3648 'to_financial_account_id' => 5,
3649 'from_financial_account_id' => 6,
3650 'total_amount' => 50,
3653 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3654 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3655 $fitemParams = array(
3656 'entity_id' => $trxnId['financialTrxnId'],
3657 'entity_table' => 'civicrm_financial_trxn',
3659 $compareParams = array(
3662 'financial_account_id' => 5,
3664 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3666 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3667 // line should be copied into all the functions that call this function & evaluated there
3668 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3669 // when calling completeTransaction or repeatTransaction.
3670 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3674 * Return financial type id on basis of name
3676 * @param string $name Financial type m/c name
3680 public function getFinancialTypeId($name) {
3681 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3685 * Cleanup function for contents of $this->ids.
3687 * This is a best effort cleanup to use in tear downs etc.
3689 * It will not fail if the data has already been removed (some tests may do
3690 * their own cleanup).
3692 protected function cleanUpSetUpIDs() {
3693 foreach ($this->setupIDs
as $entity => $id) {
3695 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3697 catch (CiviCRM_API3_Exception
$e) {
3698 // This is a best-effort cleanup function, ignore.
3704 * Create Financial Type.
3706 * @param array $params
3710 protected function createFinancialType($params = array()) {
3711 $params = array_merge($params,
3713 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3717 return $this->callAPISuccess('FinancialType', 'create', $params);
3721 * Enable Tax and Invoicing
3723 protected function enableTaxAndInvoicing($params = array()) {
3724 // Enable component contribute setting
3725 $contributeSetting = array_merge($params,
3728 'invoice_prefix' => 'INV_',
3729 'credit_notes_prefix' => 'CN_',
3731 'due_date_period' => 'days',
3733 'is_email_pdf' => 1,
3734 'tax_term' => 'Sales Tax',
3735 'tax_display_settings' => 'Inclusive',
3738 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3742 * Enable Tax and Invoicing
3744 protected function disableTaxAndInvoicing($params = array()) {
3745 // Enable component contribute setting
3746 $contributeSetting = array_merge($params,
3751 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3755 * Add Sales Tax relation for financial type with financial account.
3757 * @param int $financialTypeId
3761 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3763 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3764 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3765 'is_deductible' => 1,
3770 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3771 $entityParams = array(
3772 'entity_table' => 'civicrm_financial_type',
3773 'entity_id' => $financialTypeId,
3774 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3777 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3778 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3779 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3780 $dao->copyValues($entityParams);
3782 if ($dao->fetch()) {
3783 $entityParams['id'] = $dao->id
;
3785 $entityParams['financial_account_id'] = $account->id
;
3787 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3791 * Create price set with contribution test for test setup.
3793 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3794 * on parent class at some point (fn is not in 4.4).
3797 * @param array $params
3799 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3800 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3801 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3802 'title' => "Test Contribution Page",
3803 'financial_type_id' => 1,
3804 'currency' => 'NZD',
3805 'goal_amount' => 50,
3806 'is_pay_later' => 1,
3807 'is_monetary' => TRUE,
3808 'is_email_receipt' => FALSE,
3810 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3811 'is_quick_config' => 0,
3812 'extends' => 'CiviMember',
3813 'financial_type_id' => 1,
3814 'title' => 'my Page',
3816 $priceSetID = $priceSet['id'];
3818 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3819 $priceField = $this->callAPISuccess('price_field', 'create', array(
3820 'price_set_id' => $priceSetID,
3821 'label' => 'Goat Breed',
3822 'html_type' => 'Radio',
3824 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3825 'price_set_id' => $priceSetID,
3826 'price_field_id' => $priceField['id'],
3827 'label' => 'Long Haired Goat',
3829 'financial_type_id' => 'Donation',
3830 'membership_type_id' => $membershipTypeID,
3831 'membership_num_terms' => 1,
3834 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3835 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3836 'price_set_id' => $priceSetID,
3837 'price_field_id' => $priceField['id'],
3838 'label' => 'Shoe-eating Goat',
3840 'financial_type_id' => 'Donation',
3841 'membership_type_id' => $membershipTypeID,
3842 'membership_num_terms' => 2,
3845 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3847 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3848 'price_set_id' => $priceSetID,
3849 'price_field_id' => $priceField['id'],
3850 'label' => 'Shoe-eating Goat',
3852 'financial_type_id' => 'Donation',
3855 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3857 $this->_ids
['price_set'] = $priceSetID;
3858 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3859 $this->_ids
['price_field'] = array($priceField['id']);
3861 $this->_ids
['membership_type'] = $membershipTypeID;
3865 * No results returned.
3867 * @implements CRM_Utils_Hook::aclWhereClause
3869 * @param string $type
3870 * @param array $tables
3871 * @param array $whereTables
3872 * @param int $contactID
3873 * @param string $where
3875 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3879 * Only specified contact returned.
3880 * @implements CRM_Utils_Hook::aclWhereClause
3883 * @param $whereTables
3887 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3888 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3892 * @implements CRM_Utils_Hook::selectWhereClause
3894 * @param string $entity
3895 * @param array $clauses
3897 public function selectWhereClauseHook($entity, &$clauses) {
3898 if ($entity == 'Event') {
3899 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3904 * An implementation of hook_civicrm_post used with all our test cases.
3907 * @param string $objectName
3908 * @param int $objectId
3911 public function onPost($op, $objectName, $objectId, &$objectRef) {
3912 if ($op == 'create' && $objectName == 'Individual') {
3913 CRM_Core_DAO
::executeQuery(
3914 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3916 1 => array($objectId, 'Integer'),
3921 if ($op == 'edit' && $objectName == 'Participant') {
3923 1 => array($objectId, 'Integer'),
3925 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3926 CRM_Core_DAO
::executeQuery($query, $params);
3932 * Instantiate form object.
3934 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3936 * @param string $class
3937 * Name of form class.
3939 * @return \CRM_Core_Form
3941 public function getFormObject($class) {
3942 $form = new $class();
3943 $_SERVER['REQUEST_METHOD'] = 'GET';
3944 $form->controller
= new CRM_Core_Controller();