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 // initialize the object once db is loaded
400 CRM_Core_Config
::$_mail = NULL;
401 $config = CRM_Core_Config
::singleton();
403 // when running unit tests, use mockup user framework
404 $config->setUserFramework('UnitTests');
405 $this->hookClass
= CRM_Utils_Hook
::singleton(TRUE);
406 // also fix the fatal error handler to throw exceptions,
408 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
410 // enable backtrace to get meaningful errors
411 $config->backtrace
= 1;
413 // disable any left-over test extensions
414 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
416 // reset all the caches
417 CRM_Utils_System
::flushCache();
419 // Make sure the DB connection is setup properly
420 $config->userSystem
->setMySQLTimeZone();
421 $env = new CRM_Utils_Check_Env();
422 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
424 // clear permissions stub to not check permissions
425 $config = CRM_Core_Config
::singleton();
426 $config->userPermissionClass
->permissions
= NULL;
428 //flush component settings
429 CRM_Core_Component
::getEnabledComponents(TRUE);
431 error_reporting(E_ALL
);
433 $this->_sethtmlGlobals();
437 * Read everything from the datasets directory and insert into the db.
439 public function loadAllFixtures() {
440 $fixturesDir = __DIR__
. '/../../fixtures';
442 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
444 $xmlFiles = glob($fixturesDir . '/*.xml');
445 foreach ($xmlFiles as $xmlFixture) {
446 $op = new PHPUnit_Extensions_Database_Operation_Insert();
447 $dataset = $this->createXMLDataSet($xmlFixture);
448 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
449 $op->execute($this->_dbconn
, $dataset);
452 $yamlFiles = glob($fixturesDir . '/*.yaml');
453 foreach ($yamlFiles as $yamlFixture) {
454 $op = new PHPUnit_Extensions_Database_Operation_Insert();
455 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
456 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
457 $op->execute($this->_dbconn
, $dataset);
460 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
464 * Emulate a logged in user since certain functions use that.
465 * value to store a record in the DB (like activity)
469 * Contact ID of the created user.
471 public function createLoggedInUser() {
473 'first_name' => 'Logged In',
474 'last_name' => 'User ' . rand(),
475 'contact_type' => 'Individual',
477 $contactID = $this->individualCreate($params);
478 $this->callAPISuccess('UFMatch', 'create', array(
479 'contact_id' => $contactID,
480 'uf_name' => 'superman',
484 $session = CRM_Core_Session
::singleton();
485 $session->set('userID', $contactID);
489 public function cleanDB() {
490 self
::$populateOnce = NULL;
491 $this->DBResetRequired
= TRUE;
493 $this->_dbconn
= $this->getConnection();
494 static::_populateDB();
495 $this->tempDirs
= array();
499 * Create default domain contacts for the two domains added during test class.
500 * database population.
502 public function createDomainContacts() {
503 $default_domain_contact = $this->organizationCreate();
504 $second_domain_contact = $this->organizationCreate();
508 * Common teardown functions for all unit tests.
510 protected function tearDown() {
511 error_reporting(E_ALL
& ~E_NOTICE
);
512 CRM_Utils_Hook
::singleton()->reset();
513 $this->hookClass
->reset();
514 $session = CRM_Core_Session
::singleton();
515 $session->set('userID', NULL);
518 $this->tx
->rollback()->commit();
521 CRM_Core_Transaction
::forceRollbackIfEnabled();
522 \Civi\Core\Transaction\Manager
::singleton(TRUE);
525 CRM_Core_Transaction
::forceRollbackIfEnabled();
526 \Civi\Core\Transaction\Manager
::singleton(TRUE);
528 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
529 $this->quickCleanup($tablesToTruncate);
530 $this->createDomainContacts();
533 $this->cleanTempDirs();
534 $this->unsetExtensionSystem();
535 $this->clearOutputBuffer();
539 * FIXME: Maybe a better way to do it
541 public function foreignKeyChecksOff() {
542 self
::$utils = new Utils($GLOBALS['mysql_host'],
543 $GLOBALS['mysql_port'],
544 $GLOBALS['mysql_user'],
545 $GLOBALS['mysql_pass']
547 $dbName = self
::getDBName();
548 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
549 if (self
::$utils->do_query($query) === FALSE) {
551 echo 'Cannot set foreign_key_checks = 0';
557 public function foreignKeyChecksOn() {
558 // FIXME: might not be needed if previous fixme implemented
562 * Generic function to compare expected values after an api call to retrieved.
565 * @daoName string DAO Name of object we're evaluating.
566 * @id int Id of object
567 * @match array Associative array of field name => expected value. Empty if asserting
568 * that a DELETE occurred
569 * @delete boolean True if we're checking that a DELETE action occurred.
573 * @param bool $delete
574 * @throws \PHPUnit_Framework_AssertionFailedError
576 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
578 // adding this here since developers forget to check for an id
579 // and hence we get the first value in the db
580 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
583 $object = new $daoName();
587 // If we're asserting successful record deletion, make sure object is NOT found.
589 if ($object->find(TRUE)) {
590 $this->fail("Object not deleted by delete operation: $daoName, $id");
595 // Otherwise check matches of DAO field values against expected values in $match.
596 if ($object->find(TRUE)) {
597 $fields = &$object->fields();
598 foreach ($fields as $name => $value) {
599 $dbName = $value['name'];
600 if (isset($match[$name])) {
602 $this->assertEquals($object->$dbName, $match[$name]);
604 elseif (isset($match[$dbName])) {
606 $this->assertEquals($object->$dbName, $match[$dbName]);
611 $this->fail("Could not retrieve object: $daoName, $id");
614 $matchSize = count($match);
615 if ($verifiedCount != $matchSize) {
616 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
621 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
622 * @param string $daoName
623 * @param $searchValue
624 * @param $returnColumn
625 * @param $searchColumn
628 * @return null|string
629 * @throws PHPUnit_Framework_AssertionFailedError
631 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
632 if (empty($searchValue)) {
633 $this->fail("empty value passed to assertDBNotNull");
635 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
636 $this->assertNotNull($value, $message);
642 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
643 * @param string $daoName
644 * @param $searchValue
645 * @param $returnColumn
646 * @param $searchColumn
649 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
650 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
651 $this->assertNull($value, $message);
655 * Request a record from the DB by id. Success if row not found.
656 * @param string $daoName
658 * @param null $message
660 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
661 $message = $message ?
$message : "$daoName (#$id) should not exist";
662 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
663 $this->assertNull($value, $message);
667 * Request a record from the DB by id. Success if row not found.
668 * @param string $daoName
670 * @param null $message
672 public function assertDBRowExist($daoName, $id, $message = NULL) {
673 $message = $message ?
$message : "$daoName (#$id) should exist";
674 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
675 $this->assertEquals($id, $value, $message);
679 * Compare a single column value in a retrieved DB record to an expected value.
680 * @param string $daoName
681 * @param $searchValue
682 * @param $returnColumn
683 * @param $searchColumn
684 * @param $expectedValue
687 public function assertDBCompareValue(
688 $daoName, $searchValue, $returnColumn, $searchColumn,
689 $expectedValue, $message
691 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
692 $this->assertEquals($value, $expectedValue, $message);
696 * Compare all values in a single retrieved DB record to an array of expected values.
697 * @param string $daoName
698 * @param array $searchParams
699 * @param $expectedValues
701 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
702 //get the values from db
704 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
706 // compare db values with expected values
707 self
::assertAttributesEquals($expectedValues, $dbValues);
711 * Assert that a SQL query returns a given value.
713 * The first argument is an expected value. The remaining arguments are passed
714 * to CRM_Core_DAO::singleValueQuery
716 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
717 * array(1 => array("Whiz", "String")));
720 * @param array $params
721 * @param string $message
723 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
727 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
728 $this->assertEquals($expected, $actual,
729 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
730 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
736 * Assert that two array-trees are exactly equal, notwithstanding
737 * the sorting of keys
739 * @param array $expected
740 * @param array $actual
742 public function assertTreeEquals($expected, $actual) {
745 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
746 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
750 $this->assertEquals($e, $a);
754 * Assert that two numbers are approximately equal.
756 * @param int|float $expected
757 * @param int|float $actual
758 * @param int|float $tolerance
759 * @param string $message
761 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
762 if ($message === NULL) {
763 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
765 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
769 * Assert attributes are equal.
771 * @param $expectedValues
772 * @param $actualValues
773 * @param string $message
775 * @throws PHPUnit_Framework_AssertionFailedError
777 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
778 foreach ($expectedValues as $paramName => $paramValue) {
779 if (isset($actualValues[$paramName])) {
780 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
783 $this->fail("Attribute '$paramName' not present in actual array.");
792 public function assertArrayKeyExists($key, &$list) {
793 $result = isset($list[$key]) ?
TRUE : FALSE;
794 $this->assertTrue($result, ts("%1 element exists?",
803 public function assertArrayValueNotNull($key, &$list) {
804 $this->assertArrayKeyExists($key, $list);
806 $value = isset($list[$key]) ?
$list[$key] : NULL;
807 $this->assertTrue($value,
808 ts("%1 element not null?",
815 * Check that api returned 'is_error' => 0.
817 * @param array $apiResult
819 * @param string $prefix
820 * Extra test to add to message.
822 public function assertAPISuccess($apiResult, $prefix = '') {
823 if (!empty($prefix)) {
826 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
828 if (!empty($apiResult['debug_information'])) {
829 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
831 if (!empty($apiResult['trace'])) {
832 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
834 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
838 * Check that api returned 'is_error' => 1.
840 * @param array $apiResult
842 * @param string $prefix
843 * Extra test to add to message.
844 * @param null $expectedError
846 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
847 if (!empty($prefix)) {
850 if ($expectedError && !empty($apiResult['is_error'])) {
851 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
853 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
854 $this->assertNotEmpty($apiResult['error_message']);
860 * @param string $message
862 public function assertType($expected, $actual, $message = '') {
863 return $this->assertInternalType($expected, $actual, $message);
867 * Check that a deleted item has been deleted.
872 public function assertAPIDeleted($entity, $id) {
873 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
878 * Check that api returned 'is_error' => 1
879 * else provide full message
880 * @param array $result
882 * @param array $valuesToExclude
883 * @param string $prefix
884 * Extra test to add to message.
886 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
887 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
888 foreach ($valuesToExclude as $value) {
889 if (isset($result[$value])) {
890 unset($result[$value]);
892 if (isset($expected[$value])) {
893 unset($expected[$value]);
896 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
900 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
904 * @param array $params
907 public function civicrm_api($entity, $action, $params) {
908 return civicrm_api($entity, $action, $params);
912 * Create a batch of external API calls which can
913 * be executed concurrently.
916 * $calls = $this->createExternalAPI()
917 * ->addCall('Contact', 'get', ...)
918 * ->addCall('Contact', 'get', ...)
924 * @return \Civi\API\ExternalBatch
925 * @throws PHPUnit_Framework_SkippedTestError
927 public function createExternalAPI() {
928 global $civicrm_root;
929 $defaultParams = array(
930 'version' => $this->_apiversion
,
934 $calls = new \Civi\API\
ExternalBatch($defaultParams);
935 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
937 if (!$calls->isSupported()) {
938 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
945 * wrap api functions.
946 * so we can ensure they succeed & throw exceptions without litterering the test with checks
948 * @param string $entity
949 * @param string $action
950 * @param array $params
951 * @param mixed $checkAgainst
952 * Optional value to check result against, implemented for getvalue,.
953 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
954 * for getsingle the array is compared against an array passed in - the id is not compared (for
959 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
960 $params = array_merge(array(
961 'version' => $this->_apiversion
,
966 switch (strtolower($action)) {
968 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
971 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
974 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
976 $result = $this->civicrm_api($entity, $action, $params);
977 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
982 * This function exists to wrap api getValue function & check the result
983 * so we can ensure they succeed & throw exceptions without litterering the test with checks
984 * There is a type check in this
986 * @param string $entity
987 * @param array $params
988 * @param string $type
989 * Per http://php.net/manual/en/function.gettype.php possible types.
999 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
1001 'version' => $this->_apiversion
,
1004 $result = $this->civicrm_api($entity, 'getvalue', $params);
1006 if ($type == 'integer') {
1007 // api seems to return integers as strings
1008 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
1011 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1018 * This function exists to wrap api getsingle function & check the result
1019 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1021 * @param string $entity
1022 * @param array $params
1023 * @param array $checkAgainst
1024 * Array to compare result against.
1035 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1037 'version' => $this->_apiversion
,
1040 $result = $this->civicrm_api($entity, 'getsingle', $params);
1041 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1042 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1044 if ($checkAgainst) {
1045 // @todo - have gone with the fn that unsets id? should we check id?
1046 $this->checkArrayEquals($result, $checkAgainst);
1052 * This function exists to wrap api getValue function & check the result
1053 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1054 * There is a type check in this
1055 * @param string $entity
1056 * @param array $params
1057 * @param null $count
1061 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1063 'version' => $this->_apiversion
,
1066 $result = $this->civicrm_api($entity, 'getcount', $params);
1067 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1068 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1070 if (is_int($count)) {
1071 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1077 * This function exists to wrap api functions.
1078 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1080 * @param string $entity
1081 * @param string $action
1082 * @param array $params
1083 * @param string $function
1084 * Pass this in to create a generated example.
1085 * @param string $file
1086 * Pass this in to create a generated example.
1087 * @param string $description
1088 * @param string|null $exampleName
1092 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1093 $params['version'] = $this->_apiversion
;
1094 $result = $this->callAPISuccess($entity, $action, $params);
1095 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1100 * This function exists to wrap api functions.
1101 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1102 * @param string $entity
1103 * @param string $action
1104 * @param array $params
1105 * @param string $expectedErrorMessage
1107 * @param null $extraOutput
1110 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1111 if (is_array($params)) {
1113 'version' => $this->_apiversion
,
1116 $result = $this->civicrm_api($entity, $action, $params);
1117 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1122 * Create required data based on $this->entity & $this->params
1123 * This is just a way to set up the test data for delete & get functions
1124 * so the distinction between set
1125 * up & tested functions is clearer
1130 public function createTestEntity() {
1131 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1135 * Generic function to create Organisation, to be used in test cases
1137 * @param array $params
1138 * parameters for civicrm_contact_add api function call
1140 * sequence number if creating multiple organizations
1143 * id of Organisation created
1145 public function organizationCreate($params = array(), $seq = 0) {
1149 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1150 return $this->_contactCreate($params);
1154 * Generic function to create Individual, to be used in test cases
1156 * @param array $params
1157 * parameters for civicrm_contact_add api function call
1159 * sequence number if creating multiple individuals
1162 * id of Individual created
1164 public function individualCreate($params = array(), $seq = 0) {
1165 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1166 return $this->_contactCreate($params);
1170 * Generic function to create Household, to be used in test cases
1172 * @param array $params
1173 * parameters for civicrm_contact_add api function call
1175 * sequence number if creating multiple households
1178 * id of Household created
1180 public function householdCreate($params = array(), $seq = 0) {
1181 $params = array_merge($this->sampleContact('Household', $seq), $params);
1182 return $this->_contactCreate($params);
1186 * Helper function for getting sample contact properties.
1188 * @param string $contact_type
1189 * enum contact type: Individual, Organization
1191 * sequence number for the values of this type
1194 * properties of sample contact (ie. $params for API call)
1196 public function sampleContact($contact_type, $seq = 0) {
1198 'Individual' => array(
1199 // The number of values in each list need to be coprime numbers to not have duplicates
1200 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1201 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1202 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1204 'Organization' => array(
1205 'organization_name' => array(
1206 'Unit Test Organization',
1213 'Household' => array(
1214 'household_name' => array('Unit Test household'),
1217 $params = array('contact_type' => $contact_type);
1218 foreach ($samples[$contact_type] as $key => $values) {
1219 $params[$key] = $values[$seq %
count($values)];
1221 if ($contact_type == 'Individual') {
1222 $params['email'] = strtolower(
1223 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1225 $params['prefix_id'] = 3;
1226 $params['suffix_id'] = 3;
1232 * Private helper function for calling civicrm_contact_add.
1234 * @param array $params
1235 * For civicrm_contact_add api function call.
1240 * id of Household created
1242 private function _contactCreate($params) {
1243 $result = $this->callAPISuccess('contact', 'create', $params);
1244 if (!empty($result['is_error']) ||
empty($result['id'])) {
1245 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1247 return $result['id'];
1251 * Delete contact, ensuring it is not the domain contact
1253 * @param int $contactID
1254 * Contact ID to delete
1256 public function contactDelete($contactID) {
1257 $domain = new CRM_Core_BAO_Domain();
1258 $domain->contact_id
= $contactID;
1259 if (!$domain->find(TRUE)) {
1260 $this->callAPISuccess('contact', 'delete', array(
1262 'skip_undelete' => 1,
1268 * @param int $contactTypeId
1272 public function contactTypeDelete($contactTypeId) {
1273 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1275 throw new Exception('Could not delete contact type');
1280 * @param array $params
1284 public function membershipTypeCreate($params = array()) {
1285 CRM_Member_PseudoConstant
::flush('membershipType');
1286 CRM_Core_Config
::clearDBCache();
1287 $memberOfOrganization = $this->organizationCreate();
1288 $params = array_merge(array(
1289 'name' => 'General',
1290 'duration_unit' => 'year',
1291 'duration_interval' => 1,
1292 'period_type' => 'rolling',
1293 'member_of_contact_id' => $memberOfOrganization,
1295 'financial_type_id' => 1,
1298 'visibility' => 'Public',
1301 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1303 CRM_Member_PseudoConstant
::flush('membershipType');
1304 CRM_Utils_Cache
::singleton()->flush();
1306 return $result['id'];
1310 * @param array $params
1314 public function contactMembershipCreate($params) {
1316 'join_date' => '2007-01-21',
1317 'start_date' => '2007-01-21',
1318 'end_date' => '2007-12-21',
1319 'source' => 'Payment',
1322 foreach ($pre as $key => $val) {
1323 if (!isset($params[$key])) {
1324 $params[$key] = $val;
1328 $result = $this->callAPISuccess('Membership', 'create', $params);
1329 return $result['id'];
1333 * Delete Membership Type.
1335 * @param array $params
1337 public function membershipTypeDelete($params) {
1338 $this->callAPISuccess('MembershipType', 'Delete', $params);
1342 * @param int $membershipID
1344 public function membershipDelete($membershipID) {
1345 $deleteParams = array('id' => $membershipID);
1346 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1350 * @param string $name
1354 public function membershipStatusCreate($name = 'test member status') {
1355 $params['name'] = $name;
1356 $params['start_event'] = 'start_date';
1357 $params['end_event'] = 'end_date';
1358 $params['is_current_member'] = 1;
1359 $params['is_active'] = 1;
1361 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1362 CRM_Member_PseudoConstant
::flush('membershipStatus');
1363 return $result['id'];
1367 * @param int $membershipStatusID
1369 public function membershipStatusDelete($membershipStatusID) {
1370 if (!$membershipStatusID) {
1373 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1377 * @param array $params
1381 public function relationshipTypeCreate($params = array()) {
1382 $params = array_merge(array(
1383 'name_a_b' => 'Relation 1 for relationship type create',
1384 'name_b_a' => 'Relation 2 for relationship type create',
1385 'contact_type_a' => 'Individual',
1386 'contact_type_b' => 'Organization',
1393 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1394 CRM_Core_PseudoConstant
::flush('relationshipType');
1396 return $result['id'];
1400 * Delete Relatinship Type.
1402 * @param int $relationshipTypeID
1404 public function relationshipTypeDelete($relationshipTypeID) {
1405 $params['id'] = $relationshipTypeID;
1406 $this->callAPISuccess('relationship_type', 'delete', $params);
1410 * @param array $params
1414 public function paymentProcessorTypeCreate($params = NULL) {
1415 if (is_null($params)) {
1417 'name' => 'API_Test_PP',
1418 'title' => 'API Test Payment Processor',
1419 'class_name' => 'CRM_Core_Payment_APITest',
1420 'billing_mode' => 'form',
1426 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1428 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1430 return $result['id'];
1434 * Create test Authorize.net instance.
1436 * @param array $params
1440 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1441 $params = array_merge(array(
1442 'name' => 'Authorize',
1443 'domain_id' => CRM_Core_Config
::domainID(),
1444 'payment_processor_type_id' => 'AuthNet',
1445 'title' => 'AuthNet',
1450 'user_name' => '4y5BfuW7jm',
1451 'password' => '4cAmW927n8uLf5J8',
1452 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1453 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1454 'class_name' => 'Payment_AuthorizeNet',
1455 'billing_mode' => 1,
1458 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1459 return $result['id'];
1463 * Create Participant.
1465 * @param array $params
1466 * Array of contact id and event id values.
1469 * $id of participant created
1471 public function participantCreate($params) {
1472 if (empty($params['contact_id'])) {
1473 $params['contact_id'] = $this->individualCreate();
1475 if (empty($params['event_id'])) {
1476 $event = $this->eventCreate();
1477 $params['event_id'] = $event['id'];
1482 'register_date' => 20070219,
1483 'source' => 'Wimbeldon',
1484 'event_level' => 'Payment',
1488 $params = array_merge($defaults, $params);
1489 $result = $this->callAPISuccess('Participant', 'create', $params);
1490 return $result['id'];
1494 * Create Payment Processor.
1496 * @return CRM_Financial_DAO_PaymentProcessor
1497 * instance of Payment Processsor
1499 public function processorCreate() {
1500 $processorParams = array(
1503 'payment_processor_type_id' => 10,
1504 'financial_account_id' => 12,
1508 'url_site' => 'http://dummy.com',
1509 'url_recur' => 'http://dummy.com',
1510 'billing_mode' => 1,
1512 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1513 return $paymentProcessor;
1517 * Create contribution page.
1519 * @param array $params
1521 * Array of contribution page
1523 public function contributionPageCreate($params) {
1524 $this->_pageParams
= array(
1525 'title' => 'Test Contribution Page',
1526 'financial_type_id' => 1,
1527 'currency' => 'USD',
1528 'financial_account_id' => 1,
1529 'payment_processor' => $params['processor_id'],
1531 'is_allow_other_amount' => 1,
1533 'max_amount' => 1000,
1535 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1536 return $contributionPage;
1542 * @param array $params
1544 * result of created tag
1546 public function tagCreate($params = array()) {
1548 'name' => 'New Tag3',
1549 'description' => 'This is description for Our New Tag ',
1552 $params = array_merge($defaults, $params);
1553 $result = $this->callAPISuccess('Tag', 'create', $params);
1554 return $result['values'][$result['id']];
1561 * Id of the tag to be deleted.
1565 public function tagDelete($tagId) {
1566 require_once 'api/api.php';
1570 $result = $this->callAPISuccess('Tag', 'delete', $params);
1571 return $result['id'];
1575 * Add entity(s) to the tag
1577 * @param array $params
1581 public function entityTagAdd($params) {
1582 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1587 * Create contribution.
1593 * id of created contribution
1595 public function pledgeCreate($cID) {
1597 'contact_id' => $cID,
1598 'pledge_create_date' => date('Ymd'),
1599 'start_date' => date('Ymd'),
1600 'scheduled_date' => date('Ymd'),
1602 'pledge_status_id' => '2',
1603 'financial_type_id' => '1',
1604 'pledge_original_installment_amount' => 20,
1605 'frequency_interval' => 5,
1606 'frequency_unit' => 'year',
1607 'frequency_day' => 15,
1608 'installments' => 5,
1611 $result = $this->callAPISuccess('Pledge', 'create', $params);
1612 return $result['id'];
1616 * Delete contribution.
1618 * @param int $pledgeId
1620 public function pledgeDelete($pledgeId) {
1622 'pledge_id' => $pledgeId,
1624 $this->callAPISuccess('Pledge', 'delete', $params);
1628 * Create contribution.
1630 * @param array $params
1631 * Array of parameters.
1632 * @param int $cTypeID
1633 * Id of financial type.
1634 * @param int $invoiceID
1635 * @param int $trxnID
1636 * @param int $paymentInstrumentID
1639 * id of created contribution
1641 public function contributionCreate($params, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345,
1642 $paymentInstrumentID = 1) {
1644 $params = array_merge(array(
1646 'receive_date' => date('Ymd'),
1647 'total_amount' => 100.00,
1648 'fee_amount' => 5.00,
1649 'net_ammount' => 95.00,
1650 'financial_type_id' => $cTypeID,
1651 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1652 'non_deductible_amount' => 10.00,
1653 'trxn_id' => $trxnID,
1654 'invoice_id' => $invoiceID,
1656 'contribution_status_id' => 1,
1659 $result = $this->callAPISuccess('contribution', 'create', $params);
1660 return $result['id'];
1664 * Create online contribution.
1666 * @param array $params
1667 * @param int $financialType
1668 * Id of financial type.
1669 * @param int $invoiceID
1670 * @param int $trxnID
1673 * id of created contribution
1675 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1676 $contribParams = array(
1677 'contact_id' => $params['contact_id'],
1678 'receive_date' => date('Ymd'),
1679 'total_amount' => 100.00,
1680 'financial_type_id' => $financialType,
1681 'contribution_page_id' => $params['contribution_page_id'],
1683 'invoice_id' => 67890,
1686 $contribParams = array_merge($contribParams, $params);
1687 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1689 return $result['id'];
1693 * Delete contribution.
1695 * @param int $contributionId
1699 public function contributionDelete($contributionId) {
1701 'contribution_id' => $contributionId,
1703 $result = $this->callAPISuccess('contribution', 'delete', $params);
1710 * @param array $params
1711 * Name-value pair for an event.
1715 public function eventCreate($params = array()) {
1716 // if no contact was passed, make up a dummy event creator
1717 if (!isset($params['contact_id'])) {
1718 $params['contact_id'] = $this->_contactCreate(array(
1719 'contact_type' => 'Individual',
1720 'first_name' => 'Event',
1721 'last_name' => 'Creator',
1725 // set defaults for missing params
1726 $params = array_merge(array(
1727 'title' => 'Annual CiviCRM meet',
1728 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1729 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1730 'event_type_id' => 1,
1732 'start_date' => 20081021,
1733 'end_date' => 20081023,
1734 'is_online_registration' => 1,
1735 'registration_start_date' => 20080601,
1736 'registration_end_date' => 20081015,
1737 'max_participants' => 100,
1738 'event_full_text' => 'Sorry! We are already full',
1741 'is_show_location' => 0,
1744 return $this->callAPISuccess('Event', 'create', $params);
1755 public function eventDelete($id) {
1759 return $this->callAPISuccess('event', 'delete', $params);
1763 * Delete participant.
1765 * @param int $participantID
1769 public function participantDelete($participantID) {
1771 'id' => $participantID,
1773 return $this->callAPISuccess('Participant', 'delete', $params);
1777 * Create participant payment.
1779 * @param int $participantID
1780 * @param int $contributionID
1782 * $id of created payment
1784 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1785 //Create Participant Payment record With Values
1787 'participant_id' => $participantID,
1788 'contribution_id' => $contributionID,
1791 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1792 return $result['id'];
1796 * Delete participant payment.
1798 * @param int $paymentID
1800 public function participantPaymentDelete($paymentID) {
1804 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1810 * @param int $contactID
1812 * location id of created location
1814 public function locationAdd($contactID) {
1817 'location_type' => 'New Location Type',
1819 'name' => 'Saint Helier St',
1820 'county' => 'Marin',
1821 'country' => 'UNITED STATES',
1822 'state_province' => 'Michigan',
1823 'supplemental_address_1' => 'Hallmark Ct',
1824 'supplemental_address_2' => 'Jersey Village',
1829 'contact_id' => $contactID,
1830 'address' => $address,
1831 'location_format' => '2.0',
1832 'location_type' => 'New Location Type',
1835 $result = $this->callAPISuccess('Location', 'create', $params);
1840 * Delete Locations of contact.
1842 * @param array $params
1845 public function locationDelete($params) {
1846 $this->callAPISuccess('Location', 'delete', $params);
1850 * Add a Location Type.
1852 * @param array $params
1853 * @return CRM_Core_DAO_LocationType
1854 * location id of created location
1856 public function locationTypeCreate($params = NULL) {
1857 if ($params === NULL) {
1859 'name' => 'New Location Type',
1860 'vcard_name' => 'New Location Type',
1861 'description' => 'Location Type for Delete',
1866 $locationType = new CRM_Core_DAO_LocationType();
1867 $locationType->copyValues($params);
1868 $locationType->save();
1869 // clear getfields cache
1870 CRM_Core_PseudoConstant
::flush();
1871 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1872 return $locationType;
1876 * Delete a Location Type.
1878 * @param int $locationTypeId
1880 public function locationTypeDelete($locationTypeId) {
1881 $locationType = new CRM_Core_DAO_LocationType();
1882 $locationType->id
= $locationTypeId;
1883 $locationType->delete();
1889 * @param array $params
1891 * groupId of created group
1893 public function groupCreate($params = array()) {
1894 $params = array_merge(array(
1895 'name' => 'Test Group 1',
1897 'title' => 'New Test Group Created',
1898 'description' => 'New Test Group Created',
1900 'visibility' => 'Public Pages',
1901 'group_type' => array(
1907 $result = $this->callAPISuccess('Group', 'create', $params);
1908 return $result['id'];
1913 * Function to add a Group.
1915 * @params array to add group
1917 * @param int $groupID
1918 * @param int $totalCount
1920 * groupId of created group
1922 public function groupContactCreate($groupID, $totalCount = 10) {
1923 $params = array('group_id' => $groupID);
1924 for ($i = 1; $i <= $totalCount; $i++
) {
1925 $contactID = $this->individualCreate();
1927 $params +
= array('contact_id' => $contactID);
1930 $params +
= array("contact_id.$i" => $contactID);
1933 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1943 public function groupDelete($gid) {
1949 $this->callAPISuccess('Group', 'delete', $params);
1954 * @param array $params
1956 public function uFFieldCreate($params = array()) {
1957 $params = array_merge(array(
1959 'field_name' => 'first_name',
1962 'visibility' => 'Public Pages and Listings',
1963 'is_searchable' => '1',
1964 'label' => 'first_name',
1965 'field_type' => 'Individual',
1968 $this->callAPISuccess('uf_field', 'create', $params);
1972 * Add a UF Join Entry.
1974 * @param array $params
1976 * $id of created UF Join
1978 public function ufjoinCreate($params = NULL) {
1979 if ($params === NULL) {
1982 'module' => 'CiviEvent',
1983 'entity_table' => 'civicrm_event',
1989 $result = $this->callAPISuccess('uf_join', 'create', $params);
1994 * Delete a UF Join Entry.
1996 * @param array $params
1997 * with missing uf_group_id
1999 public function ufjoinDelete($params = NULL) {
2000 if ($params === NULL) {
2003 'module' => 'CiviEvent',
2004 'entity_table' => 'civicrm_event',
2007 'uf_group_id' => '',
2011 crm_add_uf_join($params);
2015 * @param array $params
2016 * Optional parameters.
2021 public function campaignCreate($params = array()) {
2022 $this->enableCiviCampaign();
2023 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2024 'name' => 'big_campaign',
2025 'title' => 'Campaign',
2027 return $campaign['id'];
2031 * Create Group for a contact.
2033 * @param int $contactId
2035 public function contactGroupCreate($contactId) {
2037 'contact_id.1' => $contactId,
2041 $this->callAPISuccess('GroupContact', 'Create', $params);
2045 * Delete Group for a contact.
2047 * @param int $contactId
2049 public function contactGroupDelete($contactId) {
2051 'contact_id.1' => $contactId,
2054 $this->civicrm_api('GroupContact', 'Delete', $params);
2060 * @param array $params
2063 public function activityCreate($params = NULL) {
2065 if ($params === NULL) {
2066 $individualSourceID = $this->individualCreate();
2068 $contactParams = array(
2069 'first_name' => 'Julia',
2070 'Last_name' => 'Anderson',
2072 'email' => 'julia_anderson@civicrm.org',
2073 'contact_type' => 'Individual',
2076 $individualTargetID = $this->individualCreate($contactParams);
2079 'source_contact_id' => $individualSourceID,
2080 'target_contact_id' => array($individualTargetID),
2081 'assignee_contact_id' => array($individualTargetID),
2082 'subject' => 'Discussion on warm beer',
2083 'activity_date_time' => date('Ymd'),
2084 'duration_hours' => 30,
2085 'duration_minutes' => 20,
2086 'location' => 'Baker Street',
2087 'details' => 'Lets schedule a meeting',
2089 'activity_name' => 'Meeting',
2093 $result = $this->callAPISuccess('Activity', 'create', $params);
2095 $result['target_contact_id'] = $individualTargetID;
2096 $result['assignee_contact_id'] = $individualTargetID;
2101 * Create an activity type.
2103 * @param array $params
2107 public function activityTypeCreate($params) {
2108 return $this->callAPISuccess('ActivityType', 'create', $params);
2112 * Delete activity type.
2114 * @param int $activityTypeId
2115 * Id of the activity type.
2118 public function activityTypeDelete($activityTypeId) {
2119 $params['activity_type_id'] = $activityTypeId;
2120 return $this->callAPISuccess('ActivityType', 'delete', $params);
2124 * Create custom group.
2126 * @param array $params
2129 public function customGroupCreate($params = array()) {
2131 'title' => 'new custom group',
2132 'extends' => 'Contact',
2134 'style' => 'Inline',
2138 $params = array_merge($defaults, $params);
2140 if (strlen($params['title']) > 13) {
2141 $params['title'] = substr($params['title'], 0, 13);
2144 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2145 $this->callAPISuccess('custom_group', 'get', array(
2146 'title' => $params['title'],
2147 array('api.custom_group.delete' => 1),
2150 return $this->callAPISuccess('custom_group', 'create', $params);
2154 * Existing function doesn't allow params to be over-ridden so need a new one
2155 * this one allows you to only pass in the params you want to change
2156 * @param array $params
2159 public function CustomGroupCreateByParams($params = array()) {
2161 'title' => "API Custom Group",
2162 'extends' => 'Contact',
2164 'style' => 'Inline',
2167 $params = array_merge($defaults, $params);
2168 return $this->callAPISuccess('custom_group', 'create', $params);
2172 * Create custom group with multi fields.
2173 * @param array $params
2176 public function CustomGroupMultipleCreateByParams($params = array()) {
2181 $params = array_merge($defaults, $params);
2182 return $this->CustomGroupCreateByParams($params);
2186 * Create custom group with multi fields.
2187 * @param array $params
2190 public function CustomGroupMultipleCreateWithFields($params = array()) {
2191 // also need to pass on $params['custom_field'] if not set but not in place yet
2193 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2194 $ids['custom_group_id'] = $customGroup['id'];
2196 $customField = $this->customFieldCreate(array(
2197 'custom_group_id' => $ids['custom_group_id'],
2198 'label' => 'field_1' . $ids['custom_group_id'],
2201 $ids['custom_field_id'][] = $customField['id'];
2203 $customField = $this->customFieldCreate(array(
2204 'custom_group_id' => $ids['custom_group_id'],
2205 'default_value' => '',
2206 'label' => 'field_2' . $ids['custom_group_id'],
2208 $ids['custom_field_id'][] = $customField['id'];
2210 $customField = $this->customFieldCreate(array(
2211 'custom_group_id' => $ids['custom_group_id'],
2212 'default_value' => '',
2213 'label' => 'field_3' . $ids['custom_group_id'],
2215 $ids['custom_field_id'][] = $customField['id'];
2221 * Create a custom group with a single text custom field. See
2222 * participant:testCreateWithCustom for how to use this
2224 * @param string $function
2226 * @param string $filename
2230 * ids of created objects
2232 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2233 $params = array('title' => $function);
2234 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2235 $params['extends'] = $entity ?
$entity : 'Contact';
2236 $customGroup = $this->CustomGroupCreate($params);
2237 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2238 CRM_Core_PseudoConstant
::flush();
2240 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2244 * Delete custom group.
2246 * @param int $customGroupID
2250 public function customGroupDelete($customGroupID) {
2251 $params['id'] = $customGroupID;
2252 return $this->callAPISuccess('custom_group', 'delete', $params);
2256 * Create custom field.
2258 * @param array $params
2259 * (custom_group_id) is required.
2262 public function customFieldCreate($params) {
2263 $params = array_merge(array(
2264 'label' => 'Custom Field',
2265 'data_type' => 'String',
2266 'html_type' => 'Text',
2267 'is_searchable' => 1,
2269 'default_value' => 'defaultValue',
2272 $result = $this->callAPISuccess('custom_field', 'create', $params);
2273 // these 2 functions are called with force to flush static caches
2274 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2275 CRM_Core_Component
::getEnabledComponents(1);
2280 * Delete custom field.
2282 * @param int $customFieldID
2286 public function customFieldDelete($customFieldID) {
2288 $params['id'] = $customFieldID;
2289 return $this->callAPISuccess('custom_field', 'delete', $params);
2298 public function noteCreate($cId) {
2300 'entity_table' => 'civicrm_contact',
2301 'entity_id' => $cId,
2302 'note' => 'hello I am testing Note',
2303 'contact_id' => $cId,
2304 'modified_date' => date('Ymd'),
2305 'subject' => 'Test Note',
2308 return $this->callAPISuccess('Note', 'create', $params);
2312 * Enable CiviCampaign Component.
2314 public function enableCiviCampaign() {
2315 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2316 // force reload of config object
2317 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2318 //flush cache by calling with reset
2319 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2323 * Create test generated example in api/v3/examples.
2325 * To turn this off (e.g. on the server) set
2326 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2327 * in your settings file
2329 * @param string $entity
2330 * @param string $action
2331 * @param array $params
2332 * Array as passed to civicrm_api function.
2333 * @param array $result
2334 * Array as received from the civicrm_api function.
2335 * @param string $testFunction
2336 * Calling function - generally __FUNCTION__.
2337 * @param string $testFile
2338 * Called from file - generally __FILE__.
2339 * @param string $description
2340 * Descriptive text for the example file.
2341 * @param string $exampleName
2342 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2344 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2345 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2348 $entity = _civicrm_api_get_camel_name($entity);
2349 $action = strtolower($action);
2351 if (empty($exampleName)) {
2352 // Attempt to convert lowercase action name to CamelCase.
2353 // This is clunky/imperfect due to the convention of all lowercase actions.
2354 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2355 $knownPrefixes = array(
2362 foreach ($knownPrefixes as $prefix) {
2363 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2364 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2369 $this->tidyExampleResult($result);
2370 if (isset($params['version'])) {
2371 unset($params['version']);
2373 // Format multiline description as array
2375 if (is_string($description) && strlen($description)) {
2376 foreach (explode("\n", $description) as $line) {
2377 $desc[] = trim($line);
2380 $smarty = CRM_Core_Smarty
::singleton();
2381 $smarty->assign('testFunction', $testFunction);
2382 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2383 $smarty->assign('params', $params);
2384 $smarty->assign('entity', $entity);
2385 $smarty->assign('testFile', basename($testFile));
2386 $smarty->assign('description', $desc);
2387 $smarty->assign('result', $result);
2388 $smarty->assign('action', $action);
2390 if (file_exists('../tests/templates/documentFunction.tpl')) {
2391 if (!is_dir("../api/v3/examples/$entity")) {
2392 mkdir("../api/v3/examples/$entity");
2394 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2395 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2401 * Tidy up examples array so that fields that change often ..don't
2402 * and debug related fields are unset
2404 * @param array $result
2406 public function tidyExampleResult(&$result) {
2407 if (!is_array($result)) {
2410 $fieldsToChange = array(
2411 'hash' => '67eac7789eaee00',
2412 'modified_date' => '2012-11-14 16:02:35',
2413 'created_date' => '2013-07-28 08:49:19',
2414 'create_date' => '20120130621222105',
2415 'application_received_date' => '20130728084957',
2416 'in_date' => '2013-07-28 08:50:19',
2417 'scheduled_date' => '20130728085413',
2418 'approval_date' => '20130728085413',
2419 'pledge_start_date_high' => '20130726090416',
2420 'start_date' => '2013-07-29 00:00:00',
2421 'event_start_date' => '2013-07-29 00:00:00',
2422 'end_date' => '2013-08-04 00:00:00',
2423 'event_end_date' => '2013-08-04 00:00:00',
2424 'decision_date' => '20130805000000',
2427 $keysToUnset = array('xdebug', 'undefined_fields');
2428 foreach ($keysToUnset as $unwantedKey) {
2429 if (isset($result[$unwantedKey])) {
2430 unset($result[$unwantedKey]);
2433 if (isset($result['values'])) {
2434 if (!is_array($result['values'])) {
2437 $resultArray = &$result['values'];
2439 elseif (is_array($result)) {
2440 $resultArray = &$result;
2446 foreach ($resultArray as $index => &$values) {
2447 if (!is_array($values)) {
2450 foreach ($values as $key => &$value) {
2451 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2452 if (isset($value['is_error'])) {
2453 // we have a std nested result format
2454 $this->tidyExampleResult($value);
2457 foreach ($value as &$nestedResult) {
2458 // this is an alternative syntax for nested results a keyed array of results
2459 $this->tidyExampleResult($nestedResult);
2463 if (in_array($key, $keysToUnset)) {
2464 unset($values[$key]);
2467 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2468 $value = $fieldsToChange[$key];
2470 if (is_string($value)) {
2471 $value = addslashes($value);
2480 * @param array $params
2484 public function noteDelete($params) {
2485 return $this->callAPISuccess('Note', 'delete', $params);
2489 * Create custom field with Option Values.
2491 * @param array $customGroup
2492 * @param string $name
2493 * Name of custom field.
2497 public function customFieldOptionValueCreate($customGroup, $name) {
2498 $fieldParams = array(
2499 'custom_group_id' => $customGroup['id'],
2500 'name' => 'test_custom_group',
2501 'label' => 'Country',
2502 'html_type' => 'Select',
2503 'data_type' => 'String',
2506 'is_searchable' => 0,
2510 $optionGroup = array(
2512 'name' => 'option_group1',
2513 'label' => 'option_group_label1',
2516 $optionValue = array(
2517 'option_label' => array('Label1', 'Label2'),
2518 'option_value' => array('value1', 'value2'),
2519 'option_name' => array($name . '_1', $name . '_2'),
2520 'option_weight' => array(1, 2),
2521 'option_status' => 1,
2524 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2526 return $this->callAPISuccess('custom_field', 'create', $params);
2534 public function confirmEntitiesDeleted($entities) {
2535 foreach ($entities as $entity) {
2537 $result = $this->callAPISuccess($entity, 'Get', array());
2538 if ($result['error'] == 1 ||
$result['count'] > 0) {
2539 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2547 * @param $tablesToTruncate
2548 * @param bool $dropCustomValueTables
2549 * @throws \Exception
2551 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2553 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2555 if ($dropCustomValueTables) {
2556 $tablesToTruncate[] = 'civicrm_custom_group';
2557 $tablesToTruncate[] = 'civicrm_custom_field';
2560 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2562 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2563 foreach ($tablesToTruncate as $table) {
2564 $sql = "TRUNCATE TABLE $table";
2565 CRM_Core_DAO
::executeQuery($sql);
2567 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2569 if ($dropCustomValueTables) {
2570 $dbName = self
::getDBName();
2572 SELECT TABLE_NAME as tableName
2573 FROM INFORMATION_SCHEMA.TABLES
2574 WHERE TABLE_SCHEMA = '{$dbName}'
2575 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2578 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2579 while ($tableDAO->fetch()) {
2580 $sql = "DROP TABLE {$tableDAO->tableName}";
2581 CRM_Core_DAO
::executeQuery($sql);
2587 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2589 public function quickCleanUpFinancialEntities() {
2590 $tablesToTruncate = array(
2592 'civicrm_activity_contact',
2593 'civicrm_contribution',
2594 'civicrm_contribution_soft',
2595 'civicrm_contribution_product',
2596 'civicrm_financial_trxn',
2597 'civicrm_financial_item',
2598 'civicrm_contribution_recur',
2599 'civicrm_line_item',
2600 'civicrm_contribution_page',
2601 'civicrm_payment_processor',
2602 'civicrm_entity_financial_trxn',
2603 'civicrm_membership',
2604 'civicrm_membership_type',
2605 'civicrm_membership_payment',
2606 'civicrm_membership_log',
2607 'civicrm_membership_block',
2609 'civicrm_participant',
2610 'civicrm_participant_payment',
2612 'civicrm_price_set_entity',
2613 'civicrm_price_field_value',
2614 'civicrm_price_field',
2616 $this->quickCleanup($tablesToTruncate);
2617 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2618 $this->restoreDefaultPriceSetConfig();
2620 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2621 Civi\Payment\System
::singleton()->flushProcessors();
2624 public function restoreDefaultPriceSetConfig() {
2625 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2626 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)");
2627 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)");
2630 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2631 * Default behaviour is to also delete the entity
2632 * @param array $params
2633 * Params array to check against.
2635 * Id of the entity concerned.
2636 * @param string $entity
2637 * Name of entity concerned (e.g. membership).
2638 * @param bool $delete
2639 * Should the entity be deleted as part of this check.
2640 * @param string $errorText
2641 * Text to print on error.
2644 * @param array $params
2647 * @param int $delete
2648 * @param string $errorText
2652 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2654 $result = $this->callAPISuccessGetSingle($entity, array(
2659 $this->callAPISuccess($entity, 'Delete', array(
2663 $dateFields = $keys = $dateTimeFields = array();
2664 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2665 foreach ($fields['values'] as $field => $settings) {
2666 if (array_key_exists($field, $result)) {
2667 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2670 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2672 $type = CRM_Utils_Array
::value('type', $settings);
2673 if ($type == CRM_Utils_Type
::T_DATE
) {
2674 $dateFields[] = $settings['name'];
2675 // we should identify both real names & unique names as dates
2676 if ($field != $settings['name']) {
2677 $dateFields[] = $field;
2680 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2681 $dateTimeFields[] = $settings['name'];
2682 // we should identify both real names & unique names as dates
2683 if ($field != $settings['name']) {
2684 $dateTimeFields[] = $field;
2689 if (strtolower($entity) == 'contribution') {
2690 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2691 // this is not returned in id format
2692 unset($params['payment_instrument_id']);
2693 $params['contribution_source'] = $params['source'];
2694 unset($params['source']);
2697 foreach ($params as $key => $value) {
2698 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2701 if (in_array($key, $dateFields)) {
2702 $value = date('Y-m-d', strtotime($value));
2703 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2705 if (in_array($key, $dateTimeFields)) {
2706 $value = date('Y-m-d H:i:s', strtotime($value));
2707 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2709 $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);
2714 * Get formatted values in the actual and expected result.
2715 * @param array $actual
2716 * Actual calculated values.
2717 * @param array $expected
2720 public function checkArrayEquals(&$actual, &$expected) {
2721 self
::unsetId($actual);
2722 self
::unsetId($expected);
2723 $this->assertEquals($actual, $expected);
2727 * Unset the key 'id' from the array
2728 * @param array $unformattedArray
2729 * The array from which the 'id' has to be unset.
2731 public static function unsetId(&$unformattedArray) {
2732 $formattedArray = array();
2733 if (array_key_exists('id', $unformattedArray)) {
2734 unset($unformattedArray['id']);
2736 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2737 foreach ($unformattedArray['values'] as $key => $value) {
2738 if (is_array($value)) {
2739 foreach ($value as $k => $v) {
2745 elseif ($key == 'id') {
2746 $unformattedArray[$key];
2748 $formattedArray = array($value);
2750 $unformattedArray['values'] = $formattedArray;
2755 * Helper to enable/disable custom directory support
2757 * @param array $customDirs
2759 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2760 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2762 public function customDirectories($customDirs) {
2763 require_once 'CRM/Core/Config.php';
2764 $config = CRM_Core_Config
::singleton();
2766 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2767 unset($config->customPHPPathDir
);
2769 elseif ($customDirs['php_path'] === TRUE) {
2770 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2773 $config->customPHPPathDir
= $php_path;
2776 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2777 unset($config->customTemplateDir
);
2779 elseif ($customDirs['template_path'] === TRUE) {
2780 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2783 $config->customTemplateDir
= $template_path;
2788 * Generate a temporary folder.
2790 * @param string $prefix
2793 public function createTempDir($prefix = 'test-') {
2794 $tempDir = CRM_Utils_File
::tempdir($prefix);
2795 $this->tempDirs
[] = $tempDir;
2799 public function cleanTempDirs() {
2800 if (!is_array($this->tempDirs
)) {
2801 // fix test errors where this is not set
2804 foreach ($this->tempDirs
as $tempDir) {
2805 if (is_dir($tempDir)) {
2806 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2812 * Temporarily replace the singleton extension with a different one.
2813 * @param \CRM_Extension_System $system
2815 public function setExtensionSystem(CRM_Extension_System
$system) {
2816 if ($this->origExtensionSystem
== NULL) {
2817 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2819 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2822 public function unsetExtensionSystem() {
2823 if ($this->origExtensionSystem
!== NULL) {
2824 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2825 $this->origExtensionSystem
= NULL;
2830 * Temporarily alter the settings-metadata to add a mock setting.
2832 * WARNING: The setting metadata will disappear on the next cache-clear.
2837 public function setMockSettingsMetaData($extras) {
2838 CRM_Core_BAO_Setting
::$_cache = array();
2839 $this->callAPISuccess('system', 'flush', array());
2840 CRM_Core_BAO_Setting
::$_cache = array();
2842 CRM_Utils_Hook
::singleton()
2843 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2844 $metadata = array_merge($metadata, $extras);
2847 $fields = $this->callAPISuccess('setting', 'getfields', array());
2848 foreach ($extras as $key => $spec) {
2849 $this->assertNotEmpty($spec['title']);
2850 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2855 * @param string $name
2857 public function financialAccountDelete($name) {
2858 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2859 $financialAccount->name
= $name;
2860 if ($financialAccount->find(TRUE)) {
2861 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2862 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2863 $entityFinancialType->delete();
2864 $financialAccount->delete();
2869 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2870 * (NB unclear if this is still required)
2872 public function _sethtmlGlobals() {
2873 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2874 'required' => array(
2875 'html_quickform_rule_required',
2876 'HTML/QuickForm/Rule/Required.php',
2878 'maxlength' => array(
2879 'html_quickform_rule_range',
2880 'HTML/QuickForm/Rule/Range.php',
2882 'minlength' => array(
2883 'html_quickform_rule_range',
2884 'HTML/QuickForm/Rule/Range.php',
2886 'rangelength' => array(
2887 'html_quickform_rule_range',
2888 'HTML/QuickForm/Rule/Range.php',
2891 'html_quickform_rule_email',
2892 'HTML/QuickForm/Rule/Email.php',
2895 'html_quickform_rule_regex',
2896 'HTML/QuickForm/Rule/Regex.php',
2898 'lettersonly' => array(
2899 'html_quickform_rule_regex',
2900 'HTML/QuickForm/Rule/Regex.php',
2902 'alphanumeric' => array(
2903 'html_quickform_rule_regex',
2904 'HTML/QuickForm/Rule/Regex.php',
2907 'html_quickform_rule_regex',
2908 'HTML/QuickForm/Rule/Regex.php',
2910 'nopunctuation' => array(
2911 'html_quickform_rule_regex',
2912 'HTML/QuickForm/Rule/Regex.php',
2915 'html_quickform_rule_regex',
2916 'HTML/QuickForm/Rule/Regex.php',
2918 'callback' => array(
2919 'html_quickform_rule_callback',
2920 'HTML/QuickForm/Rule/Callback.php',
2923 'html_quickform_rule_compare',
2924 'HTML/QuickForm/Rule/Compare.php',
2927 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2928 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2930 'HTML/QuickForm/group.php',
2931 'HTML_QuickForm_group',
2934 'HTML/QuickForm/hidden.php',
2935 'HTML_QuickForm_hidden',
2938 'HTML/QuickForm/reset.php',
2939 'HTML_QuickForm_reset',
2941 'checkbox' => array(
2942 'HTML/QuickForm/checkbox.php',
2943 'HTML_QuickForm_checkbox',
2946 'HTML/QuickForm/file.php',
2947 'HTML_QuickForm_file',
2950 'HTML/QuickForm/image.php',
2951 'HTML_QuickForm_image',
2953 'password' => array(
2954 'HTML/QuickForm/password.php',
2955 'HTML_QuickForm_password',
2958 'HTML/QuickForm/radio.php',
2959 'HTML_QuickForm_radio',
2962 'HTML/QuickForm/button.php',
2963 'HTML_QuickForm_button',
2966 'HTML/QuickForm/submit.php',
2967 'HTML_QuickForm_submit',
2970 'HTML/QuickForm/select.php',
2971 'HTML_QuickForm_select',
2973 'hiddenselect' => array(
2974 'HTML/QuickForm/hiddenselect.php',
2975 'HTML_QuickForm_hiddenselect',
2978 'HTML/QuickForm/text.php',
2979 'HTML_QuickForm_text',
2981 'textarea' => array(
2982 'HTML/QuickForm/textarea.php',
2983 'HTML_QuickForm_textarea',
2985 'fckeditor' => array(
2986 'HTML/QuickForm/fckeditor.php',
2987 'HTML_QuickForm_FCKEditor',
2990 'HTML/QuickForm/tinymce.php',
2991 'HTML_QuickForm_TinyMCE',
2993 'dojoeditor' => array(
2994 'HTML/QuickForm/dojoeditor.php',
2995 'HTML_QuickForm_dojoeditor',
2998 'HTML/QuickForm/link.php',
2999 'HTML_QuickForm_link',
3001 'advcheckbox' => array(
3002 'HTML/QuickForm/advcheckbox.php',
3003 'HTML_QuickForm_advcheckbox',
3006 'HTML/QuickForm/date.php',
3007 'HTML_QuickForm_date',
3010 'HTML/QuickForm/static.php',
3011 'HTML_QuickForm_static',
3014 'HTML/QuickForm/header.php',
3015 'HTML_QuickForm_header',
3018 'HTML/QuickForm/html.php',
3019 'HTML_QuickForm_html',
3021 'hierselect' => array(
3022 'HTML/QuickForm/hierselect.php',
3023 'HTML_QuickForm_hierselect',
3025 'autocomplete' => array(
3026 'HTML/QuickForm/autocomplete.php',
3027 'HTML_QuickForm_autocomplete',
3030 'HTML/QuickForm/xbutton.php',
3031 'HTML_QuickForm_xbutton',
3033 'advmultiselect' => array(
3034 'HTML/QuickForm/advmultiselect.php',
3035 'HTML_QuickForm_advmultiselect',
3041 * Set up an acl allowing contact to see 2 specified groups
3042 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3044 * You need to have pre-created these groups & created the user e.g
3045 * $this->createLoggedInUser();
3046 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3047 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3049 public function setupACL($isProfile = FALSE) {
3051 $_REQUEST = $this->_params
;
3053 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3054 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3055 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3056 'option_group_id' => $optionGroupID,
3057 'label' => 'pick me',
3061 CRM_Core_DAO
::executeQuery("
3062 TRUNCATE civicrm_acl_cache
3065 CRM_Core_DAO
::executeQuery("
3066 TRUNCATE civicrm_acl_contact_cache
3069 CRM_Core_DAO
::executeQuery("
3070 INSERT INTO civicrm_acl_entity_role (
3071 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3072 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3076 CRM_Core_DAO
::executeQuery("
3077 INSERT INTO civicrm_acl (
3078 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3081 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3086 CRM_Core_DAO
::executeQuery("
3087 INSERT INTO civicrm_acl (
3088 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3091 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3095 CRM_Core_DAO
::executeQuery("
3096 INSERT INTO civicrm_acl (
3097 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3100 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3105 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3106 $this->callAPISuccess('group_contact', 'create', array(
3107 'group_id' => $this->_permissionedGroup
,
3108 'contact_id' => $this->_loggedInUser
,
3113 CRM_ACL_BAO_Cache
::resetCache();
3114 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3115 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3120 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3122 public function offsetDefaultPriceSet() {
3123 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3124 $firstID = $contributionPriceSet['id'];
3125 $this->callAPISuccess('price_set', 'create', array(
3126 'id' => $contributionPriceSet['id'],
3130 unset($contributionPriceSet['id']);
3131 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3132 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3133 'price_set_id' => $firstID,
3134 'options' => array('limit' => 1),
3136 unset($priceField['id']);
3137 $priceField['price_set_id'] = $newPriceSet['id'];
3138 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3139 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3140 'price_set_id' => $firstID,
3142 'options' => array('limit' => 1),
3145 unset($priceFieldValue['id']);
3146 //create some padding to use up ids
3147 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3148 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3149 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3153 * Create an instance of the paypal processor.
3154 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3155 * this parent class & we don't have a structure for that yet
3156 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3157 * & the best protection against that is the functions this class affords
3158 * @param array $params
3159 * @return int $result['id'] payment processor id
3161 public function paymentProcessorCreate($params = array()) {
3162 $params = array_merge(array(
3164 'domain_id' => CRM_Core_Config
::domainID(),
3165 'payment_processor_type_id' => 'PayPal',
3169 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3170 'password' => '1183377788',
3171 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3172 'url_site' => 'https://www.sandbox.paypal.com/',
3173 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3174 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3175 'class_name' => 'Payment_PayPalImpl',
3176 'billing_mode' => 3,
3177 'financial_type_id' => 1,
3180 if (!is_numeric($params['payment_processor_type_id'])) {
3181 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3183 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3184 'name' => $params['payment_processor_type_id'],
3188 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3189 return $result['id'];
3193 * Set up initial recurring payment allowing subsequent IPN payments.
3195 public function setupRecurringPaymentProcessorTransaction() {
3196 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3197 'contact_id' => $this->_contactID
,
3200 'installments' => 5,
3201 'frequency_unit' => 'Month',
3202 'frequency_interval' => 1,
3203 'invoice_id' => $this->_invoiceID
,
3204 'contribution_status_id' => 2,
3205 'processor_id' => $this->_paymentProcessorID
,
3206 'api.contribution.create' => array(
3207 'total_amount' => '200',
3208 'invoice_id' => $this->_invoiceID
,
3209 'financial_type_id' => 1,
3210 'contribution_status_id' => 'Pending',
3211 'contact_id' => $this->_contactID
,
3212 'contribution_page_id' => $this->_contributionPageID
,
3213 'payment_processor_id' => $this->_paymentProcessorID
,
3217 $this->_contributionRecurID
= $contributionRecur['id'];
3218 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3222 * 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
3224 public function setupMembershipRecurringPaymentProcessorTransaction() {
3225 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3226 //create a contribution so our membership & contribution don't both have id = 1
3227 $this->contributionCreate(array(
3228 'contact_id' => $this->_contactID
,
3231 $this->setupRecurringPaymentProcessorTransaction();
3233 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3234 'contact_id' => $this->_contactID
,
3235 'membership_type_id' => $this->ids
['membership_type'],
3236 'contribution_recur_id' => $this->_contributionRecurID
,
3237 'format.only_id' => TRUE,
3239 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3240 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3242 $this->callAPISuccess('line_item', 'create', array(
3243 'entity_table' => 'civicrm_membership',
3244 'entity_id' => $this->ids
['membership'],
3245 'contribution_id' => $this->_contributionID
,
3246 'label' => 'General',
3248 'unit_price' => 200,
3249 'line_total' => 200,
3250 'financial_type_id' => 1,
3251 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3253 'label' => 'Membership Amount',
3255 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3257 'label' => 'General',
3260 $this->callAPISuccess('membership_payment', 'create', array(
3261 'contribution_id' => $this->_contributionID
,
3262 'membership_id' => $this->ids
['membership'],
3271 public function CiviUnitTestCase_fatalErrorHandler($message) {
3272 throw new Exception("{$message['message']}: {$message['code']}");
3276 * Helper function to create new mailing.
3279 public function createMailing() {
3281 'subject' => 'maild' . rand(),
3282 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3283 'name' => 'mailing name' . rand(),
3287 $result = $this->callAPISuccess('Mailing', 'create', $params);
3288 return $result['id'];
3292 * Helper function to delete mailing.
3295 public function deleteMailing($id) {
3300 $this->callAPISuccess('Mailing', 'delete', $params);
3304 * Wrap the entire test case in a transaction.
3306 * Only subsequent DB statements will be wrapped in TX -- this cannot
3307 * retroactively wrap old DB statements. Therefore, it makes sense to
3308 * call this at the beginning of setUp().
3310 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3311 * this option does not work with, e.g., custom-data.
3313 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3314 * if TRUNCATE or ALTER is called while using a transaction.
3317 * Whether to use nesting or reference-counting.
3319 public function useTransaction($nest = TRUE) {
3321 $this->tx
= new CRM_Core_Transaction($nest);
3322 $this->tx
->rollback();
3326 public function clearOutputBuffer() {
3327 while (ob_get_level() > 0) {
3334 * @param array $apiResult
3336 protected function assertAttachmentExistence($exists, $apiResult) {
3337 $fileId = $apiResult['id'];
3338 $this->assertTrue(is_numeric($fileId));
3339 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3340 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3341 1 => array($fileId, 'Int'),
3343 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3344 1 => array($fileId, 'Int'),