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/>.
30 * Include configuration
32 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
33 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
38 require_once CIVICRM_SETTINGS_PATH
;
40 * Include class definitions
42 require_once 'tests/phpunit/Utils.php';
43 require_once 'api/api.php';
44 require_once 'CRM/Financial/BAO/FinancialType.php';
45 define('API_LATEST_VERSION', 3);
48 * Base class for CiviCRM unit tests
50 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
51 * may opt for one or neither:
53 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
54 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
55 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
56 * 2. useTransaction() executes the test inside a transaction. It's easier to use
57 * (because you don't need to identify specific tables), but it doesn't work for tests
58 * which manipulate schema or truncate data -- and could behave inconsistently
59 * for tests which specifically examine DB transactions.
61 * Common functions for unit tests
64 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
67 * Api version - easier to override than just a define
69 protected $_apiversion = API_LATEST_VERSION
;
71 * Database has been initialized
75 private static $dbInit = FALSE;
80 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
89 static protected $_dbName;
92 * Track tables we have modified during a test
94 protected $_tablesToTruncate = array();
97 * @var array of temporary directory names
102 * @var Utils instance
104 public static $utils;
107 * @var boolean populateOnce allows to skip db resets in setUp
109 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
110 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
113 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
115 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
117 public static $populateOnce = FALSE;
120 * Allow classes to state E-notice compliance
122 public $_eNoticeCompliant = TRUE;
125 * @var boolean DBResetRequired allows skipping DB reset
126 * in specific test case. If you still need
127 * to reset single test (method) of such case, call
128 * $this->cleanDB() in the first line of this
131 public $DBResetRequired = TRUE;
134 * @var CRM_Core_Transaction|NULL
141 * Because we are overriding the parent class constructor, we
142 * need to show the same arguments as exist in the constructor of
143 * PHPUnit_Framework_TestCase, since
144 * PHPUnit_Framework_TestSuite::createTest() creates a
145 * ReflectionClass of the Test class and checks the constructor
146 * of that class to decide how to set up the test.
148 * @param string $name
150 * @param string $dataName
152 function __construct($name = NULL, array$data = array(), $dataName = '') {
153 parent
::__construct($name, $data, $dataName);
155 // we need full error reporting
156 error_reporting(E_ALL
& ~E_NOTICE
);
158 if (!empty($GLOBALS['mysql_db'])) {
159 self
::$_dbName = $GLOBALS['mysql_db'];
162 self
::$_dbName = 'civicrm_tests_dev';
165 // create test database
166 self
::$utils = new Utils($GLOBALS['mysql_host'],
167 $GLOBALS['mysql_port'],
168 $GLOBALS['mysql_user'],
169 $GLOBALS['mysql_pass']
172 // also load the class loader
173 require_once 'CRM/Core/ClassLoader.php';
174 CRM_Core_ClassLoader
::singleton()->register();
175 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
176 _civix_phpunit_setUp();
180 protected function runTest() {
182 return parent
::runTest();
183 } catch (PEAR_Exception
$e) {
184 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
185 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
192 function requireDBReset() {
193 return $this->DBResetRequired
;
199 static function getDBName() {
200 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
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;
223 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
227 * Required implementation of abstract method
229 protected function getDataSet() {
233 * @param bool $perClass
234 * @param null $object
235 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
237 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
239 if ($perClass ||
$object == NULL) {
243 $dbreset = $object->requireDBReset();
246 if (self
::$populateOnce ||
!$dbreset) {
249 self
::$populateOnce = NULL;
251 $dbName = self
::getDBName();
252 $pdo = self
::$utils->pdo
;
253 // only consider real tables and not views
254 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
255 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
257 $truncates = array();
259 foreach ($tables as $table) {
261 if (substr($table['table_name'], 0, 4) == 'log_') {
265 // don't change list of installed extensions
266 if ($table['table_name'] == 'civicrm_extension') {
270 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
271 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
274 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
280 "SET foreign_key_checks = 0",
281 // SQL mode needs to be strict, that's our standard
282 "SET SQL_MODE='STRICT_ALL_TABLES';",
283 "SET global innodb_flush_log_at_trx_commit = 2;",
285 $queries = array_merge($queries, $truncates);
286 $queries = array_merge($queries, $drops);
287 foreach ($queries as $query) {
288 if (self
::$utils->do_query($query) === FALSE) {
289 // failed to create test database
290 echo "failed to create test db.";
295 // initialize test database
296 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
297 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
298 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
300 $query2 = file_get_contents($sql_file2);
301 $query3 = file_get_contents($sql_file3);
302 $query4 = file_get_contents($sql_file4);
303 if (self
::$utils->do_query($query2) === FALSE) {
304 echo "Cannot load civicrm_data.mysql. Aborting.";
307 if (self
::$utils->do_query($query3) === FALSE) {
308 echo "Cannot load test_data.mysql. Aborting.";
311 if (self
::$utils->do_query($query4) === FALSE) {
312 echo "Cannot load test_data.mysql. Aborting.";
316 // done with all the loading, get transactions back
317 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
318 echo "Cannot set global? Huh?";
322 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
323 echo "Cannot get foreign keys back? Huh?";
327 unset($query, $query2, $query3);
330 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
332 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
333 'CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'
339 public static function setUpBeforeClass() {
340 static::_populateDB(TRUE);
342 // also set this global hack
343 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
345 $env = new CRM_Utils_Check_Env();
346 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
350 * Common setup functions for all unit tests
352 protected function setUp() {
353 $session = CRM_Core_Session
::singleton();
354 $session->set('userID', NULL);
356 CRM_Utils_Hook
::singleton(TRUE);
357 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
358 // Use a temporary file for STDIN
359 $GLOBALS['stdin'] = tmpfile();
360 if ($GLOBALS['stdin'] === FALSE) {
361 echo "Couldn't open temporary file\n";
365 // Get and save a connection to the database
366 $this->_dbconn
= $this->getConnection();
368 // reload database before each test
369 // $this->_populateDB();
371 // "initialize" CiviCRM to avoid problems when running single tests
372 // FIXME: look at it closer in second stage
374 // initialize the object once db is loaded
375 CRM_Core_Config
::$_mail = NULL;
376 $config = CRM_Core_Config
::singleton();
378 // when running unit tests, use mockup user framework
379 $config->setUserFramework('UnitTests');
381 // also fix the fatal error handler to throw exceptions,
383 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
385 // enable backtrace to get meaningful errors
386 $config->backtrace
= 1;
388 // disable any left-over test extensions
389 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
391 // reset all the caches
392 CRM_Utils_System
::flushCache();
394 // clear permissions stub to not check permissions
395 $config = CRM_Core_Config
::singleton();
396 $config->userPermissionClass
->permissions
= NULL;
398 //flush component settings
399 CRM_Core_Component
::getEnabledComponents(TRUE);
401 if ($this->_eNoticeCompliant
) {
402 error_reporting(E_ALL
);
405 error_reporting(E_ALL
& ~E_NOTICE
);
407 $this->_sethtmlGlobals();
411 * Read everything from the datasets directory and insert into the db
413 public function loadAllFixtures() {
414 $fixturesDir = __DIR__
. '/../../fixtures';
416 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
418 $xmlFiles = glob($fixturesDir . '/*.xml');
419 foreach ($xmlFiles as $xmlFixture) {
420 $op = new PHPUnit_Extensions_Database_Operation_Insert();
421 $dataset = $this->createXMLDataSet($xmlFixture);
422 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
423 $op->execute($this->_dbconn
, $dataset);
426 $yamlFiles = glob($fixturesDir . '/*.yaml');
427 foreach ($yamlFiles as $yamlFixture) {
428 $op = new PHPUnit_Extensions_Database_Operation_Insert();
429 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
430 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
431 $op->execute($this->_dbconn
, $dataset);
434 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
438 * Emulate a logged in user since certain functions use that
439 * value to store a record in the DB (like activity)
442 public function createLoggedInUser() {
444 'first_name' => 'Logged In',
445 'last_name' => 'User ' . rand(),
446 'contact_type' => 'Individual',
448 $contactID = $this->individualCreate($params);
450 $session = CRM_Core_Session
::singleton();
451 $session->set('userID', $contactID);
454 public function cleanDB() {
455 self
::$populateOnce = NULL;
456 $this->DBResetRequired
= TRUE;
458 $this->_dbconn
= $this->getConnection();
459 static::_populateDB();
460 $this->tempDirs
= array();
464 * Create default domain contacts for the two domains added during test class
465 * database population.
467 public function createDomainContacts() {
468 $default_domain_contact = $this->organizationCreate();
469 $second_domain_contact = $this->organizationCreate();
473 * Common teardown functions for all unit tests
475 protected function tearDown() {
476 error_reporting(E_ALL
& ~E_NOTICE
);
477 $session = CRM_Core_Session
::singleton();
478 $session->set('userID', NULL);
481 $this->tx
->rollback()->commit();
484 CRM_Core_Transaction
::forceRollbackIfEnabled();
485 \Civi\Core\Transaction\Manager
::singleton(TRUE);
487 CRM_Core_Transaction
::forceRollbackIfEnabled();
488 \Civi\Core\Transaction\Manager
::singleton(TRUE);
490 $tablesToTruncate = array('civicrm_contact');
491 $this->quickCleanup($tablesToTruncate);
492 $this->createDomainContacts();
495 $this->cleanTempDirs();
496 $this->unsetExtensionSystem();
497 $this->clearOutputBuffer();
501 * FIXME: Maybe a better way to do it
503 function foreignKeyChecksOff() {
504 self
::$utils = new Utils($GLOBALS['mysql_host'],
505 $GLOBALS['mysql_port'],
506 $GLOBALS['mysql_user'],
507 $GLOBALS['mysql_pass']
509 $dbName = self
::getDBName();
510 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
511 if (self
::$utils->do_query($query) === FALSE) {
513 echo 'Cannot set foreign_key_checks = 0';
519 function foreignKeyChecksOn() {
520 // FIXME: might not be needed if previous fixme implemented
524 * Generic function to compare expected values after an api call to retrieved
527 * @daoName string DAO Name of object we're evaluating.
528 * @id int Id of object
529 * @match array Associative array of field name => expected value. Empty if asserting
530 * that a DELETE occurred
531 * @delete boolean True if we're checking that a DELETE action occurred.
533 function assertDBState($daoName, $id, $match, $delete = FALSE) {
535 // adding this here since developers forget to check for an id
536 // and hence we get the first value in the db
537 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
540 $object = new $daoName();
544 // If we're asserting successful record deletion, make sure object is NOT found.
546 if ($object->find(TRUE)) {
547 $this->fail("Object not deleted by delete operation: $daoName, $id");
552 // Otherwise check matches of DAO field values against expected values in $match.
553 if ($object->find(TRUE)) {
554 $fields = & $object->fields();
555 foreach ($fields as $name => $value) {
556 $dbName = $value['name'];
557 if (isset($match[$name])) {
559 $this->assertEquals($object->$dbName, $match[$name]);
561 elseif (isset($match[$dbName])) {
563 $this->assertEquals($object->$dbName, $match[$dbName]);
568 $this->fail("Could not retrieve object: $daoName, $id");
571 $matchSize = count($match);
572 if ($verifiedCount != $matchSize) {
573 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
577 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
579 * @param string $daoName
580 * @param $searchValue
581 * @param $returnColumn
582 * @param $searchColumn
585 * @return null|string
586 * @throws PHPUnit_Framework_AssertionFailedError
588 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
589 if (empty($searchValue)) {
590 $this->fail("empty value passed to assertDBNotNull");
592 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
593 $this->assertNotNull($value, $message);
598 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
600 * @param string $daoName
601 * @param $searchValue
602 * @param $returnColumn
603 * @param $searchColumn
606 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
607 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
608 $this->assertNull($value, $message);
611 // Request a record from the DB by id. Success if row not found.
613 * @param string $daoName
615 * @param null $message
617 function assertDBRowNotExist($daoName, $id, $message = NULL) {
618 $message = $message ?
$message : "$daoName (#$id) should not exist";
619 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
620 $this->assertNull($value, $message);
623 // Request a record from the DB by id. Success if row not found.
625 * @param string $daoName
627 * @param null $message
629 function assertDBRowExist($daoName, $id, $message = NULL) {
630 $message = $message ?
$message : "$daoName (#$id) should exist";
631 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
632 $this->assertEquals($id, $value, $message);
635 // Compare a single column value in a retrieved DB record to an expected value
637 * @param string $daoName
638 * @param $searchValue
639 * @param $returnColumn
640 * @param $searchColumn
641 * @param $expectedValue
644 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
645 $expectedValue, $message
647 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
648 $this->assertEquals($value, $expectedValue, $message);
651 // Compare all values in a single retrieved DB record to an array of expected values
653 * @param string $daoName
654 * @param array $searchParams
655 * @param $expectedValues
657 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
658 //get the values from db
660 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
662 // compare db values with expected values
663 self
::assertAttributesEquals($expectedValues, $dbValues);
667 * Assert that a SQL query returns a given value
669 * The first argument is an expected value. The remaining arguments are passed
670 * to CRM_Core_DAO::singleValueQuery
672 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
673 * array(1 => array("Whiz", "String")));
675 function assertDBQuery($expected, $query, $params = array(), $message = '') {
676 if ($message) $message .= ': ';
677 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
678 $this->assertEquals($expected, $actual,
679 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
680 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
686 * Assert that two array-trees are exactly equal, notwithstanding
687 * the sorting of keys
689 * @param array $expected
690 * @param array $actual
692 function assertTreeEquals($expected, $actual) {
695 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
696 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
700 $this->assertEquals($e, $a);
704 * Assert that two numbers are approximately equal
706 * @param int|float $expected
707 * @param int|float $actual
708 * @param int|float $tolerance
709 * @param string $message
711 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
712 if ($message === NULL) {
713 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
715 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
719 * @param $expectedValues
720 * @param $actualValues
721 * @param null $message
723 * @throws PHPUnit_Framework_AssertionFailedError
725 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
726 foreach ($expectedValues as $paramName => $paramValue) {
727 if (isset($actualValues[$paramName])) {
728 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
731 $this->fail("Attribute '$paramName' not present in actual array.");
740 function assertArrayKeyExists($key, &$list) {
741 $result = isset($list[$key]) ?
TRUE : FALSE;
742 $this->assertTrue($result, ts("%1 element exists?",
751 function assertArrayValueNotNull($key, &$list) {
752 $this->assertArrayKeyExists($key, $list);
754 $value = isset($list[$key]) ?
$list[$key] : NULL;
755 $this->assertTrue($value,
756 ts("%1 element not null?",
763 * Check that api returned 'is_error' => 0
764 * else provide full message
765 * @param array $apiResult api result
766 * @param string $prefix extra test to add to message
768 function assertAPISuccess($apiResult, $prefix = '') {
769 if (!empty($prefix)) {
772 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
774 if(!empty($apiResult['debug_information'])) {
775 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
777 if(!empty($apiResult['trace'])){
778 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
780 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
784 * Check that api returned 'is_error' => 1
785 * else provide full message
787 * @param array $apiResult api result
788 * @param string $prefix extra test to add to message
789 * @param null $expectedError
791 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
792 if (!empty($prefix)) {
795 if($expectedError && !empty($apiResult['is_error'])){
796 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
798 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
799 $this->assertNotEmpty($apiResult['error_message']);
805 * @param string $message
807 function assertType($expected, $actual, $message = '') {
808 return $this->assertInternalType($expected, $actual, $message);
812 * Check that a deleted item has been deleted
814 function assertAPIDeleted($entity, $id) {
815 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
820 * Check that api returned 'is_error' => 1
821 * else provide full message
822 * @param array $result
824 * @param array $valuesToExclude
825 * @param string $prefix extra test to add to message
827 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
828 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
829 foreach ($valuesToExclude as $value) {
830 if(isset($result[$value])) {
831 unset($result[$value]);
833 if(isset($expected[$value])) {
834 unset($expected[$value]);
837 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
841 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
845 * @param array $params
848 function civicrm_api($entity, $action, $params) {
849 return civicrm_api($entity, $action, $params);
853 * This function exists to wrap api functions
854 * so we can ensure they succeed & throw exceptions without litterering the test with checks
856 * @param string $entity
857 * @param string $action
858 * @param array $params
859 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
860 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
861 * for getsingle the array is compared against an array passed in - the id is not compared (for
866 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
867 $params = array_merge(array(
868 'version' => $this->_apiversion
,
873 switch (strtolower($action)) {
875 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
877 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
879 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
881 $result = $this->civicrm_api($entity, $action, $params);
882 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
887 * This function exists to wrap api getValue function & check the result
888 * so we can ensure they succeed & throw exceptions without litterering the test with checks
889 * There is a type check in this
891 * @param string $entity
892 * @param array $params
893 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
903 function callAPISuccessGetValue($entity, $params, $type = NULL) {
905 'version' => $this->_apiversion
,
908 $result = $this->civicrm_api($entity, 'getvalue', $params);
910 if($type == 'integer'){
911 // api seems to return integers as strings
912 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
915 $this->assertType($type, $result, "returned result should have been of type $type but was " );
922 * This function exists to wrap api getsingle function & check the result
923 * so we can ensure they succeed & throw exceptions without litterering the test with checks
925 * @param string $entity
926 * @param array $params
927 * @param array $checkAgainst - array to compare result against
938 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
940 'version' => $this->_apiversion
,
943 $result = $this->civicrm_api($entity, 'getsingle', $params);
944 if(!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
945 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
948 // @todo - have gone with the fn that unsets id? should we check id?
949 $this->checkArrayEquals($result, $checkAgainst);
955 * This function exists to wrap api getValue function & check the result
956 * so we can ensure they succeed & throw exceptions without litterering the test with checks
957 * There is a type check in this
958 * @param string $entity
959 * @param array $params
963 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
971 function callAPISuccessGetCount($entity, $params, $count = NULL) {
973 'version' => $this->_apiversion
,
976 $result = $this->civicrm_api($entity, 'getcount', $params);
977 if(!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
978 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
981 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
987 * This function exists to wrap api functions
988 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
990 * @param string $entity
991 * @param string $action
992 * @param array $params
993 * @param string $function - pass this in to create a generated example
994 * @param string $file - pass this in to create a generated example
995 * @param string $description
996 * @param string|null $subfile
997 * @param string|null $actionName
1000 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
1001 $params['version'] = $this->_apiversion
;
1002 $result = $this->callAPISuccess($entity, $action, $params);
1003 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
1008 * This function exists to wrap api functions
1009 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1010 * @param string $entity
1011 * @param string $action
1012 * @param array $params
1013 * @param string $expectedErrorMessage error
1014 * @param null $extraOutput
1017 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1018 if (is_array($params)) {
1020 'version' => $this->_apiversion
,
1023 $result = $this->civicrm_api($entity, $action, $params);
1024 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1029 * Create required data based on $this->entity & $this->params
1030 * This is just a way to set up the test data for delete & get functions
1031 * so the distinction between set
1032 * up & tested functions is clearer
1034 * @return array api Result
1036 public function createTestEntity(){
1037 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1041 * Generic function to create Organisation, to be used in test cases
1043 * @param array parameters for civicrm_contact_add api function call
1044 * @param int sequence number if creating multiple organizations
1046 * @return int id of Organisation created
1048 function organizationCreate($params = array(), $seq = 0) {
1052 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1053 return $this->_contactCreate($params);
1057 * Generic function to create Individual, to be used in test cases
1059 * @param array parameters for civicrm_contact_add api function call
1060 * @param int sequence number if creating multiple individuals
1062 * @return int id of Individual created
1064 function individualCreate($params = array(), $seq = 0) {
1065 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1066 return $this->_contactCreate($params);
1070 * Generic function to create Household, to be used in test cases
1072 * @param array parameters for civicrm_contact_add api function call
1073 * @param int sequence number if creating multiple households
1075 * @return int id of Household created
1077 function householdCreate($params = array(), $seq = 0) {
1078 $params = array_merge($this->sampleContact('Household', $seq), $params);
1079 return $this->_contactCreate($params);
1083 * Helper function for getting sample contact properties
1085 * @param enum contact type: Individual, Organization
1086 * @param int sequence number for the values of this type
1088 * @return array properties of sample contact (ie. $params for API call)
1090 function sampleContact($contact_type, $seq = 0) {
1092 'Individual' => array(
1093 // The number of values in each list need to be coprime numbers to not have duplicates
1094 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1095 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1096 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1098 'Organization' => array(
1099 'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
1101 'Household' => array(
1102 'household_name' => array('Unit Test household'),
1105 $params = array('contact_type' => $contact_type);
1106 foreach ($samples[$contact_type] as $key => $values) {
1107 $params[$key] = $values[$seq %
sizeof($values)];
1109 if ($contact_type == 'Individual' ) {
1110 $params['email'] = strtolower(
1111 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1113 $params['prefix_id'] = 3;
1114 $params['suffix_id'] = 3;
1120 * Private helper function for calling civicrm_contact_add
1122 * @param array $params for civicrm_contact_add api function call
1126 * @return int id of Household created
1128 private function _contactCreate($params) {
1129 $result = $this->callAPISuccess('contact', 'create', $params);
1130 if (!empty($result['is_error']) ||
empty($result['id'])) {
1131 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1133 return $result['id'];
1137 * @param int $contactID
1141 function contactDelete($contactID) {
1144 'skip_undelete' => 1,
1147 $domain = new CRM_Core_BAO_Domain
;
1148 $domain->contact_id
= $contactID;
1149 if ($domain->find(TRUE)) {
1150 // we are finding tests trying to delete the domain contact in cleanup
1151 //since this is mainly for cleanup lets put a safeguard here
1154 $result = $this->callAPISuccess('contact', 'delete', $params);
1159 * @param int $contactTypeId
1163 function contactTypeDelete($contactTypeId) {
1164 require_once 'CRM/Contact/BAO/ContactType.php';
1165 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1167 throw new Exception('Could not delete contact type');
1172 * @param array $params
1176 function membershipTypeCreate($params = array()) {
1177 CRM_Member_PseudoConstant
::flush('membershipType');
1178 CRM_Core_Config
::clearDBCache();
1179 $memberOfOrganization = $this->organizationCreate();
1180 $params = array_merge(array(
1181 'name' => 'General',
1182 'duration_unit' => 'year',
1183 'duration_interval' => 1,
1184 'period_type' => 'rolling',
1185 'member_of_contact_id' => $memberOfOrganization,
1187 'financial_type_id' => 1,
1190 'visibility' => 'Public',
1193 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1195 CRM_Member_PseudoConstant
::flush('membershipType');
1196 CRM_Utils_Cache
::singleton()->flush();
1198 return $result['id'];
1202 * @param array $params
1206 function contactMembershipCreate($params) {
1208 'join_date' => '2007-01-21',
1209 'start_date' => '2007-01-21',
1210 'end_date' => '2007-12-21',
1211 'source' => 'Payment',
1214 foreach ($pre as $key => $val) {
1215 if (!isset($params[$key])) {
1216 $params[$key] = $val;
1220 $result = $this->callAPISuccess('Membership', 'create', $params);
1221 return $result['id'];
1225 * Delete Membership Type
1227 * @param array $params
1229 function membershipTypeDelete($params) {
1230 $this->callAPISuccess('MembershipType', 'Delete', $params);
1234 * @param int $membershipID
1236 function membershipDelete($membershipID) {
1237 $deleteParams = array('id' => $membershipID);
1238 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1243 * @param string $name
1247 function membershipStatusCreate($name = 'test member status') {
1248 $params['name'] = $name;
1249 $params['start_event'] = 'start_date';
1250 $params['end_event'] = 'end_date';
1251 $params['is_current_member'] = 1;
1252 $params['is_active'] = 1;
1254 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1255 CRM_Member_PseudoConstant
::flush('membershipStatus');
1256 return $result['id'];
1260 * @param int $membershipStatusID
1262 function membershipStatusDelete($membershipStatusID) {
1263 if (!$membershipStatusID) {
1266 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1271 * @param array $params
1275 function relationshipTypeCreate($params = array()) {
1276 $params = array_merge(array(
1277 'name_a_b' => 'Relation 1 for relationship type create',
1278 'name_b_a' => 'Relation 2 for relationship type create',
1279 'contact_type_a' => 'Individual',
1280 'contact_type_b' => 'Organization',
1287 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1288 CRM_Core_PseudoConstant
::flush('relationshipType');
1290 return $result['id'];
1294 * Delete Relatinship Type
1296 * @param int $relationshipTypeID
1298 function relationshipTypeDelete($relationshipTypeID) {
1299 $params['id'] = $relationshipTypeID;
1300 $this->callAPISuccess('relationship_type', 'delete', $params);
1304 * @param array $params
1308 function paymentProcessorTypeCreate($params = NULL) {
1309 if (is_null($params)) {
1311 'name' => 'API_Test_PP',
1312 'title' => 'API Test Payment Processor',
1313 'class_name' => 'CRM_Core_Payment_APITest',
1314 'billing_mode' => 'form',
1320 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1322 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1324 return $result['id'];
1328 * Create Participant
1330 * @param array $params array of contact id and event id values
1332 * @return int $id of participant created
1334 function participantCreate($params) {
1335 if(empty($params['contact_id'])){
1336 $params['contact_id'] = $this->individualCreate();
1338 if(empty($params['event_id'])){
1339 $event = $this->eventCreate();
1340 $params['event_id'] = $event['id'];
1345 'register_date' => 20070219,
1346 'source' => 'Wimbeldon',
1347 'event_level' => 'Payment',
1351 $params = array_merge($defaults, $params);
1352 $result = $this->callAPISuccess('Participant', 'create', $params);
1353 return $result['id'];
1357 * Create Payment Processor
1359 * @return object of Payment Processsor
1361 function processorCreate() {
1362 $processorParams = array(
1365 'payment_processor_type_id' => 10,
1366 'financial_account_id' => 12,
1369 'url_site' => 'http://dummy.com',
1370 'url_recur' => 'http://dummy.com',
1371 'billing_mode' => 1,
1373 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1374 return $paymentProcessor;
1378 * Create contribution page
1380 * @param array $params
1381 * @return object of contribution page
1383 function contributionPageCreate($params) {
1384 $this->_pageParams
= array(
1385 'title' => 'Test Contribution Page',
1386 'financial_type_id' => 1,
1387 'currency' => 'USD',
1388 'financial_account_id' => 1,
1389 'payment_processor' => $params['processor_id'],
1391 'is_allow_other_amount' => 1,
1393 'max_amount' => 1000,
1395 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1396 return $contributionPage;
1402 * @param array $params
1403 * @return array result of created tag
1405 function tagCreate($params = array()) {
1407 'name' => 'New Tag3',
1408 'description' => 'This is description for Our New Tag ',
1411 $params = array_merge($defaults, $params);
1412 $result = $this->callAPISuccess('Tag', 'create', $params);
1413 return $result['values'][$result['id']];
1419 * @param int $tagId id of the tag to be deleted
1421 function tagDelete($tagId) {
1422 require_once 'api/api.php';
1426 $result = $this->callAPISuccess('Tag', 'delete', $params);
1427 return $result['id'];
1431 * Add entity(s) to the tag
1433 * @param array $params
1437 function entityTagAdd($params) {
1438 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1443 * Create contribution
1445 * @param int $cID contact_id
1447 * @return int id of created contribution
1449 function pledgeCreate($cID) {
1451 'contact_id' => $cID,
1452 'pledge_create_date' => date('Ymd'),
1453 'start_date' => date('Ymd'),
1454 'scheduled_date' => date('Ymd'),
1456 'pledge_status_id' => '2',
1457 'financial_type_id' => '1',
1458 'pledge_original_installment_amount' => 20,
1459 'frequency_interval' => 5,
1460 'frequency_unit' => 'year',
1461 'frequency_day' => 15,
1462 'installments' => 5,
1465 $result = $this->callAPISuccess('Pledge', 'create', $params);
1466 return $result['id'];
1470 * Delete contribution
1472 * @param int $pledgeId
1474 function pledgeDelete($pledgeId) {
1476 'pledge_id' => $pledgeId,
1478 $this->callAPISuccess('Pledge', 'delete', $params);
1482 * Create contribution
1484 * @param int $cID contact_id
1485 * @param int $cTypeID id of financial type
1487 * @param int $invoiceID
1488 * @param int $trxnID
1489 * @param int $paymentInstrumentID
1490 * @param bool $isFee
1491 * @return int id of created contribution
1493 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1496 'contact_id' => $cID,
1497 'receive_date' => date('Ymd'),
1498 'total_amount' => 100.00,
1499 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1500 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1501 'non_deductible_amount' => 10.00,
1502 'trxn_id' => $trxnID,
1503 'invoice_id' => $invoiceID,
1505 'contribution_status_id' => 1,
1506 // 'note' => 'Donating for Nobel Cause', *Fixme
1510 $params['fee_amount'] = 5.00;
1511 $params['net_amount'] = 95.00;
1514 $result = $this->callAPISuccess('contribution', 'create', $params);
1515 return $result['id'];
1519 * Create online contribution
1521 * @param array $params
1522 * @param int $financialType id of financial type
1524 * @param int $invoiceID
1525 * @param int $trxnID
1526 * @return int id of created contribution
1528 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1529 $contribParams = array(
1530 'contact_id' => $params['contact_id'],
1531 'receive_date' => date('Ymd'),
1532 'total_amount' => 100.00,
1533 'financial_type_id' => $financialType,
1534 'contribution_page_id' => $params['contribution_page_id'],
1536 'invoice_id' => 67890,
1539 $contribParams = array_merge($contribParams, $params);
1540 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1542 return $result['id'];
1546 * Delete contribution
1548 * @param int $contributionId
1552 function contributionDelete($contributionId) {
1554 'contribution_id' => $contributionId,
1556 $result = $this->callAPISuccess('contribution', 'delete', $params);
1563 * @param array $params name-value pair for an event
1565 * @return array $event
1567 function eventCreate($params = array()) {
1568 // if no contact was passed, make up a dummy event creator
1569 if (!isset($params['contact_id'])) {
1570 $params['contact_id'] = $this->_contactCreate(array(
1571 'contact_type' => 'Individual',
1572 'first_name' => 'Event',
1573 'last_name' => 'Creator',
1577 // set defaults for missing params
1578 $params = array_merge(array(
1579 'title' => 'Annual CiviCRM meet',
1580 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1581 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1582 'event_type_id' => 1,
1584 'start_date' => 20081021,
1585 'end_date' => 20081023,
1586 'is_online_registration' => 1,
1587 'registration_start_date' => 20080601,
1588 'registration_end_date' => 20081015,
1589 'max_participants' => 100,
1590 'event_full_text' => 'Sorry! We are already full',
1593 'is_show_location' => 0,
1596 return $this->callAPISuccess('Event', 'create', $params);
1602 * @param int $id ID of the event
1606 function eventDelete($id) {
1610 return $this->callAPISuccess('event', 'delete', $params);
1614 * Delete participant
1616 * @param int $participantID
1620 function participantDelete($participantID) {
1622 'id' => $participantID,
1624 return $this->callAPISuccess('Participant', 'delete', $params);
1628 * Create participant payment
1630 * @param int $participantID
1631 * @param int $contributionID
1632 * @return int $id of created payment
1634 function participantPaymentCreate($participantID, $contributionID = NULL) {
1635 //Create Participant Payment record With Values
1637 'participant_id' => $participantID,
1638 'contribution_id' => $contributionID,
1641 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1642 return $result['id'];
1646 * Delete participant payment
1648 * @param int $paymentID
1650 function participantPaymentDelete($paymentID) {
1654 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1660 * @param int $contactID
1661 * @return int location id of created location
1663 function locationAdd($contactID) {
1666 'location_type' => 'New Location Type',
1668 'name' => 'Saint Helier St',
1669 'county' => 'Marin',
1670 'country' => 'United States',
1671 'state_province' => 'Michigan',
1672 'supplemental_address_1' => 'Hallmark Ct',
1673 'supplemental_address_2' => 'Jersey Village',
1678 'contact_id' => $contactID,
1679 'address' => $address,
1680 'location_format' => '2.0',
1681 'location_type' => 'New Location Type',
1684 $result = $this->callAPISuccess('Location', 'create', $params);
1689 * Delete Locations of contact
1691 * @param array $params parameters
1693 function locationDelete($params) {
1694 $this->callAPISuccess('Location', 'delete', $params);
1698 * Add a Location Type
1700 * @param array $params
1701 * @return int location id of created location
1703 function locationTypeCreate($params = NULL) {
1704 if ($params === NULL) {
1706 'name' => 'New Location Type',
1707 'vcard_name' => 'New Location Type',
1708 'description' => 'Location Type for Delete',
1713 $locationType = new CRM_Core_DAO_LocationType();
1714 $locationType->copyValues($params);
1715 $locationType->save();
1716 // clear getfields cache
1717 CRM_Core_PseudoConstant
::flush();
1718 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1719 return $locationType;
1723 * Delete a Location Type
1725 * @param int location type id
1727 function locationTypeDelete($locationTypeId) {
1728 $locationType = new CRM_Core_DAO_LocationType();
1729 $locationType->id
= $locationTypeId;
1730 $locationType->delete();
1736 * @param array $params
1737 * @return int groupId of created group
1739 function groupCreate($params = array()) {
1740 $params = array_merge(array(
1741 'name' => 'Test Group 1',
1743 'title' => 'New Test Group Created',
1744 'description' => 'New Test Group Created',
1746 'visibility' => 'Public Pages',
1747 'group_type' => array(
1753 $result = $this->callAPISuccess('Group', 'create', $params);
1754 return $result['id'];
1759 * Function to add a Group
1761 * @params array to add group
1763 * @param array $params
1764 * @return int groupId of created group
1766 function groupContactCreate($groupID, $totalCount = 10) {
1767 $params = array('group_id' => $groupID);
1768 for ($i=1; $i <= $totalCount; $i++
) {
1769 $contactID = $this->individualCreate();
1771 $params +
= array('contact_id' => $contactID);
1774 $params +
= array("contact_id.$i" => $contactID);
1777 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1787 function groupDelete($gid) {
1793 $this->callAPISuccess('Group', 'delete', $params);
1798 * @param array $params
1800 function uFFieldCreate($params = array()) {
1801 $params = array_merge(array(
1803 'field_name' => 'first_name',
1806 'visibility' => 'Public Pages and Listings',
1807 'is_searchable' => '1',
1808 'label' => 'first_name',
1809 'field_type' => 'Individual',
1812 $this->callAPISuccess('uf_field', 'create', $params);
1816 * Add a UF Join Entry
1818 * @param array $params
1819 * @return int $id of created UF Join
1821 function ufjoinCreate($params = NULL) {
1822 if ($params === NULL) {
1825 'module' => 'CiviEvent',
1826 'entity_table' => 'civicrm_event',
1832 $result = $this->callAPISuccess('uf_join', 'create', $params);
1837 * Delete a UF Join Entry
1839 * @param array with missing uf_group_id
1841 function ufjoinDelete($params = NULL) {
1842 if ($params === NULL) {
1845 'module' => 'CiviEvent',
1846 'entity_table' => 'civicrm_event',
1849 'uf_group_id' => '',
1853 crm_add_uf_join($params);
1857 * Create Group for a contact
1859 * @param int $contactId
1861 function contactGroupCreate($contactId) {
1863 'contact_id.1' => $contactId,
1867 $this->callAPISuccess('GroupContact', 'Create', $params);
1871 * Delete Group for a contact
1873 * @param int $contactId
1875 function contactGroupDelete($contactId) {
1877 'contact_id.1' => $contactId,
1880 $this->civicrm_api('GroupContact', 'Delete', $params);
1886 * @param array $params
1889 function activityCreate($params = NULL) {
1891 if ($params === NULL) {
1892 $individualSourceID = $this->individualCreate();
1894 $contactParams = array(
1895 'first_name' => 'Julia',
1896 'Last_name' => 'Anderson',
1898 'email' => 'julia_anderson@civicrm.org',
1899 'contact_type' => 'Individual',
1902 $individualTargetID = $this->individualCreate($contactParams);
1905 'source_contact_id' => $individualSourceID,
1906 'target_contact_id' => array($individualTargetID),
1907 'assignee_contact_id' => array($individualTargetID),
1908 'subject' => 'Discussion on warm beer',
1909 'activity_date_time' => date('Ymd'),
1910 'duration_hours' => 30,
1911 'duration_minutes' => 20,
1912 'location' => 'Baker Street',
1913 'details' => 'Lets schedule a meeting',
1915 'activity_name' => 'Meeting',
1919 $result = $this->callAPISuccess('Activity', 'create', $params);
1921 $result['target_contact_id'] = $individualTargetID;
1922 $result['assignee_contact_id'] = $individualTargetID;
1927 * Create an activity type
1929 * @param array $params parameters
1931 function activityTypeCreate($params) {
1932 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1937 * Delete activity type
1939 * @param int $activityTypeId id of the activity type
1941 function activityTypeDelete($activityTypeId) {
1942 $params['activity_type_id'] = $activityTypeId;
1943 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1948 * Create custom group
1950 * @param array $params
1953 function customGroupCreate($params = array()) {
1955 'title' => 'new custom group',
1956 'extends' => 'Contact',
1958 'style' => 'Inline',
1962 $params = array_merge($defaults, $params);
1964 if (strlen($params['title']) > 13) {
1965 $params['title'] = substr($params['title'], 0, 13);
1968 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1969 $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1971 return $this->callAPISuccess('custom_group', 'create', $params);
1975 * Existing function doesn't allow params to be over-ridden so need a new one
1976 * this one allows you to only pass in the params you want to change
1978 function CustomGroupCreateByParams($params = array()) {
1980 'title' => "API Custom Group",
1981 'extends' => 'Contact',
1983 'style' => 'Inline',
1986 $params = array_merge($defaults, $params);
1987 return $this->callAPISuccess('custom_group', 'create', $params);
1991 * Create custom group with multi fields
1993 function CustomGroupMultipleCreateByParams($params = array()) {
1998 $params = array_merge($defaults, $params);
1999 return $this->CustomGroupCreateByParams($params);
2003 * Create custom group with multi fields
2005 function CustomGroupMultipleCreateWithFields($params = array()) {
2006 // also need to pass on $params['custom_field'] if not set but not in place yet
2008 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2009 $ids['custom_group_id'] = $customGroup['id'];
2011 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
2013 $ids['custom_field_id'][] = $customField['id'];
2015 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
2016 $ids['custom_field_id'][] = $customField['id'];
2018 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
2019 $ids['custom_field_id'][] = $customField['id'];
2025 * Create a custom group with a single text custom field. See
2026 * participant:testCreateWithCustom for how to use this
2028 * @param string $function __FUNCTION__
2029 * @param $filename string $file __FILE__
2031 * @return array $ids ids of created objects
2033 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2034 $params = array('title' => $function);
2035 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2036 $params['extends'] = $entity ?
$entity : 'Contact';
2037 $customGroup = $this->CustomGroupCreate($params);
2038 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2039 CRM_Core_PseudoConstant
::flush();
2041 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2045 * Delete custom group
2047 * @param int $customGroupID
2051 function customGroupDelete($customGroupID) {
2052 $params['id'] = $customGroupID;
2053 return $this->callAPISuccess('custom_group', 'delete', $params);
2057 * Create custom field
2059 * @param array $params (custom_group_id) is required
2062 function customFieldCreate($params) {
2063 $params = array_merge(array(
2064 'label' => 'Custom Field',
2065 'data_type' => 'String',
2066 'html_type' => 'Text',
2067 'is_searchable' => 1,
2069 'default_value' => 'defaultValue',
2072 $result = $this->callAPISuccess('custom_field', 'create', $params);
2074 if ($result['is_error'] == 0 && isset($result['id'])) {
2075 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2076 // force reset of enabled components to help grab custom fields
2077 CRM_Core_Component
::getEnabledComponents(1);
2083 * Delete custom field
2085 * @param int $customFieldID
2089 function customFieldDelete($customFieldID) {
2091 $params['id'] = $customFieldID;
2092 return $this->callAPISuccess('custom_field', 'delete', $params);
2099 * @return array $note
2101 function noteCreate($cId) {
2103 'entity_table' => 'civicrm_contact',
2104 'entity_id' => $cId,
2105 'note' => 'hello I am testing Note',
2106 'contact_id' => $cId,
2107 'modified_date' => date('Ymd'),
2108 'subject' => 'Test Note',
2111 return $this->callAPISuccess('Note', 'create', $params);
2115 * Enable CiviCampaign Component
2117 function enableCiviCampaign() {
2118 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2119 // force reload of config object
2120 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2121 //flush cache by calling with reset
2122 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2126 * Create test generated example in api/v3/examples.
2127 * To turn this off (e.g. on the server) set
2128 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2129 * in your settings file
2130 * @param array $params array as passed to civicrm_api function
2131 * @param array $result array as received from the civicrm_api function
2132 * @param string $function calling function - generally __FUNCTION__
2133 * @param string $filename called from file - generally __FILE__
2134 * @param string $description descriptive text for the example file
2135 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2136 * @param string $action - optional action - otherwise taken from function name
2138 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2139 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2142 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2143 //todo - this is a bit cludgey
2144 if (empty($action)) {
2145 if (strstr($function, 'Create')) {
2146 $action = empty($action) ?
'create' : $action;
2147 $entityAction = 'Create';
2149 elseif (strstr($function, 'GetSingle')) {
2150 $action = empty($action) ?
'getsingle' : $action;
2151 $entityAction = 'GetSingle';
2153 elseif (strstr($function, 'GetValue')) {
2154 $action = empty($action) ?
'getvalue' : $action;
2155 $entityAction = 'GetValue';
2157 elseif (strstr($function, 'GetCount')) {
2158 $action = empty($action) ?
'getcount' : $action;
2159 $entityAction = 'GetCount';
2161 elseif (strstr($function, 'GetFields')) {
2162 $action = empty($action) ?
'getfields' : $action;
2163 $entityAction = 'GetFields';
2165 elseif (strstr($function, 'GetList')) {
2166 $action = empty($action) ?
'getlist' : $action;
2167 $entityAction = 'GetList';
2169 elseif (strstr($function, 'GetActions')) {
2170 $action = empty($action) ?
'getactions' : $action;
2171 $entityAction = 'GetActions';
2173 elseif (strstr($function, 'Get')) {
2174 $action = empty($action) ?
'get' : $action;
2175 $entityAction = 'Get';
2177 elseif (strstr($function, 'Delete')) {
2178 $action = empty($action) ?
'delete' : $action;
2179 $entityAction = 'Delete';
2181 elseif (strstr($function, 'Update')) {
2182 $action = empty($action) ?
'update' : $action;
2183 $entityAction = 'Update';
2185 elseif (strstr($function, 'Subscribe')) {
2186 $action = empty($action) ?
'subscribe' : $action;
2187 $entityAction = 'Subscribe';
2189 elseif (strstr($function, 'Submit')) {
2190 $action = empty($action) ?
'submit' : $action;
2191 $entityAction = 'Submit';
2193 elseif (strstr($function, 'Apply')) {
2194 $action = empty($action) ?
'apply' : $action;
2195 $entityAction = 'Apply';
2197 elseif (strstr($function, 'Replace')) {
2198 $action = empty($action) ?
'replace' : $action;
2199 $entityAction = 'Replace';
2203 $entityAction = ucwords($action);
2206 $this->tidyExampleResult($result);
2207 if(isset($params['version'])) {
2208 unset($params['version']);
2210 // a cleverer person than me would do it in a single regex
2211 if (strstr($entity, 'UF')) {
2212 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2215 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2217 $smarty = CRM_Core_Smarty
::singleton();
2218 $smarty->assign('testfunction', $function);
2219 $function = $fnPrefix . "_" . strtolower($action);
2220 $smarty->assign('function', $function);
2221 $smarty->assign('fnPrefix', $fnPrefix);
2222 $smarty->assign('params', $params);
2223 $smarty->assign('entity', $entity);
2224 $smarty->assign('filename', basename($filename));
2225 $smarty->assign('description', $description);
2226 $smarty->assign('result', $result);
2228 $smarty->assign('action', $action);
2229 if (empty($subfile)) {
2230 $subfile = $entityAction;
2232 if (file_exists('../tests/templates/documentFunction.tpl')) {
2233 if (!is_dir("../api/v3/examples/$entity")) {
2234 mkdir("../api/v3/examples/$entity");
2236 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2237 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2243 * Tidy up examples array so that fields that change often ..don't
2244 * and debug related fields are unset
2246 * @param array $result
2249 function tidyExampleResult(&$result){
2250 if(!is_array($result)) {
2253 $fieldsToChange = array(
2254 'hash' => '67eac7789eaee00',
2255 'modified_date' => '2012-11-14 16:02:35',
2256 'created_date' => '2013-07-28 08:49:19',
2257 'create_date' => '20120130621222105',
2258 'application_received_date' => '20130728084957',
2259 'in_date' => '2013-07-28 08:50:19',
2260 'scheduled_date' => '20130728085413',
2261 'approval_date' => '20130728085413',
2262 'pledge_start_date_high' => '20130726090416',
2263 'start_date' => '2013-07-29 00:00:00',
2264 'event_start_date' => '2013-07-29 00:00:00',
2265 'end_date' => '2013-08-04 00:00:00',
2266 'event_end_date' => '2013-08-04 00:00:00',
2267 'decision_date' => '20130805000000',
2270 $keysToUnset = array('xdebug', 'undefined_fields',);
2271 foreach ($keysToUnset as $unwantedKey) {
2272 if(isset($result[$unwantedKey])) {
2273 unset($result[$unwantedKey]);
2276 if (isset($result['values'])) {
2277 if(!is_array($result['values'])) {
2280 $resultArray = &$result['values'];
2282 elseif(is_array($result)) {
2283 $resultArray = &$result;
2289 foreach ($resultArray as $index => &$values) {
2290 if(!is_array($values)) {
2293 foreach($values as $key => &$value) {
2294 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2295 if(isset($value['is_error'])) {
2296 // we have a std nested result format
2297 $this->tidyExampleResult($value);
2300 foreach ($value as &$nestedResult) {
2301 // this is an alternative syntax for nested results a keyed array of results
2302 $this->tidyExampleResult($nestedResult);
2306 if(in_array($key, $keysToUnset)) {
2307 unset($values[$key]);
2310 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2311 $value = $fieldsToChange[$key];
2313 if(is_string($value)) {
2314 $value = addslashes($value);
2323 * @param array $params
2327 function noteDelete($params) {
2328 return $this->callAPISuccess('Note', 'delete', $params);
2332 * Create custom field with Option Values
2334 * @param array $customGroup
2335 * @param string $name name of custom field
2339 function customFieldOptionValueCreate($customGroup, $name) {
2340 $fieldParams = array(
2341 'custom_group_id' => $customGroup['id'],
2342 'name' => 'test_custom_group',
2343 'label' => 'Country',
2344 'html_type' => 'Select',
2345 'data_type' => 'String',
2348 'is_searchable' => 0,
2352 $optionGroup = array(
2354 'name' => 'option_group1',
2355 'label' => 'option_group_label1',
2358 $optionValue = array(
2359 'option_label' => array('Label1', 'Label2'),
2360 'option_value' => array('value1', 'value2'),
2361 'option_name' => array($name . '_1', $name . '_2'),
2362 'option_weight' => array(1, 2),
2363 'option_status' => 1,
2366 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2368 return $this->callAPISuccess('custom_field', 'create', $params);
2376 function confirmEntitiesDeleted($entities) {
2377 foreach ($entities as $entity) {
2379 $result = $this->callAPISuccess($entity, 'Get', array());
2380 if ($result['error'] == 1 ||
$result['count'] > 0) {
2381 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2388 * @param $tablesToTruncate
2389 * @param bool $dropCustomValueTables
2391 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2393 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2395 if ($dropCustomValueTables) {
2396 $tablesToTruncate[] = 'civicrm_custom_group';
2397 $tablesToTruncate[] = 'civicrm_custom_field';
2400 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2402 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2403 foreach ($tablesToTruncate as $table) {
2404 $sql = "TRUNCATE TABLE $table";
2405 CRM_Core_DAO
::executeQuery($sql);
2407 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2409 if ($dropCustomValueTables) {
2410 $dbName = self
::getDBName();
2412 SELECT TABLE_NAME as tableName
2413 FROM INFORMATION_SCHEMA.TABLES
2414 WHERE TABLE_SCHEMA = '{$dbName}'
2415 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2418 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2419 while ($tableDAO->fetch()) {
2420 $sql = "DROP TABLE {$tableDAO->tableName}";
2421 CRM_Core_DAO
::executeQuery($sql);
2427 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2429 function quickCleanUpFinancialEntities() {
2430 $tablesToTruncate = array(
2431 'civicrm_contribution',
2432 'civicrm_contribution_soft',
2433 'civicrm_financial_trxn',
2434 'civicrm_financial_item',
2435 'civicrm_contribution_recur',
2436 'civicrm_line_item',
2437 'civicrm_contribution_page',
2438 'civicrm_payment_processor',
2439 'civicrm_entity_financial_trxn',
2440 'civicrm_membership',
2441 'civicrm_membership_type',
2442 'civicrm_membership_payment',
2443 'civicrm_membership_log',
2444 'civicrm_membership_block',
2446 'civicrm_participant',
2447 'civicrm_participant_payment',
2449 'civicrm_price_set_entity',
2450 'civicrm_price_field_value',
2451 'civicrm_price_field',
2453 $this->quickCleanup($tablesToTruncate);
2454 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2455 $this->restoreDefaultPriceSetConfig();
2457 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2460 function restoreDefaultPriceSetConfig() {
2461 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)");
2462 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)");
2465 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2466 * Default behaviour is to also delete the entity
2467 * @param array $params params array to check agains
2468 * @param int $id id of the entity concerned
2469 * @param string $entity name of entity concerned (e.g. membership)
2470 * @param bool $delete should the entity be deleted as part of this check
2471 * @param string $errorText text to print on error
2475 * @param array $params
2478 * @param int $delete
2479 * @param string $errorText
2483 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2485 $result = $this->callAPISuccessGetSingle($entity, array(
2490 $this->callAPISuccess($entity, 'Delete', array(
2494 $dateFields = $keys = $dateTimeFields = array();
2495 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2496 foreach ($fields['values'] as $field => $settings) {
2497 if (array_key_exists($field, $result)) {
2498 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2501 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2503 $type = CRM_Utils_Array
::value('type', $settings);
2504 if ($type == CRM_Utils_Type
::T_DATE
) {
2505 $dateFields[] = $settings['name'];
2506 // we should identify both real names & unique names as dates
2507 if($field != $settings['name']) {
2508 $dateFields[] = $field;
2511 if($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2512 $dateTimeFields[] = $settings['name'];
2513 // we should identify both real names & unique names as dates
2514 if($field != $settings['name']) {
2515 $dateTimeFields[] = $field;
2520 if (strtolower($entity) == 'contribution') {
2521 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2522 // this is not returned in id format
2523 unset($params['payment_instrument_id']);
2524 $params['contribution_source'] = $params['source'];
2525 unset($params['source']);
2528 foreach ($params as $key => $value) {
2529 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2532 if (in_array($key, $dateFields)) {
2533 $value = date('Y-m-d', strtotime($value));
2534 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2536 if (in_array($key, $dateTimeFields)) {
2537 $value = date('Y-m-d H:i:s', strtotime($value));
2538 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2540 $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);
2545 * Get formatted values in the actual and expected result
2546 * @param array $actual actual calculated values
2547 * @param array $expected expected values
2550 function checkArrayEquals(&$actual, &$expected) {
2551 self
::unsetId($actual);
2552 self
::unsetId($expected);
2553 $this->assertEquals($actual, $expected);
2557 * Unset the key 'id' from the array
2558 * @param array $unformattedArray The array from which the 'id' has to be unset
2561 static function unsetId(&$unformattedArray) {
2562 $formattedArray = array();
2563 if (array_key_exists('id', $unformattedArray)) {
2564 unset($unformattedArray['id']);
2566 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2567 foreach ($unformattedArray['values'] as $key => $value) {
2568 if (is_Array($value)) {
2569 foreach ($value as $k => $v) {
2575 elseif ($key == 'id') {
2576 $unformattedArray[$key];
2578 $formattedArray = array($value);
2580 $unformattedArray['values'] = $formattedArray;
2585 * Helper to enable/disable custom directory support
2587 * @param array $customDirs with members:
2588 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2589 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2591 function customDirectories($customDirs) {
2592 require_once 'CRM/Core/Config.php';
2593 $config = CRM_Core_Config
::singleton();
2595 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2596 unset($config->customPHPPathDir
);
2598 elseif ($customDirs['php_path'] === TRUE) {
2599 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2602 $config->customPHPPathDir
= $php_path;
2605 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2606 unset($config->customTemplateDir
);
2608 elseif ($customDirs['template_path'] === TRUE) {
2609 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2612 $config->customTemplateDir
= $template_path;
2617 * Generate a temporary folder
2619 * @param string $prefix
2620 * @return string $string
2622 function createTempDir($prefix = 'test-') {
2623 $tempDir = CRM_Utils_File
::tempdir($prefix);
2624 $this->tempDirs
[] = $tempDir;
2628 function cleanTempDirs() {
2629 if (!is_array($this->tempDirs
)) {
2630 // fix test errors where this is not set
2633 foreach ($this->tempDirs
as $tempDir) {
2634 if (is_dir($tempDir)) {
2635 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2641 * Temporarily replace the singleton extension with a different one
2643 function setExtensionSystem(CRM_Extension_System
$system) {
2644 if ($this->origExtensionSystem
== NULL) {
2645 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2647 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2650 function unsetExtensionSystem() {
2651 if ($this->origExtensionSystem
!== NULL) {
2652 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2653 $this->origExtensionSystem
= NULL;
2658 * Temporarily alter the settings-metadata to add a mock setting.
2660 * WARNING: The setting metadata will disappear on the next cache-clear.
2665 function setMockSettingsMetaData($extras) {
2666 CRM_Core_BAO_Setting
::$_cache = array();
2667 $this->callAPISuccess('system','flush', array());
2668 CRM_Core_BAO_Setting
::$_cache = array();
2670 CRM_Utils_Hook
::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2671 $metadata = array_merge($metadata, $extras);
2674 $fields = $this->callAPISuccess('setting', 'getfields', array());
2675 foreach ($extras as $key => $spec) {
2676 $this->assertNotEmpty($spec['title']);
2677 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2682 * @param string $name
2684 function financialAccountDelete($name) {
2685 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2686 $financialAccount->name
= $name;
2687 if($financialAccount->find(TRUE)) {
2688 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2689 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2690 $entityFinancialType->delete();
2691 $financialAccount->delete();
2696 * Use $ids as an instruction to do test cleanup
2698 function deleteFromIDSArray() {
2699 foreach ($this->ids
as $entity => $ids) {
2700 foreach ($ids as $id) {
2701 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2707 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2708 * (NB unclear if this is still required)
2710 function _sethtmlGlobals() {
2711 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2712 'required' => array(
2713 'html_quickform_rule_required',
2714 'HTML/QuickForm/Rule/Required.php'
2716 'maxlength' => array(
2717 'html_quickform_rule_range',
2718 'HTML/QuickForm/Rule/Range.php'
2720 'minlength' => array(
2721 'html_quickform_rule_range',
2722 'HTML/QuickForm/Rule/Range.php'
2724 'rangelength' => array(
2725 'html_quickform_rule_range',
2726 'HTML/QuickForm/Rule/Range.php'
2729 'html_quickform_rule_email',
2730 'HTML/QuickForm/Rule/Email.php'
2733 'html_quickform_rule_regex',
2734 'HTML/QuickForm/Rule/Regex.php'
2736 'lettersonly' => array(
2737 'html_quickform_rule_regex',
2738 'HTML/QuickForm/Rule/Regex.php'
2740 'alphanumeric' => array(
2741 'html_quickform_rule_regex',
2742 'HTML/QuickForm/Rule/Regex.php'
2745 'html_quickform_rule_regex',
2746 'HTML/QuickForm/Rule/Regex.php'
2748 'nopunctuation' => array(
2749 'html_quickform_rule_regex',
2750 'HTML/QuickForm/Rule/Regex.php'
2753 'html_quickform_rule_regex',
2754 'HTML/QuickForm/Rule/Regex.php'
2756 'callback' => array(
2757 'html_quickform_rule_callback',
2758 'HTML/QuickForm/Rule/Callback.php'
2761 'html_quickform_rule_compare',
2762 'HTML/QuickForm/Rule/Compare.php'
2765 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2766 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2768 'HTML/QuickForm/group.php',
2769 'HTML_QuickForm_group'
2772 'HTML/QuickForm/hidden.php',
2773 'HTML_QuickForm_hidden'
2776 'HTML/QuickForm/reset.php',
2777 'HTML_QuickForm_reset'
2779 'checkbox' => array(
2780 'HTML/QuickForm/checkbox.php',
2781 'HTML_QuickForm_checkbox'
2784 'HTML/QuickForm/file.php',
2785 'HTML_QuickForm_file'
2788 'HTML/QuickForm/image.php',
2789 'HTML_QuickForm_image'
2791 'password' => array(
2792 'HTML/QuickForm/password.php',
2793 'HTML_QuickForm_password'
2796 'HTML/QuickForm/radio.php',
2797 'HTML_QuickForm_radio'
2800 'HTML/QuickForm/button.php',
2801 'HTML_QuickForm_button'
2804 'HTML/QuickForm/submit.php',
2805 'HTML_QuickForm_submit'
2808 'HTML/QuickForm/select.php',
2809 'HTML_QuickForm_select'
2811 'hiddenselect' => array(
2812 'HTML/QuickForm/hiddenselect.php',
2813 'HTML_QuickForm_hiddenselect'
2816 'HTML/QuickForm/text.php',
2817 'HTML_QuickForm_text'
2819 'textarea' => array(
2820 'HTML/QuickForm/textarea.php',
2821 'HTML_QuickForm_textarea'
2823 'fckeditor' => array(
2824 'HTML/QuickForm/fckeditor.php',
2825 'HTML_QuickForm_FCKEditor'
2828 'HTML/QuickForm/tinymce.php',
2829 'HTML_QuickForm_TinyMCE'
2831 'dojoeditor' => array(
2832 'HTML/QuickForm/dojoeditor.php',
2833 'HTML_QuickForm_dojoeditor'
2836 'HTML/QuickForm/link.php',
2837 'HTML_QuickForm_link'
2839 'advcheckbox' => array(
2840 'HTML/QuickForm/advcheckbox.php',
2841 'HTML_QuickForm_advcheckbox'
2844 'HTML/QuickForm/date.php',
2845 'HTML_QuickForm_date'
2848 'HTML/QuickForm/static.php',
2849 'HTML_QuickForm_static'
2852 'HTML/QuickForm/header.php',
2853 'HTML_QuickForm_header'
2856 'HTML/QuickForm/html.php',
2857 'HTML_QuickForm_html'
2859 'hierselect' => array(
2860 'HTML/QuickForm/hierselect.php',
2861 'HTML_QuickForm_hierselect'
2863 'autocomplete' => array(
2864 'HTML/QuickForm/autocomplete.php',
2865 'HTML_QuickForm_autocomplete'
2868 'HTML/QuickForm/xbutton.php',
2869 'HTML_QuickForm_xbutton'
2871 'advmultiselect' => array(
2872 'HTML/QuickForm/advmultiselect.php',
2873 'HTML_QuickForm_advmultiselect'
2879 * Set up an acl allowing contact to see 2 specified groups
2880 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2882 * You need to have pre-created these groups & created the user e.g
2883 * $this->createLoggedInUser();
2884 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2885 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2888 function setupACL() {
2890 $_REQUEST = $this->_params
;
2892 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2893 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2894 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2895 'label' => 'pick me',
2900 CRM_Core_DAO
::executeQuery("
2901 TRUNCATE civicrm_acl_cache
2904 CRM_Core_DAO
::executeQuery("
2905 TRUNCATE civicrm_acl_contact_cache
2909 CRM_Core_DAO
::executeQuery("
2910 INSERT INTO civicrm_acl_entity_role (
2911 `acl_role_id`, `entity_table`, `entity_id`
2912 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2915 CRM_Core_DAO
::executeQuery("
2916 INSERT INTO civicrm_acl (
2917 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2920 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2924 CRM_Core_DAO
::executeQuery("
2925 INSERT INTO civicrm_acl (
2926 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2929 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2932 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2933 $this->callAPISuccess('group_contact', 'create', array(
2934 'group_id' => $this->_permissionedGroup
,
2935 'contact_id' => $this->_loggedInUser
,
2938 CRM_ACL_BAO_Cache
::resetCache();
2939 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
2940 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2944 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2946 function offsetDefaultPriceSet() {
2947 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2948 $firstID = $contributionPriceSet['id'];
2949 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2950 unset($contributionPriceSet['id']);
2951 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2952 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2953 unset($priceField['id']);
2954 $priceField['price_set_id'] = $newPriceSet['id'];
2955 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2956 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2958 unset($priceFieldValue['id']);
2959 //create some padding to use up ids
2960 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2961 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2962 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2966 * Create an instance of the paypal processor
2967 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2968 * this parent class & we don't have a structure for that yet
2969 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2970 * & the best protection agains that is the functions this class affords
2972 function paymentProcessorCreate($params = array()) {
2973 $params = array_merge(array(
2975 'domain_id' => CRM_Core_Config
::domainID(),
2976 'payment_processor_type_id' => 'PayPal',
2980 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2981 'password' => '1183377788',
2982 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2983 'url_site' => 'https://www.sandbox.paypal.com/',
2984 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2985 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2986 'class_name' => 'Payment_PayPalImpl',
2987 'billing_mode' => 3,
2988 'financial_type_id' => 1,
2991 if(!is_numeric($params['payment_processor_type_id'])) {
2992 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2994 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2995 'name' => $params['payment_processor_type_id'],
2999 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3000 return $result['id'];
3004 * Set up initial recurring payment allowing subsequent IPN payments
3006 function setupRecurringPaymentProcessorTransaction() {
3007 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3008 'contact_id' => $this->_contactID
,
3011 'installments' => 5,
3012 'frequency_unit' => 'Month',
3013 'frequency_interval' => 1,
3014 'invoice_id' => $this->_invoiceID
,
3015 'contribution_status_id' => 2,
3016 'processor_id' => $this->_paymentProcessorID
,
3017 'api.contribution.create' => array(
3018 'total_amount' => '200',
3019 'invoice_id' => $this->_invoiceID
,
3020 'financial_type_id' => 1,
3021 'contribution_status_id' => 'Pending',
3022 'contact_id' => $this->_contactID
,
3023 'contribution_page_id' => $this->_contributionPageID
,
3024 'payment_processor_id' => $this->_paymentProcessorID
,
3027 $this->_contributionRecurID
= $contributionRecur['id'];
3028 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3032 * 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
3034 function setupMembershipRecurringPaymentProcessorTransaction() {
3035 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3036 //create a contribution so our membership & contribution don't both have id = 1
3037 $this->contributionCreate($this->_contactID
, 1, 'abcd', '345j');
3038 $this->setupRecurringPaymentProcessorTransaction();
3040 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3041 'contact_id' => $this->_contactID
,
3042 'membership_type_id' => $this->ids
['membership_type'],
3043 'contribution_recur_id' => $this->_contributionRecurID
,
3044 'format.only_id' => TRUE,
3046 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3047 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3049 $this->callAPISuccess('line_item', 'create', array(
3050 'entity_table' => 'civicrm_membership',
3051 'entity_id' => $this->ids
['membership'],
3052 'contribution_id' => $this->_contributionID
,
3053 'label' => 'General',
3055 'unit_price' => 200,
3056 'line_total' => 200,
3057 'financial_type_id' => 1,
3058 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array('return' => 'id', 'label' => 'Membership Amount')),
3059 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array('return' => 'id', 'label' => 'General')),
3061 $this->callAPISuccess('membership_payment', 'create', array('contribution_id' => $this->_contributionID
, 'membership_id' => $this->ids
['membership']));
3069 function CiviUnitTestCase_fatalErrorHandler($message) {
3070 throw new Exception("{$message['message']}: {$message['code']}");
3074 * Helper function to create new mailing
3077 function createMailing() {
3079 'subject' => 'maild' . rand(),
3080 'body_text' => 'bdkfhdskfhduew',
3081 'name' => 'mailing name' . rand(),
3083 'api.mailing_job.create' => 0,
3086 $result = $this->callAPISuccess('Mailing', 'create', $params);
3087 return $result['id'];
3091 * Helper function to delete mailing
3094 function deleteMailing($id) {
3099 $this->callAPISuccess('Mailing', 'delete', $params);
3103 * Wrap the entire test case in a transaction
3105 * Only subsequent DB statements will be wrapped in TX -- this cannot
3106 * retroactively wrap old DB statements. Therefore, it makes sense to
3107 * call this at the beginning of setUp().
3109 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3110 * this option does not work with, e.g., custom-data.
3112 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3113 * if TRUNCATE or ALTER is called while using a transaction.
3115 * @param bool $nest whether to use nesting or reference-counting
3117 function useTransaction($nest = TRUE) {
3119 $this->tx
= new CRM_Core_Transaction($nest);
3120 $this->tx
->rollback();
3124 function clearOutputBuffer() {
3125 while (ob_get_level() > 0) {