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 $config->setUserFramework('UnitTests');
414 $this->hookClass
= CRM_Utils_Hook
::singleton(TRUE);
416 // Make sure the DB connection is setup properly
417 $config->userSystem
->setMySQLTimeZone();
418 $env = new CRM_Utils_Check_Env();
419 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
421 // clear permissions stub to not check permissions
422 $config->userPermissionClass
->permissions
= NULL;
424 //flush component settings
425 CRM_Core_Component
::getEnabledComponents(TRUE);
427 error_reporting(E_ALL
);
429 $this->_sethtmlGlobals();
433 * Read everything from the datasets directory and insert into the db.
435 public function loadAllFixtures() {
436 $fixturesDir = __DIR__
. '/../../fixtures';
438 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
440 $xmlFiles = glob($fixturesDir . '/*.xml');
441 foreach ($xmlFiles as $xmlFixture) {
442 $op = new PHPUnit_Extensions_Database_Operation_Insert();
443 $dataset = $this->createXMLDataSet($xmlFixture);
444 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
445 $op->execute($this->_dbconn
, $dataset);
448 $yamlFiles = glob($fixturesDir . '/*.yaml');
449 foreach ($yamlFiles as $yamlFixture) {
450 $op = new PHPUnit_Extensions_Database_Operation_Insert();
451 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
452 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
453 $op->execute($this->_dbconn
, $dataset);
456 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
460 * Emulate a logged in user since certain functions use that.
461 * value to store a record in the DB (like activity)
465 * Contact ID of the created user.
467 public function createLoggedInUser() {
469 'first_name' => 'Logged In',
470 'last_name' => 'User ' . rand(),
471 'contact_type' => 'Individual',
473 $contactID = $this->individualCreate($params);
474 $this->callAPISuccess('UFMatch', 'create', array(
475 'contact_id' => $contactID,
476 'uf_name' => 'superman',
480 $session = CRM_Core_Session
::singleton();
481 $session->set('userID', $contactID);
485 public function cleanDB() {
486 self
::$populateOnce = NULL;
487 $this->DBResetRequired
= TRUE;
489 $this->_dbconn
= $this->getConnection();
490 static::_populateDB();
491 $this->tempDirs
= array();
495 * Create default domain contacts for the two domains added during test class.
496 * database population.
498 public function createDomainContacts() {
499 $default_domain_contact = $this->organizationCreate();
500 $second_domain_contact = $this->organizationCreate();
504 * Common teardown functions for all unit tests.
506 protected function tearDown() {
507 error_reporting(E_ALL
& ~E_NOTICE
);
508 CRM_Utils_Hook
::singleton()->reset();
509 $this->hookClass
->reset();
510 $session = CRM_Core_Session
::singleton();
511 $session->set('userID', NULL);
514 $this->tx
->rollback()->commit();
517 CRM_Core_Transaction
::forceRollbackIfEnabled();
518 \Civi\Core\Transaction\Manager
::singleton(TRUE);
521 CRM_Core_Transaction
::forceRollbackIfEnabled();
522 \Civi\Core\Transaction\Manager
::singleton(TRUE);
524 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
525 $this->quickCleanup($tablesToTruncate);
526 $this->createDomainContacts();
529 $this->cleanTempDirs();
530 $this->unsetExtensionSystem();
531 $this->clearOutputBuffer();
535 * FIXME: Maybe a better way to do it
537 public function foreignKeyChecksOff() {
538 self
::$utils = new Utils($GLOBALS['mysql_host'],
539 $GLOBALS['mysql_port'],
540 $GLOBALS['mysql_user'],
541 $GLOBALS['mysql_pass']
543 $dbName = self
::getDBName();
544 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
545 if (self
::$utils->do_query($query) === FALSE) {
547 echo 'Cannot set foreign_key_checks = 0';
553 public function foreignKeyChecksOn() {
554 // FIXME: might not be needed if previous fixme implemented
558 * Generic function to compare expected values after an api call to retrieved.
561 * @daoName string DAO Name of object we're evaluating.
562 * @id int Id of object
563 * @match array Associative array of field name => expected value. Empty if asserting
564 * that a DELETE occurred
565 * @delete boolean True if we're checking that a DELETE action occurred.
569 * @param bool $delete
570 * @throws \PHPUnit_Framework_AssertionFailedError
572 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
574 // adding this here since developers forget to check for an id
575 // and hence we get the first value in the db
576 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
579 $object = new $daoName();
583 // If we're asserting successful record deletion, make sure object is NOT found.
585 if ($object->find(TRUE)) {
586 $this->fail("Object not deleted by delete operation: $daoName, $id");
591 // Otherwise check matches of DAO field values against expected values in $match.
592 if ($object->find(TRUE)) {
593 $fields = &$object->fields();
594 foreach ($fields as $name => $value) {
595 $dbName = $value['name'];
596 if (isset($match[$name])) {
598 $this->assertEquals($object->$dbName, $match[$name]);
600 elseif (isset($match[$dbName])) {
602 $this->assertEquals($object->$dbName, $match[$dbName]);
607 $this->fail("Could not retrieve object: $daoName, $id");
610 $matchSize = count($match);
611 if ($verifiedCount != $matchSize) {
612 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
617 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
618 * @param string $daoName
619 * @param $searchValue
620 * @param $returnColumn
621 * @param $searchColumn
624 * @return null|string
625 * @throws PHPUnit_Framework_AssertionFailedError
627 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
628 if (empty($searchValue)) {
629 $this->fail("empty value passed to assertDBNotNull");
631 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
632 $this->assertNotNull($value, $message);
638 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
639 * @param string $daoName
640 * @param $searchValue
641 * @param $returnColumn
642 * @param $searchColumn
645 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
646 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
647 $this->assertNull($value, $message);
651 * Request a record from the DB by id. Success if row not found.
652 * @param string $daoName
654 * @param null $message
656 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
657 $message = $message ?
$message : "$daoName (#$id) should not exist";
658 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
659 $this->assertNull($value, $message);
663 * Request a record from the DB by id. Success if row not found.
664 * @param string $daoName
666 * @param null $message
668 public function assertDBRowExist($daoName, $id, $message = NULL) {
669 $message = $message ?
$message : "$daoName (#$id) should exist";
670 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
671 $this->assertEquals($id, $value, $message);
675 * Compare a single column value in a retrieved DB record to an expected value.
676 * @param string $daoName
677 * @param $searchValue
678 * @param $returnColumn
679 * @param $searchColumn
680 * @param $expectedValue
683 public function assertDBCompareValue(
684 $daoName, $searchValue, $returnColumn, $searchColumn,
685 $expectedValue, $message
687 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
688 $this->assertEquals($value, $expectedValue, $message);
692 * Compare all values in a single retrieved DB record to an array of expected values.
693 * @param string $daoName
694 * @param array $searchParams
695 * @param $expectedValues
697 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
698 //get the values from db
700 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
702 // compare db values with expected values
703 self
::assertAttributesEquals($expectedValues, $dbValues);
707 * Assert that a SQL query returns a given value.
709 * The first argument is an expected value. The remaining arguments are passed
710 * to CRM_Core_DAO::singleValueQuery
712 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
713 * array(1 => array("Whiz", "String")));
716 * @param array $params
717 * @param string $message
719 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
723 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
724 $this->assertEquals($expected, $actual,
725 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
726 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
732 * Assert that two array-trees are exactly equal, notwithstanding
733 * the sorting of keys
735 * @param array $expected
736 * @param array $actual
738 public function assertTreeEquals($expected, $actual) {
741 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
742 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
746 $this->assertEquals($e, $a);
750 * Assert that two numbers are approximately equal.
752 * @param int|float $expected
753 * @param int|float $actual
754 * @param int|float $tolerance
755 * @param string $message
757 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
758 if ($message === NULL) {
759 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
761 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
765 * Assert attributes are equal.
767 * @param $expectedValues
768 * @param $actualValues
769 * @param string $message
771 * @throws PHPUnit_Framework_AssertionFailedError
773 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
774 foreach ($expectedValues as $paramName => $paramValue) {
775 if (isset($actualValues[$paramName])) {
776 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
779 $this->fail("Attribute '$paramName' not present in actual array.");
788 public function assertArrayKeyExists($key, &$list) {
789 $result = isset($list[$key]) ?
TRUE : FALSE;
790 $this->assertTrue($result, ts("%1 element exists?",
799 public function assertArrayValueNotNull($key, &$list) {
800 $this->assertArrayKeyExists($key, $list);
802 $value = isset($list[$key]) ?
$list[$key] : NULL;
803 $this->assertTrue($value,
804 ts("%1 element not null?",
811 * Check that api returned 'is_error' => 0.
813 * @param array $apiResult
815 * @param string $prefix
816 * Extra test to add to message.
818 public function assertAPISuccess($apiResult, $prefix = '') {
819 if (!empty($prefix)) {
822 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
824 if (!empty($apiResult['debug_information'])) {
825 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
827 if (!empty($apiResult['trace'])) {
828 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
830 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
834 * Check that api returned 'is_error' => 1.
836 * @param array $apiResult
838 * @param string $prefix
839 * Extra test to add to message.
840 * @param null $expectedError
842 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
843 if (!empty($prefix)) {
846 if ($expectedError && !empty($apiResult['is_error'])) {
847 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
849 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
850 $this->assertNotEmpty($apiResult['error_message']);
856 * @param string $message
858 public function assertType($expected, $actual, $message = '') {
859 return $this->assertInternalType($expected, $actual, $message);
863 * Check that a deleted item has been deleted.
868 public function assertAPIDeleted($entity, $id) {
869 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
874 * Check that api returned 'is_error' => 1
875 * else provide full message
876 * @param array $result
878 * @param array $valuesToExclude
879 * @param string $prefix
880 * Extra test to add to message.
882 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
883 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
884 foreach ($valuesToExclude as $value) {
885 if (isset($result[$value])) {
886 unset($result[$value]);
888 if (isset($expected[$value])) {
889 unset($expected[$value]);
892 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
896 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
900 * @param array $params
903 public function civicrm_api($entity, $action, $params) {
904 return civicrm_api($entity, $action, $params);
908 * Create a batch of external API calls which can
909 * be executed concurrently.
912 * $calls = $this->createExternalAPI()
913 * ->addCall('Contact', 'get', ...)
914 * ->addCall('Contact', 'get', ...)
920 * @return \Civi\API\ExternalBatch
921 * @throws PHPUnit_Framework_SkippedTestError
923 public function createExternalAPI() {
924 global $civicrm_root;
925 $defaultParams = array(
926 'version' => $this->_apiversion
,
930 $calls = new \Civi\API\
ExternalBatch($defaultParams);
931 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
933 if (!$calls->isSupported()) {
934 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
941 * wrap api functions.
942 * so we can ensure they succeed & throw exceptions without litterering the test with checks
944 * @param string $entity
945 * @param string $action
946 * @param array $params
947 * @param mixed $checkAgainst
948 * Optional value to check result against, implemented for getvalue,.
949 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
950 * for getsingle the array is compared against an array passed in - the id is not compared (for
955 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
956 $params = array_merge(array(
957 'version' => $this->_apiversion
,
962 switch (strtolower($action)) {
964 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
967 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
970 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
972 $result = $this->civicrm_api($entity, $action, $params);
973 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
978 * This function exists to wrap api getValue function & check the result
979 * so we can ensure they succeed & throw exceptions without litterering the test with checks
980 * There is a type check in this
982 * @param string $entity
983 * @param array $params
984 * @param string $type
985 * Per http://php.net/manual/en/function.gettype.php possible types.
995 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
997 'version' => $this->_apiversion
,
1000 $result = $this->civicrm_api($entity, 'getvalue', $params);
1002 if ($type == 'integer') {
1003 // api seems to return integers as strings
1004 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
1007 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1014 * This function exists to wrap api getsingle function & check the result
1015 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1017 * @param string $entity
1018 * @param array $params
1019 * @param array $checkAgainst
1020 * Array to compare result against.
1031 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1033 'version' => $this->_apiversion
,
1036 $result = $this->civicrm_api($entity, 'getsingle', $params);
1037 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1038 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1040 if ($checkAgainst) {
1041 // @todo - have gone with the fn that unsets id? should we check id?
1042 $this->checkArrayEquals($result, $checkAgainst);
1048 * This function exists to wrap api getValue function & check the result
1049 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1050 * There is a type check in this
1051 * @param string $entity
1052 * @param array $params
1053 * @param null $count
1057 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1059 'version' => $this->_apiversion
,
1062 $result = $this->civicrm_api($entity, 'getcount', $params);
1063 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1064 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1066 if (is_int($count)) {
1067 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1073 * This function exists to wrap api functions.
1074 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1076 * @param string $entity
1077 * @param string $action
1078 * @param array $params
1079 * @param string $function
1080 * Pass this in to create a generated example.
1081 * @param string $file
1082 * Pass this in to create a generated example.
1083 * @param string $description
1084 * @param string|null $exampleName
1088 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1089 $params['version'] = $this->_apiversion
;
1090 $result = $this->callAPISuccess($entity, $action, $params);
1091 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1096 * This function exists to wrap api functions.
1097 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1098 * @param string $entity
1099 * @param string $action
1100 * @param array $params
1101 * @param string $expectedErrorMessage
1103 * @param null $extraOutput
1106 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1107 if (is_array($params)) {
1109 'version' => $this->_apiversion
,
1112 $result = $this->civicrm_api($entity, $action, $params);
1113 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1118 * Create required data based on $this->entity & $this->params
1119 * This is just a way to set up the test data for delete & get functions
1120 * so the distinction between set
1121 * up & tested functions is clearer
1126 public function createTestEntity() {
1127 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1131 * Generic function to create Organisation, to be used in test cases
1133 * @param array $params
1134 * parameters for civicrm_contact_add api function call
1136 * sequence number if creating multiple organizations
1139 * id of Organisation created
1141 public function organizationCreate($params = array(), $seq = 0) {
1145 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1146 return $this->_contactCreate($params);
1150 * Generic function to create Individual, to be used in test cases
1152 * @param array $params
1153 * parameters for civicrm_contact_add api function call
1155 * sequence number if creating multiple individuals
1158 * id of Individual created
1160 public function individualCreate($params = array(), $seq = 0) {
1161 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1162 return $this->_contactCreate($params);
1166 * Generic function to create Household, to be used in test cases
1168 * @param array $params
1169 * parameters for civicrm_contact_add api function call
1171 * sequence number if creating multiple households
1174 * id of Household created
1176 public function householdCreate($params = array(), $seq = 0) {
1177 $params = array_merge($this->sampleContact('Household', $seq), $params);
1178 return $this->_contactCreate($params);
1182 * Helper function for getting sample contact properties.
1184 * @param string $contact_type
1185 * enum contact type: Individual, Organization
1187 * sequence number for the values of this type
1190 * properties of sample contact (ie. $params for API call)
1192 public function sampleContact($contact_type, $seq = 0) {
1194 'Individual' => array(
1195 // The number of values in each list need to be coprime numbers to not have duplicates
1196 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1197 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1198 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1200 'Organization' => array(
1201 'organization_name' => array(
1202 'Unit Test Organization',
1209 'Household' => array(
1210 'household_name' => array('Unit Test household'),
1213 $params = array('contact_type' => $contact_type);
1214 foreach ($samples[$contact_type] as $key => $values) {
1215 $params[$key] = $values[$seq %
count($values)];
1217 if ($contact_type == 'Individual') {
1218 $params['email'] = strtolower(
1219 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1221 $params['prefix_id'] = 3;
1222 $params['suffix_id'] = 3;
1228 * Private helper function for calling civicrm_contact_add.
1230 * @param array $params
1231 * For civicrm_contact_add api function call.
1236 * id of Household created
1238 private function _contactCreate($params) {
1239 $result = $this->callAPISuccess('contact', 'create', $params);
1240 if (!empty($result['is_error']) ||
empty($result['id'])) {
1241 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1243 return $result['id'];
1247 * Delete contact, ensuring it is not the domain contact
1249 * @param int $contactID
1250 * Contact ID to delete
1252 public function contactDelete($contactID) {
1253 $domain = new CRM_Core_BAO_Domain();
1254 $domain->contact_id
= $contactID;
1255 if (!$domain->find(TRUE)) {
1256 $this->callAPISuccess('contact', 'delete', array(
1258 'skip_undelete' => 1,
1264 * @param int $contactTypeId
1268 public function contactTypeDelete($contactTypeId) {
1269 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1271 throw new Exception('Could not delete contact type');
1276 * @param array $params
1280 public function membershipTypeCreate($params = array()) {
1281 CRM_Member_PseudoConstant
::flush('membershipType');
1282 CRM_Core_Config
::clearDBCache();
1283 $memberOfOrganization = $this->organizationCreate();
1284 $params = array_merge(array(
1285 'name' => 'General',
1286 'duration_unit' => 'year',
1287 'duration_interval' => 1,
1288 'period_type' => 'rolling',
1289 'member_of_contact_id' => $memberOfOrganization,
1291 'financial_type_id' => 1,
1294 'visibility' => 'Public',
1297 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1299 CRM_Member_PseudoConstant
::flush('membershipType');
1300 CRM_Utils_Cache
::singleton()->flush();
1302 return $result['id'];
1306 * @param array $params
1310 public function contactMembershipCreate($params) {
1312 'join_date' => '2007-01-21',
1313 'start_date' => '2007-01-21',
1314 'end_date' => '2007-12-21',
1315 'source' => 'Payment',
1318 foreach ($pre as $key => $val) {
1319 if (!isset($params[$key])) {
1320 $params[$key] = $val;
1324 $result = $this->callAPISuccess('Membership', 'create', $params);
1325 return $result['id'];
1329 * Delete Membership Type.
1331 * @param array $params
1333 public function membershipTypeDelete($params) {
1334 $this->callAPISuccess('MembershipType', 'Delete', $params);
1338 * @param int $membershipID
1340 public function membershipDelete($membershipID) {
1341 $deleteParams = array('id' => $membershipID);
1342 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1346 * @param string $name
1350 public function membershipStatusCreate($name = 'test member status') {
1351 $params['name'] = $name;
1352 $params['start_event'] = 'start_date';
1353 $params['end_event'] = 'end_date';
1354 $params['is_current_member'] = 1;
1355 $params['is_active'] = 1;
1357 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1358 CRM_Member_PseudoConstant
::flush('membershipStatus');
1359 return $result['id'];
1363 * @param int $membershipStatusID
1365 public function membershipStatusDelete($membershipStatusID) {
1366 if (!$membershipStatusID) {
1369 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1373 * @param array $params
1377 public function relationshipTypeCreate($params = array()) {
1378 $params = array_merge(array(
1379 'name_a_b' => 'Relation 1 for relationship type create',
1380 'name_b_a' => 'Relation 2 for relationship type create',
1381 'contact_type_a' => 'Individual',
1382 'contact_type_b' => 'Organization',
1389 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1390 CRM_Core_PseudoConstant
::flush('relationshipType');
1392 return $result['id'];
1396 * Delete Relatinship Type.
1398 * @param int $relationshipTypeID
1400 public function relationshipTypeDelete($relationshipTypeID) {
1401 $params['id'] = $relationshipTypeID;
1402 $this->callAPISuccess('relationship_type', 'delete', $params);
1406 * @param array $params
1410 public function paymentProcessorTypeCreate($params = NULL) {
1411 if (is_null($params)) {
1413 'name' => 'API_Test_PP',
1414 'title' => 'API Test Payment Processor',
1415 'class_name' => 'CRM_Core_Payment_APITest',
1416 'billing_mode' => 'form',
1422 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1424 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1426 return $result['id'];
1430 * Create test Authorize.net instance.
1432 * @param array $params
1436 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1437 $params = array_merge(array(
1438 'name' => 'Authorize',
1439 'domain_id' => CRM_Core_Config
::domainID(),
1440 'payment_processor_type_id' => 'AuthNet',
1441 'title' => 'AuthNet',
1446 'user_name' => '4y5BfuW7jm',
1447 'password' => '4cAmW927n8uLf5J8',
1448 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1449 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1450 'class_name' => 'Payment_AuthorizeNet',
1451 'billing_mode' => 1,
1454 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1455 return $result['id'];
1459 * Create Participant.
1461 * @param array $params
1462 * Array of contact id and event id values.
1465 * $id of participant created
1467 public function participantCreate($params) {
1468 if (empty($params['contact_id'])) {
1469 $params['contact_id'] = $this->individualCreate();
1471 if (empty($params['event_id'])) {
1472 $event = $this->eventCreate();
1473 $params['event_id'] = $event['id'];
1478 'register_date' => 20070219,
1479 'source' => 'Wimbeldon',
1480 'event_level' => 'Payment',
1484 $params = array_merge($defaults, $params);
1485 $result = $this->callAPISuccess('Participant', 'create', $params);
1486 return $result['id'];
1490 * Create Payment Processor.
1492 * @return CRM_Financial_DAO_PaymentProcessor
1493 * instance of Payment Processor
1495 public function processorCreate() {
1496 $processorParams = array(
1499 'payment_processor_type_id' => 10,
1500 'financial_account_id' => 12,
1504 'url_site' => 'http://dummy.com',
1505 'url_recur' => 'http://dummy.com',
1506 'billing_mode' => 1,
1508 return CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1512 * Create Payment Processor.
1514 * @param array $processorParams
1516 * @return \CRM_Core_Payment_Dummy
1517 * Instance of Dummy Payment Processor
1519 public function dummyProcessorCreate($processorParams = array()) {
1520 $paymentProcessor = $this->processorCreate($processorParams);
1521 return Civi\Payment\System
::singleton()->getById($paymentProcessor->id
);
1525 * Create contribution page.
1527 * @param array $params
1529 * Array of contribution page
1531 public function contributionPageCreate($params) {
1532 $this->_pageParams
= array(
1533 'title' => 'Test Contribution Page',
1534 'financial_type_id' => 1,
1535 'currency' => 'USD',
1536 'financial_account_id' => 1,
1537 'payment_processor' => $params['processor_id'],
1539 'is_allow_other_amount' => 1,
1541 'max_amount' => 1000,
1543 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1544 return $contributionPage;
1550 * @param array $params
1552 * result of created tag
1554 public function tagCreate($params = array()) {
1556 'name' => 'New Tag3',
1557 'description' => 'This is description for Our New Tag ',
1560 $params = array_merge($defaults, $params);
1561 $result = $this->callAPISuccess('Tag', 'create', $params);
1562 return $result['values'][$result['id']];
1569 * Id of the tag to be deleted.
1573 public function tagDelete($tagId) {
1574 require_once 'api/api.php';
1578 $result = $this->callAPISuccess('Tag', 'delete', $params);
1579 return $result['id'];
1583 * Add entity(s) to the tag
1585 * @param array $params
1589 public function entityTagAdd($params) {
1590 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1595 * Create contribution.
1601 * id of created contribution
1603 public function pledgeCreate($cID) {
1605 'contact_id' => $cID,
1606 'pledge_create_date' => date('Ymd'),
1607 'start_date' => date('Ymd'),
1608 'scheduled_date' => date('Ymd'),
1610 'pledge_status_id' => '2',
1611 'financial_type_id' => '1',
1612 'pledge_original_installment_amount' => 20,
1613 'frequency_interval' => 5,
1614 'frequency_unit' => 'year',
1615 'frequency_day' => 15,
1616 'installments' => 5,
1619 $result = $this->callAPISuccess('Pledge', 'create', $params);
1620 return $result['id'];
1624 * Delete contribution.
1626 * @param int $pledgeId
1628 public function pledgeDelete($pledgeId) {
1630 'pledge_id' => $pledgeId,
1632 $this->callAPISuccess('Pledge', 'delete', $params);
1636 * Create contribution.
1638 * @param array $params
1639 * Array of parameters.
1640 * @param int $cTypeID
1641 * Id of financial type.
1642 * @param int $invoiceID
1643 * @param int $trxnID
1644 * @param int $paymentInstrumentID
1647 * id of created contribution
1649 public function contributionCreate($params, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345,
1650 $paymentInstrumentID = 1) {
1652 $params = array_merge(array(
1654 'receive_date' => date('Ymd'),
1655 'total_amount' => 100.00,
1656 'fee_amount' => 5.00,
1657 'net_ammount' => 95.00,
1658 'financial_type_id' => $cTypeID,
1659 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1660 'non_deductible_amount' => 10.00,
1661 'trxn_id' => $trxnID,
1662 'invoice_id' => $invoiceID,
1664 'contribution_status_id' => 1,
1667 $result = $this->callAPISuccess('contribution', 'create', $params);
1668 return $result['id'];
1672 * Create online contribution.
1674 * @param array $params
1675 * @param int $financialType
1676 * Id of financial type.
1677 * @param int $invoiceID
1678 * @param int $trxnID
1681 * id of created contribution
1683 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1684 $contribParams = array(
1685 'contact_id' => $params['contact_id'],
1686 'receive_date' => date('Ymd'),
1687 'total_amount' => 100.00,
1688 'financial_type_id' => $financialType,
1689 'contribution_page_id' => $params['contribution_page_id'],
1691 'invoice_id' => 67890,
1694 $contribParams = array_merge($contribParams, $params);
1695 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1697 return $result['id'];
1701 * Delete contribution.
1703 * @param int $contributionId
1707 public function contributionDelete($contributionId) {
1709 'contribution_id' => $contributionId,
1711 $result = $this->callAPISuccess('contribution', 'delete', $params);
1718 * @param array $params
1719 * Name-value pair for an event.
1723 public function eventCreate($params = array()) {
1724 // if no contact was passed, make up a dummy event creator
1725 if (!isset($params['contact_id'])) {
1726 $params['contact_id'] = $this->_contactCreate(array(
1727 'contact_type' => 'Individual',
1728 'first_name' => 'Event',
1729 'last_name' => 'Creator',
1733 // set defaults for missing params
1734 $params = array_merge(array(
1735 'title' => 'Annual CiviCRM meet',
1736 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1737 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1738 'event_type_id' => 1,
1740 'start_date' => 20081021,
1741 'end_date' => 20081023,
1742 'is_online_registration' => 1,
1743 'registration_start_date' => 20080601,
1744 'registration_end_date' => 20081015,
1745 'max_participants' => 100,
1746 'event_full_text' => 'Sorry! We are already full',
1749 'is_show_location' => 0,
1752 return $this->callAPISuccess('Event', 'create', $params);
1763 public function eventDelete($id) {
1767 return $this->callAPISuccess('event', 'delete', $params);
1771 * Delete participant.
1773 * @param int $participantID
1777 public function participantDelete($participantID) {
1779 'id' => $participantID,
1781 return $this->callAPISuccess('Participant', 'delete', $params);
1785 * Create participant payment.
1787 * @param int $participantID
1788 * @param int $contributionID
1790 * $id of created payment
1792 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1793 //Create Participant Payment record With Values
1795 'participant_id' => $participantID,
1796 'contribution_id' => $contributionID,
1799 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1800 return $result['id'];
1804 * Delete participant payment.
1806 * @param int $paymentID
1808 public function participantPaymentDelete($paymentID) {
1812 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1818 * @param int $contactID
1820 * location id of created location
1822 public function locationAdd($contactID) {
1825 'location_type' => 'New Location Type',
1827 'name' => 'Saint Helier St',
1828 'county' => 'Marin',
1829 'country' => 'UNITED STATES',
1830 'state_province' => 'Michigan',
1831 'supplemental_address_1' => 'Hallmark Ct',
1832 'supplemental_address_2' => 'Jersey Village',
1837 'contact_id' => $contactID,
1838 'address' => $address,
1839 'location_format' => '2.0',
1840 'location_type' => 'New Location Type',
1843 $result = $this->callAPISuccess('Location', 'create', $params);
1848 * Delete Locations of contact.
1850 * @param array $params
1853 public function locationDelete($params) {
1854 $this->callAPISuccess('Location', 'delete', $params);
1858 * Add a Location Type.
1860 * @param array $params
1861 * @return CRM_Core_DAO_LocationType
1862 * location id of created location
1864 public function locationTypeCreate($params = NULL) {
1865 if ($params === NULL) {
1867 'name' => 'New Location Type',
1868 'vcard_name' => 'New Location Type',
1869 'description' => 'Location Type for Delete',
1874 $locationType = new CRM_Core_DAO_LocationType();
1875 $locationType->copyValues($params);
1876 $locationType->save();
1877 // clear getfields cache
1878 CRM_Core_PseudoConstant
::flush();
1879 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1880 return $locationType;
1884 * Delete a Location Type.
1886 * @param int $locationTypeId
1888 public function locationTypeDelete($locationTypeId) {
1889 $locationType = new CRM_Core_DAO_LocationType();
1890 $locationType->id
= $locationTypeId;
1891 $locationType->delete();
1897 * @param array $params
1899 * groupId of created group
1901 public function groupCreate($params = array()) {
1902 $params = array_merge(array(
1903 'name' => 'Test Group 1',
1905 'title' => 'New Test Group Created',
1906 'description' => 'New Test Group Created',
1908 'visibility' => 'Public Pages',
1909 'group_type' => array(
1915 $result = $this->callAPISuccess('Group', 'create', $params);
1916 return $result['id'];
1921 * Function to add a Group.
1923 * @params array to add group
1925 * @param int $groupID
1926 * @param int $totalCount
1928 * groupId of created group
1930 public function groupContactCreate($groupID, $totalCount = 10) {
1931 $params = array('group_id' => $groupID);
1932 for ($i = 1; $i <= $totalCount; $i++
) {
1933 $contactID = $this->individualCreate();
1935 $params +
= array('contact_id' => $contactID);
1938 $params +
= array("contact_id.$i" => $contactID);
1941 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1951 public function groupDelete($gid) {
1957 $this->callAPISuccess('Group', 'delete', $params);
1962 * @param array $params
1964 public function uFFieldCreate($params = array()) {
1965 $params = array_merge(array(
1967 'field_name' => 'first_name',
1970 'visibility' => 'Public Pages and Listings',
1971 'is_searchable' => '1',
1972 'label' => 'first_name',
1973 'field_type' => 'Individual',
1976 $this->callAPISuccess('uf_field', 'create', $params);
1980 * Add a UF Join Entry.
1982 * @param array $params
1984 * $id of created UF Join
1986 public function ufjoinCreate($params = NULL) {
1987 if ($params === NULL) {
1990 'module' => 'CiviEvent',
1991 'entity_table' => 'civicrm_event',
1997 $result = $this->callAPISuccess('uf_join', 'create', $params);
2002 * Delete a UF Join Entry.
2004 * @param array $params
2005 * with missing uf_group_id
2007 public function ufjoinDelete($params = NULL) {
2008 if ($params === NULL) {
2011 'module' => 'CiviEvent',
2012 'entity_table' => 'civicrm_event',
2015 'uf_group_id' => '',
2019 crm_add_uf_join($params);
2023 * @param array $params
2024 * Optional parameters.
2029 public function campaignCreate($params = array()) {
2030 $this->enableCiviCampaign();
2031 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2032 'name' => 'big_campaign',
2033 'title' => 'Campaign',
2035 return $campaign['id'];
2039 * Create Group for a contact.
2041 * @param int $contactId
2043 public function contactGroupCreate($contactId) {
2045 'contact_id.1' => $contactId,
2049 $this->callAPISuccess('GroupContact', 'Create', $params);
2053 * Delete Group for a contact.
2055 * @param int $contactId
2057 public function contactGroupDelete($contactId) {
2059 'contact_id.1' => $contactId,
2062 $this->civicrm_api('GroupContact', 'Delete', $params);
2068 * @param array $params
2071 public function activityCreate($params = NULL) {
2073 if ($params === NULL) {
2074 $individualSourceID = $this->individualCreate();
2076 $contactParams = array(
2077 'first_name' => 'Julia',
2078 'Last_name' => 'Anderson',
2080 'email' => 'julia_anderson@civicrm.org',
2081 'contact_type' => 'Individual',
2084 $individualTargetID = $this->individualCreate($contactParams);
2087 'source_contact_id' => $individualSourceID,
2088 'target_contact_id' => array($individualTargetID),
2089 'assignee_contact_id' => array($individualTargetID),
2090 'subject' => 'Discussion on warm beer',
2091 'activity_date_time' => date('Ymd'),
2092 'duration_hours' => 30,
2093 'duration_minutes' => 20,
2094 'location' => 'Baker Street',
2095 'details' => 'Lets schedule a meeting',
2097 'activity_name' => 'Meeting',
2101 $result = $this->callAPISuccess('Activity', 'create', $params);
2103 $result['target_contact_id'] = $individualTargetID;
2104 $result['assignee_contact_id'] = $individualTargetID;
2109 * Create an activity type.
2111 * @param array $params
2115 public function activityTypeCreate($params) {
2116 return $this->callAPISuccess('ActivityType', 'create', $params);
2120 * Delete activity type.
2122 * @param int $activityTypeId
2123 * Id of the activity type.
2126 public function activityTypeDelete($activityTypeId) {
2127 $params['activity_type_id'] = $activityTypeId;
2128 return $this->callAPISuccess('ActivityType', 'delete', $params);
2132 * Create custom group.
2134 * @param array $params
2137 public function customGroupCreate($params = array()) {
2139 'title' => 'new custom group',
2140 'extends' => 'Contact',
2142 'style' => 'Inline',
2146 $params = array_merge($defaults, $params);
2148 if (strlen($params['title']) > 13) {
2149 $params['title'] = substr($params['title'], 0, 13);
2152 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2153 $this->callAPISuccess('custom_group', 'get', array(
2154 'title' => $params['title'],
2155 array('api.custom_group.delete' => 1),
2158 return $this->callAPISuccess('custom_group', 'create', $params);
2162 * Existing function doesn't allow params to be over-ridden so need a new one
2163 * this one allows you to only pass in the params you want to change
2164 * @param array $params
2167 public function CustomGroupCreateByParams($params = array()) {
2169 'title' => "API Custom Group",
2170 'extends' => 'Contact',
2172 'style' => 'Inline',
2175 $params = array_merge($defaults, $params);
2176 return $this->callAPISuccess('custom_group', 'create', $params);
2180 * Create custom group with multi fields.
2181 * @param array $params
2184 public function CustomGroupMultipleCreateByParams($params = array()) {
2189 $params = array_merge($defaults, $params);
2190 return $this->CustomGroupCreateByParams($params);
2194 * Create custom group with multi fields.
2195 * @param array $params
2198 public function CustomGroupMultipleCreateWithFields($params = array()) {
2199 // also need to pass on $params['custom_field'] if not set but not in place yet
2201 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2202 $ids['custom_group_id'] = $customGroup['id'];
2204 $customField = $this->customFieldCreate(array(
2205 'custom_group_id' => $ids['custom_group_id'],
2206 'label' => 'field_1' . $ids['custom_group_id'],
2209 $ids['custom_field_id'][] = $customField['id'];
2211 $customField = $this->customFieldCreate(array(
2212 'custom_group_id' => $ids['custom_group_id'],
2213 'default_value' => '',
2214 'label' => 'field_2' . $ids['custom_group_id'],
2216 $ids['custom_field_id'][] = $customField['id'];
2218 $customField = $this->customFieldCreate(array(
2219 'custom_group_id' => $ids['custom_group_id'],
2220 'default_value' => '',
2221 'label' => 'field_3' . $ids['custom_group_id'],
2223 $ids['custom_field_id'][] = $customField['id'];
2229 * Create a custom group with a single text custom field. See
2230 * participant:testCreateWithCustom for how to use this
2232 * @param string $function
2234 * @param string $filename
2238 * ids of created objects
2240 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2241 $params = array('title' => $function);
2242 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2243 $params['extends'] = $entity ?
$entity : 'Contact';
2244 $customGroup = $this->CustomGroupCreate($params);
2245 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2246 CRM_Core_PseudoConstant
::flush();
2248 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2252 * Delete custom group.
2254 * @param int $customGroupID
2258 public function customGroupDelete($customGroupID) {
2259 $params['id'] = $customGroupID;
2260 return $this->callAPISuccess('custom_group', 'delete', $params);
2264 * Create custom field.
2266 * @param array $params
2267 * (custom_group_id) is required.
2270 public function customFieldCreate($params) {
2271 $params = array_merge(array(
2272 'label' => 'Custom Field',
2273 'data_type' => 'String',
2274 'html_type' => 'Text',
2275 'is_searchable' => 1,
2277 'default_value' => 'defaultValue',
2280 $result = $this->callAPISuccess('custom_field', 'create', $params);
2281 // these 2 functions are called with force to flush static caches
2282 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2283 CRM_Core_Component
::getEnabledComponents(1);
2288 * Delete custom field.
2290 * @param int $customFieldID
2294 public function customFieldDelete($customFieldID) {
2296 $params['id'] = $customFieldID;
2297 return $this->callAPISuccess('custom_field', 'delete', $params);
2306 public function noteCreate($cId) {
2308 'entity_table' => 'civicrm_contact',
2309 'entity_id' => $cId,
2310 'note' => 'hello I am testing Note',
2311 'contact_id' => $cId,
2312 'modified_date' => date('Ymd'),
2313 'subject' => 'Test Note',
2316 return $this->callAPISuccess('Note', 'create', $params);
2320 * Enable CiviCampaign Component.
2322 public function enableCiviCampaign() {
2323 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2324 // force reload of config object
2325 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2326 //flush cache by calling with reset
2327 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2331 * Create test generated example in api/v3/examples.
2333 * To turn this off (e.g. on the server) set
2334 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2335 * in your settings file
2337 * @param string $entity
2338 * @param string $action
2339 * @param array $params
2340 * Array as passed to civicrm_api function.
2341 * @param array $result
2342 * Array as received from the civicrm_api function.
2343 * @param string $testFunction
2344 * Calling function - generally __FUNCTION__.
2345 * @param string $testFile
2346 * Called from file - generally __FILE__.
2347 * @param string $description
2348 * Descriptive text for the example file.
2349 * @param string $exampleName
2350 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2352 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2353 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2356 $entity = _civicrm_api_get_camel_name($entity);
2357 $action = strtolower($action);
2359 if (empty($exampleName)) {
2360 // Attempt to convert lowercase action name to CamelCase.
2361 // This is clunky/imperfect due to the convention of all lowercase actions.
2362 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2363 $knownPrefixes = array(
2370 foreach ($knownPrefixes as $prefix) {
2371 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2372 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2377 $this->tidyExampleResult($result);
2378 if (isset($params['version'])) {
2379 unset($params['version']);
2381 // Format multiline description as array
2383 if (is_string($description) && strlen($description)) {
2384 foreach (explode("\n", $description) as $line) {
2385 $desc[] = trim($line);
2388 $smarty = CRM_Core_Smarty
::singleton();
2389 $smarty->assign('testFunction', $testFunction);
2390 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2391 $smarty->assign('params', $params);
2392 $smarty->assign('entity', $entity);
2393 $smarty->assign('testFile', basename($testFile));
2394 $smarty->assign('description', $desc);
2395 $smarty->assign('result', $result);
2396 $smarty->assign('action', $action);
2398 if (file_exists('../tests/templates/documentFunction.tpl')) {
2399 if (!is_dir("../api/v3/examples/$entity")) {
2400 mkdir("../api/v3/examples/$entity");
2402 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2403 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2409 * Tidy up examples array so that fields that change often ..don't
2410 * and debug related fields are unset
2412 * @param array $result
2414 public function tidyExampleResult(&$result) {
2415 if (!is_array($result)) {
2418 $fieldsToChange = array(
2419 'hash' => '67eac7789eaee00',
2420 'modified_date' => '2012-11-14 16:02:35',
2421 'created_date' => '2013-07-28 08:49:19',
2422 'create_date' => '20120130621222105',
2423 'application_received_date' => '20130728084957',
2424 'in_date' => '2013-07-28 08:50:19',
2425 'scheduled_date' => '20130728085413',
2426 'approval_date' => '20130728085413',
2427 'pledge_start_date_high' => '20130726090416',
2428 'start_date' => '2013-07-29 00:00:00',
2429 'event_start_date' => '2013-07-29 00:00:00',
2430 'end_date' => '2013-08-04 00:00:00',
2431 'event_end_date' => '2013-08-04 00:00:00',
2432 'decision_date' => '20130805000000',
2435 $keysToUnset = array('xdebug', 'undefined_fields');
2436 foreach ($keysToUnset as $unwantedKey) {
2437 if (isset($result[$unwantedKey])) {
2438 unset($result[$unwantedKey]);
2441 if (isset($result['values'])) {
2442 if (!is_array($result['values'])) {
2445 $resultArray = &$result['values'];
2447 elseif (is_array($result)) {
2448 $resultArray = &$result;
2454 foreach ($resultArray as $index => &$values) {
2455 if (!is_array($values)) {
2458 foreach ($values as $key => &$value) {
2459 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2460 if (isset($value['is_error'])) {
2461 // we have a std nested result format
2462 $this->tidyExampleResult($value);
2465 foreach ($value as &$nestedResult) {
2466 // this is an alternative syntax for nested results a keyed array of results
2467 $this->tidyExampleResult($nestedResult);
2471 if (in_array($key, $keysToUnset)) {
2472 unset($values[$key]);
2475 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2476 $value = $fieldsToChange[$key];
2478 if (is_string($value)) {
2479 $value = addslashes($value);
2488 * @param array $params
2492 public function noteDelete($params) {
2493 return $this->callAPISuccess('Note', 'delete', $params);
2497 * Create custom field with Option Values.
2499 * @param array $customGroup
2500 * @param string $name
2501 * Name of custom field.
2505 public function customFieldOptionValueCreate($customGroup, $name) {
2506 $fieldParams = array(
2507 'custom_group_id' => $customGroup['id'],
2508 'name' => 'test_custom_group',
2509 'label' => 'Country',
2510 'html_type' => 'Select',
2511 'data_type' => 'String',
2514 'is_searchable' => 0,
2518 $optionGroup = array(
2520 'name' => 'option_group1',
2521 'label' => 'option_group_label1',
2524 $optionValue = array(
2525 'option_label' => array('Label1', 'Label2'),
2526 'option_value' => array('value1', 'value2'),
2527 'option_name' => array($name . '_1', $name . '_2'),
2528 'option_weight' => array(1, 2),
2529 'option_status' => 1,
2532 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2534 return $this->callAPISuccess('custom_field', 'create', $params);
2542 public function confirmEntitiesDeleted($entities) {
2543 foreach ($entities as $entity) {
2545 $result = $this->callAPISuccess($entity, 'Get', array());
2546 if ($result['error'] == 1 ||
$result['count'] > 0) {
2547 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2555 * @param $tablesToTruncate
2556 * @param bool $dropCustomValueTables
2557 * @throws \Exception
2559 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2561 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2563 if ($dropCustomValueTables) {
2564 $tablesToTruncate[] = 'civicrm_custom_group';
2565 $tablesToTruncate[] = 'civicrm_custom_field';
2568 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2570 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2571 foreach ($tablesToTruncate as $table) {
2572 $sql = "TRUNCATE TABLE $table";
2573 CRM_Core_DAO
::executeQuery($sql);
2575 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2577 if ($dropCustomValueTables) {
2578 $dbName = self
::getDBName();
2580 SELECT TABLE_NAME as tableName
2581 FROM INFORMATION_SCHEMA.TABLES
2582 WHERE TABLE_SCHEMA = '{$dbName}'
2583 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2586 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2587 while ($tableDAO->fetch()) {
2588 $sql = "DROP TABLE {$tableDAO->tableName}";
2589 CRM_Core_DAO
::executeQuery($sql);
2595 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2597 public function quickCleanUpFinancialEntities() {
2598 $tablesToTruncate = array(
2600 'civicrm_activity_contact',
2601 'civicrm_contribution',
2602 'civicrm_contribution_soft',
2603 'civicrm_contribution_product',
2604 'civicrm_financial_trxn',
2605 'civicrm_financial_item',
2606 'civicrm_contribution_recur',
2607 'civicrm_line_item',
2608 'civicrm_contribution_page',
2609 'civicrm_payment_processor',
2610 'civicrm_entity_financial_trxn',
2611 'civicrm_membership',
2612 'civicrm_membership_type',
2613 'civicrm_membership_payment',
2614 'civicrm_membership_log',
2615 'civicrm_membership_block',
2617 'civicrm_participant',
2618 'civicrm_participant_payment',
2620 'civicrm_price_set_entity',
2621 'civicrm_price_field_value',
2622 'civicrm_price_field',
2624 $this->quickCleanup($tablesToTruncate);
2625 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2626 $this->restoreDefaultPriceSetConfig();
2628 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2629 Civi\Payment\System
::singleton()->flushProcessors();
2632 public function restoreDefaultPriceSetConfig() {
2633 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2634 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)");
2635 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)");
2638 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2639 * Default behaviour is to also delete the entity
2640 * @param array $params
2641 * Params array to check against.
2643 * Id of the entity concerned.
2644 * @param string $entity
2645 * Name of entity concerned (e.g. membership).
2646 * @param bool $delete
2647 * Should the entity be deleted as part of this check.
2648 * @param string $errorText
2649 * Text to print on error.
2652 * @param array $params
2655 * @param int $delete
2656 * @param string $errorText
2660 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2662 $result = $this->callAPISuccessGetSingle($entity, array(
2667 $this->callAPISuccess($entity, 'Delete', array(
2671 $dateFields = $keys = $dateTimeFields = array();
2672 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2673 foreach ($fields['values'] as $field => $settings) {
2674 if (array_key_exists($field, $result)) {
2675 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2678 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2680 $type = CRM_Utils_Array
::value('type', $settings);
2681 if ($type == CRM_Utils_Type
::T_DATE
) {
2682 $dateFields[] = $settings['name'];
2683 // we should identify both real names & unique names as dates
2684 if ($field != $settings['name']) {
2685 $dateFields[] = $field;
2688 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2689 $dateTimeFields[] = $settings['name'];
2690 // we should identify both real names & unique names as dates
2691 if ($field != $settings['name']) {
2692 $dateTimeFields[] = $field;
2697 if (strtolower($entity) == 'contribution') {
2698 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2699 // this is not returned in id format
2700 unset($params['payment_instrument_id']);
2701 $params['contribution_source'] = $params['source'];
2702 unset($params['source']);
2705 foreach ($params as $key => $value) {
2706 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2709 if (in_array($key, $dateFields)) {
2710 $value = date('Y-m-d', strtotime($value));
2711 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2713 if (in_array($key, $dateTimeFields)) {
2714 $value = date('Y-m-d H:i:s', strtotime($value));
2715 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2717 $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);
2722 * Get formatted values in the actual and expected result.
2723 * @param array $actual
2724 * Actual calculated values.
2725 * @param array $expected
2728 public function checkArrayEquals(&$actual, &$expected) {
2729 self
::unsetId($actual);
2730 self
::unsetId($expected);
2731 $this->assertEquals($actual, $expected);
2735 * Unset the key 'id' from the array
2736 * @param array $unformattedArray
2737 * The array from which the 'id' has to be unset.
2739 public static function unsetId(&$unformattedArray) {
2740 $formattedArray = array();
2741 if (array_key_exists('id', $unformattedArray)) {
2742 unset($unformattedArray['id']);
2744 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2745 foreach ($unformattedArray['values'] as $key => $value) {
2746 if (is_array($value)) {
2747 foreach ($value as $k => $v) {
2753 elseif ($key == 'id') {
2754 $unformattedArray[$key];
2756 $formattedArray = array($value);
2758 $unformattedArray['values'] = $formattedArray;
2763 * Helper to enable/disable custom directory support
2765 * @param array $customDirs
2767 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2768 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2770 public function customDirectories($customDirs) {
2771 require_once 'CRM/Core/Config.php';
2772 $config = CRM_Core_Config
::singleton();
2774 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2775 unset($config->customPHPPathDir
);
2777 elseif ($customDirs['php_path'] === TRUE) {
2778 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2781 $config->customPHPPathDir
= $php_path;
2784 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2785 unset($config->customTemplateDir
);
2787 elseif ($customDirs['template_path'] === TRUE) {
2788 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2791 $config->customTemplateDir
= $template_path;
2796 * Generate a temporary folder.
2798 * @param string $prefix
2801 public function createTempDir($prefix = 'test-') {
2802 $tempDir = CRM_Utils_File
::tempdir($prefix);
2803 $this->tempDirs
[] = $tempDir;
2807 public function cleanTempDirs() {
2808 if (!is_array($this->tempDirs
)) {
2809 // fix test errors where this is not set
2812 foreach ($this->tempDirs
as $tempDir) {
2813 if (is_dir($tempDir)) {
2814 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2820 * Temporarily replace the singleton extension with a different one.
2821 * @param \CRM_Extension_System $system
2823 public function setExtensionSystem(CRM_Extension_System
$system) {
2824 if ($this->origExtensionSystem
== NULL) {
2825 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2827 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2830 public function unsetExtensionSystem() {
2831 if ($this->origExtensionSystem
!== NULL) {
2832 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2833 $this->origExtensionSystem
= NULL;
2838 * Temporarily alter the settings-metadata to add a mock setting.
2840 * WARNING: The setting metadata will disappear on the next cache-clear.
2845 public function setMockSettingsMetaData($extras) {
2846 CRM_Core_BAO_Setting
::$_cache = array();
2847 $this->callAPISuccess('system', 'flush', array());
2848 CRM_Core_BAO_Setting
::$_cache = array();
2850 CRM_Utils_Hook
::singleton()
2851 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2852 $metadata = array_merge($metadata, $extras);
2855 $fields = $this->callAPISuccess('setting', 'getfields', array());
2856 foreach ($extras as $key => $spec) {
2857 $this->assertNotEmpty($spec['title']);
2858 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2863 * @param string $name
2865 public function financialAccountDelete($name) {
2866 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2867 $financialAccount->name
= $name;
2868 if ($financialAccount->find(TRUE)) {
2869 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2870 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2871 $entityFinancialType->delete();
2872 $financialAccount->delete();
2877 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2878 * (NB unclear if this is still required)
2880 public function _sethtmlGlobals() {
2881 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2882 'required' => array(
2883 'html_quickform_rule_required',
2884 'HTML/QuickForm/Rule/Required.php',
2886 'maxlength' => array(
2887 'html_quickform_rule_range',
2888 'HTML/QuickForm/Rule/Range.php',
2890 'minlength' => array(
2891 'html_quickform_rule_range',
2892 'HTML/QuickForm/Rule/Range.php',
2894 'rangelength' => array(
2895 'html_quickform_rule_range',
2896 'HTML/QuickForm/Rule/Range.php',
2899 'html_quickform_rule_email',
2900 'HTML/QuickForm/Rule/Email.php',
2903 'html_quickform_rule_regex',
2904 'HTML/QuickForm/Rule/Regex.php',
2906 'lettersonly' => array(
2907 'html_quickform_rule_regex',
2908 'HTML/QuickForm/Rule/Regex.php',
2910 'alphanumeric' => array(
2911 'html_quickform_rule_regex',
2912 'HTML/QuickForm/Rule/Regex.php',
2915 'html_quickform_rule_regex',
2916 'HTML/QuickForm/Rule/Regex.php',
2918 'nopunctuation' => array(
2919 'html_quickform_rule_regex',
2920 'HTML/QuickForm/Rule/Regex.php',
2923 'html_quickform_rule_regex',
2924 'HTML/QuickForm/Rule/Regex.php',
2926 'callback' => array(
2927 'html_quickform_rule_callback',
2928 'HTML/QuickForm/Rule/Callback.php',
2931 'html_quickform_rule_compare',
2932 'HTML/QuickForm/Rule/Compare.php',
2935 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2936 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2938 'HTML/QuickForm/group.php',
2939 'HTML_QuickForm_group',
2942 'HTML/QuickForm/hidden.php',
2943 'HTML_QuickForm_hidden',
2946 'HTML/QuickForm/reset.php',
2947 'HTML_QuickForm_reset',
2949 'checkbox' => array(
2950 'HTML/QuickForm/checkbox.php',
2951 'HTML_QuickForm_checkbox',
2954 'HTML/QuickForm/file.php',
2955 'HTML_QuickForm_file',
2958 'HTML/QuickForm/image.php',
2959 'HTML_QuickForm_image',
2961 'password' => array(
2962 'HTML/QuickForm/password.php',
2963 'HTML_QuickForm_password',
2966 'HTML/QuickForm/radio.php',
2967 'HTML_QuickForm_radio',
2970 'HTML/QuickForm/button.php',
2971 'HTML_QuickForm_button',
2974 'HTML/QuickForm/submit.php',
2975 'HTML_QuickForm_submit',
2978 'HTML/QuickForm/select.php',
2979 'HTML_QuickForm_select',
2981 'hiddenselect' => array(
2982 'HTML/QuickForm/hiddenselect.php',
2983 'HTML_QuickForm_hiddenselect',
2986 'HTML/QuickForm/text.php',
2987 'HTML_QuickForm_text',
2989 'textarea' => array(
2990 'HTML/QuickForm/textarea.php',
2991 'HTML_QuickForm_textarea',
2993 'fckeditor' => array(
2994 'HTML/QuickForm/fckeditor.php',
2995 'HTML_QuickForm_FCKEditor',
2998 'HTML/QuickForm/tinymce.php',
2999 'HTML_QuickForm_TinyMCE',
3001 'dojoeditor' => array(
3002 'HTML/QuickForm/dojoeditor.php',
3003 'HTML_QuickForm_dojoeditor',
3006 'HTML/QuickForm/link.php',
3007 'HTML_QuickForm_link',
3009 'advcheckbox' => array(
3010 'HTML/QuickForm/advcheckbox.php',
3011 'HTML_QuickForm_advcheckbox',
3014 'HTML/QuickForm/date.php',
3015 'HTML_QuickForm_date',
3018 'HTML/QuickForm/static.php',
3019 'HTML_QuickForm_static',
3022 'HTML/QuickForm/header.php',
3023 'HTML_QuickForm_header',
3026 'HTML/QuickForm/html.php',
3027 'HTML_QuickForm_html',
3029 'hierselect' => array(
3030 'HTML/QuickForm/hierselect.php',
3031 'HTML_QuickForm_hierselect',
3033 'autocomplete' => array(
3034 'HTML/QuickForm/autocomplete.php',
3035 'HTML_QuickForm_autocomplete',
3038 'HTML/QuickForm/xbutton.php',
3039 'HTML_QuickForm_xbutton',
3041 'advmultiselect' => array(
3042 'HTML/QuickForm/advmultiselect.php',
3043 'HTML_QuickForm_advmultiselect',
3049 * Set up an acl allowing contact to see 2 specified groups
3050 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3052 * You need to have pre-created these groups & created the user e.g
3053 * $this->createLoggedInUser();
3054 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3055 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3057 public function setupACL($isProfile = FALSE) {
3059 $_REQUEST = $this->_params
;
3061 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3062 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3063 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3064 'option_group_id' => $optionGroupID,
3065 'label' => 'pick me',
3069 CRM_Core_DAO
::executeQuery("
3070 TRUNCATE civicrm_acl_cache
3073 CRM_Core_DAO
::executeQuery("
3074 TRUNCATE civicrm_acl_contact_cache
3077 CRM_Core_DAO
::executeQuery("
3078 INSERT INTO civicrm_acl_entity_role (
3079 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3080 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3084 CRM_Core_DAO
::executeQuery("
3085 INSERT INTO civicrm_acl (
3086 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3089 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3094 CRM_Core_DAO
::executeQuery("
3095 INSERT INTO civicrm_acl (
3096 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3099 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3103 CRM_Core_DAO
::executeQuery("
3104 INSERT INTO civicrm_acl (
3105 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3108 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3113 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3114 $this->callAPISuccess('group_contact', 'create', array(
3115 'group_id' => $this->_permissionedGroup
,
3116 'contact_id' => $this->_loggedInUser
,
3121 CRM_ACL_BAO_Cache
::resetCache();
3122 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3123 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3128 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3130 public function offsetDefaultPriceSet() {
3131 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3132 $firstID = $contributionPriceSet['id'];
3133 $this->callAPISuccess('price_set', 'create', array(
3134 'id' => $contributionPriceSet['id'],
3138 unset($contributionPriceSet['id']);
3139 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3140 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3141 'price_set_id' => $firstID,
3142 'options' => array('limit' => 1),
3144 unset($priceField['id']);
3145 $priceField['price_set_id'] = $newPriceSet['id'];
3146 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3147 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3148 'price_set_id' => $firstID,
3150 'options' => array('limit' => 1),
3153 unset($priceFieldValue['id']);
3154 //create some padding to use up ids
3155 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3156 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3157 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3161 * Create an instance of the paypal processor.
3162 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3163 * this parent class & we don't have a structure for that yet
3164 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3165 * & the best protection against that is the functions this class affords
3166 * @param array $params
3167 * @return int $result['id'] payment processor id
3169 public function paymentProcessorCreate($params = array()) {
3170 $params = array_merge(array(
3172 'domain_id' => CRM_Core_Config
::domainID(),
3173 'payment_processor_type_id' => 'PayPal',
3177 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3178 'password' => '1183377788',
3179 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3180 'url_site' => 'https://www.sandbox.paypal.com/',
3181 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3182 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3183 'class_name' => 'Payment_PayPalImpl',
3184 'billing_mode' => 3,
3185 'financial_type_id' => 1,
3188 if (!is_numeric($params['payment_processor_type_id'])) {
3189 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3191 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3192 'name' => $params['payment_processor_type_id'],
3196 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3197 return $result['id'];
3201 * Set up initial recurring payment allowing subsequent IPN payments.
3203 public function setupRecurringPaymentProcessorTransaction() {
3204 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3205 'contact_id' => $this->_contactID
,
3208 'installments' => 5,
3209 'frequency_unit' => 'Month',
3210 'frequency_interval' => 1,
3211 'invoice_id' => $this->_invoiceID
,
3212 'contribution_status_id' => 2,
3213 'processor_id' => $this->_paymentProcessorID
,
3214 'api.contribution.create' => array(
3215 'total_amount' => '200',
3216 'invoice_id' => $this->_invoiceID
,
3217 'financial_type_id' => 1,
3218 'contribution_status_id' => 'Pending',
3219 'contact_id' => $this->_contactID
,
3220 'contribution_page_id' => $this->_contributionPageID
,
3221 'payment_processor_id' => $this->_paymentProcessorID
,
3225 $this->_contributionRecurID
= $contributionRecur['id'];
3226 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3230 * 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
3232 public function setupMembershipRecurringPaymentProcessorTransaction() {
3233 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3234 //create a contribution so our membership & contribution don't both have id = 1
3235 $this->contributionCreate(array(
3236 'contact_id' => $this->_contactID
,
3239 $this->setupRecurringPaymentProcessorTransaction();
3241 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3242 'contact_id' => $this->_contactID
,
3243 'membership_type_id' => $this->ids
['membership_type'],
3244 'contribution_recur_id' => $this->_contributionRecurID
,
3245 'format.only_id' => TRUE,
3247 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3248 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3250 $this->callAPISuccess('line_item', 'create', array(
3251 'entity_table' => 'civicrm_membership',
3252 'entity_id' => $this->ids
['membership'],
3253 'contribution_id' => $this->_contributionID
,
3254 'label' => 'General',
3256 'unit_price' => 200,
3257 'line_total' => 200,
3258 'financial_type_id' => 1,
3259 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3261 'label' => 'Membership Amount',
3263 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3265 'label' => 'General',
3268 $this->callAPISuccess('membership_payment', 'create', array(
3269 'contribution_id' => $this->_contributionID
,
3270 'membership_id' => $this->ids
['membership'],
3279 public function CiviUnitTestCase_fatalErrorHandler($message) {
3280 throw new Exception("{$message['message']}: {$message['code']}");
3284 * Helper function to create new mailing.
3287 public function createMailing() {
3289 'subject' => 'maild' . rand(),
3290 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3291 'name' => 'mailing name' . rand(),
3295 $result = $this->callAPISuccess('Mailing', 'create', $params);
3296 return $result['id'];
3300 * Helper function to delete mailing.
3303 public function deleteMailing($id) {
3308 $this->callAPISuccess('Mailing', 'delete', $params);
3312 * Wrap the entire test case in a transaction.
3314 * Only subsequent DB statements will be wrapped in TX -- this cannot
3315 * retroactively wrap old DB statements. Therefore, it makes sense to
3316 * call this at the beginning of setUp().
3318 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3319 * this option does not work with, e.g., custom-data.
3321 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3322 * if TRUNCATE or ALTER is called while using a transaction.
3325 * Whether to use nesting or reference-counting.
3327 public function useTransaction($nest = TRUE) {
3329 $this->tx
= new CRM_Core_Transaction($nest);
3330 $this->tx
->rollback();
3334 public function clearOutputBuffer() {
3335 while (ob_get_level() > 0) {
3342 * @param array $apiResult
3344 protected function assertAttachmentExistence($exists, $apiResult) {
3345 $fileId = $apiResult['id'];
3346 $this->assertTrue(is_numeric($fileId));
3347 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3348 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3349 1 => array($fileId, 'Int'),
3351 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3352 1 => array($fileId, 'Int'),