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 require_once 'CRM/Financial/BAO/FinancialType.php';
36 define('API_LATEST_VERSION', 3);
39 * Base class for CiviCRM unit tests
41 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
42 * may opt for one or neither:
44 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
45 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
46 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
47 * 2. useTransaction() executes the test inside a transaction. It's easier to use
48 * (because you don't need to identify specific tables), but it doesn't work for tests
49 * which manipulate schema or truncate data -- and could behave inconsistently
50 * for tests which specifically examine DB transactions.
52 * Common functions for unit tests
55 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
58 * Api version - easier to override than just a define
60 protected $_apiversion = API_LATEST_VERSION
;
62 * Database has been initialized.
66 private static $dbInit = FALSE;
69 * Database connection.
71 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
80 static protected $_dbName;
83 * Track tables we have modified during a test.
85 protected $_tablesToTruncate = array();
88 * @var array of temporary directory names
93 * @var boolean populateOnce allows to skip db resets in setUp
95 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
96 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
99 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
101 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
103 public static $populateOnce = FALSE;
106 * @var boolean DBResetRequired allows skipping DB reset
107 * in specific test case. If you still need
108 * to reset single test (method) of such case, call
109 * $this->cleanDB() in the first line of this
112 public $DBResetRequired = TRUE;
115 * @var CRM_Core_Transaction|NULL
120 * @var CRM_Utils_Hook_UnitTests hookClass
121 * example of setting a method for a hook
122 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
124 public $hookClass = NULL;
127 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
129 protected $_params = array();
132 * @var CRM_Extension_System
134 protected $origExtensionSystem;
139 * Because we are overriding the parent class constructor, we
140 * need to show the same arguments as exist in the constructor of
141 * PHPUnit_Framework_TestCase, since
142 * PHPUnit_Framework_TestSuite::createTest() creates a
143 * ReflectionClass of the Test class and checks the constructor
144 * of that class to decide how to set up the test.
146 * @param string $name
148 * @param string $dataName
150 public function __construct($name = NULL, array$data = array(), $dataName = '') {
151 parent
::__construct($name, $data, $dataName);
153 // we need full error reporting
154 error_reporting(E_ALL
& ~E_NOTICE
);
156 self
::$_dbName = self
::getDBName();
158 // also load the class loader
159 require_once 'CRM/Core/ClassLoader.php';
160 CRM_Core_ClassLoader
::singleton()->register();
161 if (function_exists('_civix_phpunit_setUp')) {
162 // FIXME: loosen coupling
163 _civix_phpunit_setUp();
168 * Override to run the test and assert its state.
171 * @throws \PHPUnit_Framework_IncompleteTest
172 * @throws \PHPUnit_Framework_SkippedTest
174 protected function runTest() {
176 return parent
::runTest();
178 catch (PEAR_Exception
$e) {
179 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
180 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
187 public function requireDBReset() {
188 return $this->DBResetRequired
;
194 public static function getDBName() {
195 static $dbName = NULL;
196 if ($dbName === NULL) {
197 require_once "DB.php";
198 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
199 $dbName = $dsninfo['database'];
205 * Create database connection for this instance.
207 * Initialize the test database if it hasn't been initialized
209 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
211 protected function getConnection() {
212 $dbName = self
::$_dbName;
213 if (!self
::$dbInit) {
214 $dbName = self
::getDBName();
216 // install test database
217 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
219 static::_populateDB(FALSE, $this);
221 self
::$dbInit = TRUE;
224 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
228 * Required implementation of abstract method.
230 protected function getDataSet() {
234 * @param bool $perClass
235 * @param null $object
237 * TRUE if the populate logic runs; FALSE if it is skipped
239 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
240 if (CIVICRM_UF
!== 'UnitTests') {
241 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
244 if ($perClass ||
$object == NULL) {
248 $dbreset = $object->requireDBReset();
251 if (self
::$populateOnce ||
!$dbreset) {
254 self
::$populateOnce = NULL;
256 Civi\Test
::data()->populate();
261 public static function setUpBeforeClass() {
262 static::_populateDB(TRUE);
264 // also set this global hack
265 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
269 * Common setup functions for all unit tests.
271 protected function setUp() {
272 $session = CRM_Core_Session
::singleton();
273 $session->set('userID', NULL);
275 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
276 // Use a temporary file for STDIN
277 $GLOBALS['stdin'] = tmpfile();
278 if ($GLOBALS['stdin'] === FALSE) {
279 echo "Couldn't open temporary file\n";
283 // Get and save a connection to the database
284 $this->_dbconn
= $this->getConnection();
286 // reload database before each test
287 // $this->_populateDB();
289 // "initialize" CiviCRM to avoid problems when running single tests
290 // FIXME: look at it closer in second stage
292 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
293 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
295 // disable any left-over test extensions
296 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
298 // reset all the caches
299 CRM_Utils_System
::flushCache();
301 // initialize the object once db is loaded
303 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
305 // when running unit tests, use mockup user framework
306 $this->hookClass
= CRM_Utils_Hook
::singleton();
308 // Make sure the DB connection is setup properly
309 $config->userSystem
->setMySQLTimeZone();
310 $env = new CRM_Utils_Check_Component_Env();
311 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
313 // clear permissions stub to not check permissions
314 $config->userPermissionClass
->permissions
= NULL;
316 //flush component settings
317 CRM_Core_Component
::getEnabledComponents(TRUE);
319 error_reporting(E_ALL
);
321 $this->_sethtmlGlobals();
325 * Read everything from the datasets directory and insert into the db.
327 public function loadAllFixtures() {
328 $fixturesDir = __DIR__
. '/../../fixtures';
330 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
332 $xmlFiles = glob($fixturesDir . '/*.xml');
333 foreach ($xmlFiles as $xmlFixture) {
334 $op = new PHPUnit_Extensions_Database_Operation_Insert();
335 $dataset = $this->createXMLDataSet($xmlFixture);
336 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
337 $op->execute($this->_dbconn
, $dataset);
340 $yamlFiles = glob($fixturesDir . '/*.yaml');
341 foreach ($yamlFiles as $yamlFixture) {
342 $op = new PHPUnit_Extensions_Database_Operation_Insert();
343 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
344 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
345 $op->execute($this->_dbconn
, $dataset);
348 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
352 * Emulate a logged in user since certain functions use that.
353 * value to store a record in the DB (like activity)
357 * Contact ID of the created user.
359 public function createLoggedInUser() {
361 'first_name' => 'Logged In',
362 'last_name' => 'User ' . rand(),
363 'contact_type' => 'Individual',
365 $contactID = $this->individualCreate($params);
366 $this->callAPISuccess('UFMatch', 'create', array(
367 'contact_id' => $contactID,
368 'uf_name' => 'superman',
372 $session = CRM_Core_Session
::singleton();
373 $session->set('userID', $contactID);
378 * Create default domain contacts for the two domains added during test class.
379 * database population.
381 public function createDomainContacts() {
382 $this->organizationCreate();
383 $this->organizationCreate(array('organization_name' => 'Second Domain'));
387 * Common teardown functions for all unit tests.
389 protected function tearDown() {
390 error_reporting(E_ALL
& ~E_NOTICE
);
391 CRM_Utils_Hook
::singleton()->reset();
392 $this->hookClass
->reset();
393 $session = CRM_Core_Session
::singleton();
394 $session->set('userID', NULL);
397 $this->tx
->rollback()->commit();
400 CRM_Core_Transaction
::forceRollbackIfEnabled();
401 \Civi\Core\Transaction\Manager
::singleton(TRUE);
404 CRM_Core_Transaction
::forceRollbackIfEnabled();
405 \Civi\Core\Transaction\Manager
::singleton(TRUE);
407 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
408 $this->quickCleanup($tablesToTruncate);
409 $this->createDomainContacts();
412 $this->cleanTempDirs();
413 $this->unsetExtensionSystem();
417 * Generic function to compare expected values after an api call to retrieved.
420 * @daoName string DAO Name of object we're evaluating.
421 * @id int Id of object
422 * @match array Associative array of field name => expected value. Empty if asserting
423 * that a DELETE occurred
424 * @delete boolean True if we're checking that a DELETE action occurred.
428 * @param bool $delete
429 * @throws \PHPUnit_Framework_AssertionFailedError
431 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
433 // adding this here since developers forget to check for an id
434 // and hence we get the first value in the db
435 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
438 $object = new $daoName();
442 // If we're asserting successful record deletion, make sure object is NOT found.
444 if ($object->find(TRUE)) {
445 $this->fail("Object not deleted by delete operation: $daoName, $id");
450 // Otherwise check matches of DAO field values against expected values in $match.
451 if ($object->find(TRUE)) {
452 $fields = &$object->fields();
453 foreach ($fields as $name => $value) {
454 $dbName = $value['name'];
455 if (isset($match[$name])) {
457 $this->assertEquals($object->$dbName, $match[$name]);
459 elseif (isset($match[$dbName])) {
461 $this->assertEquals($object->$dbName, $match[$dbName]);
466 $this->fail("Could not retrieve object: $daoName, $id");
469 $matchSize = count($match);
470 if ($verifiedCount != $matchSize) {
471 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
476 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
477 * @param string $daoName
478 * @param $searchValue
479 * @param $returnColumn
480 * @param $searchColumn
483 * @return null|string
484 * @throws PHPUnit_Framework_AssertionFailedError
486 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
487 if (empty($searchValue)) {
488 $this->fail("empty value passed to assertDBNotNull");
490 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
491 $this->assertNotNull($value, $message);
497 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
498 * @param string $daoName
499 * @param $searchValue
500 * @param $returnColumn
501 * @param $searchColumn
504 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
505 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
506 $this->assertNull($value, $message);
510 * Request a record from the DB by id. Success if row not found.
511 * @param string $daoName
513 * @param null $message
515 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
516 $message = $message ?
$message : "$daoName (#$id) should not exist";
517 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
518 $this->assertNull($value, $message);
522 * Request a record from the DB by id. Success if row not found.
523 * @param string $daoName
525 * @param null $message
527 public function assertDBRowExist($daoName, $id, $message = NULL) {
528 $message = $message ?
$message : "$daoName (#$id) should exist";
529 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
530 $this->assertEquals($id, $value, $message);
534 * Compare a single column value in a retrieved DB record to an expected value.
535 * @param string $daoName
536 * @param $searchValue
537 * @param $returnColumn
538 * @param $searchColumn
539 * @param $expectedValue
542 public function assertDBCompareValue(
543 $daoName, $searchValue, $returnColumn, $searchColumn,
544 $expectedValue, $message
546 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
547 $this->assertEquals($value, $expectedValue, $message);
551 * Compare all values in a single retrieved DB record to an array of expected values.
552 * @param string $daoName
553 * @param array $searchParams
554 * @param $expectedValues
556 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
557 //get the values from db
559 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
561 // compare db values with expected values
562 self
::assertAttributesEquals($expectedValues, $dbValues);
566 * Assert that a SQL query returns a given value.
568 * The first argument is an expected value. The remaining arguments are passed
569 * to CRM_Core_DAO::singleValueQuery
571 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
572 * array(1 => array("Whiz", "String")));
575 * @param array $params
576 * @param string $message
578 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
582 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
583 $this->assertEquals($expected, $actual,
584 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
585 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
591 * Assert that two array-trees are exactly equal, notwithstanding
592 * the sorting of keys
594 * @param array $expected
595 * @param array $actual
597 public function assertTreeEquals($expected, $actual) {
600 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
601 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
605 $this->assertEquals($e, $a);
609 * Assert that two numbers are approximately equal.
611 * @param int|float $expected
612 * @param int|float $actual
613 * @param int|float $tolerance
614 * @param string $message
616 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
617 if ($message === NULL) {
618 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
620 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
624 * Assert attributes are equal.
626 * @param $expectedValues
627 * @param $actualValues
628 * @param string $message
630 * @throws PHPUnit_Framework_AssertionFailedError
632 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
633 foreach ($expectedValues as $paramName => $paramValue) {
634 if (isset($actualValues[$paramName])) {
635 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
638 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
647 public function assertArrayKeyExists($key, &$list) {
648 $result = isset($list[$key]) ?
TRUE : FALSE;
649 $this->assertTrue($result, ts("%1 element exists?",
658 public function assertArrayValueNotNull($key, &$list) {
659 $this->assertArrayKeyExists($key, $list);
661 $value = isset($list[$key]) ?
$list[$key] : NULL;
662 $this->assertTrue($value,
663 ts("%1 element not null?",
670 * Check that api returned 'is_error' => 0.
672 * @param array $apiResult
674 * @param string $prefix
675 * Extra test to add to message.
677 public function assertAPISuccess($apiResult, $prefix = '') {
678 if (!empty($prefix)) {
681 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
683 if (!empty($apiResult['debug_information'])) {
684 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
686 if (!empty($apiResult['trace'])) {
687 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
689 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
693 * Check that api returned 'is_error' => 1.
695 * @param array $apiResult
697 * @param string $prefix
698 * Extra test to add to message.
699 * @param null $expectedError
701 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
702 if (!empty($prefix)) {
705 if ($expectedError && !empty($apiResult['is_error'])) {
706 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
708 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
709 $this->assertNotEmpty($apiResult['error_message']);
715 * @param string $message
717 public function assertType($expected, $actual, $message = '') {
718 return $this->assertInternalType($expected, $actual, $message);
722 * Check that a deleted item has been deleted.
727 public function assertAPIDeleted($entity, $id) {
728 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
733 * Check that api returned 'is_error' => 1
734 * else provide full message
735 * @param array $result
737 * @param array $valuesToExclude
738 * @param string $prefix
739 * Extra test to add to message.
741 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
742 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
743 foreach ($valuesToExclude as $value) {
744 if (isset($result[$value])) {
745 unset($result[$value]);
747 if (isset($expected[$value])) {
748 unset($expected[$value]);
751 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
755 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
759 * @param array $params
762 public function civicrm_api($entity, $action, $params) {
763 return civicrm_api($entity, $action, $params);
767 * Create a batch of external API calls which can
768 * be executed concurrently.
771 * $calls = $this->createExternalAPI()
772 * ->addCall('Contact', 'get', ...)
773 * ->addCall('Contact', 'get', ...)
779 * @return \Civi\API\ExternalBatch
780 * @throws PHPUnit_Framework_SkippedTestError
782 public function createExternalAPI() {
783 global $civicrm_root;
784 $defaultParams = array(
785 'version' => $this->_apiversion
,
789 $calls = new \Civi\API\
ExternalBatch($defaultParams);
791 if (!$calls->isSupported()) {
792 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
799 * wrap api functions.
800 * so we can ensure they succeed & throw exceptions without litterering the test with checks
802 * @param string $entity
803 * @param string $action
804 * @param array $params
805 * @param mixed $checkAgainst
806 * Optional value to check result against, implemented for getvalue,.
807 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
808 * for getsingle the array is compared against an array passed in - the id is not compared (for
813 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
814 $params = array_merge(array(
815 'version' => $this->_apiversion
,
820 switch (strtolower($action)) {
822 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
825 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
828 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
830 $result = $this->civicrm_api($entity, $action, $params);
831 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
836 * This function exists to wrap api getValue function & check the result
837 * so we can ensure they succeed & throw exceptions without litterering the test with checks
838 * There is a type check in this
840 * @param string $entity
841 * @param array $params
842 * @param string $type
843 * Per http://php.net/manual/en/function.gettype.php possible types.
853 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
855 'version' => $this->_apiversion
,
858 $result = $this->civicrm_api($entity, 'getvalue', $params);
860 if ($type == 'integer') {
861 // api seems to return integers as strings
862 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
865 $this->assertType($type, $result, "returned result should have been of type $type but was ");
872 * This function exists to wrap api getsingle function & check the result
873 * so we can ensure they succeed & throw exceptions without litterering the test with checks
875 * @param string $entity
876 * @param array $params
877 * @param array $checkAgainst
878 * Array to compare result against.
889 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
891 'version' => $this->_apiversion
,
894 $result = $this->civicrm_api($entity, 'getsingle', $params);
895 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
896 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
899 // @todo - have gone with the fn that unsets id? should we check id?
900 $this->checkArrayEquals($result, $checkAgainst);
906 * This function exists to wrap api getValue function & check the result
907 * so we can ensure they succeed & throw exceptions without litterering the test with checks
908 * There is a type check in this
909 * @param string $entity
910 * @param array $params
915 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
917 'version' => $this->_apiversion
,
920 $result = $this->civicrm_api($entity, 'getcount', $params);
921 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
922 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
924 if (is_int($count)) {
925 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
931 * This function exists to wrap api functions.
932 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
934 * @param string $entity
935 * @param string $action
936 * @param array $params
937 * @param string $function
938 * Pass this in to create a generated example.
939 * @param string $file
940 * Pass this in to create a generated example.
941 * @param string $description
942 * @param string|null $exampleName
946 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
947 $params['version'] = $this->_apiversion
;
948 $result = $this->callAPISuccess($entity, $action, $params);
949 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
954 * This function exists to wrap api functions.
955 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
956 * @param string $entity
957 * @param string $action
958 * @param array $params
959 * @param string $expectedErrorMessage
961 * @param null $extraOutput
964 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
965 if (is_array($params)) {
967 'version' => $this->_apiversion
,
970 $result = $this->civicrm_api($entity, $action, $params);
971 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
976 * Create required data based on $this->entity & $this->params
977 * This is just a way to set up the test data for delete & get functions
978 * so the distinction between set
979 * up & tested functions is clearer
984 public function createTestEntity() {
985 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
989 * Generic function to create Organisation, to be used in test cases
991 * @param array $params
992 * parameters for civicrm_contact_add api function call
994 * sequence number if creating multiple organizations
997 * id of Organisation created
999 public function organizationCreate($params = array(), $seq = 0) {
1003 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1004 return $this->_contactCreate($params);
1008 * Generic function to create Individual, to be used in test cases
1010 * @param array $params
1011 * parameters for civicrm_contact_add api function call
1013 * sequence number if creating multiple individuals
1016 * id of Individual created
1018 public function individualCreate($params = array(), $seq = 0) {
1019 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1020 return $this->_contactCreate($params);
1024 * Generic function to create Household, to be used in test cases
1026 * @param array $params
1027 * parameters for civicrm_contact_add api function call
1029 * sequence number if creating multiple households
1032 * id of Household created
1034 public function householdCreate($params = array(), $seq = 0) {
1035 $params = array_merge($this->sampleContact('Household', $seq), $params);
1036 return $this->_contactCreate($params);
1040 * Helper function for getting sample contact properties.
1042 * @param string $contact_type
1043 * enum contact type: Individual, Organization
1045 * sequence number for the values of this type
1048 * properties of sample contact (ie. $params for API call)
1050 public function sampleContact($contact_type, $seq = 0) {
1052 'Individual' => array(
1053 // The number of values in each list need to be coprime numbers to not have duplicates
1054 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1055 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1056 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1058 'Organization' => array(
1059 'organization_name' => array(
1060 'Unit Test Organization',
1067 'Household' => array(
1068 'household_name' => array('Unit Test household'),
1071 $params = array('contact_type' => $contact_type);
1072 foreach ($samples[$contact_type] as $key => $values) {
1073 $params[$key] = $values[$seq %
count($values)];
1075 if ($contact_type == 'Individual') {
1076 $params['email'] = strtolower(
1077 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1079 $params['prefix_id'] = 3;
1080 $params['suffix_id'] = 3;
1086 * Private helper function for calling civicrm_contact_add.
1088 * @param array $params
1089 * For civicrm_contact_add api function call.
1094 * id of Household created
1096 private function _contactCreate($params) {
1097 $result = $this->callAPISuccess('contact', 'create', $params);
1098 if (!empty($result['is_error']) ||
empty($result['id'])) {
1099 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1101 return $result['id'];
1105 * Delete contact, ensuring it is not the domain contact
1107 * @param int $contactID
1108 * Contact ID to delete
1110 public function contactDelete($contactID) {
1111 $domain = new CRM_Core_BAO_Domain();
1112 $domain->contact_id
= $contactID;
1113 if (!$domain->find(TRUE)) {
1114 $this->callAPISuccess('contact', 'delete', array(
1116 'skip_undelete' => 1,
1122 * @param int $contactTypeId
1126 public function contactTypeDelete($contactTypeId) {
1127 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1129 throw new Exception('Could not delete contact type');
1134 * @param array $params
1138 public function membershipTypeCreate($params = array()) {
1139 CRM_Member_PseudoConstant
::flush('membershipType');
1140 CRM_Core_Config
::clearDBCache();
1141 $memberOfOrganization = $this->organizationCreate();
1142 $params = array_merge(array(
1143 'name' => 'General',
1144 'duration_unit' => 'year',
1145 'duration_interval' => 1,
1146 'period_type' => 'rolling',
1147 'member_of_contact_id' => $memberOfOrganization,
1149 'financial_type_id' => 1,
1152 'visibility' => 'Public',
1155 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1157 CRM_Member_PseudoConstant
::flush('membershipType');
1158 CRM_Utils_Cache
::singleton()->flush();
1160 return $result['id'];
1164 * @param array $params
1168 public function contactMembershipCreate($params) {
1170 'join_date' => '2007-01-21',
1171 'start_date' => '2007-01-21',
1172 'end_date' => '2007-12-21',
1173 'source' => 'Payment',
1176 foreach ($pre as $key => $val) {
1177 if (!isset($params[$key])) {
1178 $params[$key] = $val;
1182 $result = $this->callAPISuccess('Membership', 'create', $params);
1183 return $result['id'];
1187 * Delete Membership Type.
1189 * @param array $params
1191 public function membershipTypeDelete($params) {
1192 $this->callAPISuccess('MembershipType', 'Delete', $params);
1196 * @param int $membershipID
1198 public function membershipDelete($membershipID) {
1199 $deleteParams = array('id' => $membershipID);
1200 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1204 * @param string $name
1208 public function membershipStatusCreate($name = 'test member status') {
1209 $params['name'] = $name;
1210 $params['start_event'] = 'start_date';
1211 $params['end_event'] = 'end_date';
1212 $params['is_current_member'] = 1;
1213 $params['is_active'] = 1;
1215 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1216 CRM_Member_PseudoConstant
::flush('membershipStatus');
1217 return $result['id'];
1221 * @param int $membershipStatusID
1223 public function membershipStatusDelete($membershipStatusID) {
1224 if (!$membershipStatusID) {
1227 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1231 * @param array $params
1235 public function relationshipTypeCreate($params = array()) {
1236 $params = array_merge(array(
1237 'name_a_b' => 'Relation 1 for relationship type create',
1238 'name_b_a' => 'Relation 2 for relationship type create',
1239 'contact_type_a' => 'Individual',
1240 'contact_type_b' => 'Organization',
1247 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1248 CRM_Core_PseudoConstant
::flush('relationshipType');
1250 return $result['id'];
1254 * Delete Relatinship Type.
1256 * @param int $relationshipTypeID
1258 public function relationshipTypeDelete($relationshipTypeID) {
1259 $params['id'] = $relationshipTypeID;
1260 $this->callAPISuccess('relationship_type', 'delete', $params);
1264 * @param array $params
1268 public function paymentProcessorTypeCreate($params = NULL) {
1269 if (is_null($params)) {
1271 'name' => 'API_Test_PP',
1272 'title' => 'API Test Payment Processor',
1273 'class_name' => 'CRM_Core_Payment_APITest',
1274 'billing_mode' => 'form',
1280 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1282 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1284 return $result['id'];
1288 * Create test Authorize.net instance.
1290 * @param array $params
1294 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1295 $params = array_merge(array(
1296 'name' => 'Authorize',
1297 'domain_id' => CRM_Core_Config
::domainID(),
1298 'payment_processor_type_id' => 'AuthNet',
1299 'title' => 'AuthNet',
1304 'user_name' => '4y5BfuW7jm',
1305 'password' => '4cAmW927n8uLf5J8',
1306 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1307 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1308 'class_name' => 'Payment_AuthorizeNet',
1309 'billing_mode' => 1,
1312 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1313 return $result['id'];
1317 * Create Participant.
1319 * @param array $params
1320 * Array of contact id and event id values.
1323 * $id of participant created
1325 public function participantCreate($params) {
1326 if (empty($params['contact_id'])) {
1327 $params['contact_id'] = $this->individualCreate();
1329 if (empty($params['event_id'])) {
1330 $event = $this->eventCreate();
1331 $params['event_id'] = $event['id'];
1336 'register_date' => 20070219,
1337 'source' => 'Wimbeldon',
1338 'event_level' => 'Payment',
1342 $params = array_merge($defaults, $params);
1343 $result = $this->callAPISuccess('Participant', 'create', $params);
1344 return $result['id'];
1348 * Create Payment Processor.
1351 * Id Payment Processor
1353 public function processorCreate() {
1354 $processorParams = array(
1357 'payment_processor_type_id' => 'Dummy',
1358 'financial_account_id' => 12,
1362 'url_site' => 'http://dummy.com',
1363 'url_recur' => 'http://dummy.com',
1364 'billing_mode' => 1,
1367 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1368 return $processor['id'];
1372 * Create Payment Processor.
1374 * @param array $processorParams
1376 * @return \CRM_Core_Payment_Dummy
1377 * Instance of Dummy Payment Processor
1379 public function dummyProcessorCreate($processorParams = array()) {
1380 $paymentProcessorID = $this->processorCreate($processorParams);
1381 return System
::singleton()->getById($paymentProcessorID);
1385 * Create contribution page.
1387 * @param array $params
1389 * Array of contribution page
1391 public function contributionPageCreate($params) {
1392 $this->_pageParams
= array(
1393 'title' => 'Test Contribution Page',
1394 'financial_type_id' => 1,
1395 'currency' => 'USD',
1396 'financial_account_id' => 1,
1397 'payment_processor' => $params['processor_id'],
1399 'is_allow_other_amount' => 1,
1401 'max_amount' => 1000,
1403 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1404 return $contributionPage;
1408 * Create a sample batch.
1410 public function batchCreate() {
1411 $params = $this->_params
;
1412 $params['name'] = $params['title'] = 'Batch_433397';
1413 $params['status_id'] = 1;
1414 $result = $this->callAPISuccess('batch', 'create', $params);
1415 return $result['id'];
1421 * @param array $params
1423 * result of created tag
1425 public function tagCreate($params = array()) {
1427 'name' => 'New Tag3',
1428 'description' => 'This is description for Our New Tag ',
1431 $params = array_merge($defaults, $params);
1432 $result = $this->callAPISuccess('Tag', 'create', $params);
1433 return $result['values'][$result['id']];
1440 * Id of the tag to be deleted.
1444 public function tagDelete($tagId) {
1445 require_once 'api/api.php';
1449 $result = $this->callAPISuccess('Tag', 'delete', $params);
1450 return $result['id'];
1454 * Add entity(s) to the tag
1456 * @param array $params
1460 public function entityTagAdd($params) {
1461 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1466 * Create contribution.
1472 * id of created contribution
1474 public function pledgeCreate($cID) {
1476 'contact_id' => $cID,
1477 'pledge_create_date' => date('Ymd'),
1478 'start_date' => date('Ymd'),
1479 'scheduled_date' => date('Ymd'),
1481 'pledge_status_id' => '2',
1482 'financial_type_id' => '1',
1483 'pledge_original_installment_amount' => 20,
1484 'frequency_interval' => 5,
1485 'frequency_unit' => 'year',
1486 'frequency_day' => 15,
1487 'installments' => 5,
1490 $result = $this->callAPISuccess('Pledge', 'create', $params);
1491 return $result['id'];
1495 * Delete contribution.
1497 * @param int $pledgeId
1499 public function pledgeDelete($pledgeId) {
1501 'pledge_id' => $pledgeId,
1503 $this->callAPISuccess('Pledge', 'delete', $params);
1507 * Create contribution.
1509 * @param array $params
1510 * Array of parameters.
1513 * id of created contribution
1515 public function contributionCreate($params) {
1517 $params = array_merge(array(
1519 'receive_date' => date('Ymd'),
1520 'total_amount' => 100.00,
1521 'fee_amount' => 5.00,
1522 'net_ammount' => 95.00,
1523 'financial_type_id' => 1,
1524 'payment_instrument_id' => 1,
1525 'non_deductible_amount' => 10.00,
1527 'invoice_id' => 67890,
1529 'contribution_status_id' => 1,
1532 $result = $this->callAPISuccess('contribution', 'create', $params);
1533 return $result['id'];
1537 * Delete contribution.
1539 * @param int $contributionId
1543 public function contributionDelete($contributionId) {
1545 'contribution_id' => $contributionId,
1547 $result = $this->callAPISuccess('contribution', 'delete', $params);
1554 * @param array $params
1555 * Name-value pair for an event.
1559 public function eventCreate($params = array()) {
1560 // if no contact was passed, make up a dummy event creator
1561 if (!isset($params['contact_id'])) {
1562 $params['contact_id'] = $this->_contactCreate(array(
1563 'contact_type' => 'Individual',
1564 'first_name' => 'Event',
1565 'last_name' => 'Creator',
1569 // set defaults for missing params
1570 $params = array_merge(array(
1571 'title' => 'Annual CiviCRM meet',
1572 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1573 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1574 'event_type_id' => 1,
1576 'start_date' => 20081021,
1577 'end_date' => 20081023,
1578 'is_online_registration' => 1,
1579 'registration_start_date' => 20080601,
1580 'registration_end_date' => 20081015,
1581 'max_participants' => 100,
1582 'event_full_text' => 'Sorry! We are already full',
1585 'is_show_location' => 0,
1588 return $this->callAPISuccess('Event', 'create', $params);
1599 public function eventDelete($id) {
1603 return $this->callAPISuccess('event', 'delete', $params);
1607 * Delete participant.
1609 * @param int $participantID
1613 public function participantDelete($participantID) {
1615 'id' => $participantID,
1617 return $this->callAPISuccess('Participant', 'delete', $params);
1621 * Create participant payment.
1623 * @param int $participantID
1624 * @param int $contributionID
1626 * $id of created payment
1628 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1629 //Create Participant Payment record With Values
1631 'participant_id' => $participantID,
1632 'contribution_id' => $contributionID,
1635 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1636 return $result['id'];
1640 * Delete participant payment.
1642 * @param int $paymentID
1644 public function participantPaymentDelete($paymentID) {
1648 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1654 * @param int $contactID
1656 * location id of created location
1658 public function locationAdd($contactID) {
1661 'location_type' => 'New Location Type',
1663 'name' => 'Saint Helier St',
1664 'county' => 'Marin',
1665 'country' => 'UNITED STATES',
1666 'state_province' => 'Michigan',
1667 'supplemental_address_1' => 'Hallmark Ct',
1668 'supplemental_address_2' => 'Jersey Village',
1673 'contact_id' => $contactID,
1674 'address' => $address,
1675 'location_format' => '2.0',
1676 'location_type' => 'New Location Type',
1679 $result = $this->callAPISuccess('Location', 'create', $params);
1684 * Delete Locations of contact.
1686 * @param array $params
1689 public function locationDelete($params) {
1690 $this->callAPISuccess('Location', 'delete', $params);
1694 * Add a Location Type.
1696 * @param array $params
1697 * @return CRM_Core_DAO_LocationType
1698 * location id of created location
1700 public function locationTypeCreate($params = NULL) {
1701 if ($params === NULL) {
1703 'name' => 'New Location Type',
1704 'vcard_name' => 'New Location Type',
1705 'description' => 'Location Type for Delete',
1710 $locationType = new CRM_Core_DAO_LocationType();
1711 $locationType->copyValues($params);
1712 $locationType->save();
1713 // clear getfields cache
1714 CRM_Core_PseudoConstant
::flush();
1715 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1716 return $locationType;
1720 * Delete a Location Type.
1722 * @param int $locationTypeId
1724 public function locationTypeDelete($locationTypeId) {
1725 $locationType = new CRM_Core_DAO_LocationType();
1726 $locationType->id
= $locationTypeId;
1727 $locationType->delete();
1733 * @param array $params
1734 * @return CRM_Core_DAO_Mapping
1735 * Mapping id of created mapping
1737 public function mappingCreate($params = NULL) {
1738 if ($params === NULL) {
1740 'name' => 'Mapping name',
1741 'description' => 'Mapping description',
1742 // 'Export Contact' mapping.
1743 'mapping_type_id' => 7,
1747 $mapping = new CRM_Core_DAO_Mapping();
1748 $mapping->copyValues($params);
1750 // clear getfields cache
1751 CRM_Core_PseudoConstant
::flush();
1752 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1759 * @param int $mappingId
1761 public function mappingDelete($mappingId) {
1762 $mapping = new CRM_Core_DAO_Mapping();
1763 $mapping->id
= $mappingId;
1770 * @param array $params
1772 * groupId of created group
1774 public function groupCreate($params = array()) {
1775 $params = array_merge(array(
1776 'name' => 'Test Group 1',
1778 'title' => 'New Test Group Created',
1779 'description' => 'New Test Group Created',
1781 'visibility' => 'Public Pages',
1782 'group_type' => array(
1788 $result = $this->callAPISuccess('Group', 'create', $params);
1789 return $result['id'];
1794 * Function to add a Group.
1796 * @params array to add group
1798 * @param int $groupID
1799 * @param int $totalCount
1801 * groupId of created group
1803 public function groupContactCreate($groupID, $totalCount = 10) {
1804 $params = array('group_id' => $groupID);
1805 for ($i = 1; $i <= $totalCount; $i++
) {
1806 $contactID = $this->individualCreate();
1808 $params +
= array('contact_id' => $contactID);
1811 $params +
= array("contact_id.$i" => $contactID);
1814 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1824 public function groupDelete($gid) {
1830 $this->callAPISuccess('Group', 'delete', $params);
1835 * @param array $params
1837 public function uFFieldCreate($params = array()) {
1838 $params = array_merge(array(
1840 'field_name' => 'first_name',
1843 'visibility' => 'Public Pages and Listings',
1844 'is_searchable' => '1',
1845 'label' => 'first_name',
1846 'field_type' => 'Individual',
1849 $this->callAPISuccess('uf_field', 'create', $params);
1853 * Add a UF Join Entry.
1855 * @param array $params
1857 * $id of created UF Join
1859 public function ufjoinCreate($params = NULL) {
1860 if ($params === NULL) {
1863 'module' => 'CiviEvent',
1864 'entity_table' => 'civicrm_event',
1870 $result = $this->callAPISuccess('uf_join', 'create', $params);
1875 * Delete a UF Join Entry.
1877 * @param array $params
1878 * with missing uf_group_id
1880 public function ufjoinDelete($params = NULL) {
1881 if ($params === NULL) {
1884 'module' => 'CiviEvent',
1885 'entity_table' => 'civicrm_event',
1888 'uf_group_id' => '',
1892 crm_add_uf_join($params);
1896 * @param array $params
1897 * Optional parameters.
1902 public function campaignCreate($params = array()) {
1903 $this->enableCiviCampaign();
1904 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1905 'name' => 'big_campaign',
1906 'title' => 'Campaign',
1908 return $campaign['id'];
1912 * Create Group for a contact.
1914 * @param int $contactId
1916 public function contactGroupCreate($contactId) {
1918 'contact_id.1' => $contactId,
1922 $this->callAPISuccess('GroupContact', 'Create', $params);
1926 * Delete Group for a contact.
1928 * @param int $contactId
1930 public function contactGroupDelete($contactId) {
1932 'contact_id.1' => $contactId,
1935 $this->civicrm_api('GroupContact', 'Delete', $params);
1941 * @param array $params
1944 public function activityCreate($params = NULL) {
1946 if ($params === NULL) {
1947 $individualSourceID = $this->individualCreate();
1949 $contactParams = array(
1950 'first_name' => 'Julia',
1951 'Last_name' => 'Anderson',
1953 'email' => 'julia_anderson@civicrm.org',
1954 'contact_type' => 'Individual',
1957 $individualTargetID = $this->individualCreate($contactParams);
1960 'source_contact_id' => $individualSourceID,
1961 'target_contact_id' => array($individualTargetID),
1962 'assignee_contact_id' => array($individualTargetID),
1963 'subject' => 'Discussion on warm beer',
1964 'activity_date_time' => date('Ymd'),
1965 'duration_hours' => 30,
1966 'duration_minutes' => 20,
1967 'location' => 'Baker Street',
1968 'details' => 'Lets schedule a meeting',
1970 'activity_name' => 'Meeting',
1974 $result = $this->callAPISuccess('Activity', 'create', $params);
1976 $result['target_contact_id'] = $individualTargetID;
1977 $result['assignee_contact_id'] = $individualTargetID;
1982 * Create an activity type.
1984 * @param array $params
1988 public function activityTypeCreate($params) {
1989 return $this->callAPISuccess('ActivityType', 'create', $params);
1993 * Delete activity type.
1995 * @param int $activityTypeId
1996 * Id of the activity type.
1999 public function activityTypeDelete($activityTypeId) {
2000 $params['activity_type_id'] = $activityTypeId;
2001 return $this->callAPISuccess('ActivityType', 'delete', $params);
2005 * Create custom group.
2007 * @param array $params
2010 public function customGroupCreate($params = array()) {
2012 'title' => 'new custom group',
2013 'extends' => 'Contact',
2015 'style' => 'Inline',
2019 $params = array_merge($defaults, $params);
2021 if (strlen($params['title']) > 13) {
2022 $params['title'] = substr($params['title'], 0, 13);
2025 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2026 $this->callAPISuccess('custom_group', 'get', array(
2027 'title' => $params['title'],
2028 array('api.custom_group.delete' => 1),
2031 return $this->callAPISuccess('custom_group', 'create', $params);
2035 * Existing function doesn't allow params to be over-ridden so need a new one
2036 * this one allows you to only pass in the params you want to change
2037 * @param array $params
2040 public function CustomGroupCreateByParams($params = array()) {
2042 'title' => "API Custom Group",
2043 'extends' => 'Contact',
2045 'style' => 'Inline',
2048 $params = array_merge($defaults, $params);
2049 return $this->callAPISuccess('custom_group', 'create', $params);
2053 * Create custom group with multi fields.
2054 * @param array $params
2057 public function CustomGroupMultipleCreateByParams($params = array()) {
2062 $params = array_merge($defaults, $params);
2063 return $this->CustomGroupCreateByParams($params);
2067 * Create custom group with multi fields.
2068 * @param array $params
2071 public function CustomGroupMultipleCreateWithFields($params = array()) {
2072 // also need to pass on $params['custom_field'] if not set but not in place yet
2074 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2075 $ids['custom_group_id'] = $customGroup['id'];
2077 $customField = $this->customFieldCreate(array(
2078 'custom_group_id' => $ids['custom_group_id'],
2079 'label' => 'field_1' . $ids['custom_group_id'],
2082 $ids['custom_field_id'][] = $customField['id'];
2084 $customField = $this->customFieldCreate(array(
2085 'custom_group_id' => $ids['custom_group_id'],
2086 'default_value' => '',
2087 'label' => 'field_2' . $ids['custom_group_id'],
2089 $ids['custom_field_id'][] = $customField['id'];
2091 $customField = $this->customFieldCreate(array(
2092 'custom_group_id' => $ids['custom_group_id'],
2093 'default_value' => '',
2094 'label' => 'field_3' . $ids['custom_group_id'],
2096 $ids['custom_field_id'][] = $customField['id'];
2102 * Create a custom group with a single text custom field. See
2103 * participant:testCreateWithCustom for how to use this
2105 * @param string $function
2107 * @param string $filename
2111 * ids of created objects
2113 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2114 $params = array('title' => $function);
2115 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2116 $params['extends'] = $entity ?
$entity : 'Contact';
2117 $customGroup = $this->CustomGroupCreate($params);
2118 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2119 CRM_Core_PseudoConstant
::flush();
2121 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2125 * Delete custom group.
2127 * @param int $customGroupID
2131 public function customGroupDelete($customGroupID) {
2132 $params['id'] = $customGroupID;
2133 return $this->callAPISuccess('custom_group', 'delete', $params);
2137 * Create custom field.
2139 * @param array $params
2140 * (custom_group_id) is required.
2143 public function customFieldCreate($params) {
2144 $params = array_merge(array(
2145 'label' => 'Custom Field',
2146 'data_type' => 'String',
2147 'html_type' => 'Text',
2148 'is_searchable' => 1,
2150 'default_value' => 'defaultValue',
2153 $result = $this->callAPISuccess('custom_field', 'create', $params);
2154 // these 2 functions are called with force to flush static caches
2155 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2156 CRM_Core_Component
::getEnabledComponents(1);
2161 * Delete custom field.
2163 * @param int $customFieldID
2167 public function customFieldDelete($customFieldID) {
2169 $params['id'] = $customFieldID;
2170 return $this->callAPISuccess('custom_field', 'delete', $params);
2179 public function noteCreate($cId) {
2181 'entity_table' => 'civicrm_contact',
2182 'entity_id' => $cId,
2183 'note' => 'hello I am testing Note',
2184 'contact_id' => $cId,
2185 'modified_date' => date('Ymd'),
2186 'subject' => 'Test Note',
2189 return $this->callAPISuccess('Note', 'create', $params);
2193 * Enable CiviCampaign Component.
2195 public function enableCiviCampaign() {
2196 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2197 // force reload of config object
2198 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2199 //flush cache by calling with reset
2200 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2204 * Create test generated example in api/v3/examples.
2206 * To turn this off (e.g. on the server) set
2207 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2208 * in your settings file
2210 * @param string $entity
2211 * @param string $action
2212 * @param array $params
2213 * Array as passed to civicrm_api function.
2214 * @param array $result
2215 * Array as received from the civicrm_api function.
2216 * @param string $testFunction
2217 * Calling function - generally __FUNCTION__.
2218 * @param string $testFile
2219 * Called from file - generally __FILE__.
2220 * @param string $description
2221 * Descriptive text for the example file.
2222 * @param string $exampleName
2223 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2225 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2226 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2229 $entity = _civicrm_api_get_camel_name($entity);
2230 $action = strtolower($action);
2232 if (empty($exampleName)) {
2233 // Attempt to convert lowercase action name to CamelCase.
2234 // This is clunky/imperfect due to the convention of all lowercase actions.
2235 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2236 $knownPrefixes = array(
2243 foreach ($knownPrefixes as $prefix) {
2244 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2245 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2250 $this->tidyExampleResult($result);
2251 if (isset($params['version'])) {
2252 unset($params['version']);
2254 // Format multiline description as array
2256 if (is_string($description) && strlen($description)) {
2257 foreach (explode("\n", $description) as $line) {
2258 $desc[] = trim($line);
2261 $smarty = CRM_Core_Smarty
::singleton();
2262 $smarty->assign('testFunction', $testFunction);
2263 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2264 $smarty->assign('params', $params);
2265 $smarty->assign('entity', $entity);
2266 $smarty->assign('testFile', basename($testFile));
2267 $smarty->assign('description', $desc);
2268 $smarty->assign('result', $result);
2269 $smarty->assign('action', $action);
2271 if (file_exists('../tests/templates/documentFunction.tpl')) {
2272 if (!is_dir("../api/v3/examples/$entity")) {
2273 mkdir("../api/v3/examples/$entity");
2275 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2276 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2282 * Tidy up examples array so that fields that change often ..don't
2283 * and debug related fields are unset
2285 * @param array $result
2287 public function tidyExampleResult(&$result) {
2288 if (!is_array($result)) {
2291 $fieldsToChange = array(
2292 'hash' => '67eac7789eaee00',
2293 'modified_date' => '2012-11-14 16:02:35',
2294 'created_date' => '2013-07-28 08:49:19',
2295 'create_date' => '20120130621222105',
2296 'application_received_date' => '20130728084957',
2297 'in_date' => '2013-07-28 08:50:19',
2298 'scheduled_date' => '20130728085413',
2299 'approval_date' => '20130728085413',
2300 'pledge_start_date_high' => '20130726090416',
2301 'start_date' => '2013-07-29 00:00:00',
2302 'event_start_date' => '2013-07-29 00:00:00',
2303 'end_date' => '2013-08-04 00:00:00',
2304 'event_end_date' => '2013-08-04 00:00:00',
2305 'decision_date' => '20130805000000',
2308 $keysToUnset = array('xdebug', 'undefined_fields');
2309 foreach ($keysToUnset as $unwantedKey) {
2310 if (isset($result[$unwantedKey])) {
2311 unset($result[$unwantedKey]);
2314 if (isset($result['values'])) {
2315 if (!is_array($result['values'])) {
2318 $resultArray = &$result['values'];
2320 elseif (is_array($result)) {
2321 $resultArray = &$result;
2327 foreach ($resultArray as $index => &$values) {
2328 if (!is_array($values)) {
2331 foreach ($values as $key => &$value) {
2332 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2333 if (isset($value['is_error'])) {
2334 // we have a std nested result format
2335 $this->tidyExampleResult($value);
2338 foreach ($value as &$nestedResult) {
2339 // this is an alternative syntax for nested results a keyed array of results
2340 $this->tidyExampleResult($nestedResult);
2344 if (in_array($key, $keysToUnset)) {
2345 unset($values[$key]);
2348 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2349 $value = $fieldsToChange[$key];
2351 if (is_string($value)) {
2352 $value = addslashes($value);
2361 * @param array $params
2365 public function noteDelete($params) {
2366 return $this->callAPISuccess('Note', 'delete', $params);
2370 * Create custom field with Option Values.
2372 * @param array $customGroup
2373 * @param string $name
2374 * Name of custom field.
2378 public function customFieldOptionValueCreate($customGroup, $name) {
2379 $fieldParams = array(
2380 'custom_group_id' => $customGroup['id'],
2381 'name' => 'test_custom_group',
2382 'label' => 'Country',
2383 'html_type' => 'Select',
2384 'data_type' => 'String',
2387 'is_searchable' => 0,
2391 $optionGroup = array(
2393 'name' => 'option_group1',
2394 'label' => 'option_group_label1',
2397 $optionValue = array(
2398 'option_label' => array('Label1', 'Label2'),
2399 'option_value' => array('value1', 'value2'),
2400 'option_name' => array($name . '_1', $name . '_2'),
2401 'option_weight' => array(1, 2),
2402 'option_status' => 1,
2405 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2407 return $this->callAPISuccess('custom_field', 'create', $params);
2415 public function confirmEntitiesDeleted($entities) {
2416 foreach ($entities as $entity) {
2418 $result = $this->callAPISuccess($entity, 'Get', array());
2419 if ($result['error'] == 1 ||
$result['count'] > 0) {
2420 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2428 * Quick clean by emptying tables created for the test.
2430 * @param array $tablesToTruncate
2431 * @param bool $dropCustomValueTables
2432 * @throws \Exception
2434 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2436 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2438 if ($dropCustomValueTables) {
2439 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2440 while ($optionGroupResult->fetch()) {
2441 if (!empty($optionGroupResult->option_group_id
)) {
2442 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2445 $tablesToTruncate[] = 'civicrm_custom_group';
2446 $tablesToTruncate[] = 'civicrm_custom_field';
2449 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2451 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2452 foreach ($tablesToTruncate as $table) {
2453 $sql = "TRUNCATE TABLE $table";
2454 CRM_Core_DAO
::executeQuery($sql);
2456 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2458 if ($dropCustomValueTables) {
2459 $dbName = self
::getDBName();
2461 SELECT TABLE_NAME as tableName
2462 FROM INFORMATION_SCHEMA.TABLES
2463 WHERE TABLE_SCHEMA = '{$dbName}'
2464 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2467 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2468 while ($tableDAO->fetch()) {
2469 $sql = "DROP TABLE {$tableDAO->tableName}";
2470 CRM_Core_DAO
::executeQuery($sql);
2476 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2478 public function quickCleanUpFinancialEntities() {
2479 $tablesToTruncate = array(
2481 'civicrm_activity_contact',
2482 'civicrm_contribution',
2483 'civicrm_contribution_soft',
2484 'civicrm_contribution_product',
2485 'civicrm_financial_trxn',
2486 'civicrm_financial_item',
2487 'civicrm_contribution_recur',
2488 'civicrm_line_item',
2489 'civicrm_contribution_page',
2490 'civicrm_payment_processor',
2491 'civicrm_entity_financial_trxn',
2492 'civicrm_membership',
2493 'civicrm_membership_type',
2494 'civicrm_membership_payment',
2495 'civicrm_membership_log',
2496 'civicrm_membership_block',
2498 'civicrm_participant',
2499 'civicrm_participant_payment',
2501 'civicrm_price_set_entity',
2502 'civicrm_price_field_value',
2503 'civicrm_price_field',
2505 $this->quickCleanup($tablesToTruncate);
2506 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2507 $this->restoreDefaultPriceSetConfig();
2509 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2510 System
::singleton()->flushProcessors();
2513 public function restoreDefaultPriceSetConfig() {
2514 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2515 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)");
2516 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2519 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2520 * Default behaviour is to also delete the entity
2521 * @param array $params
2522 * Params array to check against.
2524 * Id of the entity concerned.
2525 * @param string $entity
2526 * Name of entity concerned (e.g. membership).
2527 * @param bool $delete
2528 * Should the entity be deleted as part of this check.
2529 * @param string $errorText
2530 * Text to print on error.
2533 * @param array $params
2536 * @param int $delete
2537 * @param string $errorText
2541 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2543 $result = $this->callAPISuccessGetSingle($entity, array(
2548 $this->callAPISuccess($entity, 'Delete', array(
2552 $dateFields = $keys = $dateTimeFields = array();
2553 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2554 foreach ($fields['values'] as $field => $settings) {
2555 if (array_key_exists($field, $result)) {
2556 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2559 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2561 $type = CRM_Utils_Array
::value('type', $settings);
2562 if ($type == CRM_Utils_Type
::T_DATE
) {
2563 $dateFields[] = $settings['name'];
2564 // we should identify both real names & unique names as dates
2565 if ($field != $settings['name']) {
2566 $dateFields[] = $field;
2569 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2570 $dateTimeFields[] = $settings['name'];
2571 // we should identify both real names & unique names as dates
2572 if ($field != $settings['name']) {
2573 $dateTimeFields[] = $field;
2578 if (strtolower($entity) == 'contribution') {
2579 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2580 // this is not returned in id format
2581 unset($params['payment_instrument_id']);
2582 $params['contribution_source'] = $params['source'];
2583 unset($params['source']);
2586 foreach ($params as $key => $value) {
2587 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2590 if (in_array($key, $dateFields)) {
2591 $value = date('Y-m-d', strtotime($value));
2592 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2594 if (in_array($key, $dateTimeFields)) {
2595 $value = date('Y-m-d H:i:s', strtotime($value));
2596 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2598 $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);
2603 * Get formatted values in the actual and expected result.
2604 * @param array $actual
2605 * Actual calculated values.
2606 * @param array $expected
2609 public function checkArrayEquals(&$actual, &$expected) {
2610 self
::unsetId($actual);
2611 self
::unsetId($expected);
2612 $this->assertEquals($actual, $expected);
2616 * Unset the key 'id' from the array
2617 * @param array $unformattedArray
2618 * The array from which the 'id' has to be unset.
2620 public static function unsetId(&$unformattedArray) {
2621 $formattedArray = array();
2622 if (array_key_exists('id', $unformattedArray)) {
2623 unset($unformattedArray['id']);
2625 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2626 foreach ($unformattedArray['values'] as $key => $value) {
2627 if (is_array($value)) {
2628 foreach ($value as $k => $v) {
2634 elseif ($key == 'id') {
2635 $unformattedArray[$key];
2637 $formattedArray = array($value);
2639 $unformattedArray['values'] = $formattedArray;
2644 * Helper to enable/disable custom directory support
2646 * @param array $customDirs
2648 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2649 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2651 public function customDirectories($customDirs) {
2652 $config = CRM_Core_Config
::singleton();
2654 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2655 unset($config->customPHPPathDir
);
2657 elseif ($customDirs['php_path'] === TRUE) {
2658 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2661 $config->customPHPPathDir
= $php_path;
2664 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2665 unset($config->customTemplateDir
);
2667 elseif ($customDirs['template_path'] === TRUE) {
2668 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2671 $config->customTemplateDir
= $template_path;
2676 * Generate a temporary folder.
2678 * @param string $prefix
2681 public function createTempDir($prefix = 'test-') {
2682 $tempDir = CRM_Utils_File
::tempdir($prefix);
2683 $this->tempDirs
[] = $tempDir;
2687 public function cleanTempDirs() {
2688 if (!is_array($this->tempDirs
)) {
2689 // fix test errors where this is not set
2692 foreach ($this->tempDirs
as $tempDir) {
2693 if (is_dir($tempDir)) {
2694 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2700 * Temporarily replace the singleton extension with a different one.
2701 * @param \CRM_Extension_System $system
2703 public function setExtensionSystem(CRM_Extension_System
$system) {
2704 if ($this->origExtensionSystem
== NULL) {
2705 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2707 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2710 public function unsetExtensionSystem() {
2711 if ($this->origExtensionSystem
!== NULL) {
2712 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2713 $this->origExtensionSystem
= NULL;
2718 * Temporarily alter the settings-metadata to add a mock setting.
2720 * WARNING: The setting metadata will disappear on the next cache-clear.
2725 public function setMockSettingsMetaData($extras) {
2726 Civi
::service('settings_manager')->flush();
2728 CRM_Utils_Hook
::singleton()
2729 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2730 $metadata = array_merge($metadata, $extras);
2733 $fields = $this->callAPISuccess('setting', 'getfields', array());
2734 foreach ($extras as $key => $spec) {
2735 $this->assertNotEmpty($spec['title']);
2736 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2741 * @param string $name
2743 public function financialAccountDelete($name) {
2744 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2745 $financialAccount->name
= $name;
2746 if ($financialAccount->find(TRUE)) {
2747 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2748 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2749 $entityFinancialType->delete();
2750 $financialAccount->delete();
2755 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2756 * (NB unclear if this is still required)
2758 public function _sethtmlGlobals() {
2759 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2760 'required' => array(
2761 'html_quickform_rule_required',
2762 'HTML/QuickForm/Rule/Required.php',
2764 'maxlength' => array(
2765 'html_quickform_rule_range',
2766 'HTML/QuickForm/Rule/Range.php',
2768 'minlength' => array(
2769 'html_quickform_rule_range',
2770 'HTML/QuickForm/Rule/Range.php',
2772 'rangelength' => array(
2773 'html_quickform_rule_range',
2774 'HTML/QuickForm/Rule/Range.php',
2777 'html_quickform_rule_email',
2778 'HTML/QuickForm/Rule/Email.php',
2781 'html_quickform_rule_regex',
2782 'HTML/QuickForm/Rule/Regex.php',
2784 'lettersonly' => array(
2785 'html_quickform_rule_regex',
2786 'HTML/QuickForm/Rule/Regex.php',
2788 'alphanumeric' => array(
2789 'html_quickform_rule_regex',
2790 'HTML/QuickForm/Rule/Regex.php',
2793 'html_quickform_rule_regex',
2794 'HTML/QuickForm/Rule/Regex.php',
2796 'nopunctuation' => array(
2797 'html_quickform_rule_regex',
2798 'HTML/QuickForm/Rule/Regex.php',
2801 'html_quickform_rule_regex',
2802 'HTML/QuickForm/Rule/Regex.php',
2804 'callback' => array(
2805 'html_quickform_rule_callback',
2806 'HTML/QuickForm/Rule/Callback.php',
2809 'html_quickform_rule_compare',
2810 'HTML/QuickForm/Rule/Compare.php',
2813 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2814 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2816 'HTML/QuickForm/group.php',
2817 'HTML_QuickForm_group',
2820 'HTML/QuickForm/hidden.php',
2821 'HTML_QuickForm_hidden',
2824 'HTML/QuickForm/reset.php',
2825 'HTML_QuickForm_reset',
2827 'checkbox' => array(
2828 'HTML/QuickForm/checkbox.php',
2829 'HTML_QuickForm_checkbox',
2832 'HTML/QuickForm/file.php',
2833 'HTML_QuickForm_file',
2836 'HTML/QuickForm/image.php',
2837 'HTML_QuickForm_image',
2839 'password' => array(
2840 'HTML/QuickForm/password.php',
2841 'HTML_QuickForm_password',
2844 'HTML/QuickForm/radio.php',
2845 'HTML_QuickForm_radio',
2848 'HTML/QuickForm/button.php',
2849 'HTML_QuickForm_button',
2852 'HTML/QuickForm/submit.php',
2853 'HTML_QuickForm_submit',
2856 'HTML/QuickForm/select.php',
2857 'HTML_QuickForm_select',
2859 'hiddenselect' => array(
2860 'HTML/QuickForm/hiddenselect.php',
2861 'HTML_QuickForm_hiddenselect',
2864 'HTML/QuickForm/text.php',
2865 'HTML_QuickForm_text',
2867 'textarea' => array(
2868 'HTML/QuickForm/textarea.php',
2869 'HTML_QuickForm_textarea',
2871 'fckeditor' => array(
2872 'HTML/QuickForm/fckeditor.php',
2873 'HTML_QuickForm_FCKEditor',
2876 'HTML/QuickForm/tinymce.php',
2877 'HTML_QuickForm_TinyMCE',
2879 'dojoeditor' => array(
2880 'HTML/QuickForm/dojoeditor.php',
2881 'HTML_QuickForm_dojoeditor',
2884 'HTML/QuickForm/link.php',
2885 'HTML_QuickForm_link',
2887 'advcheckbox' => array(
2888 'HTML/QuickForm/advcheckbox.php',
2889 'HTML_QuickForm_advcheckbox',
2892 'HTML/QuickForm/date.php',
2893 'HTML_QuickForm_date',
2896 'HTML/QuickForm/static.php',
2897 'HTML_QuickForm_static',
2900 'HTML/QuickForm/header.php',
2901 'HTML_QuickForm_header',
2904 'HTML/QuickForm/html.php',
2905 'HTML_QuickForm_html',
2907 'hierselect' => array(
2908 'HTML/QuickForm/hierselect.php',
2909 'HTML_QuickForm_hierselect',
2911 'autocomplete' => array(
2912 'HTML/QuickForm/autocomplete.php',
2913 'HTML_QuickForm_autocomplete',
2916 'HTML/QuickForm/xbutton.php',
2917 'HTML_QuickForm_xbutton',
2919 'advmultiselect' => array(
2920 'HTML/QuickForm/advmultiselect.php',
2921 'HTML_QuickForm_advmultiselect',
2927 * Set up an acl allowing contact to see 2 specified groups
2928 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2930 * You need to have pre-created these groups & created the user e.g
2931 * $this->createLoggedInUser();
2932 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2933 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2935 * @param bool $isProfile
2937 public function setupACL($isProfile = FALSE) {
2939 $_REQUEST = $this->_params
;
2941 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2942 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2943 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2944 'option_group_id' => $optionGroupID,
2945 'label' => 'pick me',
2949 CRM_Core_DAO
::executeQuery("
2950 TRUNCATE civicrm_acl_cache
2953 CRM_Core_DAO
::executeQuery("
2954 TRUNCATE civicrm_acl_contact_cache
2957 CRM_Core_DAO
::executeQuery("
2958 INSERT INTO civicrm_acl_entity_role (
2959 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2960 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2964 CRM_Core_DAO
::executeQuery("
2965 INSERT INTO civicrm_acl (
2966 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2969 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2974 CRM_Core_DAO
::executeQuery("
2975 INSERT INTO civicrm_acl (
2976 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2979 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2983 CRM_Core_DAO
::executeQuery("
2984 INSERT INTO civicrm_acl (
2985 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2988 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2993 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2994 $this->callAPISuccess('group_contact', 'create', array(
2995 'group_id' => $this->_permissionedGroup
,
2996 'contact_id' => $this->_loggedInUser
,
3001 CRM_ACL_BAO_Cache
::resetCache();
3002 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3003 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3008 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3010 public function offsetDefaultPriceSet() {
3011 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3012 $firstID = $contributionPriceSet['id'];
3013 $this->callAPISuccess('price_set', 'create', array(
3014 'id' => $contributionPriceSet['id'],
3018 unset($contributionPriceSet['id']);
3019 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3020 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3021 'price_set_id' => $firstID,
3022 'options' => array('limit' => 1),
3024 unset($priceField['id']);
3025 $priceField['price_set_id'] = $newPriceSet['id'];
3026 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3027 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3028 'price_set_id' => $firstID,
3030 'options' => array('limit' => 1),
3033 unset($priceFieldValue['id']);
3034 //create some padding to use up ids
3035 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3036 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3037 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3041 * Create an instance of the paypal processor.
3042 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3043 * this parent class & we don't have a structure for that yet
3044 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3045 * & the best protection against that is the functions this class affords
3046 * @param array $params
3047 * @return int $result['id'] payment processor id
3049 public function paymentProcessorCreate($params = array()) {
3050 $params = array_merge(array(
3052 'domain_id' => CRM_Core_Config
::domainID(),
3053 'payment_processor_type_id' => 'PayPal',
3057 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3058 'password' => '1183377788',
3059 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3060 'url_site' => 'https://www.sandbox.paypal.com/',
3061 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3062 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3063 'class_name' => 'Payment_PayPalImpl',
3064 'billing_mode' => 3,
3065 'financial_type_id' => 1,
3068 if (!is_numeric($params['payment_processor_type_id'])) {
3069 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3071 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3072 'name' => $params['payment_processor_type_id'],
3076 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3077 return $result['id'];
3081 * Set up initial recurring payment allowing subsequent IPN payments.
3083 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3084 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3085 'contact_id' => $this->_contactID
,
3088 'installments' => 5,
3089 'frequency_unit' => 'Month',
3090 'frequency_interval' => 1,
3091 'invoice_id' => $this->_invoiceID
,
3092 'contribution_status_id' => 2,
3093 'payment_processor_id' => $this->_paymentProcessorID
,
3094 // processor provided ID - use contact ID as proxy.
3095 'processor_id' => $this->_contactID
,
3096 'api.contribution.create' => array(
3097 'total_amount' => '200',
3098 'invoice_id' => $this->_invoiceID
,
3099 'financial_type_id' => 1,
3100 'contribution_status_id' => 'Pending',
3101 'contact_id' => $this->_contactID
,
3102 'contribution_page_id' => $this->_contributionPageID
,
3103 'payment_processor_id' => $this->_paymentProcessorID
,
3107 $this->_contributionRecurID
= $contributionRecur['id'];
3108 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3112 * 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
3114 public function setupMembershipRecurringPaymentProcessorTransaction() {
3115 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3116 //create a contribution so our membership & contribution don't both have id = 1
3117 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3118 $this->contributionCreate(array(
3119 'contact_id' => $this->_contactID
,
3121 'financial_type_id' => 1,
3122 'invoice_id' => 'abcd',
3126 $this->setupRecurringPaymentProcessorTransaction();
3128 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3129 'contact_id' => $this->_contactID
,
3130 'membership_type_id' => $this->ids
['membership_type'],
3131 'contribution_recur_id' => $this->_contributionRecurID
,
3132 'format.only_id' => TRUE,
3134 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3135 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3137 $this->callAPISuccess('line_item', 'create', array(
3138 'entity_table' => 'civicrm_membership',
3139 'entity_id' => $this->ids
['membership'],
3140 'contribution_id' => $this->_contributionID
,
3141 'label' => 'General',
3143 'unit_price' => 200,
3144 'line_total' => 200,
3145 'financial_type_id' => 1,
3146 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3148 'label' => 'Membership Amount',
3149 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3151 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3153 'label' => 'General',
3154 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3157 $this->callAPISuccess('membership_payment', 'create', array(
3158 'contribution_id' => $this->_contributionID
,
3159 'membership_id' => $this->ids
['membership'],
3168 public function CiviUnitTestCase_fatalErrorHandler($message) {
3169 throw new Exception("{$message['message']}: {$message['code']}");
3173 * Helper function to create new mailing.
3176 public function createMailing() {
3178 'subject' => 'maild' . rand(),
3179 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3180 'name' => 'mailing name' . rand(),
3184 $result = $this->callAPISuccess('Mailing', 'create', $params);
3185 return $result['id'];
3189 * Helper function to delete mailing.
3192 public function deleteMailing($id) {
3197 $this->callAPISuccess('Mailing', 'delete', $params);
3201 * Wrap the entire test case in a transaction.
3203 * Only subsequent DB statements will be wrapped in TX -- this cannot
3204 * retroactively wrap old DB statements. Therefore, it makes sense to
3205 * call this at the beginning of setUp().
3207 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3208 * this option does not work with, e.g., custom-data.
3210 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3211 * if TRUNCATE or ALTER is called while using a transaction.
3214 * Whether to use nesting or reference-counting.
3216 public function useTransaction($nest = TRUE) {
3218 $this->tx
= new CRM_Core_Transaction($nest);
3219 $this->tx
->rollback();
3224 * Assert the attachment exists.
3226 * @param bool $exists
3227 * @param array $apiResult
3229 protected function assertAttachmentExistence($exists, $apiResult) {
3230 $fileId = $apiResult['id'];
3231 $this->assertTrue(is_numeric($fileId));
3232 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3233 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3234 1 => array($fileId, 'Int'),
3236 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3237 1 => array($fileId, 'Int'),
3242 * Create a price set for an event.
3244 * @param int $feeTotal
3249 protected function eventPriceSetCreate($feeTotal) {
3250 // creating price set, price field
3251 $paramsSet['title'] = 'Price Set';
3252 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3253 $paramsSet['is_active'] = FALSE;
3254 $paramsSet['extends'] = 1;
3256 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3257 $priceSetId = $priceset->id
;
3259 //Checking for priceset added in the table.
3260 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3261 'id', $paramsSet['title'], 'Check DB for created priceset'
3263 $paramsField = array(
3264 'label' => 'Price Field',
3265 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3266 'html_type' => 'Text',
3267 'price' => $feeTotal,
3268 'option_label' => array('1' => 'Price Field'),
3269 'option_value' => array('1' => $feeTotal),
3270 'option_name' => array('1' => $feeTotal),
3271 'option_weight' => array('1' => 1),
3272 'option_amount' => array('1' => 1),
3273 'is_display_amounts' => 1,
3275 'options_per_line' => 1,
3276 'is_active' => array('1' => 1),
3277 'price_set_id' => $priceset->id
,
3278 'is_enter_qty' => 1,
3279 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3281 CRM_Price_BAO_PriceField
::create($paramsField);
3287 * Add a profile to a contribution page.
3289 * @param string $name
3290 * @param int $contributionPageID
3292 protected function addProfile($name, $contributionPageID) {
3293 $this->callAPISuccess('UFJoin', 'create', array(
3294 'uf_group_id' => $name,
3295 'module' => 'CiviContribute',
3296 'entity_table' => 'civicrm_contribution_page',
3297 'entity_id' => $contributionPageID,
3303 * Add participant with contribution
3307 protected function createParticipantWithContribution() {
3308 // creating price set, price field
3309 $this->_contactId
= Contact
::createIndividual();
3310 $this->_eventId
= Event
::create($this->_contactId
);
3311 $eventParams = array(
3312 'id' => $this->_eventId
,
3313 'financial_type_id' => 4,
3316 $this->callAPISuccess('event', 'create', $eventParams);
3317 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3318 $participantParams = array(
3319 'financial_type_id' => 4,
3320 'event_id' => $this->_eventId
,
3323 'fee_currency' => 'USD',
3324 'contact_id' => $this->_contactId
,
3326 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3327 $contributionParams = array(
3328 'total_amount' => 150,
3329 'currency' => 'USD',
3330 'contact_id' => $this->_contactId
,
3331 'financial_type_id' => 4,
3332 'contribution_status_id' => 1,
3333 'partial_payment_total' => 300.00,
3334 'partial_amount_pay' => 150,
3335 'contribution_mode' => 'participant',
3336 'participant_id' => $participant['id'],
3338 foreach ($priceFields['values'] as $key => $priceField) {
3339 $lineItems[1][$key] = array(
3340 'price_field_id' => $priceField['price_field_id'],
3341 'price_field_value_id' => $priceField['id'],
3342 'label' => $priceField['label'],
3343 'field_title' => $priceField['label'],
3345 'unit_price' => $priceField['amount'],
3346 'line_total' => $priceField['amount'],
3347 'financial_type_id' => $priceField['financial_type_id'],
3350 $contributionParams['line_item'] = $lineItems;
3351 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3352 $paymentParticipant = array(
3353 'participant_id' => $participant['id'],
3354 'contribution_id' => $contribution['id'],
3357 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3358 return array($lineItems, $contribution);
3364 * @param string $component
3365 * @param int $componentId
3369 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3370 $paramsSet['title'] = 'Price Set';
3371 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3372 $paramsSet['is_active'] = TRUE;
3373 $paramsSet['financial_type_id'] = 4;
3374 $paramsSet['extends'] = 1;
3375 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3376 $priceSetId = $priceSet['id'];
3377 //Checking for priceset added in the table.
3378 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3379 'id', $paramsSet['title'], 'Check DB for created priceset'
3381 $paramsField = array(
3382 'label' => 'Price Field',
3383 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3384 'html_type' => 'CheckBox',
3385 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3386 'option_value' => array('1' => 100, '2' => 200),
3387 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3388 'option_weight' => array('1' => 1, '2' => 2),
3389 'option_amount' => array('1' => 100, '2' => 200),
3390 'is_display_amounts' => 1,
3392 'options_per_line' => 1,
3393 'is_active' => array('1' => 1, '2' => 1),
3394 'price_set_id' => $priceSet['id'],
3395 'is_enter_qty' => 1,
3396 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3398 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3400 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3402 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));