3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
32 * Include class definitions
34 require_once 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
57 * Api version - easier to override than just a define
59 protected $_apiversion = API_LATEST_VERSION
;
61 * Database has been initialized.
65 private static $dbInit = FALSE;
68 * Does the current setup support ONLY_FULL_GROUP_BY mode
70 protected $_supportFullGroupBy;
73 * Database connection.
75 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
84 static protected $_dbName;
87 * Track tables we have modified during a test.
89 protected $_tablesToTruncate = array();
92 * @var array of temporary directory names
97 * @var boolean populateOnce allows to skip db resets in setUp
99 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
100 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
103 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
105 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
107 public static $populateOnce = FALSE;
110 * @var boolean DBResetRequired allows skipping DB reset
111 * in specific test case. If you still need
112 * to reset single test (method) of such case, call
113 * $this->cleanDB() in the first line of this
116 public $DBResetRequired = TRUE;
119 * @var CRM_Core_Transaction|NULL
124 * @var CRM_Utils_Hook_UnitTests hookClass
125 * example of setting a method for a hook
126 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
128 public $hookClass = NULL;
131 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
133 protected $_params = array();
136 * @var CRM_Extension_System
138 protected $origExtensionSystem;
141 * Array of IDs created during test setup routine.
143 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
147 public $setupIDs = array();
152 * Because we are overriding the parent class constructor, we
153 * need to show the same arguments as exist in the constructor of
154 * PHPUnit_Framework_TestCase, since
155 * PHPUnit_Framework_TestSuite::createTest() creates a
156 * ReflectionClass of the Test class and checks the constructor
157 * of that class to decide how to set up the test.
159 * @param string $name
161 * @param string $dataName
163 public function __construct($name = NULL, array$data = array(), $dataName = '') {
164 parent
::__construct($name, $data, $dataName);
166 // we need full error reporting
167 error_reporting(E_ALL
& ~E_NOTICE
);
169 self
::$_dbName = self
::getDBName();
171 // also load the class loader
172 require_once 'CRM/Core/ClassLoader.php';
173 CRM_Core_ClassLoader
::singleton()->register();
174 if (function_exists('_civix_phpunit_setUp')) {
175 // FIXME: loosen coupling
176 _civix_phpunit_setUp();
181 * Override to run the test and assert its state.
184 * @throws \PHPUnit_Framework_IncompleteTest
185 * @throws \PHPUnit_Framework_SkippedTest
187 protected function runTest() {
189 return parent
::runTest();
191 catch (PEAR_Exception
$e) {
192 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
193 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
200 public function requireDBReset() {
201 return $this->DBResetRequired
;
207 public static function getDBName() {
208 static $dbName = NULL;
209 if ($dbName === NULL) {
210 require_once "DB.php";
211 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
212 $dbName = $dsninfo['database'];
218 * Create database connection for this instance.
220 * Initialize the test database if it hasn't been initialized
222 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
224 protected function getConnection() {
225 $dbName = self
::$_dbName;
226 if (!self
::$dbInit) {
227 $dbName = self
::getDBName();
229 // install test database
230 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
232 static::_populateDB(FALSE, $this);
234 self
::$dbInit = TRUE;
237 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
241 * Required implementation of abstract method.
243 protected function getDataSet() {
247 * @param bool $perClass
248 * @param null $object
250 * TRUE if the populate logic runs; FALSE if it is skipped
252 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
253 if (CIVICRM_UF
!== 'UnitTests') {
254 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
257 if ($perClass ||
$object == NULL) {
261 $dbreset = $object->requireDBReset();
264 if (self
::$populateOnce ||
!$dbreset) {
267 self
::$populateOnce = NULL;
269 Civi\Test
::data()->populate();
274 public static function setUpBeforeClass() {
275 static::_populateDB(TRUE);
277 // also set this global hack
278 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
282 * Common setup functions for all unit tests.
284 protected function setUp() {
285 $session = CRM_Core_Session
::singleton();
286 $session->set('userID', NULL);
288 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
289 // Use a temporary file for STDIN
290 $GLOBALS['stdin'] = tmpfile();
291 if ($GLOBALS['stdin'] === FALSE) {
292 echo "Couldn't open temporary file\n";
296 // Get and save a connection to the database
297 $this->_dbconn
= $this->getConnection();
299 $this->_supportFullGroupBy
= CRM_Utils_SQL
::supportsFullGroupBy();
301 // reload database before each test
302 // $this->_populateDB();
304 // "initialize" CiviCRM to avoid problems when running single tests
305 // FIXME: look at it closer in second stage
307 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
308 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
310 // disable any left-over test extensions
311 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
313 // reset all the caches
314 CRM_Utils_System
::flushCache();
316 // initialize the object once db is loaded
318 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
320 // when running unit tests, use mockup user framework
321 $this->hookClass
= CRM_Utils_Hook
::singleton();
323 // Make sure the DB connection is setup properly
324 $config->userSystem
->setMySQLTimeZone();
325 $env = new CRM_Utils_Check_Component_Env();
326 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
328 // clear permissions stub to not check permissions
329 $config->userPermissionClass
->permissions
= NULL;
331 //flush component settings
332 CRM_Core_Component
::getEnabledComponents(TRUE);
334 error_reporting(E_ALL
);
336 $this->_sethtmlGlobals();
340 * Read everything from the datasets directory and insert into the db.
342 public function loadAllFixtures() {
343 $fixturesDir = __DIR__
. '/../../fixtures';
345 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
347 $xmlFiles = glob($fixturesDir . '/*.xml');
348 foreach ($xmlFiles as $xmlFixture) {
349 $op = new PHPUnit_Extensions_Database_Operation_Insert();
350 $dataset = $this->createXMLDataSet($xmlFixture);
351 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
352 $op->execute($this->_dbconn
, $dataset);
355 $yamlFiles = glob($fixturesDir . '/*.yaml');
356 foreach ($yamlFiles as $yamlFixture) {
357 $op = new PHPUnit_Extensions_Database_Operation_Insert();
358 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
359 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
360 $op->execute($this->_dbconn
, $dataset);
363 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
367 * Emulate a logged in user since certain functions use that.
368 * value to store a record in the DB (like activity)
372 * Contact ID of the created user.
374 public function createLoggedInUser() {
376 'first_name' => 'Logged In',
377 'last_name' => 'User ' . rand(),
378 'contact_type' => 'Individual',
380 $contactID = $this->individualCreate($params);
381 $this->callAPISuccess('UFMatch', 'create', array(
382 'contact_id' => $contactID,
383 'uf_name' => 'superman',
387 $session = CRM_Core_Session
::singleton();
388 $session->set('userID', $contactID);
393 * Create default domain contacts for the two domains added during test class.
394 * database population.
396 public function createDomainContacts() {
397 $this->organizationCreate();
398 $this->organizationCreate(array('organization_name' => 'Second Domain'));
402 * Common teardown functions for all unit tests.
404 protected function tearDown() {
405 error_reporting(E_ALL
& ~E_NOTICE
);
406 CRM_Utils_Hook
::singleton()->reset();
407 $this->hookClass
->reset();
408 $session = CRM_Core_Session
::singleton();
409 $session->set('userID', NULL);
412 $this->tx
->rollback()->commit();
415 CRM_Core_Transaction
::forceRollbackIfEnabled();
416 \Civi\Core\Transaction\Manager
::singleton(TRUE);
419 CRM_Core_Transaction
::forceRollbackIfEnabled();
420 \Civi\Core\Transaction\Manager
::singleton(TRUE);
422 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
423 $this->quickCleanup($tablesToTruncate);
424 $this->createDomainContacts();
427 $this->cleanTempDirs();
428 $this->unsetExtensionSystem();
432 * Generic function to compare expected values after an api call to retrieved.
435 * @daoName string DAO Name of object we're evaluating.
436 * @id int Id of object
437 * @match array Associative array of field name => expected value. Empty if asserting
438 * that a DELETE occurred
439 * @delete boolean True if we're checking that a DELETE action occurred.
443 * @param bool $delete
444 * @throws \PHPUnit_Framework_AssertionFailedError
446 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
448 // adding this here since developers forget to check for an id
449 // and hence we get the first value in the db
450 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
453 $object = new $daoName();
457 // If we're asserting successful record deletion, make sure object is NOT found.
459 if ($object->find(TRUE)) {
460 $this->fail("Object not deleted by delete operation: $daoName, $id");
465 // Otherwise check matches of DAO field values against expected values in $match.
466 if ($object->find(TRUE)) {
467 $fields = &$object->fields();
468 foreach ($fields as $name => $value) {
469 $dbName = $value['name'];
470 if (isset($match[$name])) {
472 $this->assertEquals($object->$dbName, $match[$name]);
474 elseif (isset($match[$dbName])) {
476 $this->assertEquals($object->$dbName, $match[$dbName]);
481 $this->fail("Could not retrieve object: $daoName, $id");
484 $matchSize = count($match);
485 if ($verifiedCount != $matchSize) {
486 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
491 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
492 * @param string $daoName
493 * @param $searchValue
494 * @param $returnColumn
495 * @param $searchColumn
498 * @return null|string
499 * @throws PHPUnit_Framework_AssertionFailedError
501 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
502 if (empty($searchValue)) {
503 $this->fail("empty value passed to assertDBNotNull");
505 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
506 $this->assertNotNull($value, $message);
512 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
513 * @param string $daoName
514 * @param $searchValue
515 * @param $returnColumn
516 * @param $searchColumn
519 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
520 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
521 $this->assertNull($value, $message);
525 * Request a record from the DB by id. Success if row not found.
526 * @param string $daoName
528 * @param null $message
530 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
531 $message = $message ?
$message : "$daoName (#$id) should not exist";
532 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
533 $this->assertNull($value, $message);
537 * Request a record from the DB by id. Success if row not found.
538 * @param string $daoName
540 * @param null $message
542 public function assertDBRowExist($daoName, $id, $message = NULL) {
543 $message = $message ?
$message : "$daoName (#$id) should exist";
544 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
545 $this->assertEquals($id, $value, $message);
549 * Compare a single column value in a retrieved DB record to an expected value.
550 * @param string $daoName
551 * @param $searchValue
552 * @param $returnColumn
553 * @param $searchColumn
554 * @param $expectedValue
557 public function assertDBCompareValue(
558 $daoName, $searchValue, $returnColumn, $searchColumn,
559 $expectedValue, $message
561 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
562 $this->assertEquals($value, $expectedValue, $message);
566 * Compare all values in a single retrieved DB record to an array of expected values.
567 * @param string $daoName
568 * @param array $searchParams
569 * @param $expectedValues
571 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
572 //get the values from db
574 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
576 // compare db values with expected values
577 self
::assertAttributesEquals($expectedValues, $dbValues);
581 * Assert that a SQL query returns a given value.
583 * The first argument is an expected value. The remaining arguments are passed
584 * to CRM_Core_DAO::singleValueQuery
586 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
587 * array(1 => array("Whiz", "String")));
590 * @param array $params
591 * @param string $message
593 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
597 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
598 $this->assertEquals($expected, $actual,
599 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
600 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
606 * Assert that two array-trees are exactly equal, notwithstanding
607 * the sorting of keys
609 * @param array $expected
610 * @param array $actual
612 public function assertTreeEquals($expected, $actual) {
615 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
616 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
620 $this->assertEquals($e, $a);
624 * Assert that two numbers are approximately equal.
626 * @param int|float $expected
627 * @param int|float $actual
628 * @param int|float $tolerance
629 * @param string $message
631 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
632 if ($message === NULL) {
633 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
635 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
639 * Assert attributes are equal.
641 * @param $expectedValues
642 * @param $actualValues
643 * @param string $message
645 * @throws PHPUnit_Framework_AssertionFailedError
647 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
648 foreach ($expectedValues as $paramName => $paramValue) {
649 if (isset($actualValues[$paramName])) {
650 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
653 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
662 public function assertArrayKeyExists($key, &$list) {
663 $result = isset($list[$key]) ?
TRUE : FALSE;
664 $this->assertTrue($result, ts("%1 element exists?",
673 public function assertArrayValueNotNull($key, &$list) {
674 $this->assertArrayKeyExists($key, $list);
676 $value = isset($list[$key]) ?
$list[$key] : NULL;
677 $this->assertTrue($value,
678 ts("%1 element not null?",
685 * Check that api returned 'is_error' => 0.
687 * @param array $apiResult
689 * @param string $prefix
690 * Extra test to add to message.
692 public function assertAPISuccess($apiResult, $prefix = '') {
693 if (!empty($prefix)) {
696 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
698 if (!empty($apiResult['debug_information'])) {
699 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
701 if (!empty($apiResult['trace'])) {
702 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
704 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
708 * Check that api returned 'is_error' => 1.
710 * @param array $apiResult
712 * @param string $prefix
713 * Extra test to add to message.
714 * @param null $expectedError
716 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
717 if (!empty($prefix)) {
720 if ($expectedError && !empty($apiResult['is_error'])) {
721 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
723 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
724 $this->assertNotEmpty($apiResult['error_message']);
730 * @param string $message
732 public function assertType($expected, $actual, $message = '') {
733 return $this->assertInternalType($expected, $actual, $message);
737 * Check that a deleted item has been deleted.
742 public function assertAPIDeleted($entity, $id) {
743 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
748 * Check that api returned 'is_error' => 1
749 * else provide full message
750 * @param array $result
752 * @param array $valuesToExclude
753 * @param string $prefix
754 * Extra test to add to message.
756 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
757 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
758 foreach ($valuesToExclude as $value) {
759 if (isset($result[$value])) {
760 unset($result[$value]);
762 if (isset($expected[$value])) {
763 unset($expected[$value]);
766 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
770 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
774 * @param array $params
777 public function civicrm_api($entity, $action, $params) {
778 return civicrm_api($entity, $action, $params);
782 * Create a batch of external API calls which can
783 * be executed concurrently.
786 * $calls = $this->createExternalAPI()
787 * ->addCall('Contact', 'get', ...)
788 * ->addCall('Contact', 'get', ...)
794 * @return \Civi\API\ExternalBatch
795 * @throws PHPUnit_Framework_SkippedTestError
797 public function createExternalAPI() {
798 global $civicrm_root;
799 $defaultParams = array(
800 'version' => $this->_apiversion
,
804 $calls = new \Civi\API\
ExternalBatch($defaultParams);
806 if (!$calls->isSupported()) {
807 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
814 * wrap api functions.
815 * so we can ensure they succeed & throw exceptions without litterering the test with checks
817 * @param string $entity
818 * @param string $action
819 * @param array $params
820 * @param mixed $checkAgainst
821 * Optional value to check result against, implemented for getvalue,.
822 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
823 * for getsingle the array is compared against an array passed in - the id is not compared (for
828 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
829 $params = array_merge(array(
830 'version' => $this->_apiversion
,
835 switch (strtolower($action)) {
837 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
840 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
843 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
845 $result = $this->civicrm_api($entity, $action, $params);
846 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
851 * This function exists to wrap api getValue function & check the result
852 * so we can ensure they succeed & throw exceptions without litterering the test with checks
853 * There is a type check in this
855 * @param string $entity
856 * @param array $params
857 * @param string $type
858 * Per http://php.net/manual/en/function.gettype.php possible types.
868 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
870 'version' => $this->_apiversion
,
873 $result = $this->civicrm_api($entity, 'getvalue', $params);
875 if ($type == 'integer') {
876 // api seems to return integers as strings
877 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
880 $this->assertType($type, $result, "returned result should have been of type $type but was ");
887 * This function exists to wrap api getsingle function & check the result
888 * so we can ensure they succeed & throw exceptions without litterering the test with checks
890 * @param string $entity
891 * @param array $params
892 * @param array $checkAgainst
893 * Array to compare result against.
904 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
906 'version' => $this->_apiversion
,
908 $result = $this->civicrm_api($entity, 'getsingle', $params);
909 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
910 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
913 // @todo - have gone with the fn that unsets id? should we check id?
914 $this->checkArrayEquals($result, $checkAgainst);
920 * This function exists to wrap api getValue function & check the result
921 * so we can ensure they succeed & throw exceptions without litterering the test with checks
922 * There is a type check in this
923 * @param string $entity
924 * @param array $params
929 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
931 'version' => $this->_apiversion
,
934 $result = $this->civicrm_api($entity, 'getcount', $params);
935 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
936 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
938 if (is_int($count)) {
939 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
945 * This function exists to wrap api functions.
946 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
948 * @param string $entity
949 * @param string $action
950 * @param array $params
951 * @param string $function
952 * Pass this in to create a generated example.
953 * @param string $file
954 * Pass this in to create a generated example.
955 * @param string $description
956 * @param string|null $exampleName
960 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
961 $params['version'] = $this->_apiversion
;
962 $result = $this->callAPISuccess($entity, $action, $params);
963 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
968 * This function exists to wrap api functions.
969 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
970 * @param string $entity
971 * @param string $action
972 * @param array $params
973 * @param string $expectedErrorMessage
975 * @param null $extraOutput
978 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
979 if (is_array($params)) {
981 'version' => $this->_apiversion
,
984 $result = $this->civicrm_api($entity, $action, $params);
985 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
990 * Create required data based on $this->entity & $this->params
991 * This is just a way to set up the test data for delete & get functions
992 * so the distinction between set
993 * up & tested functions is clearer
998 public function createTestEntity() {
999 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1003 * Generic function to create Organisation, to be used in test cases
1005 * @param array $params
1006 * parameters for civicrm_contact_add api function call
1008 * sequence number if creating multiple organizations
1011 * id of Organisation created
1013 public function organizationCreate($params = array(), $seq = 0) {
1017 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1018 return $this->_contactCreate($params);
1022 * Generic function to create Individual, to be used in test cases
1024 * @param array $params
1025 * parameters for civicrm_contact_add api function call
1027 * sequence number if creating multiple individuals
1030 * id of Individual created
1032 public function individualCreate($params = array(), $seq = 0) {
1033 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1034 return $this->_contactCreate($params);
1038 * Generic function to create Household, to be used in test cases
1040 * @param array $params
1041 * parameters for civicrm_contact_add api function call
1043 * sequence number if creating multiple households
1046 * id of Household created
1048 public function householdCreate($params = array(), $seq = 0) {
1049 $params = array_merge($this->sampleContact('Household', $seq), $params);
1050 return $this->_contactCreate($params);
1054 * Helper function for getting sample contact properties.
1056 * @param string $contact_type
1057 * enum contact type: Individual, Organization
1059 * sequence number for the values of this type
1062 * properties of sample contact (ie. $params for API call)
1064 public function sampleContact($contact_type, $seq = 0) {
1066 'Individual' => array(
1067 // The number of values in each list need to be coprime numbers to not have duplicates
1068 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1069 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1070 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1072 'Organization' => array(
1073 'organization_name' => array(
1074 'Unit Test Organization',
1081 'Household' => array(
1082 'household_name' => array('Unit Test household'),
1085 $params = array('contact_type' => $contact_type);
1086 foreach ($samples[$contact_type] as $key => $values) {
1087 $params[$key] = $values[$seq %
count($values)];
1089 if ($contact_type == 'Individual') {
1090 $params['email'] = strtolower(
1091 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1093 $params['prefix_id'] = 3;
1094 $params['suffix_id'] = 3;
1100 * Private helper function for calling civicrm_contact_add.
1102 * @param array $params
1103 * For civicrm_contact_add api function call.
1108 * id of Household created
1110 private function _contactCreate($params) {
1111 $result = $this->callAPISuccess('contact', 'create', $params);
1112 if (!empty($result['is_error']) ||
empty($result['id'])) {
1113 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1115 return $result['id'];
1119 * Delete contact, ensuring it is not the domain contact
1121 * @param int $contactID
1122 * Contact ID to delete
1124 public function contactDelete($contactID) {
1125 $domain = new CRM_Core_BAO_Domain();
1126 $domain->contact_id
= $contactID;
1127 if (!$domain->find(TRUE)) {
1128 $this->callAPISuccess('contact', 'delete', array(
1130 'skip_undelete' => 1,
1136 * @param int $contactTypeId
1140 public function contactTypeDelete($contactTypeId) {
1141 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1143 throw new Exception('Could not delete contact type');
1148 * @param array $params
1152 public function membershipTypeCreate($params = array()) {
1153 CRM_Member_PseudoConstant
::flush('membershipType');
1154 CRM_Core_Config
::clearDBCache();
1155 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
1156 $params = array_merge(array(
1157 'name' => 'General',
1158 'duration_unit' => 'year',
1159 'duration_interval' => 1,
1160 'period_type' => 'rolling',
1161 'member_of_contact_id' => $memberOfOrganization,
1163 'financial_type_id' => 2,
1166 'visibility' => 'Public',
1169 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1171 CRM_Member_PseudoConstant
::flush('membershipType');
1172 CRM_Utils_Cache
::singleton()->flush();
1174 return $result['id'];
1178 * @param array $params
1182 public function contactMembershipCreate($params) {
1183 $params = array_merge(array(
1184 'join_date' => '2007-01-21',
1185 'start_date' => '2007-01-21',
1186 'end_date' => '2007-12-21',
1187 'source' => 'Payment',
1188 'membership_type_id' => 'General',
1190 if (!is_numeric($params['membership_type_id'])) {
1191 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
1192 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
1193 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
1197 $result = $this->callAPISuccess('Membership', 'create', $params);
1198 return $result['id'];
1202 * Delete Membership Type.
1204 * @param array $params
1206 public function membershipTypeDelete($params) {
1207 $this->callAPISuccess('MembershipType', 'Delete', $params);
1211 * @param int $membershipID
1213 public function membershipDelete($membershipID) {
1214 $deleteParams = array('id' => $membershipID);
1215 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1219 * @param string $name
1223 public function membershipStatusCreate($name = 'test member status') {
1224 $params['name'] = $name;
1225 $params['start_event'] = 'start_date';
1226 $params['end_event'] = 'end_date';
1227 $params['is_current_member'] = 1;
1228 $params['is_active'] = 1;
1230 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1231 CRM_Member_PseudoConstant
::flush('membershipStatus');
1232 return $result['id'];
1236 * @param int $membershipStatusID
1238 public function membershipStatusDelete($membershipStatusID) {
1239 if (!$membershipStatusID) {
1242 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1246 * @param array $params
1250 public function relationshipTypeCreate($params = array()) {
1251 $params = array_merge(array(
1252 'name_a_b' => 'Relation 1 for relationship type create',
1253 'name_b_a' => 'Relation 2 for relationship type create',
1254 'contact_type_a' => 'Individual',
1255 'contact_type_b' => 'Organization',
1262 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1263 CRM_Core_PseudoConstant
::flush('relationshipType');
1265 return $result['id'];
1269 * Delete Relatinship Type.
1271 * @param int $relationshipTypeID
1273 public function relationshipTypeDelete($relationshipTypeID) {
1274 $params['id'] = $relationshipTypeID;
1275 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1276 if (!empty($check['count'])) {
1277 $this->callAPISuccess('relationship_type', 'delete', $params);
1282 * @param array $params
1286 public function paymentProcessorTypeCreate($params = NULL) {
1287 if (is_null($params)) {
1289 'name' => 'API_Test_PP',
1290 'title' => 'API Test Payment Processor',
1291 'class_name' => 'CRM_Core_Payment_APITest',
1292 'billing_mode' => 'form',
1298 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1300 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1302 return $result['id'];
1306 * Create test Authorize.net instance.
1308 * @param array $params
1312 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1313 $params = array_merge(array(
1314 'name' => 'Authorize',
1315 'domain_id' => CRM_Core_Config
::domainID(),
1316 'payment_processor_type_id' => 'AuthNet',
1317 'title' => 'AuthNet',
1322 'user_name' => '4y5BfuW7jm',
1323 'password' => '4cAmW927n8uLf5J8',
1324 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1325 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1326 'class_name' => 'Payment_AuthorizeNet',
1327 'billing_mode' => 1,
1330 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1331 return $result['id'];
1335 * Create Participant.
1337 * @param array $params
1338 * Array of contact id and event id values.
1341 * $id of participant created
1343 public function participantCreate($params) {
1344 if (empty($params['contact_id'])) {
1345 $params['contact_id'] = $this->individualCreate();
1347 if (empty($params['event_id'])) {
1348 $event = $this->eventCreate();
1349 $params['event_id'] = $event['id'];
1354 'register_date' => 20070219,
1355 'source' => 'Wimbeldon',
1356 'event_level' => 'Payment',
1360 $params = array_merge($defaults, $params);
1361 $result = $this->callAPISuccess('Participant', 'create', $params);
1362 return $result['id'];
1366 * Create Payment Processor.
1369 * Id Payment Processor
1371 public function processorCreate($params = array()) {
1372 $processorParams = array(
1375 'payment_processor_type_id' => 'Dummy',
1376 'financial_account_id' => 12,
1380 'url_site' => 'http://dummy.com',
1381 'url_recur' => 'http://dummy.com',
1382 'billing_mode' => 1,
1384 'payment_instrument_id' => 'Debit Card',
1386 $processorParams = array_merge($processorParams, $params);
1387 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1388 return $processor['id'];
1392 * Create Payment Processor.
1394 * @param array $processorParams
1396 * @return \CRM_Core_Payment_Dummy
1397 * Instance of Dummy Payment Processor
1399 public function dummyProcessorCreate($processorParams = array()) {
1400 $paymentProcessorID = $this->processorCreate($processorParams);
1401 return System
::singleton()->getById($paymentProcessorID);
1405 * Create contribution page.
1407 * @param array $params
1409 * Array of contribution page
1411 public function contributionPageCreate($params = array()) {
1412 $this->_pageParams
= array_merge(array(
1413 'title' => 'Test Contribution Page',
1414 'financial_type_id' => 1,
1415 'currency' => 'USD',
1416 'financial_account_id' => 1,
1418 'is_allow_other_amount' => 1,
1420 'max_amount' => 1000,
1422 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1426 * Create a sample batch.
1428 public function batchCreate() {
1429 $params = $this->_params
;
1430 $params['name'] = $params['title'] = 'Batch_433397';
1431 $params['status_id'] = 1;
1432 $result = $this->callAPISuccess('batch', 'create', $params);
1433 return $result['id'];
1439 * @param array $params
1441 * result of created tag
1443 public function tagCreate($params = array()) {
1445 'name' => 'New Tag3',
1446 'description' => 'This is description for Our New Tag ',
1449 $params = array_merge($defaults, $params);
1450 $result = $this->callAPISuccess('Tag', 'create', $params);
1451 return $result['values'][$result['id']];
1458 * Id of the tag to be deleted.
1462 public function tagDelete($tagId) {
1463 require_once 'api/api.php';
1467 $result = $this->callAPISuccess('Tag', 'delete', $params);
1468 return $result['id'];
1472 * Add entity(s) to the tag
1474 * @param array $params
1478 public function entityTagAdd($params) {
1479 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1486 * @param array $params
1490 * id of created pledge
1492 public function pledgeCreate($params) {
1493 $params = array_merge(array(
1494 'pledge_create_date' => date('Ymd'),
1495 'start_date' => date('Ymd'),
1496 'scheduled_date' => date('Ymd'),
1498 'pledge_status_id' => '2',
1499 'financial_type_id' => '1',
1500 'pledge_original_installment_amount' => 20,
1501 'frequency_interval' => 5,
1502 'frequency_unit' => 'year',
1503 'frequency_day' => 15,
1504 'installments' => 5,
1508 $result = $this->callAPISuccess('Pledge', 'create', $params);
1509 return $result['id'];
1513 * Delete contribution.
1515 * @param int $pledgeId
1517 public function pledgeDelete($pledgeId) {
1519 'pledge_id' => $pledgeId,
1521 $this->callAPISuccess('Pledge', 'delete', $params);
1525 * Create contribution.
1527 * @param array $params
1528 * Array of parameters.
1531 * id of created contribution
1533 public function contributionCreate($params) {
1535 $params = array_merge(array(
1537 'receive_date' => date('Ymd'),
1538 'total_amount' => 100.00,
1539 'fee_amount' => 5.00,
1540 'financial_type_id' => 1,
1541 'payment_instrument_id' => 1,
1542 'non_deductible_amount' => 10.00,
1544 'invoice_id' => 67890,
1546 'contribution_status_id' => 1,
1549 $result = $this->callAPISuccess('contribution', 'create', $params);
1550 return $result['id'];
1554 * Delete contribution.
1556 * @param int $contributionId
1560 public function contributionDelete($contributionId) {
1562 'contribution_id' => $contributionId,
1564 $result = $this->callAPISuccess('contribution', 'delete', $params);
1571 * @param array $params
1572 * Name-value pair for an event.
1576 public function eventCreate($params = array()) {
1577 // if no contact was passed, make up a dummy event creator
1578 if (!isset($params['contact_id'])) {
1579 $params['contact_id'] = $this->_contactCreate(array(
1580 'contact_type' => 'Individual',
1581 'first_name' => 'Event',
1582 'last_name' => 'Creator',
1586 // set defaults for missing params
1587 $params = array_merge(array(
1588 'title' => 'Annual CiviCRM meet',
1589 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1590 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1591 'event_type_id' => 1,
1593 'start_date' => 20081021,
1594 'end_date' => 20081023,
1595 'is_online_registration' => 1,
1596 'registration_start_date' => 20080601,
1597 'registration_end_date' => 20081015,
1598 'max_participants' => 100,
1599 'event_full_text' => 'Sorry! We are already full',
1602 'is_show_location' => 0,
1605 return $this->callAPISuccess('Event', 'create', $params);
1609 * Create a paid event.
1611 * @param array $params
1615 protected function eventCreatePaid($params) {
1616 $event = $this->eventCreate($params);
1617 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1618 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1619 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1620 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1621 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1633 public function eventDelete($id) {
1637 return $this->callAPISuccess('event', 'delete', $params);
1641 * Delete participant.
1643 * @param int $participantID
1647 public function participantDelete($participantID) {
1649 'id' => $participantID,
1651 $check = $this->callAPISuccess('Participant', 'get', $params);
1652 if ($check['count'] > 0) {
1653 return $this->callAPISuccess('Participant', 'delete', $params);
1658 * Create participant payment.
1660 * @param int $participantID
1661 * @param int $contributionID
1663 * $id of created payment
1665 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1666 //Create Participant Payment record With Values
1668 'participant_id' => $participantID,
1669 'contribution_id' => $contributionID,
1672 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1673 return $result['id'];
1677 * Delete participant payment.
1679 * @param int $paymentID
1681 public function participantPaymentDelete($paymentID) {
1685 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1691 * @param int $contactID
1693 * location id of created location
1695 public function locationAdd($contactID) {
1698 'location_type' => 'New Location Type',
1700 'name' => 'Saint Helier St',
1701 'county' => 'Marin',
1702 'country' => 'UNITED STATES',
1703 'state_province' => 'Michigan',
1704 'supplemental_address_1' => 'Hallmark Ct',
1705 'supplemental_address_2' => 'Jersey Village',
1706 'supplemental_address_3' => 'My Town',
1711 'contact_id' => $contactID,
1712 'address' => $address,
1713 'location_format' => '2.0',
1714 'location_type' => 'New Location Type',
1717 $result = $this->callAPISuccess('Location', 'create', $params);
1722 * Delete Locations of contact.
1724 * @param array $params
1727 public function locationDelete($params) {
1728 $this->callAPISuccess('Location', 'delete', $params);
1732 * Add a Location Type.
1734 * @param array $params
1735 * @return CRM_Core_DAO_LocationType
1736 * location id of created location
1738 public function locationTypeCreate($params = NULL) {
1739 if ($params === NULL) {
1741 'name' => 'New Location Type',
1742 'vcard_name' => 'New Location Type',
1743 'description' => 'Location Type for Delete',
1748 $locationType = new CRM_Core_DAO_LocationType();
1749 $locationType->copyValues($params);
1750 $locationType->save();
1751 // clear getfields cache
1752 CRM_Core_PseudoConstant
::flush();
1753 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1754 return $locationType;
1758 * Delete a Location Type.
1760 * @param int $locationTypeId
1762 public function locationTypeDelete($locationTypeId) {
1763 $locationType = new CRM_Core_DAO_LocationType();
1764 $locationType->id
= $locationTypeId;
1765 $locationType->delete();
1771 * @param array $params
1772 * @return CRM_Core_DAO_Mapping
1773 * Mapping id of created mapping
1775 public function mappingCreate($params = NULL) {
1776 if ($params === NULL) {
1778 'name' => 'Mapping name',
1779 'description' => 'Mapping description',
1780 // 'Export Contact' mapping.
1781 'mapping_type_id' => 7,
1785 $mapping = new CRM_Core_DAO_Mapping();
1786 $mapping->copyValues($params);
1788 // clear getfields cache
1789 CRM_Core_PseudoConstant
::flush();
1790 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1797 * @param int $mappingId
1799 public function mappingDelete($mappingId) {
1800 $mapping = new CRM_Core_DAO_Mapping();
1801 $mapping->id
= $mappingId;
1808 * @param array $params
1810 * groupId of created group
1812 public function groupCreate($params = array()) {
1813 $params = array_merge(array(
1814 'name' => 'Test Group 1',
1816 'title' => 'New Test Group Created',
1817 'description' => 'New Test Group Created',
1819 'visibility' => 'Public Pages',
1820 'group_type' => array(
1826 $result = $this->callAPISuccess('Group', 'create', $params);
1827 return $result['id'];
1831 * Prepare class for ACLs.
1833 protected function prepareForACLs() {
1834 $config = CRM_Core_Config
::singleton();
1835 $config->userPermissionClass
->permissions
= array();
1841 protected function cleanUpAfterACLs() {
1842 CRM_Utils_Hook
::singleton()->reset();
1843 $tablesToTruncate = array(
1845 'civicrm_acl_cache',
1846 'civicrm_acl_entity_role',
1847 'civicrm_acl_contact_cache',
1849 $this->quickCleanup($tablesToTruncate);
1850 $config = CRM_Core_Config
::singleton();
1851 unset($config->userPermissionClass
->permissions
);
1854 * Create a smart group.
1856 * By default it will be a group of households.
1858 * @param array $smartGroupParams
1859 * @param array $groupParams
1862 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1863 $smartGroupParams = array_merge(array(
1864 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1867 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1869 $groupParams['saved_search_id'] = $savedSearch->id
;
1870 return $this->groupCreate($groupParams);
1874 * Function to add a Group.
1876 * @params array to add group
1878 * @param int $groupID
1879 * @param int $totalCount
1881 * groupId of created group
1883 public function groupContactCreate($groupID, $totalCount = 10) {
1884 $params = array('group_id' => $groupID);
1885 for ($i = 1; $i <= $totalCount; $i++
) {
1886 $contactID = $this->individualCreate();
1888 $params +
= array('contact_id' => $contactID);
1891 $params +
= array("contact_id.$i" => $contactID);
1894 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1904 public function groupDelete($gid) {
1910 $this->callAPISuccess('Group', 'delete', $params);
1915 * @param array $params
1917 public function uFFieldCreate($params = array()) {
1918 $params = array_merge(array(
1920 'field_name' => 'first_name',
1923 'visibility' => 'Public Pages and Listings',
1924 'is_searchable' => '1',
1925 'label' => 'first_name',
1926 'field_type' => 'Individual',
1929 $this->callAPISuccess('uf_field', 'create', $params);
1933 * Add a UF Join Entry.
1935 * @param array $params
1937 * $id of created UF Join
1939 public function ufjoinCreate($params = NULL) {
1940 if ($params === NULL) {
1943 'module' => 'CiviEvent',
1944 'entity_table' => 'civicrm_event',
1950 $result = $this->callAPISuccess('uf_join', 'create', $params);
1955 * Delete a UF Join Entry.
1957 * @param array $params
1958 * with missing uf_group_id
1960 public function ufjoinDelete($params = NULL) {
1961 if ($params === NULL) {
1964 'module' => 'CiviEvent',
1965 'entity_table' => 'civicrm_event',
1968 'uf_group_id' => '',
1972 crm_add_uf_join($params);
1976 * @param array $params
1977 * Optional parameters.
1978 * @param bool $reloadConfig
1979 * While enabling CiviCampaign component, we shouldn't always forcibly
1980 * reload config as this hinder hook call in test environment
1985 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1986 $this->enableCiviCampaign($reloadConfig);
1987 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1988 'name' => 'big_campaign',
1989 'title' => 'Campaign',
1991 return $campaign['id'];
1995 * Create Group for a contact.
1997 * @param int $contactId
1999 public function contactGroupCreate($contactId) {
2001 'contact_id.1' => $contactId,
2005 $this->callAPISuccess('GroupContact', 'Create', $params);
2009 * Delete Group for a contact.
2011 * @param int $contactId
2013 public function contactGroupDelete($contactId) {
2015 'contact_id.1' => $contactId,
2018 $this->civicrm_api('GroupContact', 'Delete', $params);
2024 * @param array $params
2027 public function activityCreate($params = array()) {
2028 $params = array_merge(array(
2029 'subject' => 'Discussion on warm beer',
2030 'activity_date_time' => date('Ymd'),
2031 'duration_hours' => 30,
2032 'duration_minutes' => 20,
2033 'location' => 'Baker Street',
2034 'details' => 'Lets schedule a meeting',
2036 'activity_name' => 'Meeting',
2038 if (!isset($params['source_contact_id'])) {
2039 $params['source_contact_id'] = $this->individualCreate();
2041 if (!isset($params['target_contact_id'])) {
2042 $params['target_contact_id'] = $this->individualCreate(array(
2043 'first_name' => 'Julia',
2044 'Last_name' => 'Anderson',
2046 'email' => 'julia_anderson@civicrm.org',
2047 'contact_type' => 'Individual',
2050 if (!isset($params['assignee_contact_id'])) {
2051 $params['assignee_contact_id'] = $params['target_contact_id'];
2054 $result = $this->callAPISuccess('Activity', 'create', $params);
2056 $result['target_contact_id'] = $params['target_contact_id'];
2057 $result['assignee_contact_id'] = $params['assignee_contact_id'];
2062 * Create an activity type.
2064 * @param array $params
2068 public function activityTypeCreate($params) {
2069 return $this->callAPISuccess('ActivityType', 'create', $params);
2073 * Delete activity type.
2075 * @param int $activityTypeId
2076 * Id of the activity type.
2079 public function activityTypeDelete($activityTypeId) {
2080 $params['activity_type_id'] = $activityTypeId;
2081 return $this->callAPISuccess('ActivityType', 'delete', $params);
2085 * Create custom group.
2087 * @param array $params
2090 public function customGroupCreate($params = array()) {
2092 'title' => 'new custom group',
2093 'extends' => 'Contact',
2095 'style' => 'Inline',
2099 $params = array_merge($defaults, $params);
2101 if (strlen($params['title']) > 13) {
2102 $params['title'] = substr($params['title'], 0, 13);
2105 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2106 $this->callAPISuccess('custom_group', 'get', array(
2107 'title' => $params['title'],
2108 array('api.custom_group.delete' => 1),
2111 return $this->callAPISuccess('custom_group', 'create', $params);
2115 * Existing function doesn't allow params to be over-ridden so need a new one
2116 * this one allows you to only pass in the params you want to change
2117 * @param array $params
2120 public function CustomGroupCreateByParams($params = array()) {
2122 'title' => "API Custom Group",
2123 'extends' => 'Contact',
2125 'style' => 'Inline',
2128 $params = array_merge($defaults, $params);
2129 return $this->callAPISuccess('custom_group', 'create', $params);
2133 * Create custom group with multi fields.
2134 * @param array $params
2137 public function CustomGroupMultipleCreateByParams($params = array()) {
2142 $params = array_merge($defaults, $params);
2143 return $this->CustomGroupCreateByParams($params);
2147 * Create custom group with multi fields.
2148 * @param array $params
2151 public function CustomGroupMultipleCreateWithFields($params = array()) {
2152 // also need to pass on $params['custom_field'] if not set but not in place yet
2154 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2155 $ids['custom_group_id'] = $customGroup['id'];
2157 $customField = $this->customFieldCreate(array(
2158 'custom_group_id' => $ids['custom_group_id'],
2159 'label' => 'field_1' . $ids['custom_group_id'],
2163 $ids['custom_field_id'][] = $customField['id'];
2165 $customField = $this->customFieldCreate(array(
2166 'custom_group_id' => $ids['custom_group_id'],
2167 'default_value' => '',
2168 'label' => 'field_2' . $ids['custom_group_id'],
2171 $ids['custom_field_id'][] = $customField['id'];
2173 $customField = $this->customFieldCreate(array(
2174 'custom_group_id' => $ids['custom_group_id'],
2175 'default_value' => '',
2176 'label' => 'field_3' . $ids['custom_group_id'],
2179 $ids['custom_field_id'][] = $customField['id'];
2185 * Create a custom group with a single text custom field. See
2186 * participant:testCreateWithCustom for how to use this
2188 * @param string $function
2190 * @param string $filename
2194 * ids of created objects
2196 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2197 $params = array('title' => $function);
2198 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2199 $params['extends'] = $entity ?
$entity : 'Contact';
2200 $customGroup = $this->CustomGroupCreate($params);
2201 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2202 CRM_Core_PseudoConstant
::flush();
2204 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2208 * Delete custom group.
2210 * @param int $customGroupID
2214 public function customGroupDelete($customGroupID) {
2215 $params['id'] = $customGroupID;
2216 return $this->callAPISuccess('custom_group', 'delete', $params);
2220 * Create custom field.
2222 * @param array $params
2223 * (custom_group_id) is required.
2226 public function customFieldCreate($params) {
2227 $params = array_merge(array(
2228 'label' => 'Custom Field',
2229 'data_type' => 'String',
2230 'html_type' => 'Text',
2231 'is_searchable' => 1,
2233 'default_value' => 'defaultValue',
2236 $result = $this->callAPISuccess('custom_field', 'create', $params);
2237 // these 2 functions are called with force to flush static caches
2238 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2239 CRM_Core_Component
::getEnabledComponents(1);
2244 * Delete custom field.
2246 * @param int $customFieldID
2250 public function customFieldDelete($customFieldID) {
2252 $params['id'] = $customFieldID;
2253 return $this->callAPISuccess('custom_field', 'delete', $params);
2262 public function noteCreate($cId) {
2264 'entity_table' => 'civicrm_contact',
2265 'entity_id' => $cId,
2266 'note' => 'hello I am testing Note',
2267 'contact_id' => $cId,
2268 'modified_date' => date('Ymd'),
2269 'subject' => 'Test Note',
2272 return $this->callAPISuccess('Note', 'create', $params);
2276 * Enable CiviCampaign Component.
2278 * @param bool $reloadConfig
2279 * Force relaod config or not
2281 public function enableCiviCampaign($reloadConfig = TRUE) {
2282 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2283 if ($reloadConfig) {
2284 // force reload of config object
2285 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2287 //flush cache by calling with reset
2288 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2292 * Create test generated example in api/v3/examples.
2294 * To turn this off (e.g. on the server) set
2295 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2296 * in your settings file
2298 * @param string $entity
2299 * @param string $action
2300 * @param array $params
2301 * Array as passed to civicrm_api function.
2302 * @param array $result
2303 * Array as received from the civicrm_api function.
2304 * @param string $testFunction
2305 * Calling function - generally __FUNCTION__.
2306 * @param string $testFile
2307 * Called from file - generally __FILE__.
2308 * @param string $description
2309 * Descriptive text for the example file.
2310 * @param string $exampleName
2311 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2313 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2314 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2317 $entity = _civicrm_api_get_camel_name($entity);
2318 $action = strtolower($action);
2320 if (empty($exampleName)) {
2321 // Attempt to convert lowercase action name to CamelCase.
2322 // This is clunky/imperfect due to the convention of all lowercase actions.
2323 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2324 $knownPrefixes = array(
2331 foreach ($knownPrefixes as $prefix) {
2332 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2333 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2338 $this->tidyExampleResult($result);
2339 if (isset($params['version'])) {
2340 unset($params['version']);
2342 // Format multiline description as array
2344 if (is_string($description) && strlen($description)) {
2345 foreach (explode("\n", $description) as $line) {
2346 $desc[] = trim($line);
2349 $smarty = CRM_Core_Smarty
::singleton();
2350 $smarty->assign('testFunction', $testFunction);
2351 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2352 foreach ($params as $index => $param) {
2353 if (is_string($param)) {
2354 $params[$index] = addslashes($param);
2357 $smarty->assign('params', $params);
2358 $smarty->assign('entity', $entity);
2359 $smarty->assign('testFile', basename($testFile));
2360 $smarty->assign('description', $desc);
2361 $smarty->assign('result', $result);
2362 $smarty->assign('action', $action);
2364 global $civicrm_root;
2365 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2366 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2367 mkdir($civicrm_root . "/api/v3/examples/$entity");
2369 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2370 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2376 * Tidy up examples array so that fields that change often ..don't
2377 * and debug related fields are unset
2379 * @param array $result
2381 public function tidyExampleResult(&$result) {
2382 if (!is_array($result)) {
2385 $fieldsToChange = array(
2386 'hash' => '67eac7789eaee00',
2387 'modified_date' => '2012-11-14 16:02:35',
2388 'created_date' => '2013-07-28 08:49:19',
2389 'create_date' => '20120130621222105',
2390 'application_received_date' => '20130728084957',
2391 'in_date' => '2013-07-28 08:50:19',
2392 'scheduled_date' => '20130728085413',
2393 'approval_date' => '20130728085413',
2394 'pledge_start_date_high' => '20130726090416',
2395 'start_date' => '2013-07-29 00:00:00',
2396 'event_start_date' => '2013-07-29 00:00:00',
2397 'end_date' => '2013-08-04 00:00:00',
2398 'event_end_date' => '2013-08-04 00:00:00',
2399 'decision_date' => '20130805000000',
2402 $keysToUnset = array('xdebug', 'undefined_fields');
2403 foreach ($keysToUnset as $unwantedKey) {
2404 if (isset($result[$unwantedKey])) {
2405 unset($result[$unwantedKey]);
2408 if (isset($result['values'])) {
2409 if (!is_array($result['values'])) {
2412 $resultArray = &$result['values'];
2414 elseif (is_array($result)) {
2415 $resultArray = &$result;
2421 foreach ($resultArray as $index => &$values) {
2422 if (!is_array($values)) {
2425 foreach ($values as $key => &$value) {
2426 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2427 if (isset($value['is_error'])) {
2428 // we have a std nested result format
2429 $this->tidyExampleResult($value);
2432 foreach ($value as &$nestedResult) {
2433 // this is an alternative syntax for nested results a keyed array of results
2434 $this->tidyExampleResult($nestedResult);
2438 if (in_array($key, $keysToUnset)) {
2439 unset($values[$key]);
2442 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2443 $value = $fieldsToChange[$key];
2445 if (is_string($value)) {
2446 $value = addslashes($value);
2453 * Create custom field with Option Values.
2455 * @param array $customGroup
2456 * @param string $name
2457 * Name of custom field.
2458 * @param array $extraParams
2459 * Additional parameters to pass through.
2463 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2464 $fieldParams = array(
2465 'custom_group_id' => $customGroup['id'],
2466 'name' => 'test_custom_group',
2467 'label' => 'Country',
2468 'html_type' => 'Select',
2469 'data_type' => 'String',
2472 'is_searchable' => 0,
2476 $optionGroup = array(
2478 'name' => 'option_group1',
2479 'label' => 'option_group_label1',
2482 $optionValue = array(
2483 'option_label' => array('Label1', 'Label2'),
2484 'option_value' => array('value1', 'value2'),
2485 'option_name' => array($name . '_1', $name . '_2'),
2486 'option_weight' => array(1, 2),
2487 'option_status' => 1,
2490 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2492 return $this->callAPISuccess('custom_field', 'create', $params);
2500 public function confirmEntitiesDeleted($entities) {
2501 foreach ($entities as $entity) {
2503 $result = $this->callAPISuccess($entity, 'Get', array());
2504 if ($result['error'] == 1 ||
$result['count'] > 0) {
2505 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2513 * Quick clean by emptying tables created for the test.
2515 * @param array $tablesToTruncate
2516 * @param bool $dropCustomValueTables
2517 * @throws \Exception
2519 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2521 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2523 if ($dropCustomValueTables) {
2524 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2525 while ($optionGroupResult->fetch()) {
2526 if (!empty($optionGroupResult->option_group_id
)) {
2527 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2530 $tablesToTruncate[] = 'civicrm_custom_group';
2531 $tablesToTruncate[] = 'civicrm_custom_field';
2534 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2536 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2537 foreach ($tablesToTruncate as $table) {
2538 $sql = "TRUNCATE TABLE $table";
2539 CRM_Core_DAO
::executeQuery($sql);
2541 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2543 if ($dropCustomValueTables) {
2544 $dbName = self
::getDBName();
2546 SELECT TABLE_NAME as tableName
2547 FROM INFORMATION_SCHEMA.TABLES
2548 WHERE TABLE_SCHEMA = '{$dbName}'
2549 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2552 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2553 while ($tableDAO->fetch()) {
2554 $sql = "DROP TABLE {$tableDAO->tableName}";
2555 CRM_Core_DAO
::executeQuery($sql);
2561 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2563 public function quickCleanUpFinancialEntities() {
2564 $tablesToTruncate = array(
2566 'civicrm_activity_contact',
2567 'civicrm_contribution',
2568 'civicrm_contribution_soft',
2569 'civicrm_contribution_product',
2570 'civicrm_financial_trxn',
2571 'civicrm_financial_item',
2572 'civicrm_contribution_recur',
2573 'civicrm_line_item',
2574 'civicrm_contribution_page',
2575 'civicrm_payment_processor',
2576 'civicrm_entity_financial_trxn',
2577 'civicrm_membership',
2578 'civicrm_membership_type',
2579 'civicrm_membership_payment',
2580 'civicrm_membership_log',
2581 'civicrm_membership_block',
2583 'civicrm_participant',
2584 'civicrm_participant_payment',
2586 'civicrm_pledge_payment',
2587 'civicrm_price_set_entity',
2588 'civicrm_price_field_value',
2589 'civicrm_price_field',
2591 $this->quickCleanup($tablesToTruncate);
2592 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2593 $this->restoreDefaultPriceSetConfig();
2595 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2596 $this->disableTaxAndInvoicing();
2597 System
::singleton()->flushProcessors();
2600 public function restoreDefaultPriceSetConfig() {
2601 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2602 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)");
2603 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)");
2606 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2607 * Default behaviour is to also delete the entity
2608 * @param array $params
2609 * Params array to check against.
2611 * Id of the entity concerned.
2612 * @param string $entity
2613 * Name of entity concerned (e.g. membership).
2614 * @param bool $delete
2615 * Should the entity be deleted as part of this check.
2616 * @param string $errorText
2617 * Text to print on error.
2620 * @param array $params
2623 * @param int $delete
2624 * @param string $errorText
2628 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2630 $result = $this->callAPISuccessGetSingle($entity, array(
2635 $this->callAPISuccess($entity, 'Delete', array(
2639 $dateFields = $keys = $dateTimeFields = array();
2640 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2641 foreach ($fields['values'] as $field => $settings) {
2642 if (array_key_exists($field, $result)) {
2643 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2646 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2648 $type = CRM_Utils_Array
::value('type', $settings);
2649 if ($type == CRM_Utils_Type
::T_DATE
) {
2650 $dateFields[] = $settings['name'];
2651 // we should identify both real names & unique names as dates
2652 if ($field != $settings['name']) {
2653 $dateFields[] = $field;
2656 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2657 $dateTimeFields[] = $settings['name'];
2658 // we should identify both real names & unique names as dates
2659 if ($field != $settings['name']) {
2660 $dateTimeFields[] = $field;
2665 if (strtolower($entity) == 'contribution') {
2666 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2667 // this is not returned in id format
2668 unset($params['payment_instrument_id']);
2669 $params['contribution_source'] = $params['source'];
2670 unset($params['source']);
2673 foreach ($params as $key => $value) {
2674 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2677 if (in_array($key, $dateFields)) {
2678 $value = date('Y-m-d', strtotime($value));
2679 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2681 if (in_array($key, $dateTimeFields)) {
2682 $value = date('Y-m-d H:i:s', strtotime($value));
2683 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2685 $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);
2690 * Get formatted values in the actual and expected result.
2691 * @param array $actual
2692 * Actual calculated values.
2693 * @param array $expected
2696 public function checkArrayEquals(&$actual, &$expected) {
2697 self
::unsetId($actual);
2698 self
::unsetId($expected);
2699 $this->assertEquals($actual, $expected);
2703 * Unset the key 'id' from the array
2704 * @param array $unformattedArray
2705 * The array from which the 'id' has to be unset.
2707 public static function unsetId(&$unformattedArray) {
2708 $formattedArray = array();
2709 if (array_key_exists('id', $unformattedArray)) {
2710 unset($unformattedArray['id']);
2712 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2713 foreach ($unformattedArray['values'] as $key => $value) {
2714 if (is_array($value)) {
2715 foreach ($value as $k => $v) {
2721 elseif ($key == 'id') {
2722 $unformattedArray[$key];
2724 $formattedArray = array($value);
2726 $unformattedArray['values'] = $formattedArray;
2731 * Helper to enable/disable custom directory support
2733 * @param array $customDirs
2735 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2736 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2738 public function customDirectories($customDirs) {
2739 $config = CRM_Core_Config
::singleton();
2741 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2742 unset($config->customPHPPathDir
);
2744 elseif ($customDirs['php_path'] === TRUE) {
2745 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2748 $config->customPHPPathDir
= $php_path;
2751 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2752 unset($config->customTemplateDir
);
2754 elseif ($customDirs['template_path'] === TRUE) {
2755 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2758 $config->customTemplateDir
= $template_path;
2763 * Generate a temporary folder.
2765 * @param string $prefix
2768 public function createTempDir($prefix = 'test-') {
2769 $tempDir = CRM_Utils_File
::tempdir($prefix);
2770 $this->tempDirs
[] = $tempDir;
2774 public function cleanTempDirs() {
2775 if (!is_array($this->tempDirs
)) {
2776 // fix test errors where this is not set
2779 foreach ($this->tempDirs
as $tempDir) {
2780 if (is_dir($tempDir)) {
2781 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2787 * Temporarily replace the singleton extension with a different one.
2788 * @param \CRM_Extension_System $system
2790 public function setExtensionSystem(CRM_Extension_System
$system) {
2791 if ($this->origExtensionSystem
== NULL) {
2792 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2794 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2797 public function unsetExtensionSystem() {
2798 if ($this->origExtensionSystem
!== NULL) {
2799 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2800 $this->origExtensionSystem
= NULL;
2805 * Temporarily alter the settings-metadata to add a mock setting.
2807 * WARNING: The setting metadata will disappear on the next cache-clear.
2812 public function setMockSettingsMetaData($extras) {
2813 Civi
::service('settings_manager')->flush();
2815 CRM_Utils_Hook
::singleton()
2816 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2817 $metadata = array_merge($metadata, $extras);
2820 $fields = $this->callAPISuccess('setting', 'getfields', array());
2821 foreach ($extras as $key => $spec) {
2822 $this->assertNotEmpty($spec['title']);
2823 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2828 * @param string $name
2830 public function financialAccountDelete($name) {
2831 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2832 $financialAccount->name
= $name;
2833 if ($financialAccount->find(TRUE)) {
2834 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2835 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2836 $entityFinancialType->delete();
2837 $financialAccount->delete();
2842 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2843 * (NB unclear if this is still required)
2845 public function _sethtmlGlobals() {
2846 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2847 'required' => array(
2848 'html_quickform_rule_required',
2849 'HTML/QuickForm/Rule/Required.php',
2851 'maxlength' => array(
2852 'html_quickform_rule_range',
2853 'HTML/QuickForm/Rule/Range.php',
2855 'minlength' => array(
2856 'html_quickform_rule_range',
2857 'HTML/QuickForm/Rule/Range.php',
2859 'rangelength' => array(
2860 'html_quickform_rule_range',
2861 'HTML/QuickForm/Rule/Range.php',
2864 'html_quickform_rule_email',
2865 'HTML/QuickForm/Rule/Email.php',
2868 'html_quickform_rule_regex',
2869 'HTML/QuickForm/Rule/Regex.php',
2871 'lettersonly' => array(
2872 'html_quickform_rule_regex',
2873 'HTML/QuickForm/Rule/Regex.php',
2875 'alphanumeric' => array(
2876 'html_quickform_rule_regex',
2877 'HTML/QuickForm/Rule/Regex.php',
2880 'html_quickform_rule_regex',
2881 'HTML/QuickForm/Rule/Regex.php',
2883 'nopunctuation' => array(
2884 'html_quickform_rule_regex',
2885 'HTML/QuickForm/Rule/Regex.php',
2888 'html_quickform_rule_regex',
2889 'HTML/QuickForm/Rule/Regex.php',
2891 'callback' => array(
2892 'html_quickform_rule_callback',
2893 'HTML/QuickForm/Rule/Callback.php',
2896 'html_quickform_rule_compare',
2897 'HTML/QuickForm/Rule/Compare.php',
2900 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2901 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2903 'HTML/QuickForm/group.php',
2904 'HTML_QuickForm_group',
2907 'HTML/QuickForm/hidden.php',
2908 'HTML_QuickForm_hidden',
2911 'HTML/QuickForm/reset.php',
2912 'HTML_QuickForm_reset',
2914 'checkbox' => array(
2915 'HTML/QuickForm/checkbox.php',
2916 'HTML_QuickForm_checkbox',
2919 'HTML/QuickForm/file.php',
2920 'HTML_QuickForm_file',
2923 'HTML/QuickForm/image.php',
2924 'HTML_QuickForm_image',
2926 'password' => array(
2927 'HTML/QuickForm/password.php',
2928 'HTML_QuickForm_password',
2931 'HTML/QuickForm/radio.php',
2932 'HTML_QuickForm_radio',
2935 'HTML/QuickForm/button.php',
2936 'HTML_QuickForm_button',
2939 'HTML/QuickForm/submit.php',
2940 'HTML_QuickForm_submit',
2943 'HTML/QuickForm/select.php',
2944 'HTML_QuickForm_select',
2946 'hiddenselect' => array(
2947 'HTML/QuickForm/hiddenselect.php',
2948 'HTML_QuickForm_hiddenselect',
2951 'HTML/QuickForm/text.php',
2952 'HTML_QuickForm_text',
2954 'textarea' => array(
2955 'HTML/QuickForm/textarea.php',
2956 'HTML_QuickForm_textarea',
2958 'fckeditor' => array(
2959 'HTML/QuickForm/fckeditor.php',
2960 'HTML_QuickForm_FCKEditor',
2963 'HTML/QuickForm/tinymce.php',
2964 'HTML_QuickForm_TinyMCE',
2966 'dojoeditor' => array(
2967 'HTML/QuickForm/dojoeditor.php',
2968 'HTML_QuickForm_dojoeditor',
2971 'HTML/QuickForm/link.php',
2972 'HTML_QuickForm_link',
2974 'advcheckbox' => array(
2975 'HTML/QuickForm/advcheckbox.php',
2976 'HTML_QuickForm_advcheckbox',
2979 'HTML/QuickForm/date.php',
2980 'HTML_QuickForm_date',
2983 'HTML/QuickForm/static.php',
2984 'HTML_QuickForm_static',
2987 'HTML/QuickForm/header.php',
2988 'HTML_QuickForm_header',
2991 'HTML/QuickForm/html.php',
2992 'HTML_QuickForm_html',
2994 'hierselect' => array(
2995 'HTML/QuickForm/hierselect.php',
2996 'HTML_QuickForm_hierselect',
2998 'autocomplete' => array(
2999 'HTML/QuickForm/autocomplete.php',
3000 'HTML_QuickForm_autocomplete',
3003 'HTML/QuickForm/xbutton.php',
3004 'HTML_QuickForm_xbutton',
3006 'advmultiselect' => array(
3007 'HTML/QuickForm/advmultiselect.php',
3008 'HTML_QuickForm_advmultiselect',
3014 * Set up an acl allowing contact to see 2 specified groups
3015 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3017 * You need to have pre-created these groups & created the user e.g
3018 * $this->createLoggedInUser();
3019 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3020 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3022 * @param bool $isProfile
3024 public function setupACL($isProfile = FALSE) {
3026 $_REQUEST = $this->_params
;
3028 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3029 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3030 $ov = new CRM_Core_DAO_OptionValue();
3031 $ov->option_group_id
= $optionGroupID;
3033 if ($ov->find(TRUE)) {
3034 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
3036 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3037 'option_group_id' => $optionGroupID,
3038 'label' => 'pick me',
3042 CRM_Core_DAO
::executeQuery("
3043 TRUNCATE civicrm_acl_cache
3046 CRM_Core_DAO
::executeQuery("
3047 TRUNCATE civicrm_acl_contact_cache
3050 CRM_Core_DAO
::executeQuery("
3051 INSERT INTO civicrm_acl_entity_role (
3052 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3053 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3057 CRM_Core_DAO
::executeQuery("
3058 INSERT INTO civicrm_acl (
3059 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3062 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3067 CRM_Core_DAO
::executeQuery("
3068 INSERT INTO civicrm_acl (
3069 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3072 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3076 CRM_Core_DAO
::executeQuery("
3077 INSERT INTO civicrm_acl (
3078 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3081 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3086 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3087 $this->callAPISuccess('group_contact', 'create', array(
3088 'group_id' => $this->_permissionedGroup
,
3089 'contact_id' => $this->_loggedInUser
,
3094 CRM_ACL_BAO_Cache
::resetCache();
3095 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3096 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3101 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3103 public function offsetDefaultPriceSet() {
3104 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3105 $firstID = $contributionPriceSet['id'];
3106 $this->callAPISuccess('price_set', 'create', array(
3107 'id' => $contributionPriceSet['id'],
3111 unset($contributionPriceSet['id']);
3112 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3113 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3114 'price_set_id' => $firstID,
3115 'options' => array('limit' => 1),
3117 unset($priceField['id']);
3118 $priceField['price_set_id'] = $newPriceSet['id'];
3119 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3120 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3121 'price_set_id' => $firstID,
3123 'options' => array('limit' => 1),
3126 unset($priceFieldValue['id']);
3127 //create some padding to use up ids
3128 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3129 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3130 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3134 * Create an instance of the paypal processor.
3135 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3136 * this parent class & we don't have a structure for that yet
3137 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3138 * & the best protection against that is the functions this class affords
3139 * @param array $params
3140 * @return int $result['id'] payment processor id
3142 public function paymentProcessorCreate($params = array()) {
3143 $params = array_merge(array(
3145 'domain_id' => CRM_Core_Config
::domainID(),
3146 'payment_processor_type_id' => 'PayPal',
3150 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3151 'password' => '1183377788',
3152 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3153 'url_site' => 'https://www.sandbox.paypal.com/',
3154 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3155 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3156 'class_name' => 'Payment_PayPalImpl',
3157 'billing_mode' => 3,
3158 'financial_type_id' => 1,
3159 'financial_account_id' => 12,
3160 // Credit card = 1 so can pass 'by accident'.
3161 'payment_instrument_id' => 'Debit Card',
3164 if (!is_numeric($params['payment_processor_type_id'])) {
3165 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3167 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3168 'name' => $params['payment_processor_type_id'],
3172 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3173 return $result['id'];
3177 * Set up initial recurring payment allowing subsequent IPN payments.
3179 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3180 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3181 'contact_id' => $this->_contactID
,
3184 'installments' => 5,
3185 'frequency_unit' => 'Month',
3186 'frequency_interval' => 1,
3187 'invoice_id' => $this->_invoiceID
,
3188 'contribution_status_id' => 2,
3189 'payment_processor_id' => $this->_paymentProcessorID
,
3190 // processor provided ID - use contact ID as proxy.
3191 'processor_id' => $this->_contactID
,
3192 'api.contribution.create' => array(
3193 'total_amount' => '200',
3194 'invoice_id' => $this->_invoiceID
,
3195 'financial_type_id' => 1,
3196 'contribution_status_id' => 'Pending',
3197 'contact_id' => $this->_contactID
,
3198 'contribution_page_id' => $this->_contributionPageID
,
3199 'payment_processor_id' => $this->_paymentProcessorID
,
3203 $this->_contributionRecurID
= $contributionRecur['id'];
3204 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3208 * 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
3210 public function setupMembershipRecurringPaymentProcessorTransaction() {
3211 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3212 //create a contribution so our membership & contribution don't both have id = 1
3213 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3214 $this->contributionCreate(array(
3215 'contact_id' => $this->_contactID
,
3217 'financial_type_id' => 1,
3218 'invoice_id' => 'abcd',
3222 $this->setupRecurringPaymentProcessorTransaction();
3224 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3225 'contact_id' => $this->_contactID
,
3226 'membership_type_id' => $this->ids
['membership_type'],
3227 'contribution_recur_id' => $this->_contributionRecurID
,
3228 'format.only_id' => TRUE,
3230 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3231 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3233 $this->callAPISuccess('line_item', 'create', array(
3234 'entity_table' => 'civicrm_membership',
3235 'entity_id' => $this->ids
['membership'],
3236 'contribution_id' => $this->_contributionID
,
3237 'label' => 'General',
3239 'unit_price' => 200,
3240 'line_total' => 200,
3241 'financial_type_id' => 1,
3242 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3244 'label' => 'Membership Amount',
3245 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3247 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3249 'label' => 'General',
3250 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3253 $this->callAPISuccess('membership_payment', 'create', array(
3254 'contribution_id' => $this->_contributionID
,
3255 'membership_id' => $this->ids
['membership'],
3264 public function CiviUnitTestCase_fatalErrorHandler($message) {
3265 throw new Exception("{$message['message']}: {$message['code']}");
3269 * Helper function to create new mailing.
3271 * @param array $params
3275 public function createMailing($params = array()) {
3276 $params = array_merge(array(
3277 'subject' => 'maild' . rand(),
3278 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3279 'name' => 'mailing name' . rand(),
3283 $result = $this->callAPISuccess('Mailing', 'create', $params);
3284 return $result['id'];
3288 * Helper function to delete mailing.
3291 public function deleteMailing($id) {
3296 $this->callAPISuccess('Mailing', 'delete', $params);
3300 * Wrap the entire test case in a transaction.
3302 * Only subsequent DB statements will be wrapped in TX -- this cannot
3303 * retroactively wrap old DB statements. Therefore, it makes sense to
3304 * call this at the beginning of setUp().
3306 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3307 * this option does not work with, e.g., custom-data.
3309 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3310 * if TRUNCATE or ALTER is called while using a transaction.
3313 * Whether to use nesting or reference-counting.
3315 public function useTransaction($nest = TRUE) {
3317 $this->tx
= new CRM_Core_Transaction($nest);
3318 $this->tx
->rollback();
3323 * Assert the attachment exists.
3325 * @param bool $exists
3326 * @param array $apiResult
3328 protected function assertAttachmentExistence($exists, $apiResult) {
3329 $fileId = $apiResult['id'];
3330 $this->assertTrue(is_numeric($fileId));
3331 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3332 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3333 1 => array($fileId, 'Int'),
3335 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3336 1 => array($fileId, 'Int'),
3341 * Create a price set for an event.
3343 * @param int $feeTotal
3344 * @param int $minAmt
3345 * @param string $type
3350 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3351 // creating price set, price field
3352 $paramsSet['title'] = 'Price Set';
3353 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3354 $paramsSet['is_active'] = FALSE;
3355 $paramsSet['extends'] = 1;
3356 $paramsSet['min_amount'] = $minAmt;
3358 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
3359 $this->_ids
['price_set'] = $priceSet->id
;
3361 $paramsField = array(
3362 'label' => 'Price Field',
3363 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3364 'html_type' => $type,
3365 'price' => $feeTotal,
3366 'option_label' => array('1' => 'Price Field'),
3367 'option_value' => array('1' => $feeTotal),
3368 'option_name' => array('1' => $feeTotal),
3369 'option_weight' => array('1' => 1),
3370 'option_amount' => array('1' => 1),
3371 'is_display_amounts' => 1,
3373 'options_per_line' => 1,
3374 'is_active' => array('1' => 1),
3375 'price_set_id' => $this->_ids
['price_set'],
3376 'is_enter_qty' => 1,
3377 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3379 if ($type === 'Radio') {
3380 $paramsField['is_enter_qty'] = 0;
3381 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3382 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3384 CRM_Price_BAO_PriceField
::create($paramsField);
3385 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
3386 $this->_ids
['price_field'] = array_keys($fields['values']);
3387 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
3388 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
3390 return $this->_ids
['price_set'];
3394 * Add a profile to a contribution page.
3396 * @param string $name
3397 * @param int $contributionPageID
3399 protected function addProfile($name, $contributionPageID) {
3400 $this->callAPISuccess('UFJoin', 'create', array(
3401 'uf_group_id' => $name,
3402 'module' => 'CiviContribute',
3403 'entity_table' => 'civicrm_contribution_page',
3404 'entity_id' => $contributionPageID,
3410 * Add participant with contribution
3414 protected function createParticipantWithContribution() {
3415 // creating price set, price field
3416 $this->_contactId
= $this->individualCreate();
3417 $event = $this->eventCreate();
3418 $this->_eventId
= $event['id'];
3419 $eventParams = array(
3420 'id' => $this->_eventId
,
3421 'financial_type_id' => 4,
3424 $this->callAPISuccess('event', 'create', $eventParams);
3425 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3426 $participantParams = array(
3427 'financial_type_id' => 4,
3428 'event_id' => $this->_eventId
,
3431 'fee_currency' => 'USD',
3432 'contact_id' => $this->_contactId
,
3434 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3435 $contributionParams = array(
3436 'total_amount' => 150,
3437 'currency' => 'USD',
3438 'contact_id' => $this->_contactId
,
3439 'financial_type_id' => 4,
3440 'contribution_status_id' => 1,
3441 'partial_payment_total' => 300.00,
3442 'partial_amount_to_pay' => 150,
3443 'contribution_mode' => 'participant',
3444 'participant_id' => $participant['id'],
3446 foreach ($priceFields['values'] as $key => $priceField) {
3447 $lineItems[1][$key] = array(
3448 'price_field_id' => $priceField['price_field_id'],
3449 'price_field_value_id' => $priceField['id'],
3450 'label' => $priceField['label'],
3451 'field_title' => $priceField['label'],
3453 'unit_price' => $priceField['amount'],
3454 'line_total' => $priceField['amount'],
3455 'financial_type_id' => $priceField['financial_type_id'],
3458 $contributionParams['line_item'] = $lineItems;
3459 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3460 $paymentParticipant = array(
3461 'participant_id' => $participant['id'],
3462 'contribution_id' => $contribution['id'],
3464 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3465 return array($lineItems, $contribution);
3471 * @param string $component
3472 * @param int $componentId
3476 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3477 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3478 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3479 $paramsSet['is_active'] = TRUE;
3480 $paramsSet['financial_type_id'] = 4;
3481 $paramsSet['extends'] = 1;
3482 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3483 $priceSetId = $priceSet['id'];
3484 //Checking for priceset added in the table.
3485 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3486 'id', $paramsSet['title'], 'Check DB for created priceset'
3488 $paramsField = array_merge(array(
3489 'label' => 'Price Field',
3490 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3491 'html_type' => 'CheckBox',
3492 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3493 'option_value' => array('1' => 100, '2' => 200),
3494 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3495 'option_weight' => array('1' => 1, '2' => 2),
3496 'option_amount' => array('1' => 100, '2' => 200),
3497 'is_display_amounts' => 1,
3499 'options_per_line' => 1,
3500 'is_active' => array('1' => 1, '2' => 1),
3501 'price_set_id' => $priceSet['id'],
3502 'is_enter_qty' => 1,
3503 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3504 ), $priceFieldOptions);
3506 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3508 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3510 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3514 * Replace the template with a test-oriented template designed to show all the variables.
3516 * @param string $templateName
3518 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3519 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3520 CRM_Core_DAO
::executeQuery(
3521 "UPDATE civicrm_option_group og
3522 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3523 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3524 SET m.msg_html = '{$testTemplate}'
3525 WHERE og.name = 'msg_tpl_workflow_contribution'
3526 AND ov.name = '{$templateName}'
3527 AND m.is_default = 1"
3532 * Reinstate the default template.
3534 * @param string $templateName
3536 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3537 CRM_Core_DAO
::executeQuery(
3538 "UPDATE civicrm_option_group og
3539 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3540 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3541 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3542 SET m.msg_html = m2.msg_html
3543 WHERE og.name = 'msg_tpl_workflow_contribution'
3544 AND ov.name = '{$templateName}'
3545 AND m.is_default = 1"
3550 * Flush statics relating to financial type.
3552 protected function flushFinancialTypeStatics() {
3553 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3554 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3556 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3557 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3559 CRM_Contribute_PseudoConstant
::flush('financialType');
3560 CRM_Contribute_PseudoConstant
::flush('membershipType');
3561 // Pseudoconstants may be saved to the cache table.
3562 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3563 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3564 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3568 * Set the permissions to the supplied array.
3570 * @param array $permissions
3572 protected function setPermissions($permissions) {
3573 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3574 $this->flushFinancialTypeStatics();
3575 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3579 * @param array $params
3582 public function _checkFinancialRecords($params, $context) {
3583 $entityParams = array(
3584 'entity_id' => $params['id'],
3585 'entity_table' => 'civicrm_contribution',
3587 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3588 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3589 if ($context == 'pending') {
3590 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3591 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3594 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3595 $trxnParams = array(
3596 'id' => $trxn['financial_trxn_id'],
3598 if ($context != 'online' && $context != 'payLater') {
3599 $compareParams = array(
3600 'to_financial_account_id' => 6,
3601 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3605 if ($context == 'feeAmount') {
3606 $compareParams['fee_amount'] = 50;
3608 elseif ($context == 'online') {
3609 $compareParams = array(
3610 'to_financial_account_id' => 12,
3611 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3613 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3616 elseif ($context == 'payLater') {
3617 $compareParams = array(
3618 'to_financial_account_id' => 7,
3619 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3623 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3624 $entityParams = array(
3625 'financial_trxn_id' => $trxn['financial_trxn_id'],
3626 'entity_table' => 'civicrm_financial_item',
3628 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3629 $fitemParams = array(
3630 'id' => $entityTrxn['entity_id'],
3632 $compareParams = array(
3633 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3635 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3637 if ($context == 'payLater') {
3638 $compareParams = array(
3639 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3641 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3644 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3645 if ($context == 'feeAmount') {
3647 'entity_id' => $params['id'],
3648 'entity_table' => 'civicrm_contribution',
3650 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3651 $trxnParams = array(
3652 'id' => $maxTrxn['financial_trxn_id'],
3654 $compareParams = array(
3655 'to_financial_account_id' => 5,
3656 'from_financial_account_id' => 6,
3657 'total_amount' => 50,
3660 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3661 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3662 $fitemParams = array(
3663 'entity_id' => $trxnId['financialTrxnId'],
3664 'entity_table' => 'civicrm_financial_trxn',
3666 $compareParams = array(
3669 'financial_account_id' => 5,
3671 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3673 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3674 // line should be copied into all the functions that call this function & evaluated there
3675 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3676 // when calling completeTransaction or repeatTransaction.
3677 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3681 * Return financial type id on basis of name
3683 * @param string $name Financial type m/c name
3687 public function getFinancialTypeId($name) {
3688 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3692 * Cleanup function for contents of $this->ids.
3694 * This is a best effort cleanup to use in tear downs etc.
3696 * It will not fail if the data has already been removed (some tests may do
3697 * their own cleanup).
3699 protected function cleanUpSetUpIDs() {
3700 foreach ($this->setupIDs
as $entity => $id) {
3702 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3704 catch (CiviCRM_API3_Exception
$e) {
3705 // This is a best-effort cleanup function, ignore.
3711 * Create Financial Type.
3713 * @param array $params
3717 protected function createFinancialType($params = array()) {
3718 $params = array_merge($params,
3720 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3724 return $this->callAPISuccess('FinancialType', 'create', $params);
3728 * Enable Tax and Invoicing
3730 protected function enableTaxAndInvoicing($params = array()) {
3731 // Enable component contribute setting
3732 $contributeSetting = array_merge($params,
3735 'invoice_prefix' => 'INV_',
3736 'credit_notes_prefix' => 'CN_',
3738 'due_date_period' => 'days',
3740 'is_email_pdf' => 1,
3741 'tax_term' => 'Sales Tax',
3742 'tax_display_settings' => 'Inclusive',
3745 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3749 * Enable Tax and Invoicing
3751 protected function disableTaxAndInvoicing($params = array()) {
3752 // Enable component contribute setting
3753 $contributeSetting = array_merge($params,
3758 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3762 * Add Sales Tax relation for financial type with financial account.
3764 * @param int $financialTypeId
3768 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3770 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3771 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3772 'is_deductible' => 1,
3777 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3778 $entityParams = array(
3779 'entity_table' => 'civicrm_financial_type',
3780 'entity_id' => $financialTypeId,
3781 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3784 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3785 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3786 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3787 $dao->copyValues($entityParams);
3789 if ($dao->fetch()) {
3790 $entityParams['id'] = $dao->id
;
3792 $entityParams['financial_account_id'] = $account->id
;
3794 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3798 * Create price set with contribution test for test setup.
3800 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3801 * on parent class at some point (fn is not in 4.4).
3804 * @param array $params
3806 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3807 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3808 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3809 'title' => "Test Contribution Page",
3810 'financial_type_id' => 1,
3811 'currency' => 'NZD',
3812 'goal_amount' => 50,
3813 'is_pay_later' => 1,
3814 'is_monetary' => TRUE,
3815 'is_email_receipt' => FALSE,
3817 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3818 'is_quick_config' => 0,
3819 'extends' => 'CiviMember',
3820 'financial_type_id' => 1,
3821 'title' => 'my Page',
3823 $priceSetID = $priceSet['id'];
3825 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3826 $priceField = $this->callAPISuccess('price_field', 'create', array(
3827 'price_set_id' => $priceSetID,
3828 'label' => 'Goat Breed',
3829 'html_type' => 'Radio',
3831 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3832 'price_set_id' => $priceSetID,
3833 'price_field_id' => $priceField['id'],
3834 'label' => 'Long Haired Goat',
3836 'financial_type_id' => 'Donation',
3837 'membership_type_id' => $membershipTypeID,
3838 'membership_num_terms' => 1,
3841 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3842 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3843 'price_set_id' => $priceSetID,
3844 'price_field_id' => $priceField['id'],
3845 'label' => 'Shoe-eating Goat',
3847 'financial_type_id' => 'Donation',
3848 'membership_type_id' => $membershipTypeID,
3849 'membership_num_terms' => 2,
3852 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3854 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3855 'price_set_id' => $priceSetID,
3856 'price_field_id' => $priceField['id'],
3857 'label' => 'Shoe-eating Goat',
3859 'financial_type_id' => 'Donation',
3862 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3864 $this->_ids
['price_set'] = $priceSetID;
3865 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3866 $this->_ids
['price_field'] = array($priceField['id']);
3868 $this->_ids
['membership_type'] = $membershipTypeID;
3872 * No results returned.
3874 * @implements CRM_Utils_Hook::aclWhereClause
3876 * @param string $type
3877 * @param array $tables
3878 * @param array $whereTables
3879 * @param int $contactID
3880 * @param string $where
3882 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3886 * Only specified contact returned.
3887 * @implements CRM_Utils_Hook::aclWhereClause
3890 * @param $whereTables
3894 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3895 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3899 * @implements CRM_Utils_Hook::selectWhereClause
3901 * @param string $entity
3902 * @param array $clauses
3904 public function selectWhereClauseHook($entity, &$clauses) {
3905 if ($entity == 'Event') {
3906 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3911 * An implementation of hook_civicrm_post used with all our test cases.
3914 * @param string $objectName
3915 * @param int $objectId
3918 public function onPost($op, $objectName, $objectId, &$objectRef) {
3919 if ($op == 'create' && $objectName == 'Individual') {
3920 CRM_Core_DAO
::executeQuery(
3921 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3923 1 => array($objectId, 'Integer'),
3928 if ($op == 'edit' && $objectName == 'Participant') {
3930 1 => array($objectId, 'Integer'),
3932 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3933 CRM_Core_DAO
::executeQuery($query, $params);
3939 * Instantiate form object.
3941 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3943 * @param string $class
3944 * Name of form class.
3946 * @return \CRM_Core_Form
3948 public function getFormObject($class) {
3949 $form = new $class();
3950 $_SERVER['REQUEST_METHOD'] = 'GET';
3951 $form->controller
= new CRM_Core_Controller();