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
139 * @var CRM_Utils_Hook_UnitTests hookClass
140 * example of setting a method for a hook
141 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
143 public $hookClass = NULL;
146 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
148 protected $_params = array();
151 * @var CRM_Extension_System
153 protected $origExtensionSystem;
158 * Because we are overriding the parent class constructor, we
159 * need to show the same arguments as exist in the constructor of
160 * PHPUnit_Framework_TestCase, since
161 * PHPUnit_Framework_TestSuite::createTest() creates a
162 * ReflectionClass of the Test class and checks the constructor
163 * of that class to decide how to set up the test.
165 * @param string $name
167 * @param string $dataName
169 public function __construct($name = NULL, array$data = array(), $dataName = '') {
170 parent
::__construct($name, $data, $dataName);
172 // we need full error reporting
173 error_reporting(E_ALL
& ~E_NOTICE
);
175 if (!empty($GLOBALS['mysql_db'])) {
176 self
::$_dbName = $GLOBALS['mysql_db'];
179 self
::$_dbName = 'civicrm_tests_dev';
182 // create test database
183 self
::$utils = new Utils($GLOBALS['mysql_host'],
184 $GLOBALS['mysql_port'],
185 $GLOBALS['mysql_user'],
186 $GLOBALS['mysql_pass']
189 // also load the class loader
190 require_once 'CRM/Core/ClassLoader.php';
191 CRM_Core_ClassLoader
::singleton()->register();
192 if (function_exists('_civix_phpunit_setUp')) {
193 // FIXME: loosen coupling
194 _civix_phpunit_setUp();
199 * Override to run the test and assert its state.
202 * @throws \PHPUnit_Framework_IncompleteTest
203 * @throws \PHPUnit_Framework_SkippedTest
205 protected function runTest() {
207 return parent
::runTest();
209 catch (PEAR_Exception
$e) {
210 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
211 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
218 public function requireDBReset() {
219 return $this->DBResetRequired
;
225 public static function getDBName() {
226 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
231 * Create database connection for this instance
233 * Initialize the test database if it hasn't been initialized
235 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
237 protected function getConnection() {
238 $dbName = self
::$_dbName;
239 if (!self
::$dbInit) {
240 $dbName = self
::getDBName();
242 // install test database
243 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
245 static::_populateDB(FALSE, $this);
247 self
::$dbInit = TRUE;
249 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
253 * Required implementation of abstract method
255 protected function getDataSet() {
259 * @param bool $perClass
260 * @param null $object
262 * TRUE if the populate logic runs; FALSE if it is skipped
264 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
266 if ($perClass ||
$object == NULL) {
270 $dbreset = $object->requireDBReset();
273 if (self
::$populateOnce ||
!$dbreset) {
276 self
::$populateOnce = NULL;
278 $dbName = self
::getDBName();
279 $pdo = self
::$utils->pdo
;
280 // only consider real tables and not views
281 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
282 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
284 $truncates = array();
286 foreach ($tables as $table) {
288 if (substr($table['table_name'], 0, 4) == 'log_') {
292 // don't change list of installed extensions
293 if ($table['table_name'] == 'civicrm_extension') {
297 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
298 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
301 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
307 "SET foreign_key_checks = 0",
308 // SQL mode needs to be strict, that's our standard
309 "SET SQL_MODE='STRICT_ALL_TABLES';",
310 "SET global innodb_flush_log_at_trx_commit = 2;",
312 $queries = array_merge($queries, $truncates);
313 $queries = array_merge($queries, $drops);
314 foreach ($queries as $query) {
315 if (self
::$utils->do_query($query) === FALSE) {
316 // failed to create test database
317 echo "failed to create test db.";
322 // initialize test database
323 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
324 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
325 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
327 $query2 = file_get_contents($sql_file2);
328 $query3 = file_get_contents($sql_file3);
329 $query4 = file_get_contents($sql_file4);
330 if (self
::$utils->do_query($query2) === FALSE) {
331 echo "Cannot load civicrm_data.mysql. Aborting.";
334 if (self
::$utils->do_query($query3) === FALSE) {
335 echo "Cannot load test_data.mysql. Aborting.";
338 if (self
::$utils->do_query($query4) === FALSE) {
339 echo "Cannot load test_data.mysql. Aborting.";
343 // done with all the loading, get transactions back
344 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
345 echo "Cannot set global? Huh?";
349 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
350 echo "Cannot get foreign keys back? Huh?";
354 unset($query, $query2, $query3);
357 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
359 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
371 public static function setUpBeforeClass() {
372 static::_populateDB(TRUE);
374 // also set this global hack
375 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
377 $env = new CRM_Utils_Check_Env();
378 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
382 * Common setup functions for all unit tests
384 protected function setUp() {
385 $session = CRM_Core_Session
::singleton();
386 $session->set('userID', NULL);
388 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
389 // Use a temporary file for STDIN
390 $GLOBALS['stdin'] = tmpfile();
391 if ($GLOBALS['stdin'] === FALSE) {
392 echo "Couldn't open temporary file\n";
396 // Get and save a connection to the database
397 $this->_dbconn
= $this->getConnection();
399 // reload database before each test
400 // $this->_populateDB();
402 // "initialize" CiviCRM to avoid problems when running single tests
403 // FIXME: look at it closer in second stage
405 // initialize the object once db is loaded
406 CRM_Core_Config
::$_mail = NULL;
407 $config = CRM_Core_Config
::singleton();
409 // when running unit tests, use mockup user framework
410 $config->setUserFramework('UnitTests');
411 $this->hookClass
= CRM_Utils_Hook
::singleton(TRUE);
412 // also fix the fatal error handler to throw exceptions,
414 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
416 // enable backtrace to get meaningful errors
417 $config->backtrace
= 1;
419 // disable any left-over test extensions
420 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
422 // reset all the caches
423 CRM_Utils_System
::flushCache();
425 // clear permissions stub to not check permissions
426 $config = CRM_Core_Config
::singleton();
427 $config->userPermissionClass
->permissions
= NULL;
429 //flush component settings
430 CRM_Core_Component
::getEnabledComponents(TRUE);
432 if ($this->_eNoticeCompliant
) {
433 error_reporting(E_ALL
);
436 error_reporting(E_ALL
& ~E_NOTICE
);
438 $this->_sethtmlGlobals();
442 * Read everything from the datasets directory and insert into the db
444 public function loadAllFixtures() {
445 $fixturesDir = __DIR__
. '/../../fixtures';
447 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
449 $xmlFiles = glob($fixturesDir . '/*.xml');
450 foreach ($xmlFiles as $xmlFixture) {
451 $op = new PHPUnit_Extensions_Database_Operation_Insert();
452 $dataset = $this->createXMLDataSet($xmlFixture);
453 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
454 $op->execute($this->_dbconn
, $dataset);
457 $yamlFiles = glob($fixturesDir . '/*.yaml');
458 foreach ($yamlFiles as $yamlFixture) {
459 $op = new PHPUnit_Extensions_Database_Operation_Insert();
460 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
461 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
462 $op->execute($this->_dbconn
, $dataset);
465 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
469 * Emulate a logged in user since certain functions use that
470 * value to store a record in the DB (like activity)
473 public function createLoggedInUser() {
475 'first_name' => 'Logged In',
476 'last_name' => 'User ' . rand(),
477 'contact_type' => 'Individual',
479 $contactID = $this->individualCreate($params);
481 $session = CRM_Core_Session
::singleton();
482 $session->set('userID', $contactID);
485 public function cleanDB() {
486 self
::$populateOnce = NULL;
487 $this->DBResetRequired
= TRUE;
489 $this->_dbconn
= $this->getConnection();
490 static::_populateDB();
491 $this->tempDirs
= array();
495 * Create default domain contacts for the two domains added during test class
496 * database population.
498 public function createDomainContacts() {
499 $default_domain_contact = $this->organizationCreate();
500 $second_domain_contact = $this->organizationCreate();
504 * Common teardown functions for all unit tests
506 protected function tearDown() {
507 error_reporting(E_ALL
& ~E_NOTICE
);
508 CRM_Utils_Hook
::singleton()->reset();
509 $this->hookClass
->reset();
510 $session = CRM_Core_Session
::singleton();
511 $session->set('userID', NULL);
514 $this->tx
->rollback()->commit();
517 CRM_Core_Transaction
::forceRollbackIfEnabled();
518 \Civi\Core\Transaction\Manager
::singleton(TRUE);
521 CRM_Core_Transaction
::forceRollbackIfEnabled();
522 \Civi\Core\Transaction\Manager
::singleton(TRUE);
524 $tablesToTruncate = array('civicrm_contact');
525 $this->quickCleanup($tablesToTruncate);
526 $this->createDomainContacts();
529 $this->cleanTempDirs();
530 $this->unsetExtensionSystem();
531 $this->clearOutputBuffer();
535 * FIXME: Maybe a better way to do it
537 public function foreignKeyChecksOff() {
538 self
::$utils = new Utils($GLOBALS['mysql_host'],
539 $GLOBALS['mysql_port'],
540 $GLOBALS['mysql_user'],
541 $GLOBALS['mysql_pass']
543 $dbName = self
::getDBName();
544 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
545 if (self
::$utils->do_query($query) === FALSE) {
547 echo 'Cannot set foreign_key_checks = 0';
553 public function foreignKeyChecksOn() {
554 // FIXME: might not be needed if previous fixme implemented
558 * Generic function to compare expected values after an api call to retrieved
561 * @daoName string DAO Name of object we're evaluating.
562 * @id int Id of object
563 * @match array Associative array of field name => expected value. Empty if asserting
564 * that a DELETE occurred
565 * @delete boolean True if we're checking that a DELETE action occurred.
569 * @param bool $delete
570 * @throws \PHPUnit_Framework_AssertionFailedError
572 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
574 // adding this here since developers forget to check for an id
575 // and hence we get the first value in the db
576 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
579 $object = new $daoName();
583 // If we're asserting successful record deletion, make sure object is NOT found.
585 if ($object->find(TRUE)) {
586 $this->fail("Object not deleted by delete operation: $daoName, $id");
591 // Otherwise check matches of DAO field values against expected values in $match.
592 if ($object->find(TRUE)) {
593 $fields = &$object->fields();
594 foreach ($fields as $name => $value) {
595 $dbName = $value['name'];
596 if (isset($match[$name])) {
598 $this->assertEquals($object->$dbName, $match[$name]);
600 elseif (isset($match[$dbName])) {
602 $this->assertEquals($object->$dbName, $match[$dbName]);
607 $this->fail("Could not retrieve object: $daoName, $id");
610 $matchSize = count($match);
611 if ($verifiedCount != $matchSize) {
612 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
617 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
618 * @param string $daoName
619 * @param $searchValue
620 * @param $returnColumn
621 * @param $searchColumn
624 * @return null|string
625 * @throws PHPUnit_Framework_AssertionFailedError
627 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
628 if (empty($searchValue)) {
629 $this->fail("empty value passed to assertDBNotNull");
631 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
632 $this->assertNotNull($value, $message);
638 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
639 * @param string $daoName
640 * @param $searchValue
641 * @param $returnColumn
642 * @param $searchColumn
645 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
646 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
647 $this->assertNull($value, $message);
651 * Request a record from the DB by id. Success if row not found.
652 * @param string $daoName
654 * @param null $message
656 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
657 $message = $message ?
$message : "$daoName (#$id) should not exist";
658 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
659 $this->assertNull($value, $message);
663 * Request a record from the DB by id. Success if row not found.
664 * @param string $daoName
666 * @param null $message
668 public function assertDBRowExist($daoName, $id, $message = NULL) {
669 $message = $message ?
$message : "$daoName (#$id) should exist";
670 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
671 $this->assertEquals($id, $value, $message);
675 * Compare a single column value in a retrieved DB record to an expected value
676 * @param string $daoName
677 * @param $searchValue
678 * @param $returnColumn
679 * @param $searchColumn
680 * @param $expectedValue
683 public function assertDBCompareValue(
684 $daoName, $searchValue, $returnColumn, $searchColumn,
685 $expectedValue, $message
687 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
688 $this->assertEquals($value, $expectedValue, $message);
692 * Compare all values in a single retrieved DB record to an array of expected values
693 * @param string $daoName
694 * @param array $searchParams
695 * @param $expectedValues
697 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
698 //get the values from db
700 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
702 // compare db values with expected values
703 self
::assertAttributesEquals($expectedValues, $dbValues);
707 * Assert that a SQL query returns a given value
709 * The first argument is an expected value. The remaining arguments are passed
710 * to CRM_Core_DAO::singleValueQuery
712 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
713 * array(1 => array("Whiz", "String")));
716 * @param array $params
717 * @param string $message
719 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
723 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
724 $this->assertEquals($expected, $actual,
725 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
726 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
732 * Assert that two array-trees are exactly equal, notwithstanding
733 * the sorting of keys
735 * @param array $expected
736 * @param array $actual
738 public function assertTreeEquals($expected, $actual) {
741 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
742 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
746 $this->assertEquals($e, $a);
750 * Assert that two numbers are approximately equal
752 * @param int|float $expected
753 * @param int|float $actual
754 * @param int|float $tolerance
755 * @param string $message
757 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
758 if ($message === NULL) {
759 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
761 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
765 * @param $expectedValues
766 * @param $actualValues
767 * @param null $message
769 * @throws PHPUnit_Framework_AssertionFailedError
771 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
772 foreach ($expectedValues as $paramName => $paramValue) {
773 if (isset($actualValues[$paramName])) {
774 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
777 $this->fail("Attribute '$paramName' not present in actual array.");
786 public function assertArrayKeyExists($key, &$list) {
787 $result = isset($list[$key]) ?
TRUE : FALSE;
788 $this->assertTrue($result, ts("%1 element exists?",
797 public function assertArrayValueNotNull($key, &$list) {
798 $this->assertArrayKeyExists($key, $list);
800 $value = isset($list[$key]) ?
$list[$key] : NULL;
801 $this->assertTrue($value,
802 ts("%1 element not null?",
809 * Check that api returned 'is_error' => 0
810 * else provide full message
811 * @param array $apiResult
813 * @param string $prefix
814 * Extra test to add to message.
816 public function assertAPISuccess($apiResult, $prefix = '') {
817 if (!empty($prefix)) {
820 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
822 if (!empty($apiResult['debug_information'])) {
823 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
825 if (!empty($apiResult['trace'])) {
826 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
828 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
832 * Check that api returned 'is_error' => 1
833 * else provide full message
835 * @param array $apiResult
837 * @param string $prefix
838 * Extra test to add to message.
839 * @param null $expectedError
841 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
842 if (!empty($prefix)) {
845 if ($expectedError && !empty($apiResult['is_error'])) {
846 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
848 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
849 $this->assertNotEmpty($apiResult['error_message']);
855 * @param string $message
857 public function assertType($expected, $actual, $message = '') {
858 return $this->assertInternalType($expected, $actual, $message);
862 * Check that a deleted item has been deleted
866 public function assertAPIDeleted($entity, $id) {
867 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
872 * Check that api returned 'is_error' => 1
873 * else provide full message
874 * @param array $result
876 * @param array $valuesToExclude
877 * @param string $prefix
878 * Extra test to add to message.
880 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
881 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
882 foreach ($valuesToExclude as $value) {
883 if (isset($result[$value])) {
884 unset($result[$value]);
886 if (isset($expected[$value])) {
887 unset($expected[$value]);
890 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
894 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
898 * @param array $params
901 public function civicrm_api($entity, $action, $params) {
902 return civicrm_api($entity, $action, $params);
907 * so we can ensure they succeed & throw exceptions without litterering the test with checks
909 * @param string $entity
910 * @param string $action
911 * @param array $params
912 * @param mixed $checkAgainst
913 * Optional value to check result against, implemented for getvalue,.
914 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
915 * for getsingle the array is compared against an array passed in - the id is not compared (for
920 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
921 $params = array_merge(array(
922 'version' => $this->_apiversion
,
927 switch (strtolower($action)) {
929 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
932 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
935 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
937 $result = $this->civicrm_api($entity, $action, $params);
938 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
943 * This function exists to wrap api getValue function & check the result
944 * so we can ensure they succeed & throw exceptions without litterering the test with checks
945 * There is a type check in this
947 * @param string $entity
948 * @param array $params
949 * @param string $type
950 * Per http://php.net/manual/en/function.gettype.php possible types.
960 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
962 'version' => $this->_apiversion
,
965 $result = $this->civicrm_api($entity, 'getvalue', $params);
967 if ($type == 'integer') {
968 // api seems to return integers as strings
969 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
972 $this->assertType($type, $result, "returned result should have been of type $type but was ");
979 * This function exists to wrap api getsingle function & check the result
980 * so we can ensure they succeed & throw exceptions without litterering the test with checks
982 * @param string $entity
983 * @param array $params
984 * @param array $checkAgainst
985 * Array to compare result against.
996 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
998 'version' => $this->_apiversion
,
1001 $result = $this->civicrm_api($entity, 'getsingle', $params);
1002 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1003 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1005 if ($checkAgainst) {
1006 // @todo - have gone with the fn that unsets id? should we check id?
1007 $this->checkArrayEquals($result, $checkAgainst);
1013 * This function exists to wrap api getValue function & check the result
1014 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1015 * There is a type check in this
1016 * @param string $entity
1017 * @param array $params
1018 * @param null $count
1022 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1024 'version' => $this->_apiversion
,
1027 $result = $this->civicrm_api($entity, 'getcount', $params);
1028 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1029 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1031 if (is_int($count)) {
1032 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1038 * This function exists to wrap api functions
1039 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1041 * @param string $entity
1042 * @param string $action
1043 * @param array $params
1044 * @param string $function
1045 * Pass this in to create a generated example.
1046 * @param string $file
1047 * Pass this in to create a generated example.
1048 * @param string $description
1049 * @param string|null $subfile
1050 * @param string|null $actionName
1053 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL) {
1054 $params['version'] = $this->_apiversion
;
1055 $result = $this->callAPISuccess($entity, $action, $params);
1056 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
1061 * This function exists to wrap api functions
1062 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1063 * @param string $entity
1064 * @param string $action
1065 * @param array $params
1066 * @param string $expectedErrorMessage
1068 * @param null $extraOutput
1071 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1072 if (is_array($params)) {
1074 'version' => $this->_apiversion
,
1077 $result = $this->civicrm_api($entity, $action, $params);
1078 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1083 * Create required data based on $this->entity & $this->params
1084 * This is just a way to set up the test data for delete & get functions
1085 * so the distinction between set
1086 * up & tested functions is clearer
1091 public function createTestEntity() {
1092 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1096 * Generic function to create Organisation, to be used in test cases
1098 * @param array $params
1099 * parameters for civicrm_contact_add api function call
1101 * sequence number if creating multiple organizations
1104 * id of Organisation created
1106 public function organizationCreate($params = array(), $seq = 0) {
1110 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1111 return $this->_contactCreate($params);
1115 * Generic function to create Individual, to be used in test cases
1117 * @param array $params
1118 * parameters for civicrm_contact_add api function call
1120 * sequence number if creating multiple individuals
1123 * id of Individual created
1125 public function individualCreate($params = array(), $seq = 0) {
1126 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1127 return $this->_contactCreate($params);
1131 * Generic function to create Household, to be used in test cases
1133 * @param array $params
1134 * parameters for civicrm_contact_add api function call
1136 * sequence number if creating multiple households
1139 * id of Household created
1141 public function householdCreate($params = array(), $seq = 0) {
1142 $params = array_merge($this->sampleContact('Household', $seq), $params);
1143 return $this->_contactCreate($params);
1147 * Helper function for getting sample contact properties
1149 * @param string $contact_type
1150 * enum contact type: Individual, Organization
1152 * sequence number for the values of this type
1155 * properties of sample contact (ie. $params for API call)
1157 public function sampleContact($contact_type, $seq = 0) {
1159 'Individual' => array(
1160 // The number of values in each list need to be coprime numbers to not have duplicates
1161 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1162 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1163 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1165 'Organization' => array(
1166 'organization_name' => array(
1167 'Unit Test Organization',
1174 'Household' => array(
1175 'household_name' => array('Unit Test household'),
1178 $params = array('contact_type' => $contact_type);
1179 foreach ($samples[$contact_type] as $key => $values) {
1180 $params[$key] = $values[$seq %
count($values)];
1182 if ($contact_type == 'Individual') {
1183 $params['email'] = strtolower(
1184 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1186 $params['prefix_id'] = 3;
1187 $params['suffix_id'] = 3;
1193 * Private helper function for calling civicrm_contact_add
1195 * @param array $params
1196 * For civicrm_contact_add api function call.
1201 * id of Household created
1203 private function _contactCreate($params) {
1204 $result = $this->callAPISuccess('contact', 'create', $params);
1205 if (!empty($result['is_error']) ||
empty($result['id'])) {
1206 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1208 return $result['id'];
1212 * Delete contact, ensuring it is not the domain contact
1214 * @param int $contactID
1215 * Contact ID to delete
1217 public function contactDelete($contactID) {
1218 $domain = new CRM_Core_BAO_Domain();
1219 $domain->contact_id
= $contactID;
1220 if (!$domain->find(TRUE)) {
1221 $this->callAPISuccess('contact', 'delete', array(
1223 'skip_undelete' => 1,
1229 * @param int $contactTypeId
1233 public function contactTypeDelete($contactTypeId) {
1234 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1236 throw new Exception('Could not delete contact type');
1241 * @param array $params
1245 public function membershipTypeCreate($params = array()) {
1246 CRM_Member_PseudoConstant
::flush('membershipType');
1247 CRM_Core_Config
::clearDBCache();
1248 $memberOfOrganization = $this->organizationCreate();
1249 $params = array_merge(array(
1250 'name' => 'General',
1251 'duration_unit' => 'year',
1252 'duration_interval' => 1,
1253 'period_type' => 'rolling',
1254 'member_of_contact_id' => $memberOfOrganization,
1256 'financial_type_id' => 1,
1259 'visibility' => 'Public',
1262 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1264 CRM_Member_PseudoConstant
::flush('membershipType');
1265 CRM_Utils_Cache
::singleton()->flush();
1267 return $result['id'];
1271 * @param array $params
1275 public function contactMembershipCreate($params) {
1277 'join_date' => '2007-01-21',
1278 'start_date' => '2007-01-21',
1279 'end_date' => '2007-12-21',
1280 'source' => 'Payment',
1283 foreach ($pre as $key => $val) {
1284 if (!isset($params[$key])) {
1285 $params[$key] = $val;
1289 $result = $this->callAPISuccess('Membership', 'create', $params);
1290 return $result['id'];
1294 * Delete Membership Type
1296 * @param array $params
1298 public function membershipTypeDelete($params) {
1299 $this->callAPISuccess('MembershipType', 'Delete', $params);
1303 * @param int $membershipID
1305 public function membershipDelete($membershipID) {
1306 $deleteParams = array('id' => $membershipID);
1307 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1311 * @param string $name
1315 public function membershipStatusCreate($name = 'test member status') {
1316 $params['name'] = $name;
1317 $params['start_event'] = 'start_date';
1318 $params['end_event'] = 'end_date';
1319 $params['is_current_member'] = 1;
1320 $params['is_active'] = 1;
1322 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1323 CRM_Member_PseudoConstant
::flush('membershipStatus');
1324 return $result['id'];
1328 * @param int $membershipStatusID
1330 public function membershipStatusDelete($membershipStatusID) {
1331 if (!$membershipStatusID) {
1334 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1338 * @param array $params
1342 public function relationshipTypeCreate($params = array()) {
1343 $params = array_merge(array(
1344 'name_a_b' => 'Relation 1 for relationship type create',
1345 'name_b_a' => 'Relation 2 for relationship type create',
1346 'contact_type_a' => 'Individual',
1347 'contact_type_b' => 'Organization',
1354 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1355 CRM_Core_PseudoConstant
::flush('relationshipType');
1357 return $result['id'];
1361 * Delete Relatinship Type
1363 * @param int $relationshipTypeID
1365 public function relationshipTypeDelete($relationshipTypeID) {
1366 $params['id'] = $relationshipTypeID;
1367 $this->callAPISuccess('relationship_type', 'delete', $params);
1371 * @param array $params
1375 public function paymentProcessorTypeCreate($params = NULL) {
1376 if (is_null($params)) {
1378 'name' => 'API_Test_PP',
1379 'title' => 'API Test Payment Processor',
1380 'class_name' => 'CRM_Core_Payment_APITest',
1381 'billing_mode' => 'form',
1387 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1389 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1391 return $result['id'];
1395 * Create Participant
1397 * @param array $params
1398 * Array of contact id and event id values.
1401 * $id of participant created
1403 public function participantCreate($params) {
1404 if (empty($params['contact_id'])) {
1405 $params['contact_id'] = $this->individualCreate();
1407 if (empty($params['event_id'])) {
1408 $event = $this->eventCreate();
1409 $params['event_id'] = $event['id'];
1414 'register_date' => 20070219,
1415 'source' => 'Wimbeldon',
1416 'event_level' => 'Payment',
1420 $params = array_merge($defaults, $params);
1421 $result = $this->callAPISuccess('Participant', 'create', $params);
1422 return $result['id'];
1426 * Create Payment Processor
1428 * @return CRM_Financial_DAO_PaymentProcessor
1429 * instance of Payment Processsor
1431 public function processorCreate() {
1432 $processorParams = array(
1435 'payment_processor_type_id' => 10,
1436 'financial_account_id' => 12,
1439 'url_site' => 'http://dummy.com',
1440 'url_recur' => 'http://dummy.com',
1441 'billing_mode' => 1,
1443 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1444 return $paymentProcessor;
1448 * Create contribution page
1450 * @param array $params
1452 * Array of contribution page
1454 public function contributionPageCreate($params) {
1455 $this->_pageParams
= array(
1456 'title' => 'Test Contribution Page',
1457 'financial_type_id' => 1,
1458 'currency' => 'USD',
1459 'financial_account_id' => 1,
1460 'payment_processor' => $params['processor_id'],
1462 'is_allow_other_amount' => 1,
1464 'max_amount' => 1000,
1466 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1467 return $contributionPage;
1473 * @param array $params
1475 * result of created tag
1477 public function tagCreate($params = array()) {
1479 'name' => 'New Tag3',
1480 'description' => 'This is description for Our New Tag ',
1483 $params = array_merge($defaults, $params);
1484 $result = $this->callAPISuccess('Tag', 'create', $params);
1485 return $result['values'][$result['id']];
1492 * Id of the tag to be deleted.
1496 public function tagDelete($tagId) {
1497 require_once 'api/api.php';
1501 $result = $this->callAPISuccess('Tag', 'delete', $params);
1502 return $result['id'];
1506 * Add entity(s) to the tag
1508 * @param array $params
1512 public function entityTagAdd($params) {
1513 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1518 * Create contribution
1524 * id of created contribution
1526 public function pledgeCreate($cID) {
1528 'contact_id' => $cID,
1529 'pledge_create_date' => date('Ymd'),
1530 'start_date' => date('Ymd'),
1531 'scheduled_date' => date('Ymd'),
1533 'pledge_status_id' => '2',
1534 'financial_type_id' => '1',
1535 'pledge_original_installment_amount' => 20,
1536 'frequency_interval' => 5,
1537 'frequency_unit' => 'year',
1538 'frequency_day' => 15,
1539 'installments' => 5,
1542 $result = $this->callAPISuccess('Pledge', 'create', $params);
1543 return $result['id'];
1547 * Delete contribution
1549 * @param int $pledgeId
1551 public function pledgeDelete($pledgeId) {
1553 'pledge_id' => $pledgeId,
1555 $this->callAPISuccess('Pledge', 'delete', $params);
1559 * Create contribution
1563 * @param int $cTypeID
1564 * Id of financial type.
1565 * @param int $invoiceID
1566 * @param int $trxnID
1567 * @param int $paymentInstrumentID
1568 * @param bool $isFee
1571 * id of created contribution
1573 public function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1576 'contact_id' => $cID,
1577 'receive_date' => date('Ymd'),
1578 'total_amount' => 100.00,
1579 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1580 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1581 'non_deductible_amount' => 10.00,
1582 'trxn_id' => $trxnID,
1583 'invoice_id' => $invoiceID,
1585 'contribution_status_id' => 1,
1586 // 'note' => 'Donating for Nobel Cause', *Fixme
1590 $params['fee_amount'] = 5.00;
1591 $params['net_amount'] = 95.00;
1594 $result = $this->callAPISuccess('contribution', 'create', $params);
1595 return $result['id'];
1599 * Create online contribution
1601 * @param array $params
1602 * @param int $financialType
1603 * Id of financial type.
1604 * @param int $invoiceID
1605 * @param int $trxnID
1608 * id of created contribution
1610 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1611 $contribParams = array(
1612 'contact_id' => $params['contact_id'],
1613 'receive_date' => date('Ymd'),
1614 'total_amount' => 100.00,
1615 'financial_type_id' => $financialType,
1616 'contribution_page_id' => $params['contribution_page_id'],
1618 'invoice_id' => 67890,
1621 $contribParams = array_merge($contribParams, $params);
1622 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1624 return $result['id'];
1628 * Delete contribution
1630 * @param int $contributionId
1634 public function contributionDelete($contributionId) {
1636 'contribution_id' => $contributionId,
1638 $result = $this->callAPISuccess('contribution', 'delete', $params);
1645 * @param array $params
1646 * Name-value pair for an event.
1650 public function eventCreate($params = array()) {
1651 // if no contact was passed, make up a dummy event creator
1652 if (!isset($params['contact_id'])) {
1653 $params['contact_id'] = $this->_contactCreate(array(
1654 'contact_type' => 'Individual',
1655 'first_name' => 'Event',
1656 'last_name' => 'Creator',
1660 // set defaults for missing params
1661 $params = array_merge(array(
1662 'title' => 'Annual CiviCRM meet',
1663 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1664 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1665 'event_type_id' => 1,
1667 'start_date' => 20081021,
1668 'end_date' => 20081023,
1669 'is_online_registration' => 1,
1670 'registration_start_date' => 20080601,
1671 'registration_end_date' => 20081015,
1672 'max_participants' => 100,
1673 'event_full_text' => 'Sorry! We are already full',
1676 'is_show_location' => 0,
1679 return $this->callAPISuccess('Event', 'create', $params);
1690 public function eventDelete($id) {
1694 return $this->callAPISuccess('event', 'delete', $params);
1698 * Delete participant
1700 * @param int $participantID
1704 public function participantDelete($participantID) {
1706 'id' => $participantID,
1708 return $this->callAPISuccess('Participant', 'delete', $params);
1712 * Create participant payment
1714 * @param int $participantID
1715 * @param int $contributionID
1717 * $id of created payment
1719 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1720 //Create Participant Payment record With Values
1722 'participant_id' => $participantID,
1723 'contribution_id' => $contributionID,
1726 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1727 return $result['id'];
1731 * Delete participant payment
1733 * @param int $paymentID
1735 public function participantPaymentDelete($paymentID) {
1739 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1745 * @param int $contactID
1747 * location id of created location
1749 public function locationAdd($contactID) {
1752 'location_type' => 'New Location Type',
1754 'name' => 'Saint Helier St',
1755 'county' => 'Marin',
1756 'country' => 'United States',
1757 'state_province' => 'Michigan',
1758 'supplemental_address_1' => 'Hallmark Ct',
1759 'supplemental_address_2' => 'Jersey Village',
1764 'contact_id' => $contactID,
1765 'address' => $address,
1766 'location_format' => '2.0',
1767 'location_type' => 'New Location Type',
1770 $result = $this->callAPISuccess('Location', 'create', $params);
1775 * Delete Locations of contact
1777 * @param array $params
1780 public function locationDelete($params) {
1781 $this->callAPISuccess('Location', 'delete', $params);
1785 * Add a Location Type
1787 * @param array $params
1788 * @return CRM_Core_DAO_LocationType
1789 * location id of created location
1791 public function locationTypeCreate($params = NULL) {
1792 if ($params === NULL) {
1794 'name' => 'New Location Type',
1795 'vcard_name' => 'New Location Type',
1796 'description' => 'Location Type for Delete',
1801 $locationType = new CRM_Core_DAO_LocationType();
1802 $locationType->copyValues($params);
1803 $locationType->save();
1804 // clear getfields cache
1805 CRM_Core_PseudoConstant
::flush();
1806 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1807 return $locationType;
1811 * Delete a Location Type
1813 * @param int $locationTypeId
1815 public function locationTypeDelete($locationTypeId) {
1816 $locationType = new CRM_Core_DAO_LocationType();
1817 $locationType->id
= $locationTypeId;
1818 $locationType->delete();
1824 * @param array $params
1826 * groupId of created group
1828 public function groupCreate($params = array()) {
1829 $params = array_merge(array(
1830 'name' => 'Test Group 1',
1832 'title' => 'New Test Group Created',
1833 'description' => 'New Test Group Created',
1835 'visibility' => 'Public Pages',
1836 'group_type' => array(
1842 $result = $this->callAPISuccess('Group', 'create', $params);
1843 return $result['id'];
1848 * Function to add a Group
1850 * @params array to add group
1852 * @param int $groupID
1853 * @param int $totalCount
1855 * groupId of created group
1857 public function groupContactCreate($groupID, $totalCount = 10) {
1858 $params = array('group_id' => $groupID);
1859 for ($i = 1; $i <= $totalCount; $i++
) {
1860 $contactID = $this->individualCreate();
1862 $params +
= array('contact_id' => $contactID);
1865 $params +
= array("contact_id.$i" => $contactID);
1868 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1878 public function groupDelete($gid) {
1884 $this->callAPISuccess('Group', 'delete', $params);
1889 * @param array $params
1891 public function uFFieldCreate($params = array()) {
1892 $params = array_merge(array(
1894 'field_name' => 'first_name',
1897 'visibility' => 'Public Pages and Listings',
1898 'is_searchable' => '1',
1899 'label' => 'first_name',
1900 'field_type' => 'Individual',
1903 $this->callAPISuccess('uf_field', 'create', $params);
1907 * Add a UF Join Entry
1909 * @param array $params
1911 * $id of created UF Join
1913 public function ufjoinCreate($params = NULL) {
1914 if ($params === NULL) {
1917 'module' => 'CiviEvent',
1918 'entity_table' => 'civicrm_event',
1924 $result = $this->callAPISuccess('uf_join', 'create', $params);
1929 * Delete a UF Join Entry
1931 * @param array $params
1932 * with missing uf_group_id
1934 public function ufjoinDelete($params = NULL) {
1935 if ($params === NULL) {
1938 'module' => 'CiviEvent',
1939 'entity_table' => 'civicrm_event',
1942 'uf_group_id' => '',
1946 crm_add_uf_join($params);
1950 * Create Group for a contact
1952 * @param int $contactId
1954 public function contactGroupCreate($contactId) {
1956 'contact_id.1' => $contactId,
1960 $this->callAPISuccess('GroupContact', 'Create', $params);
1964 * Delete Group for a contact
1966 * @param int $contactId
1968 public function contactGroupDelete($contactId) {
1970 'contact_id.1' => $contactId,
1973 $this->civicrm_api('GroupContact', 'Delete', $params);
1979 * @param array $params
1982 public function activityCreate($params = NULL) {
1984 if ($params === NULL) {
1985 $individualSourceID = $this->individualCreate();
1987 $contactParams = array(
1988 'first_name' => 'Julia',
1989 'Last_name' => 'Anderson',
1991 'email' => 'julia_anderson@civicrm.org',
1992 'contact_type' => 'Individual',
1995 $individualTargetID = $this->individualCreate($contactParams);
1998 'source_contact_id' => $individualSourceID,
1999 'target_contact_id' => array($individualTargetID),
2000 'assignee_contact_id' => array($individualTargetID),
2001 'subject' => 'Discussion on warm beer',
2002 'activity_date_time' => date('Ymd'),
2003 'duration_hours' => 30,
2004 'duration_minutes' => 20,
2005 'location' => 'Baker Street',
2006 'details' => 'Lets schedule a meeting',
2008 'activity_name' => 'Meeting',
2012 $result = $this->callAPISuccess('Activity', 'create', $params);
2014 $result['target_contact_id'] = $individualTargetID;
2015 $result['assignee_contact_id'] = $individualTargetID;
2020 * Create an activity type
2022 * @param array $params
2026 public function activityTypeCreate($params) {
2027 return $this->callAPISuccess('ActivityType', 'create', $params);
2031 * Delete activity type
2033 * @param int $activityTypeId
2034 * Id of the activity type.
2037 public function activityTypeDelete($activityTypeId) {
2038 $params['activity_type_id'] = $activityTypeId;
2039 return $this->callAPISuccess('ActivityType', 'delete', $params);
2043 * Create custom group
2045 * @param array $params
2048 public function customGroupCreate($params = array()) {
2050 'title' => 'new custom group',
2051 'extends' => 'Contact',
2053 'style' => 'Inline',
2057 $params = array_merge($defaults, $params);
2059 if (strlen($params['title']) > 13) {
2060 $params['title'] = substr($params['title'], 0, 13);
2063 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2064 $this->callAPISuccess('custom_group', 'get', array(
2065 'title' => $params['title'],
2066 array('api.custom_group.delete' => 1),
2069 return $this->callAPISuccess('custom_group', 'create', $params);
2073 * Existing function doesn't allow params to be over-ridden so need a new one
2074 * this one allows you to only pass in the params you want to change
2075 * @param array $params
2078 public function CustomGroupCreateByParams($params = array()) {
2080 'title' => "API Custom Group",
2081 'extends' => 'Contact',
2083 'style' => 'Inline',
2086 $params = array_merge($defaults, $params);
2087 return $this->callAPISuccess('custom_group', 'create', $params);
2091 * Create custom group with multi fields
2092 * @param array $params
2095 public function CustomGroupMultipleCreateByParams($params = array()) {
2100 $params = array_merge($defaults, $params);
2101 return $this->CustomGroupCreateByParams($params);
2105 * Create custom group with multi fields
2106 * @param array $params
2109 public function CustomGroupMultipleCreateWithFields($params = array()) {
2110 // also need to pass on $params['custom_field'] if not set but not in place yet
2112 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2113 $ids['custom_group_id'] = $customGroup['id'];
2115 $customField = $this->customFieldCreate(array(
2116 'custom_group_id' => $ids['custom_group_id'],
2117 'label' => 'field_1' . $ids['custom_group_id'],
2120 $ids['custom_field_id'][] = $customField['id'];
2122 $customField = $this->customFieldCreate(array(
2123 'custom_group_id' => $ids['custom_group_id'],
2124 'default_value' => '',
2125 'label' => 'field_2' . $ids['custom_group_id'],
2127 $ids['custom_field_id'][] = $customField['id'];
2129 $customField = $this->customFieldCreate(array(
2130 'custom_group_id' => $ids['custom_group_id'],
2131 'default_value' => '',
2132 'label' => 'field_3' . $ids['custom_group_id'],
2134 $ids['custom_field_id'][] = $customField['id'];
2140 * Create a custom group with a single text custom field. See
2141 * participant:testCreateWithCustom for how to use this
2143 * @param string $function
2145 * @param string $filename
2149 * ids of created objects
2151 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2152 $params = array('title' => $function);
2153 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2154 $params['extends'] = $entity ?
$entity : 'Contact';
2155 $customGroup = $this->CustomGroupCreate($params);
2156 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2157 CRM_Core_PseudoConstant
::flush();
2159 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2163 * Delete custom group
2165 * @param int $customGroupID
2169 public function customGroupDelete($customGroupID) {
2170 $params['id'] = $customGroupID;
2171 return $this->callAPISuccess('custom_group', 'delete', $params);
2175 * Create custom field
2177 * @param array $params
2178 * (custom_group_id) is required.
2181 public function customFieldCreate($params) {
2182 $params = array_merge(array(
2183 'label' => 'Custom Field',
2184 'data_type' => 'String',
2185 'html_type' => 'Text',
2186 'is_searchable' => 1,
2188 'default_value' => 'defaultValue',
2191 $result = $this->callAPISuccess('custom_field', 'create', $params);
2192 // these 2 functions are called with force to flush static caches
2193 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2194 CRM_Core_Component
::getEnabledComponents(1);
2199 * Delete custom field
2201 * @param int $customFieldID
2205 public function customFieldDelete($customFieldID) {
2207 $params['id'] = $customFieldID;
2208 return $this->callAPISuccess('custom_field', 'delete', $params);
2217 public function noteCreate($cId) {
2219 'entity_table' => 'civicrm_contact',
2220 'entity_id' => $cId,
2221 'note' => 'hello I am testing Note',
2222 'contact_id' => $cId,
2223 'modified_date' => date('Ymd'),
2224 'subject' => 'Test Note',
2227 return $this->callAPISuccess('Note', 'create', $params);
2231 * Enable CiviCampaign Component
2233 public function enableCiviCampaign() {
2234 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2235 // force reload of config object
2236 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2237 //flush cache by calling with reset
2238 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2242 * Create test generated example in api/v3/examples.
2243 * To turn this off (e.g. on the server) set
2244 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2245 * in your settings file
2246 * @param array $params
2247 * Array as passed to civicrm_api function.
2248 * @param array $result
2249 * Array as received from the civicrm_api function.
2250 * @param string $function
2251 * Calling function - generally __FUNCTION__.
2252 * @param string $filename
2253 * Called from file - generally __FILE__.
2254 * @param string $description
2255 * Descriptive text for the example file.
2256 * @param string $subfile
2257 * Name for subfile - if this is completed the example will be put in a subfolder (named by the entity).
2258 * @param string $action
2259 * Optional action - otherwise taken from function name.
2261 public function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2262 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2265 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2266 //todo - this is a bit cludgey
2267 if (empty($action)) {
2268 if (strstr($function, 'Create')) {
2269 $action = empty($action) ?
'create' : $action;
2270 $entityAction = 'Create';
2272 elseif (strstr($function, 'GetSingle')) {
2273 $action = empty($action) ?
'getsingle' : $action;
2274 $entityAction = 'GetSingle';
2276 elseif (strstr($function, 'GetValue')) {
2277 $action = empty($action) ?
'getvalue' : $action;
2278 $entityAction = 'GetValue';
2280 elseif (strstr($function, 'GetCount')) {
2281 $action = empty($action) ?
'getcount' : $action;
2282 $entityAction = 'GetCount';
2284 elseif (strstr($function, 'GetFields')) {
2285 $action = empty($action) ?
'getfields' : $action;
2286 $entityAction = 'GetFields';
2288 elseif (strstr($function, 'GetList')) {
2289 $action = empty($action) ?
'getlist' : $action;
2290 $entityAction = 'GetList';
2292 elseif (strstr($function, 'GetActions')) {
2293 $action = empty($action) ?
'getactions' : $action;
2294 $entityAction = 'GetActions';
2296 elseif (strstr($function, 'Get')) {
2297 $action = empty($action) ?
'get' : $action;
2298 $entityAction = 'Get';
2300 elseif (strstr($function, 'Delete')) {
2301 $action = empty($action) ?
'delete' : $action;
2302 $entityAction = 'Delete';
2304 elseif (strstr($function, 'Update')) {
2305 $action = empty($action) ?
'update' : $action;
2306 $entityAction = 'Update';
2308 elseif (strstr($function, 'Subscribe')) {
2309 $action = empty($action) ?
'subscribe' : $action;
2310 $entityAction = 'Subscribe';
2312 elseif (strstr($function, 'Submit')) {
2313 $action = empty($action) ?
'submit' : $action;
2314 $entityAction = 'Submit';
2316 elseif (strstr($function, 'Apply')) {
2317 $action = empty($action) ?
'apply' : $action;
2318 $entityAction = 'Apply';
2320 elseif (strstr($function, 'Replace')) {
2321 $action = empty($action) ?
'replace' : $action;
2322 $entityAction = 'Replace';
2326 $entityAction = ucwords($action);
2329 $this->tidyExampleResult($result);
2330 if (isset($params['version'])) {
2331 unset($params['version']);
2333 // a cleverer person than me would do it in a single regex
2334 if (strstr($entity, 'UF')) {
2335 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2338 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2340 $smarty = CRM_Core_Smarty
::singleton();
2341 $smarty->assign('testfunction', $function);
2342 $function = $fnPrefix . "_" . strtolower($action);
2343 $smarty->assign('function', $function);
2344 $smarty->assign('fnPrefix', $fnPrefix);
2345 $smarty->assign('params', $params);
2346 $smarty->assign('entity', $entity);
2347 $smarty->assign('filename', basename($filename));
2348 $smarty->assign('description', $description);
2349 $smarty->assign('result', $result);
2351 $smarty->assign('action', $action);
2352 if (empty($subfile)) {
2353 $subfile = $entityAction;
2355 if (file_exists('../tests/templates/documentFunction.tpl')) {
2356 if (!is_dir("../api/v3/examples/$entity")) {
2357 mkdir("../api/v3/examples/$entity");
2359 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2360 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2366 * Tidy up examples array so that fields that change often ..don't
2367 * and debug related fields are unset
2369 * @param array $result
2371 public function tidyExampleResult(&$result) {
2372 if (!is_array($result)) {
2375 $fieldsToChange = array(
2376 'hash' => '67eac7789eaee00',
2377 'modified_date' => '2012-11-14 16:02:35',
2378 'created_date' => '2013-07-28 08:49:19',
2379 'create_date' => '20120130621222105',
2380 'application_received_date' => '20130728084957',
2381 'in_date' => '2013-07-28 08:50:19',
2382 'scheduled_date' => '20130728085413',
2383 'approval_date' => '20130728085413',
2384 'pledge_start_date_high' => '20130726090416',
2385 'start_date' => '2013-07-29 00:00:00',
2386 'event_start_date' => '2013-07-29 00:00:00',
2387 'end_date' => '2013-08-04 00:00:00',
2388 'event_end_date' => '2013-08-04 00:00:00',
2389 'decision_date' => '20130805000000',
2392 $keysToUnset = array('xdebug', 'undefined_fields');
2393 foreach ($keysToUnset as $unwantedKey) {
2394 if (isset($result[$unwantedKey])) {
2395 unset($result[$unwantedKey]);
2398 if (isset($result['values'])) {
2399 if (!is_array($result['values'])) {
2402 $resultArray = &$result['values'];
2404 elseif (is_array($result)) {
2405 $resultArray = &$result;
2411 foreach ($resultArray as $index => &$values) {
2412 if (!is_array($values)) {
2415 foreach ($values as $key => &$value) {
2416 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2417 if (isset($value['is_error'])) {
2418 // we have a std nested result format
2419 $this->tidyExampleResult($value);
2422 foreach ($value as &$nestedResult) {
2423 // this is an alternative syntax for nested results a keyed array of results
2424 $this->tidyExampleResult($nestedResult);
2428 if (in_array($key, $keysToUnset)) {
2429 unset($values[$key]);
2432 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2433 $value = $fieldsToChange[$key];
2435 if (is_string($value)) {
2436 $value = addslashes($value);
2445 * @param array $params
2449 public function noteDelete($params) {
2450 return $this->callAPISuccess('Note', 'delete', $params);
2454 * Create custom field with Option Values
2456 * @param array $customGroup
2457 * @param string $name
2458 * Name of custom field.
2462 public function customFieldOptionValueCreate($customGroup, $name) {
2463 $fieldParams = array(
2464 'custom_group_id' => $customGroup['id'],
2465 'name' => 'test_custom_group',
2466 'label' => 'Country',
2467 'html_type' => 'Select',
2468 'data_type' => 'String',
2471 'is_searchable' => 0,
2475 $optionGroup = array(
2477 'name' => 'option_group1',
2478 'label' => 'option_group_label1',
2481 $optionValue = array(
2482 'option_label' => array('Label1', 'Label2'),
2483 'option_value' => array('value1', 'value2'),
2484 'option_name' => array($name . '_1', $name . '_2'),
2485 'option_weight' => array(1, 2),
2486 'option_status' => 1,
2489 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2491 return $this->callAPISuccess('custom_field', 'create', $params);
2499 public function confirmEntitiesDeleted($entities) {
2500 foreach ($entities as $entity) {
2502 $result = $this->callAPISuccess($entity, 'Get', array());
2503 if ($result['error'] == 1 ||
$result['count'] > 0) {
2504 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2512 * @param $tablesToTruncate
2513 * @param bool $dropCustomValueTables
2514 * @throws \Exception
2516 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2518 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2520 if ($dropCustomValueTables) {
2521 $tablesToTruncate[] = 'civicrm_custom_group';
2522 $tablesToTruncate[] = 'civicrm_custom_field';
2525 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2527 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2528 foreach ($tablesToTruncate as $table) {
2529 $sql = "TRUNCATE TABLE $table";
2530 CRM_Core_DAO
::executeQuery($sql);
2532 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2534 if ($dropCustomValueTables) {
2535 $dbName = self
::getDBName();
2537 SELECT TABLE_NAME as tableName
2538 FROM INFORMATION_SCHEMA.TABLES
2539 WHERE TABLE_SCHEMA = '{$dbName}'
2540 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2543 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2544 while ($tableDAO->fetch()) {
2545 $sql = "DROP TABLE {$tableDAO->tableName}";
2546 CRM_Core_DAO
::executeQuery($sql);
2552 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2554 public function quickCleanUpFinancialEntities() {
2555 $tablesToTruncate = array(
2556 'civicrm_contribution',
2557 'civicrm_contribution_soft',
2558 'civicrm_financial_trxn',
2559 'civicrm_financial_item',
2560 'civicrm_contribution_recur',
2561 'civicrm_line_item',
2562 'civicrm_contribution_page',
2563 'civicrm_payment_processor',
2564 'civicrm_entity_financial_trxn',
2565 'civicrm_membership',
2566 'civicrm_membership_type',
2567 'civicrm_membership_payment',
2568 'civicrm_membership_log',
2569 'civicrm_membership_block',
2571 'civicrm_participant',
2572 'civicrm_participant_payment',
2574 'civicrm_price_set_entity',
2575 'civicrm_price_field_value',
2576 'civicrm_price_field',
2578 $this->quickCleanup($tablesToTruncate);
2579 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2580 $this->restoreDefaultPriceSetConfig();
2582 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2585 public function restoreDefaultPriceSetConfig() {
2586 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)");
2587 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)");
2590 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2591 * Default behaviour is to also delete the entity
2592 * @param array $params
2593 * Params array to check agains.
2595 * Id of the entity concerned.
2596 * @param string $entity
2597 * Name of entity concerned (e.g. membership).
2598 * @param bool $delete
2599 * Should the entity be deleted as part of this check.
2600 * @param string $errorText
2601 * Text to print on error.
2604 * @param array $params
2607 * @param int $delete
2608 * @param string $errorText
2612 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2614 $result = $this->callAPISuccessGetSingle($entity, array(
2619 $this->callAPISuccess($entity, 'Delete', array(
2623 $dateFields = $keys = $dateTimeFields = array();
2624 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2625 foreach ($fields['values'] as $field => $settings) {
2626 if (array_key_exists($field, $result)) {
2627 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2630 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2632 $type = CRM_Utils_Array
::value('type', $settings);
2633 if ($type == CRM_Utils_Type
::T_DATE
) {
2634 $dateFields[] = $settings['name'];
2635 // we should identify both real names & unique names as dates
2636 if ($field != $settings['name']) {
2637 $dateFields[] = $field;
2640 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2641 $dateTimeFields[] = $settings['name'];
2642 // we should identify both real names & unique names as dates
2643 if ($field != $settings['name']) {
2644 $dateTimeFields[] = $field;
2649 if (strtolower($entity) == 'contribution') {
2650 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2651 // this is not returned in id format
2652 unset($params['payment_instrument_id']);
2653 $params['contribution_source'] = $params['source'];
2654 unset($params['source']);
2657 foreach ($params as $key => $value) {
2658 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2661 if (in_array($key, $dateFields)) {
2662 $value = date('Y-m-d', strtotime($value));
2663 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2665 if (in_array($key, $dateTimeFields)) {
2666 $value = date('Y-m-d H:i:s', strtotime($value));
2667 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2669 $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);
2674 * Get formatted values in the actual and expected result
2675 * @param array $actual
2676 * Actual calculated values.
2677 * @param array $expected
2680 public function checkArrayEquals(&$actual, &$expected) {
2681 self
::unsetId($actual);
2682 self
::unsetId($expected);
2683 $this->assertEquals($actual, $expected);
2687 * Unset the key 'id' from the array
2688 * @param array $unformattedArray
2689 * The array from which the 'id' has to be unset.
2691 public static function unsetId(&$unformattedArray) {
2692 $formattedArray = array();
2693 if (array_key_exists('id', $unformattedArray)) {
2694 unset($unformattedArray['id']);
2696 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2697 foreach ($unformattedArray['values'] as $key => $value) {
2698 if (is_array($value)) {
2699 foreach ($value as $k => $v) {
2705 elseif ($key == 'id') {
2706 $unformattedArray[$key];
2708 $formattedArray = array($value);
2710 $unformattedArray['values'] = $formattedArray;
2715 * Helper to enable/disable custom directory support
2717 * @param array $customDirs
2719 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2720 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2722 public function customDirectories($customDirs) {
2723 require_once 'CRM/Core/Config.php';
2724 $config = CRM_Core_Config
::singleton();
2726 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2727 unset($config->customPHPPathDir
);
2729 elseif ($customDirs['php_path'] === TRUE) {
2730 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2733 $config->customPHPPathDir
= $php_path;
2736 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2737 unset($config->customTemplateDir
);
2739 elseif ($customDirs['template_path'] === TRUE) {
2740 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2743 $config->customTemplateDir
= $template_path;
2748 * Generate a temporary folder
2750 * @param string $prefix
2753 public function createTempDir($prefix = 'test-') {
2754 $tempDir = CRM_Utils_File
::tempdir($prefix);
2755 $this->tempDirs
[] = $tempDir;
2759 public function cleanTempDirs() {
2760 if (!is_array($this->tempDirs
)) {
2761 // fix test errors where this is not set
2764 foreach ($this->tempDirs
as $tempDir) {
2765 if (is_dir($tempDir)) {
2766 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2772 * Temporarily replace the singleton extension with a different one
2773 * @param \CRM_Extension_System $system
2775 public function setExtensionSystem(CRM_Extension_System
$system) {
2776 if ($this->origExtensionSystem
== NULL) {
2777 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2779 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2782 public function unsetExtensionSystem() {
2783 if ($this->origExtensionSystem
!== NULL) {
2784 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2785 $this->origExtensionSystem
= NULL;
2790 * Temporarily alter the settings-metadata to add a mock setting.
2792 * WARNING: The setting metadata will disappear on the next cache-clear.
2797 public function setMockSettingsMetaData($extras) {
2798 CRM_Core_BAO_Setting
::$_cache = array();
2799 $this->callAPISuccess('system', 'flush', array());
2800 CRM_Core_BAO_Setting
::$_cache = array();
2802 CRM_Utils_Hook
::singleton()
2803 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2804 $metadata = array_merge($metadata, $extras);
2807 $fields = $this->callAPISuccess('setting', 'getfields', array());
2808 foreach ($extras as $key => $spec) {
2809 $this->assertNotEmpty($spec['title']);
2810 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2815 * @param string $name
2817 public function financialAccountDelete($name) {
2818 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2819 $financialAccount->name
= $name;
2820 if ($financialAccount->find(TRUE)) {
2821 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2822 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2823 $entityFinancialType->delete();
2824 $financialAccount->delete();
2829 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2830 * (NB unclear if this is still required)
2832 public function _sethtmlGlobals() {
2833 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2834 'required' => array(
2835 'html_quickform_rule_required',
2836 'HTML/QuickForm/Rule/Required.php',
2838 'maxlength' => array(
2839 'html_quickform_rule_range',
2840 'HTML/QuickForm/Rule/Range.php',
2842 'minlength' => array(
2843 'html_quickform_rule_range',
2844 'HTML/QuickForm/Rule/Range.php',
2846 'rangelength' => array(
2847 'html_quickform_rule_range',
2848 'HTML/QuickForm/Rule/Range.php',
2851 'html_quickform_rule_email',
2852 'HTML/QuickForm/Rule/Email.php',
2855 'html_quickform_rule_regex',
2856 'HTML/QuickForm/Rule/Regex.php',
2858 'lettersonly' => array(
2859 'html_quickform_rule_regex',
2860 'HTML/QuickForm/Rule/Regex.php',
2862 'alphanumeric' => array(
2863 'html_quickform_rule_regex',
2864 'HTML/QuickForm/Rule/Regex.php',
2867 'html_quickform_rule_regex',
2868 'HTML/QuickForm/Rule/Regex.php',
2870 'nopunctuation' => array(
2871 'html_quickform_rule_regex',
2872 'HTML/QuickForm/Rule/Regex.php',
2875 'html_quickform_rule_regex',
2876 'HTML/QuickForm/Rule/Regex.php',
2878 'callback' => array(
2879 'html_quickform_rule_callback',
2880 'HTML/QuickForm/Rule/Callback.php',
2883 'html_quickform_rule_compare',
2884 'HTML/QuickForm/Rule/Compare.php',
2887 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2888 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2890 'HTML/QuickForm/group.php',
2891 'HTML_QuickForm_group',
2894 'HTML/QuickForm/hidden.php',
2895 'HTML_QuickForm_hidden',
2898 'HTML/QuickForm/reset.php',
2899 'HTML_QuickForm_reset',
2901 'checkbox' => array(
2902 'HTML/QuickForm/checkbox.php',
2903 'HTML_QuickForm_checkbox',
2906 'HTML/QuickForm/file.php',
2907 'HTML_QuickForm_file',
2910 'HTML/QuickForm/image.php',
2911 'HTML_QuickForm_image',
2913 'password' => array(
2914 'HTML/QuickForm/password.php',
2915 'HTML_QuickForm_password',
2918 'HTML/QuickForm/radio.php',
2919 'HTML_QuickForm_radio',
2922 'HTML/QuickForm/button.php',
2923 'HTML_QuickForm_button',
2926 'HTML/QuickForm/submit.php',
2927 'HTML_QuickForm_submit',
2930 'HTML/QuickForm/select.php',
2931 'HTML_QuickForm_select',
2933 'hiddenselect' => array(
2934 'HTML/QuickForm/hiddenselect.php',
2935 'HTML_QuickForm_hiddenselect',
2938 'HTML/QuickForm/text.php',
2939 'HTML_QuickForm_text',
2941 'textarea' => array(
2942 'HTML/QuickForm/textarea.php',
2943 'HTML_QuickForm_textarea',
2945 'fckeditor' => array(
2946 'HTML/QuickForm/fckeditor.php',
2947 'HTML_QuickForm_FCKEditor',
2950 'HTML/QuickForm/tinymce.php',
2951 'HTML_QuickForm_TinyMCE',
2953 'dojoeditor' => array(
2954 'HTML/QuickForm/dojoeditor.php',
2955 'HTML_QuickForm_dojoeditor',
2958 'HTML/QuickForm/link.php',
2959 'HTML_QuickForm_link',
2961 'advcheckbox' => array(
2962 'HTML/QuickForm/advcheckbox.php',
2963 'HTML_QuickForm_advcheckbox',
2966 'HTML/QuickForm/date.php',
2967 'HTML_QuickForm_date',
2970 'HTML/QuickForm/static.php',
2971 'HTML_QuickForm_static',
2974 'HTML/QuickForm/header.php',
2975 'HTML_QuickForm_header',
2978 'HTML/QuickForm/html.php',
2979 'HTML_QuickForm_html',
2981 'hierselect' => array(
2982 'HTML/QuickForm/hierselect.php',
2983 'HTML_QuickForm_hierselect',
2985 'autocomplete' => array(
2986 'HTML/QuickForm/autocomplete.php',
2987 'HTML_QuickForm_autocomplete',
2990 'HTML/QuickForm/xbutton.php',
2991 'HTML_QuickForm_xbutton',
2993 'advmultiselect' => array(
2994 'HTML/QuickForm/advmultiselect.php',
2995 'HTML_QuickForm_advmultiselect',
3001 * Set up an acl allowing contact to see 2 specified groups
3002 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3004 * You need to have pre-created these groups & created the user e.g
3005 * $this->createLoggedInUser();
3006 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3007 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3009 public function setupACL() {
3011 $_REQUEST = $this->_params
;
3013 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3014 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3015 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3016 'option_group_id' => $optionGroupID,
3017 'label' => 'pick me',
3021 CRM_Core_DAO
::executeQuery("
3022 TRUNCATE civicrm_acl_cache
3025 CRM_Core_DAO
::executeQuery("
3026 TRUNCATE civicrm_acl_contact_cache
3029 CRM_Core_DAO
::executeQuery("
3030 INSERT INTO civicrm_acl_entity_role (
3031 `acl_role_id`, `entity_table`, `entity_id`
3032 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
3035 CRM_Core_DAO
::executeQuery("
3036 INSERT INTO civicrm_acl (
3037 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3040 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3044 CRM_Core_DAO
::executeQuery("
3045 INSERT INTO civicrm_acl (
3046 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3049 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3052 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3053 $this->callAPISuccess('group_contact', 'create', array(
3054 'group_id' => $this->_permissionedGroup
,
3055 'contact_id' => $this->_loggedInUser
,
3058 CRM_ACL_BAO_Cache
::resetCache();
3059 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3060 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3064 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3066 public function offsetDefaultPriceSet() {
3067 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3068 $firstID = $contributionPriceSet['id'];
3069 $this->callAPISuccess('price_set', 'create', array(
3070 'id' => $contributionPriceSet['id'],
3074 unset($contributionPriceSet['id']);
3075 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3076 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3077 'price_set_id' => $firstID,
3078 'options' => array('limit' => 1),
3080 unset($priceField['id']);
3081 $priceField['price_set_id'] = $newPriceSet['id'];
3082 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3083 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3084 'price_set_id' => $firstID,
3086 'options' => array('limit' => 1),
3089 unset($priceFieldValue['id']);
3090 //create some padding to use up ids
3091 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3092 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3093 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3097 * Create an instance of the paypal processor
3098 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3099 * this parent class & we don't have a structure for that yet
3100 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3101 * & the best protection agains that is the functions this class affords
3102 * @param array $params
3103 * @return int $result['id'] payment processor id
3105 public function paymentProcessorCreate($params = array()) {
3106 $params = array_merge(array(
3108 'domain_id' => CRM_Core_Config
::domainID(),
3109 'payment_processor_type_id' => 'PayPal',
3113 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3114 'password' => '1183377788',
3115 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3116 'url_site' => 'https://www.sandbox.paypal.com/',
3117 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3118 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3119 'class_name' => 'Payment_PayPalImpl',
3120 'billing_mode' => 3,
3121 'financial_type_id' => 1,
3124 if (!is_numeric($params['payment_processor_type_id'])) {
3125 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3127 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3128 'name' => $params['payment_processor_type_id'],
3132 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3133 return $result['id'];
3137 * Set up initial recurring payment allowing subsequent IPN payments
3139 public function setupRecurringPaymentProcessorTransaction() {
3140 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3141 'contact_id' => $this->_contactID
,
3144 'installments' => 5,
3145 'frequency_unit' => 'Month',
3146 'frequency_interval' => 1,
3147 'invoice_id' => $this->_invoiceID
,
3148 'contribution_status_id' => 2,
3149 'processor_id' => $this->_paymentProcessorID
,
3150 'api.contribution.create' => array(
3151 'total_amount' => '200',
3152 'invoice_id' => $this->_invoiceID
,
3153 'financial_type_id' => 1,
3154 'contribution_status_id' => 'Pending',
3155 'contact_id' => $this->_contactID
,
3156 'contribution_page_id' => $this->_contributionPageID
,
3157 'payment_processor_id' => $this->_paymentProcessorID
,
3160 $this->_contributionRecurID
= $contributionRecur['id'];
3161 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3165 * 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
3167 public function setupMembershipRecurringPaymentProcessorTransaction() {
3168 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3169 //create a contribution so our membership & contribution don't both have id = 1
3170 $this->contributionCreate($this->_contactID
, 1, 'abcd', '345j');
3171 $this->setupRecurringPaymentProcessorTransaction();
3173 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3174 'contact_id' => $this->_contactID
,
3175 'membership_type_id' => $this->ids
['membership_type'],
3176 'contribution_recur_id' => $this->_contributionRecurID
,
3177 'format.only_id' => TRUE,
3179 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3180 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3182 $this->callAPISuccess('line_item', 'create', array(
3183 'entity_table' => 'civicrm_membership',
3184 'entity_id' => $this->ids
['membership'],
3185 'contribution_id' => $this->_contributionID
,
3186 'label' => 'General',
3188 'unit_price' => 200,
3189 'line_total' => 200,
3190 'financial_type_id' => 1,
3191 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3193 'label' => 'Membership Amount',
3195 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3197 'label' => 'General',
3200 $this->callAPISuccess('membership_payment', 'create', array(
3201 'contribution_id' => $this->_contributionID
,
3202 'membership_id' => $this->ids
['membership'],
3211 public function CiviUnitTestCase_fatalErrorHandler($message) {
3212 throw new Exception("{$message['message']}: {$message['code']}");
3216 * Helper function to create new mailing
3219 public function createMailing() {
3221 'subject' => 'maild' . rand(),
3222 'body_text' => 'bdkfhdskfhduew',
3223 'name' => 'mailing name' . rand(),
3225 'api.mailing_job.create' => 0,
3228 $result = $this->callAPISuccess('Mailing', 'create', $params);
3229 return $result['id'];
3233 * Helper function to delete mailing
3236 public function deleteMailing($id) {
3241 $this->callAPISuccess('Mailing', 'delete', $params);
3245 * Wrap the entire test case in a transaction
3247 * Only subsequent DB statements will be wrapped in TX -- this cannot
3248 * retroactively wrap old DB statements. Therefore, it makes sense to
3249 * call this at the beginning of setUp().
3251 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3252 * this option does not work with, e.g., custom-data.
3254 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3255 * if TRUNCATE or ALTER is called while using a transaction.
3258 * Whether to use nesting or reference-counting.
3260 public function useTransaction($nest = TRUE) {
3262 $this->tx
= new CRM_Core_Transaction($nest);
3263 $this->tx
->rollback();
3267 public function clearOutputBuffer() {
3268 while (ob_get_level() > 0) {