3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
32 * Include configuration
34 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
35 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
37 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
38 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
40 require_once CIVICRM_SETTINGS_PATH
;
42 * Include class definitions
44 require_once 'tests/phpunit/Utils.php';
45 require_once 'api/api.php';
46 require_once 'CRM/Financial/BAO/FinancialType.php';
47 define('API_LATEST_VERSION', 3);
50 * Base class for CiviCRM unit tests
52 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
53 * may opt for one or neither:
55 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
56 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
57 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
58 * 2. useTransaction() executes the test inside a transaction. It's easier to use
59 * (because you don't need to identify specific tables), but it doesn't work for tests
60 * which manipulate schema or truncate data -- and could behave inconsistently
61 * for tests which specifically examine DB transactions.
63 * Common functions for unit tests
66 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
69 * Api version - easier to override than just a define
71 protected $_apiversion = API_LATEST_VERSION
;
73 * Database has been initialized.
77 private static $dbInit = FALSE;
80 * Database connection.
82 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
91 static protected $_dbName;
94 * Track tables we have modified during a test.
96 protected $_tablesToTruncate = array();
99 * @var array of temporary directory names
104 * @var Utils instance
106 public static $utils;
109 * @var boolean populateOnce allows to skip db resets in setUp
111 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
112 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
115 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
117 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
119 public static $populateOnce = FALSE;
122 * @var boolean DBResetRequired allows skipping DB reset
123 * in specific test case. If you still need
124 * to reset single test (method) of such case, call
125 * $this->cleanDB() in the first line of this
128 public $DBResetRequired = TRUE;
131 * @var CRM_Core_Transaction|NULL
136 * @var CRM_Utils_Hook_UnitTests hookClass
137 * example of setting a method for a hook
138 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
140 public $hookClass = NULL;
143 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
145 protected $_params = array();
148 * @var CRM_Extension_System
150 protected $origExtensionSystem;
155 * Because we are overriding the parent class constructor, we
156 * need to show the same arguments as exist in the constructor of
157 * PHPUnit_Framework_TestCase, since
158 * PHPUnit_Framework_TestSuite::createTest() creates a
159 * ReflectionClass of the Test class and checks the constructor
160 * of that class to decide how to set up the test.
162 * @param string $name
164 * @param string $dataName
166 public function __construct($name = NULL, array$data = array(), $dataName = '') {
167 parent
::__construct($name, $data, $dataName);
169 // we need full error reporting
170 error_reporting(E_ALL
& ~E_NOTICE
);
172 if (!empty($GLOBALS['mysql_db'])) {
173 self
::$_dbName = $GLOBALS['mysql_db'];
176 self
::$_dbName = 'civicrm_tests_dev';
179 // create test database
180 self
::$utils = new Utils($GLOBALS['mysql_host'],
181 $GLOBALS['mysql_port'],
182 $GLOBALS['mysql_user'],
183 $GLOBALS['mysql_pass']
186 // also load the class loader
187 require_once 'CRM/Core/ClassLoader.php';
188 CRM_Core_ClassLoader
::singleton()->register();
189 if (function_exists('_civix_phpunit_setUp')) {
190 // FIXME: loosen coupling
191 _civix_phpunit_setUp();
196 * Override to run the test and assert its state.
199 * @throws \PHPUnit_Framework_IncompleteTest
200 * @throws \PHPUnit_Framework_SkippedTest
202 protected function runTest() {
204 return parent
::runTest();
206 catch (PEAR_Exception
$e) {
207 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
208 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
215 public function requireDBReset() {
216 return $this->DBResetRequired
;
222 public static function getDBName() {
223 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
228 * Create database connection for this instance.
230 * Initialize the test database if it hasn't been initialized
232 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
234 protected function getConnection() {
235 $dbName = self
::$_dbName;
236 if (!self
::$dbInit) {
237 $dbName = self
::getDBName();
239 // install test database
240 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
242 static::_populateDB(FALSE, $this);
244 self
::$dbInit = TRUE;
246 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
250 * Required implementation of abstract method.
252 protected function getDataSet() {
256 * @param bool $perClass
257 * @param null $object
259 * TRUE if the populate logic runs; FALSE if it is skipped
261 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
263 if ($perClass ||
$object == NULL) {
267 $dbreset = $object->requireDBReset();
270 if (self
::$populateOnce ||
!$dbreset) {
273 self
::$populateOnce = NULL;
275 $dbName = self
::getDBName();
276 $pdo = self
::$utils->pdo
;
277 // only consider real tables and not views
278 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
279 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
281 $truncates = array();
283 foreach ($tables as $table) {
285 if (substr($table['table_name'], 0, 4) == 'log_') {
289 // don't change list of installed extensions
290 if ($table['table_name'] == 'civicrm_extension') {
294 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
295 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
298 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
304 "SET foreign_key_checks = 0",
305 // SQL mode needs to be strict, that's our standard
306 "SET SQL_MODE='STRICT_ALL_TABLES';",
307 "SET global innodb_flush_log_at_trx_commit = 2;",
309 $queries = array_merge($queries, $truncates);
310 $queries = array_merge($queries, $drops);
311 foreach ($queries as $query) {
312 if (self
::$utils->do_query($query) === FALSE) {
313 // failed to create test database
314 echo "failed to create test db.";
319 // initialize test database
320 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
321 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
322 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
324 $query2 = file_get_contents($sql_file2);
325 $query3 = file_get_contents($sql_file3);
326 $query4 = file_get_contents($sql_file4);
327 if (self
::$utils->do_query($query2) === FALSE) {
328 echo "Cannot load civicrm_data.mysql. Aborting.";
331 if (self
::$utils->do_query($query3) === FALSE) {
332 echo "Cannot load test_data.mysql. Aborting.";
335 if (self
::$utils->do_query($query4) === FALSE) {
336 echo "Cannot load test_data.mysql. Aborting.";
340 // done with all the loading, get transactions back
341 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
342 echo "Cannot set global? Huh?";
346 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
347 echo "Cannot get foreign keys back? Huh?";
351 unset($query, $query2, $query3);
354 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
356 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
368 public static function setUpBeforeClass() {
369 static::_populateDB(TRUE);
371 // also set this global hack
372 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
376 * Common setup functions for all unit tests.
378 protected function setUp() {
379 $session = CRM_Core_Session
::singleton();
380 $session->set('userID', NULL);
382 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
383 // Use a temporary file for STDIN
384 $GLOBALS['stdin'] = tmpfile();
385 if ($GLOBALS['stdin'] === FALSE) {
386 echo "Couldn't open temporary file\n";
390 // Get and save a connection to the database
391 $this->_dbconn
= $this->getConnection();
393 // reload database before each test
394 // $this->_populateDB();
396 // "initialize" CiviCRM to avoid problems when running single tests
397 // FIXME: look at it closer in second stage
399 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
400 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
402 // disable any left-over test extensions
403 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
405 // reset all the caches
406 CRM_Utils_System
::flushCache();
408 // initialize the object once db is loaded
410 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
412 // when running unit tests, use mockup user framework
413 $this->hookClass
= CRM_Utils_Hook
::singleton();
415 // Make sure the DB connection is setup properly
416 $config->userSystem
->setMySQLTimeZone();
417 $env = new CRM_Utils_Check_Env();
418 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
420 // clear permissions stub to not check permissions
421 $config->userPermissionClass
->permissions
= NULL;
423 //flush component settings
424 CRM_Core_Component
::getEnabledComponents(TRUE);
426 error_reporting(E_ALL
);
428 $this->_sethtmlGlobals();
432 * Read everything from the datasets directory and insert into the db.
434 public function loadAllFixtures() {
435 $fixturesDir = __DIR__
. '/../../fixtures';
437 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
439 $xmlFiles = glob($fixturesDir . '/*.xml');
440 foreach ($xmlFiles as $xmlFixture) {
441 $op = new PHPUnit_Extensions_Database_Operation_Insert();
442 $dataset = $this->createXMLDataSet($xmlFixture);
443 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
444 $op->execute($this->_dbconn
, $dataset);
447 $yamlFiles = glob($fixturesDir . '/*.yaml');
448 foreach ($yamlFiles as $yamlFixture) {
449 $op = new PHPUnit_Extensions_Database_Operation_Insert();
450 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
451 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
452 $op->execute($this->_dbconn
, $dataset);
455 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
459 * Emulate a logged in user since certain functions use that.
460 * value to store a record in the DB (like activity)
464 * Contact ID of the created user.
466 public function createLoggedInUser() {
468 'first_name' => 'Logged In',
469 'last_name' => 'User ' . rand(),
470 'contact_type' => 'Individual',
472 $contactID = $this->individualCreate($params);
473 $this->callAPISuccess('UFMatch', 'create', array(
474 'contact_id' => $contactID,
475 'uf_name' => 'superman',
479 $session = CRM_Core_Session
::singleton();
480 $session->set('userID', $contactID);
484 public function cleanDB() {
485 self
::$populateOnce = NULL;
486 $this->DBResetRequired
= TRUE;
488 $this->_dbconn
= $this->getConnection();
489 static::_populateDB();
490 $this->tempDirs
= array();
494 * Create default domain contacts for the two domains added during test class.
495 * database population.
497 public function createDomainContacts() {
498 $default_domain_contact = $this->organizationCreate();
499 $second_domain_contact = $this->organizationCreate();
503 * Common teardown functions for all unit tests.
505 protected function tearDown() {
506 error_reporting(E_ALL
& ~E_NOTICE
);
507 CRM_Utils_Hook
::singleton()->reset();
508 $this->hookClass
->reset();
509 $session = CRM_Core_Session
::singleton();
510 $session->set('userID', NULL);
513 $this->tx
->rollback()->commit();
516 CRM_Core_Transaction
::forceRollbackIfEnabled();
517 \Civi\Core\Transaction\Manager
::singleton(TRUE);
520 CRM_Core_Transaction
::forceRollbackIfEnabled();
521 \Civi\Core\Transaction\Manager
::singleton(TRUE);
523 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
524 $this->quickCleanup($tablesToTruncate);
525 $this->createDomainContacts();
528 $this->cleanTempDirs();
529 $this->unsetExtensionSystem();
530 $this->clearOutputBuffer();
534 * FIXME: Maybe a better way to do it
536 public function foreignKeyChecksOff() {
537 self
::$utils = new Utils($GLOBALS['mysql_host'],
538 $GLOBALS['mysql_port'],
539 $GLOBALS['mysql_user'],
540 $GLOBALS['mysql_pass']
542 $dbName = self
::getDBName();
543 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
544 if (self
::$utils->do_query($query) === FALSE) {
546 echo 'Cannot set foreign_key_checks = 0';
552 public function foreignKeyChecksOn() {
553 // FIXME: might not be needed if previous fixme implemented
557 * Generic function to compare expected values after an api call to retrieved.
560 * @daoName string DAO Name of object we're evaluating.
561 * @id int Id of object
562 * @match array Associative array of field name => expected value. Empty if asserting
563 * that a DELETE occurred
564 * @delete boolean True if we're checking that a DELETE action occurred.
568 * @param bool $delete
569 * @throws \PHPUnit_Framework_AssertionFailedError
571 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
573 // adding this here since developers forget to check for an id
574 // and hence we get the first value in the db
575 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
578 $object = new $daoName();
582 // If we're asserting successful record deletion, make sure object is NOT found.
584 if ($object->find(TRUE)) {
585 $this->fail("Object not deleted by delete operation: $daoName, $id");
590 // Otherwise check matches of DAO field values against expected values in $match.
591 if ($object->find(TRUE)) {
592 $fields = &$object->fields();
593 foreach ($fields as $name => $value) {
594 $dbName = $value['name'];
595 if (isset($match[$name])) {
597 $this->assertEquals($object->$dbName, $match[$name]);
599 elseif (isset($match[$dbName])) {
601 $this->assertEquals($object->$dbName, $match[$dbName]);
606 $this->fail("Could not retrieve object: $daoName, $id");
609 $matchSize = count($match);
610 if ($verifiedCount != $matchSize) {
611 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
616 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
617 * @param string $daoName
618 * @param $searchValue
619 * @param $returnColumn
620 * @param $searchColumn
623 * @return null|string
624 * @throws PHPUnit_Framework_AssertionFailedError
626 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
627 if (empty($searchValue)) {
628 $this->fail("empty value passed to assertDBNotNull");
630 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
631 $this->assertNotNull($value, $message);
637 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
638 * @param string $daoName
639 * @param $searchValue
640 * @param $returnColumn
641 * @param $searchColumn
644 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
645 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
646 $this->assertNull($value, $message);
650 * Request a record from the DB by id. Success if row not found.
651 * @param string $daoName
653 * @param null $message
655 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
656 $message = $message ?
$message : "$daoName (#$id) should not exist";
657 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
658 $this->assertNull($value, $message);
662 * Request a record from the DB by id. Success if row not found.
663 * @param string $daoName
665 * @param null $message
667 public function assertDBRowExist($daoName, $id, $message = NULL) {
668 $message = $message ?
$message : "$daoName (#$id) should exist";
669 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
670 $this->assertEquals($id, $value, $message);
674 * Compare a single column value in a retrieved DB record to an expected value.
675 * @param string $daoName
676 * @param $searchValue
677 * @param $returnColumn
678 * @param $searchColumn
679 * @param $expectedValue
682 public function assertDBCompareValue(
683 $daoName, $searchValue, $returnColumn, $searchColumn,
684 $expectedValue, $message
686 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
687 $this->assertEquals($value, $expectedValue, $message);
691 * Compare all values in a single retrieved DB record to an array of expected values.
692 * @param string $daoName
693 * @param array $searchParams
694 * @param $expectedValues
696 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
697 //get the values from db
699 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
701 // compare db values with expected values
702 self
::assertAttributesEquals($expectedValues, $dbValues);
706 * Assert that a SQL query returns a given value.
708 * The first argument is an expected value. The remaining arguments are passed
709 * to CRM_Core_DAO::singleValueQuery
711 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
712 * array(1 => array("Whiz", "String")));
715 * @param array $params
716 * @param string $message
718 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
722 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
723 $this->assertEquals($expected, $actual,
724 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
725 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
731 * Assert that two array-trees are exactly equal, notwithstanding
732 * the sorting of keys
734 * @param array $expected
735 * @param array $actual
737 public function assertTreeEquals($expected, $actual) {
740 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
741 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
745 $this->assertEquals($e, $a);
749 * Assert that two numbers are approximately equal.
751 * @param int|float $expected
752 * @param int|float $actual
753 * @param int|float $tolerance
754 * @param string $message
756 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
757 if ($message === NULL) {
758 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
760 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
764 * Assert attributes are equal.
766 * @param $expectedValues
767 * @param $actualValues
768 * @param string $message
770 * @throws PHPUnit_Framework_AssertionFailedError
772 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
773 foreach ($expectedValues as $paramName => $paramValue) {
774 if (isset($actualValues[$paramName])) {
775 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
778 $this->fail("Attribute '$paramName' not present in actual array.");
787 public function assertArrayKeyExists($key, &$list) {
788 $result = isset($list[$key]) ?
TRUE : FALSE;
789 $this->assertTrue($result, ts("%1 element exists?",
798 public function assertArrayValueNotNull($key, &$list) {
799 $this->assertArrayKeyExists($key, $list);
801 $value = isset($list[$key]) ?
$list[$key] : NULL;
802 $this->assertTrue($value,
803 ts("%1 element not null?",
810 * Check that api returned 'is_error' => 0.
812 * @param array $apiResult
814 * @param string $prefix
815 * Extra test to add to message.
817 public function assertAPISuccess($apiResult, $prefix = '') {
818 if (!empty($prefix)) {
821 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
823 if (!empty($apiResult['debug_information'])) {
824 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
826 if (!empty($apiResult['trace'])) {
827 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
829 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
833 * Check that api returned 'is_error' => 1.
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.
867 public function assertAPIDeleted($entity, $id) {
868 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
873 * Check that api returned 'is_error' => 1
874 * else provide full message
875 * @param array $result
877 * @param array $valuesToExclude
878 * @param string $prefix
879 * Extra test to add to message.
881 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
882 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
883 foreach ($valuesToExclude as $value) {
884 if (isset($result[$value])) {
885 unset($result[$value]);
887 if (isset($expected[$value])) {
888 unset($expected[$value]);
891 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
895 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
899 * @param array $params
902 public function civicrm_api($entity, $action, $params) {
903 return civicrm_api($entity, $action, $params);
907 * Create a batch of external API calls which can
908 * be executed concurrently.
911 * $calls = $this->createExternalAPI()
912 * ->addCall('Contact', 'get', ...)
913 * ->addCall('Contact', 'get', ...)
919 * @return \Civi\API\ExternalBatch
920 * @throws PHPUnit_Framework_SkippedTestError
922 public function createExternalAPI() {
923 global $civicrm_root;
924 $defaultParams = array(
925 'version' => $this->_apiversion
,
929 $calls = new \Civi\API\
ExternalBatch($defaultParams);
930 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
932 if (!$calls->isSupported()) {
933 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
940 * wrap api functions.
941 * so we can ensure they succeed & throw exceptions without litterering the test with checks
943 * @param string $entity
944 * @param string $action
945 * @param array $params
946 * @param mixed $checkAgainst
947 * Optional value to check result against, implemented for getvalue,.
948 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
949 * for getsingle the array is compared against an array passed in - the id is not compared (for
954 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
955 $params = array_merge(array(
956 'version' => $this->_apiversion
,
961 switch (strtolower($action)) {
963 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
966 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
969 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
971 $result = $this->civicrm_api($entity, $action, $params);
972 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
977 * This function exists to wrap api getValue function & check the result
978 * so we can ensure they succeed & throw exceptions without litterering the test with checks
979 * There is a type check in this
981 * @param string $entity
982 * @param array $params
983 * @param string $type
984 * Per http://php.net/manual/en/function.gettype.php possible types.
994 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
996 'version' => $this->_apiversion
,
999 $result = $this->civicrm_api($entity, 'getvalue', $params);
1001 if ($type == 'integer') {
1002 // api seems to return integers as strings
1003 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
1006 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1013 * This function exists to wrap api getsingle function & check the result
1014 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1016 * @param string $entity
1017 * @param array $params
1018 * @param array $checkAgainst
1019 * Array to compare result against.
1030 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1032 'version' => $this->_apiversion
,
1035 $result = $this->civicrm_api($entity, 'getsingle', $params);
1036 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1037 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1039 if ($checkAgainst) {
1040 // @todo - have gone with the fn that unsets id? should we check id?
1041 $this->checkArrayEquals($result, $checkAgainst);
1047 * This function exists to wrap api getValue function & check the result
1048 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1049 * There is a type check in this
1050 * @param string $entity
1051 * @param array $params
1052 * @param null $count
1056 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1058 'version' => $this->_apiversion
,
1061 $result = $this->civicrm_api($entity, 'getcount', $params);
1062 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1063 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1065 if (is_int($count)) {
1066 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1072 * This function exists to wrap api functions.
1073 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1075 * @param string $entity
1076 * @param string $action
1077 * @param array $params
1078 * @param string $function
1079 * Pass this in to create a generated example.
1080 * @param string $file
1081 * Pass this in to create a generated example.
1082 * @param string $description
1083 * @param string|null $exampleName
1087 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1088 $params['version'] = $this->_apiversion
;
1089 $result = $this->callAPISuccess($entity, $action, $params);
1090 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1095 * This function exists to wrap api functions.
1096 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1097 * @param string $entity
1098 * @param string $action
1099 * @param array $params
1100 * @param string $expectedErrorMessage
1102 * @param null $extraOutput
1105 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1106 if (is_array($params)) {
1108 'version' => $this->_apiversion
,
1111 $result = $this->civicrm_api($entity, $action, $params);
1112 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1117 * Create required data based on $this->entity & $this->params
1118 * This is just a way to set up the test data for delete & get functions
1119 * so the distinction between set
1120 * up & tested functions is clearer
1125 public function createTestEntity() {
1126 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1130 * Generic function to create Organisation, to be used in test cases
1132 * @param array $params
1133 * parameters for civicrm_contact_add api function call
1135 * sequence number if creating multiple organizations
1138 * id of Organisation created
1140 public function organizationCreate($params = array(), $seq = 0) {
1144 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1145 return $this->_contactCreate($params);
1149 * Generic function to create Individual, to be used in test cases
1151 * @param array $params
1152 * parameters for civicrm_contact_add api function call
1154 * sequence number if creating multiple individuals
1157 * id of Individual created
1159 public function individualCreate($params = array(), $seq = 0) {
1160 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1161 return $this->_contactCreate($params);
1165 * Generic function to create Household, to be used in test cases
1167 * @param array $params
1168 * parameters for civicrm_contact_add api function call
1170 * sequence number if creating multiple households
1173 * id of Household created
1175 public function householdCreate($params = array(), $seq = 0) {
1176 $params = array_merge($this->sampleContact('Household', $seq), $params);
1177 return $this->_contactCreate($params);
1181 * Helper function for getting sample contact properties.
1183 * @param string $contact_type
1184 * enum contact type: Individual, Organization
1186 * sequence number for the values of this type
1189 * properties of sample contact (ie. $params for API call)
1191 public function sampleContact($contact_type, $seq = 0) {
1193 'Individual' => array(
1194 // The number of values in each list need to be coprime numbers to not have duplicates
1195 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1196 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1197 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1199 'Organization' => array(
1200 'organization_name' => array(
1201 'Unit Test Organization',
1208 'Household' => array(
1209 'household_name' => array('Unit Test household'),
1212 $params = array('contact_type' => $contact_type);
1213 foreach ($samples[$contact_type] as $key => $values) {
1214 $params[$key] = $values[$seq %
count($values)];
1216 if ($contact_type == 'Individual') {
1217 $params['email'] = strtolower(
1218 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1220 $params['prefix_id'] = 3;
1221 $params['suffix_id'] = 3;
1227 * Private helper function for calling civicrm_contact_add.
1229 * @param array $params
1230 * For civicrm_contact_add api function call.
1235 * id of Household created
1237 private function _contactCreate($params) {
1238 $result = $this->callAPISuccess('contact', 'create', $params);
1239 if (!empty($result['is_error']) ||
empty($result['id'])) {
1240 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1242 return $result['id'];
1246 * Delete contact, ensuring it is not the domain contact
1248 * @param int $contactID
1249 * Contact ID to delete
1251 public function contactDelete($contactID) {
1252 $domain = new CRM_Core_BAO_Domain();
1253 $domain->contact_id
= $contactID;
1254 if (!$domain->find(TRUE)) {
1255 $this->callAPISuccess('contact', 'delete', array(
1257 'skip_undelete' => 1,
1263 * @param int $contactTypeId
1267 public function contactTypeDelete($contactTypeId) {
1268 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1270 throw new Exception('Could not delete contact type');
1275 * @param array $params
1279 public function membershipTypeCreate($params = array()) {
1280 CRM_Member_PseudoConstant
::flush('membershipType');
1281 CRM_Core_Config
::clearDBCache();
1282 $memberOfOrganization = $this->organizationCreate();
1283 $params = array_merge(array(
1284 'name' => 'General',
1285 'duration_unit' => 'year',
1286 'duration_interval' => 1,
1287 'period_type' => 'rolling',
1288 'member_of_contact_id' => $memberOfOrganization,
1290 'financial_type_id' => 1,
1293 'visibility' => 'Public',
1296 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1298 CRM_Member_PseudoConstant
::flush('membershipType');
1299 CRM_Utils_Cache
::singleton()->flush();
1301 return $result['id'];
1305 * @param array $params
1309 public function contactMembershipCreate($params) {
1311 'join_date' => '2007-01-21',
1312 'start_date' => '2007-01-21',
1313 'end_date' => '2007-12-21',
1314 'source' => 'Payment',
1317 foreach ($pre as $key => $val) {
1318 if (!isset($params[$key])) {
1319 $params[$key] = $val;
1323 $result = $this->callAPISuccess('Membership', 'create', $params);
1324 return $result['id'];
1328 * Delete Membership Type.
1330 * @param array $params
1332 public function membershipTypeDelete($params) {
1333 $this->callAPISuccess('MembershipType', 'Delete', $params);
1337 * @param int $membershipID
1339 public function membershipDelete($membershipID) {
1340 $deleteParams = array('id' => $membershipID);
1341 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1345 * @param string $name
1349 public function membershipStatusCreate($name = 'test member status') {
1350 $params['name'] = $name;
1351 $params['start_event'] = 'start_date';
1352 $params['end_event'] = 'end_date';
1353 $params['is_current_member'] = 1;
1354 $params['is_active'] = 1;
1356 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1357 CRM_Member_PseudoConstant
::flush('membershipStatus');
1358 return $result['id'];
1362 * @param int $membershipStatusID
1364 public function membershipStatusDelete($membershipStatusID) {
1365 if (!$membershipStatusID) {
1368 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1372 * @param array $params
1376 public function relationshipTypeCreate($params = array()) {
1377 $params = array_merge(array(
1378 'name_a_b' => 'Relation 1 for relationship type create',
1379 'name_b_a' => 'Relation 2 for relationship type create',
1380 'contact_type_a' => 'Individual',
1381 'contact_type_b' => 'Organization',
1388 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1389 CRM_Core_PseudoConstant
::flush('relationshipType');
1391 return $result['id'];
1395 * Delete Relatinship Type.
1397 * @param int $relationshipTypeID
1399 public function relationshipTypeDelete($relationshipTypeID) {
1400 $params['id'] = $relationshipTypeID;
1401 $this->callAPISuccess('relationship_type', 'delete', $params);
1405 * @param array $params
1409 public function paymentProcessorTypeCreate($params = NULL) {
1410 if (is_null($params)) {
1412 'name' => 'API_Test_PP',
1413 'title' => 'API Test Payment Processor',
1414 'class_name' => 'CRM_Core_Payment_APITest',
1415 'billing_mode' => 'form',
1421 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1423 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1425 return $result['id'];
1429 * Create test Authorize.net instance.
1431 * @param array $params
1435 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1436 $params = array_merge(array(
1437 'name' => 'Authorize',
1438 'domain_id' => CRM_Core_Config
::domainID(),
1439 'payment_processor_type_id' => 'AuthNet',
1440 'title' => 'AuthNet',
1445 'user_name' => '4y5BfuW7jm',
1446 'password' => '4cAmW927n8uLf5J8',
1447 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1448 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1449 'class_name' => 'Payment_AuthorizeNet',
1450 'billing_mode' => 1,
1453 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1454 return $result['id'];
1458 * Create Participant.
1460 * @param array $params
1461 * Array of contact id and event id values.
1464 * $id of participant created
1466 public function participantCreate($params) {
1467 if (empty($params['contact_id'])) {
1468 $params['contact_id'] = $this->individualCreate();
1470 if (empty($params['event_id'])) {
1471 $event = $this->eventCreate();
1472 $params['event_id'] = $event['id'];
1477 'register_date' => 20070219,
1478 'source' => 'Wimbeldon',
1479 'event_level' => 'Payment',
1483 $params = array_merge($defaults, $params);
1484 $result = $this->callAPISuccess('Participant', 'create', $params);
1485 return $result['id'];
1489 * Create Payment Processor.
1492 * Id Payment Processor
1494 public function processorCreate() {
1495 $processorParams = array(
1498 'payment_processor_type_id' => 'Dummy',
1499 'financial_account_id' => 12,
1503 'url_site' => 'http://dummy.com',
1504 'url_recur' => 'http://dummy.com',
1505 'billing_mode' => 1,
1508 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1509 return $processor['id'];
1513 * Create Payment Processor.
1515 * @param array $processorParams
1517 * @return \CRM_Core_Payment_Dummy
1518 * Instance of Dummy Payment Processor
1520 public function dummyProcessorCreate($processorParams = array()) {
1521 $paymentProcessorID = $this->processorCreate($processorParams);
1522 return Civi\Payment\System
::singleton()->getById($paymentProcessorID);
1526 * Create contribution page.
1528 * @param array $params
1530 * Array of contribution page
1532 public function contributionPageCreate($params) {
1533 $this->_pageParams
= array(
1534 'title' => 'Test Contribution Page',
1535 'financial_type_id' => 1,
1536 'currency' => 'USD',
1537 'financial_account_id' => 1,
1538 'payment_processor' => $params['processor_id'],
1540 'is_allow_other_amount' => 1,
1542 'max_amount' => 1000,
1544 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1545 return $contributionPage;
1549 * Create a sample batch.
1551 public function batchCreate() {
1552 $params = $this->_params
;
1553 $params['name'] = $params['title'] = 'Batch_433397';
1554 $params['status_id'] = 1;
1555 $result = $this->callAPISuccess('batch', 'create', $params);
1556 return $result['id'];
1562 * @param array $params
1564 * result of created tag
1566 public function tagCreate($params = array()) {
1568 'name' => 'New Tag3',
1569 'description' => 'This is description for Our New Tag ',
1572 $params = array_merge($defaults, $params);
1573 $result = $this->callAPISuccess('Tag', 'create', $params);
1574 return $result['values'][$result['id']];
1581 * Id of the tag to be deleted.
1585 public function tagDelete($tagId) {
1586 require_once 'api/api.php';
1590 $result = $this->callAPISuccess('Tag', 'delete', $params);
1591 return $result['id'];
1595 * Add entity(s) to the tag
1597 * @param array $params
1601 public function entityTagAdd($params) {
1602 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1607 * Create contribution.
1613 * id of created contribution
1615 public function pledgeCreate($cID) {
1617 'contact_id' => $cID,
1618 'pledge_create_date' => date('Ymd'),
1619 'start_date' => date('Ymd'),
1620 'scheduled_date' => date('Ymd'),
1622 'pledge_status_id' => '2',
1623 'financial_type_id' => '1',
1624 'pledge_original_installment_amount' => 20,
1625 'frequency_interval' => 5,
1626 'frequency_unit' => 'year',
1627 'frequency_day' => 15,
1628 'installments' => 5,
1631 $result = $this->callAPISuccess('Pledge', 'create', $params);
1632 return $result['id'];
1636 * Delete contribution.
1638 * @param int $pledgeId
1640 public function pledgeDelete($pledgeId) {
1642 'pledge_id' => $pledgeId,
1644 $this->callAPISuccess('Pledge', 'delete', $params);
1648 * Create contribution.
1650 * @param array $params
1651 * Array of parameters.
1654 * id of created contribution
1656 public function contributionCreate($params) {
1658 $params = array_merge(array(
1660 'receive_date' => date('Ymd'),
1661 'total_amount' => 100.00,
1662 'fee_amount' => 5.00,
1663 'net_ammount' => 95.00,
1664 'financial_type_id' => 1,
1665 'payment_instrument_id' => 1,
1666 'non_deductible_amount' => 10.00,
1668 'invoice_id' => 67890,
1670 'contribution_status_id' => 1,
1673 $result = $this->callAPISuccess('contribution', 'create', $params);
1674 return $result['id'];
1678 * Delete contribution.
1680 * @param int $contributionId
1684 public function contributionDelete($contributionId) {
1686 'contribution_id' => $contributionId,
1688 $result = $this->callAPISuccess('contribution', 'delete', $params);
1695 * @param array $params
1696 * Name-value pair for an event.
1700 public function eventCreate($params = array()) {
1701 // if no contact was passed, make up a dummy event creator
1702 if (!isset($params['contact_id'])) {
1703 $params['contact_id'] = $this->_contactCreate(array(
1704 'contact_type' => 'Individual',
1705 'first_name' => 'Event',
1706 'last_name' => 'Creator',
1710 // set defaults for missing params
1711 $params = array_merge(array(
1712 'title' => 'Annual CiviCRM meet',
1713 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1714 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1715 'event_type_id' => 1,
1717 'start_date' => 20081021,
1718 'end_date' => 20081023,
1719 'is_online_registration' => 1,
1720 'registration_start_date' => 20080601,
1721 'registration_end_date' => 20081015,
1722 'max_participants' => 100,
1723 'event_full_text' => 'Sorry! We are already full',
1726 'is_show_location' => 0,
1729 return $this->callAPISuccess('Event', 'create', $params);
1740 public function eventDelete($id) {
1744 return $this->callAPISuccess('event', 'delete', $params);
1748 * Delete participant.
1750 * @param int $participantID
1754 public function participantDelete($participantID) {
1756 'id' => $participantID,
1758 return $this->callAPISuccess('Participant', 'delete', $params);
1762 * Create participant payment.
1764 * @param int $participantID
1765 * @param int $contributionID
1767 * $id of created payment
1769 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1770 //Create Participant Payment record With Values
1772 'participant_id' => $participantID,
1773 'contribution_id' => $contributionID,
1776 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1777 return $result['id'];
1781 * Delete participant payment.
1783 * @param int $paymentID
1785 public function participantPaymentDelete($paymentID) {
1789 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1795 * @param int $contactID
1797 * location id of created location
1799 public function locationAdd($contactID) {
1802 'location_type' => 'New Location Type',
1804 'name' => 'Saint Helier St',
1805 'county' => 'Marin',
1806 'country' => 'UNITED STATES',
1807 'state_province' => 'Michigan',
1808 'supplemental_address_1' => 'Hallmark Ct',
1809 'supplemental_address_2' => 'Jersey Village',
1814 'contact_id' => $contactID,
1815 'address' => $address,
1816 'location_format' => '2.0',
1817 'location_type' => 'New Location Type',
1820 $result = $this->callAPISuccess('Location', 'create', $params);
1825 * Delete Locations of contact.
1827 * @param array $params
1830 public function locationDelete($params) {
1831 $this->callAPISuccess('Location', 'delete', $params);
1835 * Add a Location Type.
1837 * @param array $params
1838 * @return CRM_Core_DAO_LocationType
1839 * location id of created location
1841 public function locationTypeCreate($params = NULL) {
1842 if ($params === NULL) {
1844 'name' => 'New Location Type',
1845 'vcard_name' => 'New Location Type',
1846 'description' => 'Location Type for Delete',
1851 $locationType = new CRM_Core_DAO_LocationType();
1852 $locationType->copyValues($params);
1853 $locationType->save();
1854 // clear getfields cache
1855 CRM_Core_PseudoConstant
::flush();
1856 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1857 return $locationType;
1861 * Delete a Location Type.
1863 * @param int $locationTypeId
1865 public function locationTypeDelete($locationTypeId) {
1866 $locationType = new CRM_Core_DAO_LocationType();
1867 $locationType->id
= $locationTypeId;
1868 $locationType->delete();
1874 * @param array $params
1876 * groupId of created group
1878 public function groupCreate($params = array()) {
1879 $params = array_merge(array(
1880 'name' => 'Test Group 1',
1882 'title' => 'New Test Group Created',
1883 'description' => 'New Test Group Created',
1885 'visibility' => 'Public Pages',
1886 'group_type' => array(
1892 $result = $this->callAPISuccess('Group', 'create', $params);
1893 return $result['id'];
1898 * Function to add a Group.
1900 * @params array to add group
1902 * @param int $groupID
1903 * @param int $totalCount
1905 * groupId of created group
1907 public function groupContactCreate($groupID, $totalCount = 10) {
1908 $params = array('group_id' => $groupID);
1909 for ($i = 1; $i <= $totalCount; $i++
) {
1910 $contactID = $this->individualCreate();
1912 $params +
= array('contact_id' => $contactID);
1915 $params +
= array("contact_id.$i" => $contactID);
1918 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1928 public function groupDelete($gid) {
1934 $this->callAPISuccess('Group', 'delete', $params);
1939 * @param array $params
1941 public function uFFieldCreate($params = array()) {
1942 $params = array_merge(array(
1944 'field_name' => 'first_name',
1947 'visibility' => 'Public Pages and Listings',
1948 'is_searchable' => '1',
1949 'label' => 'first_name',
1950 'field_type' => 'Individual',
1953 $this->callAPISuccess('uf_field', 'create', $params);
1957 * Add a UF Join Entry.
1959 * @param array $params
1961 * $id of created UF Join
1963 public function ufjoinCreate($params = NULL) {
1964 if ($params === NULL) {
1967 'module' => 'CiviEvent',
1968 'entity_table' => 'civicrm_event',
1974 $result = $this->callAPISuccess('uf_join', 'create', $params);
1979 * Delete a UF Join Entry.
1981 * @param array $params
1982 * with missing uf_group_id
1984 public function ufjoinDelete($params = NULL) {
1985 if ($params === NULL) {
1988 'module' => 'CiviEvent',
1989 'entity_table' => 'civicrm_event',
1992 'uf_group_id' => '',
1996 crm_add_uf_join($params);
2000 * @param array $params
2001 * Optional parameters.
2006 public function campaignCreate($params = array()) {
2007 $this->enableCiviCampaign();
2008 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2009 'name' => 'big_campaign',
2010 'title' => 'Campaign',
2012 return $campaign['id'];
2016 * Create Group for a contact.
2018 * @param int $contactId
2020 public function contactGroupCreate($contactId) {
2022 'contact_id.1' => $contactId,
2026 $this->callAPISuccess('GroupContact', 'Create', $params);
2030 * Delete Group for a contact.
2032 * @param int $contactId
2034 public function contactGroupDelete($contactId) {
2036 'contact_id.1' => $contactId,
2039 $this->civicrm_api('GroupContact', 'Delete', $params);
2045 * @param array $params
2048 public function activityCreate($params = NULL) {
2050 if ($params === NULL) {
2051 $individualSourceID = $this->individualCreate();
2053 $contactParams = array(
2054 'first_name' => 'Julia',
2055 'Last_name' => 'Anderson',
2057 'email' => 'julia_anderson@civicrm.org',
2058 'contact_type' => 'Individual',
2061 $individualTargetID = $this->individualCreate($contactParams);
2064 'source_contact_id' => $individualSourceID,
2065 'target_contact_id' => array($individualTargetID),
2066 'assignee_contact_id' => array($individualTargetID),
2067 'subject' => 'Discussion on warm beer',
2068 'activity_date_time' => date('Ymd'),
2069 'duration_hours' => 30,
2070 'duration_minutes' => 20,
2071 'location' => 'Baker Street',
2072 'details' => 'Lets schedule a meeting',
2074 'activity_name' => 'Meeting',
2078 $result = $this->callAPISuccess('Activity', 'create', $params);
2080 $result['target_contact_id'] = $individualTargetID;
2081 $result['assignee_contact_id'] = $individualTargetID;
2086 * Create an activity type.
2088 * @param array $params
2092 public function activityTypeCreate($params) {
2093 return $this->callAPISuccess('ActivityType', 'create', $params);
2097 * Delete activity type.
2099 * @param int $activityTypeId
2100 * Id of the activity type.
2103 public function activityTypeDelete($activityTypeId) {
2104 $params['activity_type_id'] = $activityTypeId;
2105 return $this->callAPISuccess('ActivityType', 'delete', $params);
2109 * Create custom group.
2111 * @param array $params
2114 public function customGroupCreate($params = array()) {
2116 'title' => 'new custom group',
2117 'extends' => 'Contact',
2119 'style' => 'Inline',
2123 $params = array_merge($defaults, $params);
2125 if (strlen($params['title']) > 13) {
2126 $params['title'] = substr($params['title'], 0, 13);
2129 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2130 $this->callAPISuccess('custom_group', 'get', array(
2131 'title' => $params['title'],
2132 array('api.custom_group.delete' => 1),
2135 return $this->callAPISuccess('custom_group', 'create', $params);
2139 * Existing function doesn't allow params to be over-ridden so need a new one
2140 * this one allows you to only pass in the params you want to change
2141 * @param array $params
2144 public function CustomGroupCreateByParams($params = array()) {
2146 'title' => "API Custom Group",
2147 'extends' => 'Contact',
2149 'style' => 'Inline',
2152 $params = array_merge($defaults, $params);
2153 return $this->callAPISuccess('custom_group', 'create', $params);
2157 * Create custom group with multi fields.
2158 * @param array $params
2161 public function CustomGroupMultipleCreateByParams($params = array()) {
2166 $params = array_merge($defaults, $params);
2167 return $this->CustomGroupCreateByParams($params);
2171 * Create custom group with multi fields.
2172 * @param array $params
2175 public function CustomGroupMultipleCreateWithFields($params = array()) {
2176 // also need to pass on $params['custom_field'] if not set but not in place yet
2178 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2179 $ids['custom_group_id'] = $customGroup['id'];
2181 $customField = $this->customFieldCreate(array(
2182 'custom_group_id' => $ids['custom_group_id'],
2183 'label' => 'field_1' . $ids['custom_group_id'],
2186 $ids['custom_field_id'][] = $customField['id'];
2188 $customField = $this->customFieldCreate(array(
2189 'custom_group_id' => $ids['custom_group_id'],
2190 'default_value' => '',
2191 'label' => 'field_2' . $ids['custom_group_id'],
2193 $ids['custom_field_id'][] = $customField['id'];
2195 $customField = $this->customFieldCreate(array(
2196 'custom_group_id' => $ids['custom_group_id'],
2197 'default_value' => '',
2198 'label' => 'field_3' . $ids['custom_group_id'],
2200 $ids['custom_field_id'][] = $customField['id'];
2206 * Create a custom group with a single text custom field. See
2207 * participant:testCreateWithCustom for how to use this
2209 * @param string $function
2211 * @param string $filename
2215 * ids of created objects
2217 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2218 $params = array('title' => $function);
2219 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2220 $params['extends'] = $entity ?
$entity : 'Contact';
2221 $customGroup = $this->CustomGroupCreate($params);
2222 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2223 CRM_Core_PseudoConstant
::flush();
2225 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2229 * Delete custom group.
2231 * @param int $customGroupID
2235 public function customGroupDelete($customGroupID) {
2236 $params['id'] = $customGroupID;
2237 return $this->callAPISuccess('custom_group', 'delete', $params);
2241 * Create custom field.
2243 * @param array $params
2244 * (custom_group_id) is required.
2247 public function customFieldCreate($params) {
2248 $params = array_merge(array(
2249 'label' => 'Custom Field',
2250 'data_type' => 'String',
2251 'html_type' => 'Text',
2252 'is_searchable' => 1,
2254 'default_value' => 'defaultValue',
2257 $result = $this->callAPISuccess('custom_field', 'create', $params);
2258 // these 2 functions are called with force to flush static caches
2259 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2260 CRM_Core_Component
::getEnabledComponents(1);
2265 * Delete custom field.
2267 * @param int $customFieldID
2271 public function customFieldDelete($customFieldID) {
2273 $params['id'] = $customFieldID;
2274 return $this->callAPISuccess('custom_field', 'delete', $params);
2283 public function noteCreate($cId) {
2285 'entity_table' => 'civicrm_contact',
2286 'entity_id' => $cId,
2287 'note' => 'hello I am testing Note',
2288 'contact_id' => $cId,
2289 'modified_date' => date('Ymd'),
2290 'subject' => 'Test Note',
2293 return $this->callAPISuccess('Note', 'create', $params);
2297 * Enable CiviCampaign Component.
2299 public function enableCiviCampaign() {
2300 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2301 // force reload of config object
2302 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2303 //flush cache by calling with reset
2304 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2308 * Create test generated example in api/v3/examples.
2310 * To turn this off (e.g. on the server) set
2311 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2312 * in your settings file
2314 * @param string $entity
2315 * @param string $action
2316 * @param array $params
2317 * Array as passed to civicrm_api function.
2318 * @param array $result
2319 * Array as received from the civicrm_api function.
2320 * @param string $testFunction
2321 * Calling function - generally __FUNCTION__.
2322 * @param string $testFile
2323 * Called from file - generally __FILE__.
2324 * @param string $description
2325 * Descriptive text for the example file.
2326 * @param string $exampleName
2327 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2329 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2330 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2333 $entity = _civicrm_api_get_camel_name($entity);
2334 $action = strtolower($action);
2336 if (empty($exampleName)) {
2337 // Attempt to convert lowercase action name to CamelCase.
2338 // This is clunky/imperfect due to the convention of all lowercase actions.
2339 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2340 $knownPrefixes = array(
2347 foreach ($knownPrefixes as $prefix) {
2348 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2349 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2354 $this->tidyExampleResult($result);
2355 if (isset($params['version'])) {
2356 unset($params['version']);
2358 // Format multiline description as array
2360 if (is_string($description) && strlen($description)) {
2361 foreach (explode("\n", $description) as $line) {
2362 $desc[] = trim($line);
2365 $smarty = CRM_Core_Smarty
::singleton();
2366 $smarty->assign('testFunction', $testFunction);
2367 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2368 $smarty->assign('params', $params);
2369 $smarty->assign('entity', $entity);
2370 $smarty->assign('testFile', basename($testFile));
2371 $smarty->assign('description', $desc);
2372 $smarty->assign('result', $result);
2373 $smarty->assign('action', $action);
2375 if (file_exists('../tests/templates/documentFunction.tpl')) {
2376 if (!is_dir("../api/v3/examples/$entity")) {
2377 mkdir("../api/v3/examples/$entity");
2379 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2380 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2386 * Tidy up examples array so that fields that change often ..don't
2387 * and debug related fields are unset
2389 * @param array $result
2391 public function tidyExampleResult(&$result) {
2392 if (!is_array($result)) {
2395 $fieldsToChange = array(
2396 'hash' => '67eac7789eaee00',
2397 'modified_date' => '2012-11-14 16:02:35',
2398 'created_date' => '2013-07-28 08:49:19',
2399 'create_date' => '20120130621222105',
2400 'application_received_date' => '20130728084957',
2401 'in_date' => '2013-07-28 08:50:19',
2402 'scheduled_date' => '20130728085413',
2403 'approval_date' => '20130728085413',
2404 'pledge_start_date_high' => '20130726090416',
2405 'start_date' => '2013-07-29 00:00:00',
2406 'event_start_date' => '2013-07-29 00:00:00',
2407 'end_date' => '2013-08-04 00:00:00',
2408 'event_end_date' => '2013-08-04 00:00:00',
2409 'decision_date' => '20130805000000',
2412 $keysToUnset = array('xdebug', 'undefined_fields');
2413 foreach ($keysToUnset as $unwantedKey) {
2414 if (isset($result[$unwantedKey])) {
2415 unset($result[$unwantedKey]);
2418 if (isset($result['values'])) {
2419 if (!is_array($result['values'])) {
2422 $resultArray = &$result['values'];
2424 elseif (is_array($result)) {
2425 $resultArray = &$result;
2431 foreach ($resultArray as $index => &$values) {
2432 if (!is_array($values)) {
2435 foreach ($values as $key => &$value) {
2436 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2437 if (isset($value['is_error'])) {
2438 // we have a std nested result format
2439 $this->tidyExampleResult($value);
2442 foreach ($value as &$nestedResult) {
2443 // this is an alternative syntax for nested results a keyed array of results
2444 $this->tidyExampleResult($nestedResult);
2448 if (in_array($key, $keysToUnset)) {
2449 unset($values[$key]);
2452 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2453 $value = $fieldsToChange[$key];
2455 if (is_string($value)) {
2456 $value = addslashes($value);
2465 * @param array $params
2469 public function noteDelete($params) {
2470 return $this->callAPISuccess('Note', 'delete', $params);
2474 * Create custom field with Option Values.
2476 * @param array $customGroup
2477 * @param string $name
2478 * Name of custom field.
2482 public function customFieldOptionValueCreate($customGroup, $name) {
2483 $fieldParams = array(
2484 'custom_group_id' => $customGroup['id'],
2485 'name' => 'test_custom_group',
2486 'label' => 'Country',
2487 'html_type' => 'Select',
2488 'data_type' => 'String',
2491 'is_searchable' => 0,
2495 $optionGroup = array(
2497 'name' => 'option_group1',
2498 'label' => 'option_group_label1',
2501 $optionValue = array(
2502 'option_label' => array('Label1', 'Label2'),
2503 'option_value' => array('value1', 'value2'),
2504 'option_name' => array($name . '_1', $name . '_2'),
2505 'option_weight' => array(1, 2),
2506 'option_status' => 1,
2509 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2511 return $this->callAPISuccess('custom_field', 'create', $params);
2519 public function confirmEntitiesDeleted($entities) {
2520 foreach ($entities as $entity) {
2522 $result = $this->callAPISuccess($entity, 'Get', array());
2523 if ($result['error'] == 1 ||
$result['count'] > 0) {
2524 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2532 * @param $tablesToTruncate
2533 * @param bool $dropCustomValueTables
2534 * @throws \Exception
2536 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2538 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2540 if ($dropCustomValueTables) {
2541 $tablesToTruncate[] = 'civicrm_custom_group';
2542 $tablesToTruncate[] = 'civicrm_custom_field';
2545 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2547 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2548 foreach ($tablesToTruncate as $table) {
2549 $sql = "TRUNCATE TABLE $table";
2550 CRM_Core_DAO
::executeQuery($sql);
2552 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2554 if ($dropCustomValueTables) {
2555 $dbName = self
::getDBName();
2557 SELECT TABLE_NAME as tableName
2558 FROM INFORMATION_SCHEMA.TABLES
2559 WHERE TABLE_SCHEMA = '{$dbName}'
2560 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2563 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2564 while ($tableDAO->fetch()) {
2565 $sql = "DROP TABLE {$tableDAO->tableName}";
2566 CRM_Core_DAO
::executeQuery($sql);
2572 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2574 public function quickCleanUpFinancialEntities() {
2575 $tablesToTruncate = array(
2577 'civicrm_activity_contact',
2578 'civicrm_contribution',
2579 'civicrm_contribution_soft',
2580 'civicrm_contribution_product',
2581 'civicrm_financial_trxn',
2582 'civicrm_financial_item',
2583 'civicrm_contribution_recur',
2584 'civicrm_line_item',
2585 'civicrm_contribution_page',
2586 'civicrm_payment_processor',
2587 'civicrm_entity_financial_trxn',
2588 'civicrm_membership',
2589 'civicrm_membership_type',
2590 'civicrm_membership_payment',
2591 'civicrm_membership_log',
2592 'civicrm_membership_block',
2594 'civicrm_participant',
2595 'civicrm_participant_payment',
2597 'civicrm_price_set_entity',
2598 'civicrm_price_field_value',
2599 'civicrm_price_field',
2601 $this->quickCleanup($tablesToTruncate);
2602 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2603 $this->restoreDefaultPriceSetConfig();
2605 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2606 Civi\Payment\System
::singleton()->flushProcessors();
2609 public function restoreDefaultPriceSetConfig() {
2610 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2611 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)");
2612 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)");
2615 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2616 * Default behaviour is to also delete the entity
2617 * @param array $params
2618 * Params array to check against.
2620 * Id of the entity concerned.
2621 * @param string $entity
2622 * Name of entity concerned (e.g. membership).
2623 * @param bool $delete
2624 * Should the entity be deleted as part of this check.
2625 * @param string $errorText
2626 * Text to print on error.
2629 * @param array $params
2632 * @param int $delete
2633 * @param string $errorText
2637 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2639 $result = $this->callAPISuccessGetSingle($entity, array(
2644 $this->callAPISuccess($entity, 'Delete', array(
2648 $dateFields = $keys = $dateTimeFields = array();
2649 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2650 foreach ($fields['values'] as $field => $settings) {
2651 if (array_key_exists($field, $result)) {
2652 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2655 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2657 $type = CRM_Utils_Array
::value('type', $settings);
2658 if ($type == CRM_Utils_Type
::T_DATE
) {
2659 $dateFields[] = $settings['name'];
2660 // we should identify both real names & unique names as dates
2661 if ($field != $settings['name']) {
2662 $dateFields[] = $field;
2665 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2666 $dateTimeFields[] = $settings['name'];
2667 // we should identify both real names & unique names as dates
2668 if ($field != $settings['name']) {
2669 $dateTimeFields[] = $field;
2674 if (strtolower($entity) == 'contribution') {
2675 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2676 // this is not returned in id format
2677 unset($params['payment_instrument_id']);
2678 $params['contribution_source'] = $params['source'];
2679 unset($params['source']);
2682 foreach ($params as $key => $value) {
2683 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2686 if (in_array($key, $dateFields)) {
2687 $value = date('Y-m-d', strtotime($value));
2688 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2690 if (in_array($key, $dateTimeFields)) {
2691 $value = date('Y-m-d H:i:s', strtotime($value));
2692 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2694 $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);
2699 * Get formatted values in the actual and expected result.
2700 * @param array $actual
2701 * Actual calculated values.
2702 * @param array $expected
2705 public function checkArrayEquals(&$actual, &$expected) {
2706 self
::unsetId($actual);
2707 self
::unsetId($expected);
2708 $this->assertEquals($actual, $expected);
2712 * Unset the key 'id' from the array
2713 * @param array $unformattedArray
2714 * The array from which the 'id' has to be unset.
2716 public static function unsetId(&$unformattedArray) {
2717 $formattedArray = array();
2718 if (array_key_exists('id', $unformattedArray)) {
2719 unset($unformattedArray['id']);
2721 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2722 foreach ($unformattedArray['values'] as $key => $value) {
2723 if (is_array($value)) {
2724 foreach ($value as $k => $v) {
2730 elseif ($key == 'id') {
2731 $unformattedArray[$key];
2733 $formattedArray = array($value);
2735 $unformattedArray['values'] = $formattedArray;
2740 * Helper to enable/disable custom directory support
2742 * @param array $customDirs
2744 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2745 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2747 public function customDirectories($customDirs) {
2748 require_once 'CRM/Core/Config.php';
2749 $config = CRM_Core_Config
::singleton();
2751 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2752 unset($config->customPHPPathDir
);
2754 elseif ($customDirs['php_path'] === TRUE) {
2755 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2758 $config->customPHPPathDir
= $php_path;
2761 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2762 unset($config->customTemplateDir
);
2764 elseif ($customDirs['template_path'] === TRUE) {
2765 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2768 $config->customTemplateDir
= $template_path;
2773 * Generate a temporary folder.
2775 * @param string $prefix
2778 public function createTempDir($prefix = 'test-') {
2779 $tempDir = CRM_Utils_File
::tempdir($prefix);
2780 $this->tempDirs
[] = $tempDir;
2784 public function cleanTempDirs() {
2785 if (!is_array($this->tempDirs
)) {
2786 // fix test errors where this is not set
2789 foreach ($this->tempDirs
as $tempDir) {
2790 if (is_dir($tempDir)) {
2791 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2797 * Temporarily replace the singleton extension with a different one.
2798 * @param \CRM_Extension_System $system
2800 public function setExtensionSystem(CRM_Extension_System
$system) {
2801 if ($this->origExtensionSystem
== NULL) {
2802 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2804 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2807 public function unsetExtensionSystem() {
2808 if ($this->origExtensionSystem
!== NULL) {
2809 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2810 $this->origExtensionSystem
= NULL;
2815 * Temporarily alter the settings-metadata to add a mock setting.
2817 * WARNING: The setting metadata will disappear on the next cache-clear.
2822 public function setMockSettingsMetaData($extras) {
2823 Civi
::service('settings_manager')->flush();
2825 CRM_Utils_Hook
::singleton()
2826 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2827 $metadata = array_merge($metadata, $extras);
2830 $fields = $this->callAPISuccess('setting', 'getfields', array());
2831 foreach ($extras as $key => $spec) {
2832 $this->assertNotEmpty($spec['title']);
2833 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2838 * @param string $name
2840 public function financialAccountDelete($name) {
2841 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2842 $financialAccount->name
= $name;
2843 if ($financialAccount->find(TRUE)) {
2844 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2845 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2846 $entityFinancialType->delete();
2847 $financialAccount->delete();
2852 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2853 * (NB unclear if this is still required)
2855 public function _sethtmlGlobals() {
2856 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2857 'required' => array(
2858 'html_quickform_rule_required',
2859 'HTML/QuickForm/Rule/Required.php',
2861 'maxlength' => array(
2862 'html_quickform_rule_range',
2863 'HTML/QuickForm/Rule/Range.php',
2865 'minlength' => array(
2866 'html_quickform_rule_range',
2867 'HTML/QuickForm/Rule/Range.php',
2869 'rangelength' => array(
2870 'html_quickform_rule_range',
2871 'HTML/QuickForm/Rule/Range.php',
2874 'html_quickform_rule_email',
2875 'HTML/QuickForm/Rule/Email.php',
2878 'html_quickform_rule_regex',
2879 'HTML/QuickForm/Rule/Regex.php',
2881 'lettersonly' => array(
2882 'html_quickform_rule_regex',
2883 'HTML/QuickForm/Rule/Regex.php',
2885 'alphanumeric' => array(
2886 'html_quickform_rule_regex',
2887 'HTML/QuickForm/Rule/Regex.php',
2890 'html_quickform_rule_regex',
2891 'HTML/QuickForm/Rule/Regex.php',
2893 'nopunctuation' => array(
2894 'html_quickform_rule_regex',
2895 'HTML/QuickForm/Rule/Regex.php',
2898 'html_quickform_rule_regex',
2899 'HTML/QuickForm/Rule/Regex.php',
2901 'callback' => array(
2902 'html_quickform_rule_callback',
2903 'HTML/QuickForm/Rule/Callback.php',
2906 'html_quickform_rule_compare',
2907 'HTML/QuickForm/Rule/Compare.php',
2910 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2911 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2913 'HTML/QuickForm/group.php',
2914 'HTML_QuickForm_group',
2917 'HTML/QuickForm/hidden.php',
2918 'HTML_QuickForm_hidden',
2921 'HTML/QuickForm/reset.php',
2922 'HTML_QuickForm_reset',
2924 'checkbox' => array(
2925 'HTML/QuickForm/checkbox.php',
2926 'HTML_QuickForm_checkbox',
2929 'HTML/QuickForm/file.php',
2930 'HTML_QuickForm_file',
2933 'HTML/QuickForm/image.php',
2934 'HTML_QuickForm_image',
2936 'password' => array(
2937 'HTML/QuickForm/password.php',
2938 'HTML_QuickForm_password',
2941 'HTML/QuickForm/radio.php',
2942 'HTML_QuickForm_radio',
2945 'HTML/QuickForm/button.php',
2946 'HTML_QuickForm_button',
2949 'HTML/QuickForm/submit.php',
2950 'HTML_QuickForm_submit',
2953 'HTML/QuickForm/select.php',
2954 'HTML_QuickForm_select',
2956 'hiddenselect' => array(
2957 'HTML/QuickForm/hiddenselect.php',
2958 'HTML_QuickForm_hiddenselect',
2961 'HTML/QuickForm/text.php',
2962 'HTML_QuickForm_text',
2964 'textarea' => array(
2965 'HTML/QuickForm/textarea.php',
2966 'HTML_QuickForm_textarea',
2968 'fckeditor' => array(
2969 'HTML/QuickForm/fckeditor.php',
2970 'HTML_QuickForm_FCKEditor',
2973 'HTML/QuickForm/tinymce.php',
2974 'HTML_QuickForm_TinyMCE',
2976 'dojoeditor' => array(
2977 'HTML/QuickForm/dojoeditor.php',
2978 'HTML_QuickForm_dojoeditor',
2981 'HTML/QuickForm/link.php',
2982 'HTML_QuickForm_link',
2984 'advcheckbox' => array(
2985 'HTML/QuickForm/advcheckbox.php',
2986 'HTML_QuickForm_advcheckbox',
2989 'HTML/QuickForm/date.php',
2990 'HTML_QuickForm_date',
2993 'HTML/QuickForm/static.php',
2994 'HTML_QuickForm_static',
2997 'HTML/QuickForm/header.php',
2998 'HTML_QuickForm_header',
3001 'HTML/QuickForm/html.php',
3002 'HTML_QuickForm_html',
3004 'hierselect' => array(
3005 'HTML/QuickForm/hierselect.php',
3006 'HTML_QuickForm_hierselect',
3008 'autocomplete' => array(
3009 'HTML/QuickForm/autocomplete.php',
3010 'HTML_QuickForm_autocomplete',
3013 'HTML/QuickForm/xbutton.php',
3014 'HTML_QuickForm_xbutton',
3016 'advmultiselect' => array(
3017 'HTML/QuickForm/advmultiselect.php',
3018 'HTML_QuickForm_advmultiselect',
3024 * Set up an acl allowing contact to see 2 specified groups
3025 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3027 * You need to have pre-created these groups & created the user e.g
3028 * $this->createLoggedInUser();
3029 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3030 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3032 * @param bool $isProfile
3034 public function setupACL($isProfile = FALSE) {
3036 $_REQUEST = $this->_params
;
3038 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3039 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3040 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3041 'option_group_id' => $optionGroupID,
3042 'label' => 'pick me',
3046 CRM_Core_DAO
::executeQuery("
3047 TRUNCATE civicrm_acl_cache
3050 CRM_Core_DAO
::executeQuery("
3051 TRUNCATE civicrm_acl_contact_cache
3054 CRM_Core_DAO
::executeQuery("
3055 INSERT INTO civicrm_acl_entity_role (
3056 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3057 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3061 CRM_Core_DAO
::executeQuery("
3062 INSERT INTO civicrm_acl (
3063 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3066 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3071 CRM_Core_DAO
::executeQuery("
3072 INSERT INTO civicrm_acl (
3073 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3076 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3080 CRM_Core_DAO
::executeQuery("
3081 INSERT INTO civicrm_acl (
3082 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3085 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3090 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3091 $this->callAPISuccess('group_contact', 'create', array(
3092 'group_id' => $this->_permissionedGroup
,
3093 'contact_id' => $this->_loggedInUser
,
3098 CRM_ACL_BAO_Cache
::resetCache();
3099 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3100 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3105 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3107 public function offsetDefaultPriceSet() {
3108 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3109 $firstID = $contributionPriceSet['id'];
3110 $this->callAPISuccess('price_set', 'create', array(
3111 'id' => $contributionPriceSet['id'],
3115 unset($contributionPriceSet['id']);
3116 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3117 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3118 'price_set_id' => $firstID,
3119 'options' => array('limit' => 1),
3121 unset($priceField['id']);
3122 $priceField['price_set_id'] = $newPriceSet['id'];
3123 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3124 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3125 'price_set_id' => $firstID,
3127 'options' => array('limit' => 1),
3130 unset($priceFieldValue['id']);
3131 //create some padding to use up ids
3132 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3133 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3134 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3138 * Create an instance of the paypal processor.
3139 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3140 * this parent class & we don't have a structure for that yet
3141 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3142 * & the best protection against that is the functions this class affords
3143 * @param array $params
3144 * @return int $result['id'] payment processor id
3146 public function paymentProcessorCreate($params = array()) {
3147 $params = array_merge(array(
3149 'domain_id' => CRM_Core_Config
::domainID(),
3150 'payment_processor_type_id' => 'PayPal',
3154 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3155 'password' => '1183377788',
3156 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3157 'url_site' => 'https://www.sandbox.paypal.com/',
3158 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3159 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3160 'class_name' => 'Payment_PayPalImpl',
3161 'billing_mode' => 3,
3162 'financial_type_id' => 1,
3165 if (!is_numeric($params['payment_processor_type_id'])) {
3166 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3168 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3169 'name' => $params['payment_processor_type_id'],
3173 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3174 return $result['id'];
3178 * Set up initial recurring payment allowing subsequent IPN payments.
3180 public function setupRecurringPaymentProcessorTransaction() {
3181 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3182 'contact_id' => $this->_contactID
,
3185 'installments' => 5,
3186 'frequency_unit' => 'Month',
3187 'frequency_interval' => 1,
3188 'invoice_id' => $this->_invoiceID
,
3189 'contribution_status_id' => 2,
3190 'processor_id' => $this->_paymentProcessorID
,
3191 'api.contribution.create' => array(
3192 'total_amount' => '200',
3193 'invoice_id' => $this->_invoiceID
,
3194 'financial_type_id' => 1,
3195 'contribution_status_id' => 'Pending',
3196 'contact_id' => $this->_contactID
,
3197 'contribution_page_id' => $this->_contributionPageID
,
3198 'payment_processor_id' => $this->_paymentProcessorID
,
3202 $this->_contributionRecurID
= $contributionRecur['id'];
3203 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3207 * 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
3209 public function setupMembershipRecurringPaymentProcessorTransaction() {
3210 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3211 //create a contribution so our membership & contribution don't both have id = 1
3212 $this->contributionCreate(array(
3213 'contact_id' => $this->_contactID
,
3215 'financial_type_id' => 1,
3216 'invoice_id' => 'abcd',
3219 $this->setupRecurringPaymentProcessorTransaction();
3221 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3222 'contact_id' => $this->_contactID
,
3223 'membership_type_id' => $this->ids
['membership_type'],
3224 'contribution_recur_id' => $this->_contributionRecurID
,
3225 'format.only_id' => TRUE,
3227 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3228 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3230 $this->callAPISuccess('line_item', 'create', array(
3231 'entity_table' => 'civicrm_membership',
3232 'entity_id' => $this->ids
['membership'],
3233 'contribution_id' => $this->_contributionID
,
3234 'label' => 'General',
3236 'unit_price' => 200,
3237 'line_total' => 200,
3238 'financial_type_id' => 1,
3239 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3241 'label' => 'Membership Amount',
3243 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3245 'label' => 'General',
3248 $this->callAPISuccess('membership_payment', 'create', array(
3249 'contribution_id' => $this->_contributionID
,
3250 'membership_id' => $this->ids
['membership'],
3259 public function CiviUnitTestCase_fatalErrorHandler($message) {
3260 throw new Exception("{$message['message']}: {$message['code']}");
3264 * Helper function to create new mailing.
3267 public function createMailing() {
3269 'subject' => 'maild' . rand(),
3270 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3271 'name' => 'mailing name' . rand(),
3275 $result = $this->callAPISuccess('Mailing', 'create', $params);
3276 return $result['id'];
3280 * Helper function to delete mailing.
3283 public function deleteMailing($id) {
3288 $this->callAPISuccess('Mailing', 'delete', $params);
3292 * Wrap the entire test case in a transaction.
3294 * Only subsequent DB statements will be wrapped in TX -- this cannot
3295 * retroactively wrap old DB statements. Therefore, it makes sense to
3296 * call this at the beginning of setUp().
3298 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3299 * this option does not work with, e.g., custom-data.
3301 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3302 * if TRUNCATE or ALTER is called while using a transaction.
3305 * Whether to use nesting or reference-counting.
3307 public function useTransaction($nest = TRUE) {
3309 $this->tx
= new CRM_Core_Transaction($nest);
3310 $this->tx
->rollback();
3314 public function clearOutputBuffer() {
3315 while (ob_get_level() > 0) {
3321 * Assert the attachment exists.
3323 * @param bool $exists
3324 * @param array $apiResult
3326 protected function assertAttachmentExistence($exists, $apiResult) {
3327 $fileId = $apiResult['id'];
3328 $this->assertTrue(is_numeric($fileId));
3329 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3330 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3331 1 => array($fileId, 'Int'),
3333 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3334 1 => array($fileId, 'Int'),
3339 * Create a price set for an event.
3341 * @param int $feeTotal
3346 protected function eventPriceSetCreate($feeTotal) {
3347 // creating price set, price field
3348 $paramsSet['title'] = 'Price Set';
3349 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3350 $paramsSet['is_active'] = FALSE;
3351 $paramsSet['extends'] = 1;
3353 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3354 $priceSetId = $priceset->id
;
3356 //Checking for priceset added in the table.
3357 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3358 'id', $paramsSet['title'], 'Check DB for created priceset'
3360 $paramsField = array(
3361 'label' => 'Price Field',
3362 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3363 'html_type' => 'Text',
3364 'price' => $feeTotal,
3365 'option_label' => array('1' => 'Price Field'),
3366 'option_value' => array('1' => $feeTotal),
3367 'option_name' => array('1' => $feeTotal),
3368 'option_weight' => array('1' => 1),
3369 'option_amount' => array('1' => 1),
3370 'is_display_amounts' => 1,
3372 'options_per_line' => 1,
3373 'is_active' => array('1' => 1),
3374 'price_set_id' => $priceset->id
,
3375 'is_enter_qty' => 1,
3376 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3378 CRM_Price_BAO_PriceField
::create($paramsField);