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 * Allow classes to state E-notice compliance
124 public $_eNoticeCompliant = TRUE;
127 * @var boolean DBResetRequired allows skipping DB reset
128 * in specific test case. If you still need
129 * to reset single test (method) of such case, call
130 * $this->cleanDB() in the first line of this
133 public $DBResetRequired = TRUE;
136 * @var CRM_Core_Transaction|NULL
141 * @var CRM_Utils_Hook_UnitTests hookClass
142 * example of setting a method for a hook
143 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
145 public $hookClass = NULL;
148 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
150 protected $_params = array();
153 * @var CRM_Extension_System
155 protected $origExtensionSystem;
160 * Because we are overriding the parent class constructor, we
161 * need to show the same arguments as exist in the constructor of
162 * PHPUnit_Framework_TestCase, since
163 * PHPUnit_Framework_TestSuite::createTest() creates a
164 * ReflectionClass of the Test class and checks the constructor
165 * of that class to decide how to set up the test.
167 * @param string $name
169 * @param string $dataName
171 public function __construct($name = NULL, array$data = array(), $dataName = '') {
172 parent
::__construct($name, $data, $dataName);
174 // we need full error reporting
175 error_reporting(E_ALL
& ~E_NOTICE
);
177 if (!empty($GLOBALS['mysql_db'])) {
178 self
::$_dbName = $GLOBALS['mysql_db'];
181 self
::$_dbName = 'civicrm_tests_dev';
184 // create test database
185 self
::$utils = new Utils($GLOBALS['mysql_host'],
186 $GLOBALS['mysql_port'],
187 $GLOBALS['mysql_user'],
188 $GLOBALS['mysql_pass']
191 // also load the class loader
192 require_once 'CRM/Core/ClassLoader.php';
193 CRM_Core_ClassLoader
::singleton()->register();
194 if (function_exists('_civix_phpunit_setUp')) {
195 // FIXME: loosen coupling
196 _civix_phpunit_setUp();
201 * Override to run the test and assert its state.
204 * @throws \PHPUnit_Framework_IncompleteTest
205 * @throws \PHPUnit_Framework_SkippedTest
207 protected function runTest() {
209 return parent
::runTest();
211 catch (PEAR_Exception
$e) {
212 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
213 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
220 public function requireDBReset() {
221 return $this->DBResetRequired
;
227 public static function getDBName() {
228 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
233 * Create database connection for this instance.
235 * Initialize the test database if it hasn't been initialized
237 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
239 protected function getConnection() {
240 $dbName = self
::$_dbName;
241 if (!self
::$dbInit) {
242 $dbName = self
::getDBName();
244 // install test database
245 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
247 static::_populateDB(FALSE, $this);
249 self
::$dbInit = TRUE;
251 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
255 * Required implementation of abstract method.
257 protected function getDataSet() {
261 * @param bool $perClass
262 * @param null $object
264 * TRUE if the populate logic runs; FALSE if it is skipped
266 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
268 if ($perClass ||
$object == NULL) {
272 $dbreset = $object->requireDBReset();
275 if (self
::$populateOnce ||
!$dbreset) {
278 self
::$populateOnce = NULL;
280 $dbName = self
::getDBName();
281 $pdo = self
::$utils->pdo
;
282 // only consider real tables and not views
283 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
284 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
286 $truncates = array();
288 foreach ($tables as $table) {
290 if (substr($table['table_name'], 0, 4) == 'log_') {
294 // don't change list of installed extensions
295 if ($table['table_name'] == 'civicrm_extension') {
299 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
300 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
303 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
309 "SET foreign_key_checks = 0",
310 // SQL mode needs to be strict, that's our standard
311 "SET SQL_MODE='STRICT_ALL_TABLES';",
312 "SET global innodb_flush_log_at_trx_commit = 2;",
314 $queries = array_merge($queries, $truncates);
315 $queries = array_merge($queries, $drops);
316 foreach ($queries as $query) {
317 if (self
::$utils->do_query($query) === FALSE) {
318 // failed to create test database
319 echo "failed to create test db.";
324 // initialize test database
325 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
326 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
327 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
329 $query2 = file_get_contents($sql_file2);
330 $query3 = file_get_contents($sql_file3);
331 $query4 = file_get_contents($sql_file4);
332 if (self
::$utils->do_query($query2) === FALSE) {
333 echo "Cannot load civicrm_data.mysql. Aborting.";
336 if (self
::$utils->do_query($query3) === FALSE) {
337 echo "Cannot load test_data.mysql. Aborting.";
340 if (self
::$utils->do_query($query4) === FALSE) {
341 echo "Cannot load test_data.mysql. Aborting.";
345 // done with all the loading, get transactions back
346 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
347 echo "Cannot set global? Huh?";
351 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
352 echo "Cannot get foreign keys back? Huh?";
356 unset($query, $query2, $query3);
359 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
361 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
373 public static function setUpBeforeClass() {
374 static::_populateDB(TRUE);
376 // also set this global hack
377 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
381 * Common setup functions for all unit tests.
383 protected function setUp() {
384 $session = CRM_Core_Session
::singleton();
385 $session->set('userID', NULL);
387 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
388 // Use a temporary file for STDIN
389 $GLOBALS['stdin'] = tmpfile();
390 if ($GLOBALS['stdin'] === FALSE) {
391 echo "Couldn't open temporary file\n";
395 // Get and save a connection to the database
396 $this->_dbconn
= $this->getConnection();
398 // reload database before each test
399 // $this->_populateDB();
401 // "initialize" CiviCRM to avoid problems when running single tests
402 // FIXME: look at it closer in second stage
404 // initialize the object once db is loaded
405 CRM_Core_Config
::$_mail = NULL;
406 $config = CRM_Core_Config
::singleton();
408 // when running unit tests, use mockup user framework
409 $config->setUserFramework('UnitTests');
410 $this->hookClass
= CRM_Utils_Hook
::singleton(TRUE);
411 // also fix the fatal error handler to throw exceptions,
413 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
415 // enable backtrace to get meaningful errors
416 $config->backtrace
= 1;
418 // disable any left-over test extensions
419 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
421 // reset all the caches
422 CRM_Utils_System
::flushCache();
424 // Make sure the DB connection is setup properly
425 $config->userSystem
->setMySQLTimeZone();
426 $env = new CRM_Utils_Check_Env();
427 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
429 // clear permissions stub to not check permissions
430 $config = CRM_Core_Config
::singleton();
431 $config->userPermissionClass
->permissions
= NULL;
433 //flush component settings
434 CRM_Core_Component
::getEnabledComponents(TRUE);
436 if ($this->_eNoticeCompliant
) {
437 error_reporting(E_ALL
);
440 error_reporting(E_ALL
& ~E_NOTICE
);
442 $this->_sethtmlGlobals();
446 * Read everything from the datasets directory and insert into the db.
448 public function loadAllFixtures() {
449 $fixturesDir = __DIR__
. '/../../fixtures';
451 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
453 $xmlFiles = glob($fixturesDir . '/*.xml');
454 foreach ($xmlFiles as $xmlFixture) {
455 $op = new PHPUnit_Extensions_Database_Operation_Insert();
456 $dataset = $this->createXMLDataSet($xmlFixture);
457 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
458 $op->execute($this->_dbconn
, $dataset);
461 $yamlFiles = glob($fixturesDir . '/*.yaml');
462 foreach ($yamlFiles as $yamlFixture) {
463 $op = new PHPUnit_Extensions_Database_Operation_Insert();
464 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
465 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
466 $op->execute($this->_dbconn
, $dataset);
469 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
473 * Emulate a logged in user since certain functions use that.
474 * value to store a record in the DB (like activity)
478 * Contact ID of the created user.
480 public function createLoggedInUser() {
482 'first_name' => 'Logged In',
483 'last_name' => 'User ' . rand(),
484 'contact_type' => 'Individual',
486 $contactID = $this->individualCreate($params);
487 $this->callAPISuccess('UFMatch', 'create', array(
488 'contact_id' => $contactID,
489 'uf_name' => 'superman',
493 $session = CRM_Core_Session
::singleton();
494 $session->set('userID', $contactID);
498 public function cleanDB() {
499 self
::$populateOnce = NULL;
500 $this->DBResetRequired
= TRUE;
502 $this->_dbconn
= $this->getConnection();
503 static::_populateDB();
504 $this->tempDirs
= array();
508 * Create default domain contacts for the two domains added during test class.
509 * database population.
511 public function createDomainContacts() {
512 $default_domain_contact = $this->organizationCreate();
513 $second_domain_contact = $this->organizationCreate();
517 * Common teardown functions for all unit tests.
519 protected function tearDown() {
520 error_reporting(E_ALL
& ~E_NOTICE
);
521 CRM_Utils_Hook
::singleton()->reset();
522 $this->hookClass
->reset();
523 $session = CRM_Core_Session
::singleton();
524 $session->set('userID', NULL);
527 $this->tx
->rollback()->commit();
530 CRM_Core_Transaction
::forceRollbackIfEnabled();
531 \Civi\Core\Transaction\Manager
::singleton(TRUE);
534 CRM_Core_Transaction
::forceRollbackIfEnabled();
535 \Civi\Core\Transaction\Manager
::singleton(TRUE);
537 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
538 $this->quickCleanup($tablesToTruncate);
539 $this->createDomainContacts();
542 $this->cleanTempDirs();
543 $this->unsetExtensionSystem();
544 $this->clearOutputBuffer();
548 * FIXME: Maybe a better way to do it
550 public function foreignKeyChecksOff() {
551 self
::$utils = new Utils($GLOBALS['mysql_host'],
552 $GLOBALS['mysql_port'],
553 $GLOBALS['mysql_user'],
554 $GLOBALS['mysql_pass']
556 $dbName = self
::getDBName();
557 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
558 if (self
::$utils->do_query($query) === FALSE) {
560 echo 'Cannot set foreign_key_checks = 0';
566 public function foreignKeyChecksOn() {
567 // FIXME: might not be needed if previous fixme implemented
571 * Generic function to compare expected values after an api call to retrieved.
574 * @daoName string DAO Name of object we're evaluating.
575 * @id int Id of object
576 * @match array Associative array of field name => expected value. Empty if asserting
577 * that a DELETE occurred
578 * @delete boolean True if we're checking that a DELETE action occurred.
582 * @param bool $delete
583 * @throws \PHPUnit_Framework_AssertionFailedError
585 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
587 // adding this here since developers forget to check for an id
588 // and hence we get the first value in the db
589 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
592 $object = new $daoName();
596 // If we're asserting successful record deletion, make sure object is NOT found.
598 if ($object->find(TRUE)) {
599 $this->fail("Object not deleted by delete operation: $daoName, $id");
604 // Otherwise check matches of DAO field values against expected values in $match.
605 if ($object->find(TRUE)) {
606 $fields = &$object->fields();
607 foreach ($fields as $name => $value) {
608 $dbName = $value['name'];
609 if (isset($match[$name])) {
611 $this->assertEquals($object->$dbName, $match[$name]);
613 elseif (isset($match[$dbName])) {
615 $this->assertEquals($object->$dbName, $match[$dbName]);
620 $this->fail("Could not retrieve object: $daoName, $id");
623 $matchSize = count($match);
624 if ($verifiedCount != $matchSize) {
625 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
630 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
631 * @param string $daoName
632 * @param $searchValue
633 * @param $returnColumn
634 * @param $searchColumn
637 * @return null|string
638 * @throws PHPUnit_Framework_AssertionFailedError
640 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
641 if (empty($searchValue)) {
642 $this->fail("empty value passed to assertDBNotNull");
644 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
645 $this->assertNotNull($value, $message);
651 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
652 * @param string $daoName
653 * @param $searchValue
654 * @param $returnColumn
655 * @param $searchColumn
658 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
659 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
660 $this->assertNull($value, $message);
664 * Request a record from the DB by id. Success if row not found.
665 * @param string $daoName
667 * @param null $message
669 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
670 $message = $message ?
$message : "$daoName (#$id) should not exist";
671 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
672 $this->assertNull($value, $message);
676 * Request a record from the DB by id. Success if row not found.
677 * @param string $daoName
679 * @param null $message
681 public function assertDBRowExist($daoName, $id, $message = NULL) {
682 $message = $message ?
$message : "$daoName (#$id) should exist";
683 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
684 $this->assertEquals($id, $value, $message);
688 * Compare a single column value in a retrieved DB record to an expected value.
689 * @param string $daoName
690 * @param $searchValue
691 * @param $returnColumn
692 * @param $searchColumn
693 * @param $expectedValue
696 public function assertDBCompareValue(
697 $daoName, $searchValue, $returnColumn, $searchColumn,
698 $expectedValue, $message
700 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
701 $this->assertEquals($value, $expectedValue, $message);
705 * Compare all values in a single retrieved DB record to an array of expected values.
706 * @param string $daoName
707 * @param array $searchParams
708 * @param $expectedValues
710 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
711 //get the values from db
713 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
715 // compare db values with expected values
716 self
::assertAttributesEquals($expectedValues, $dbValues);
720 * Assert that a SQL query returns a given value.
722 * The first argument is an expected value. The remaining arguments are passed
723 * to CRM_Core_DAO::singleValueQuery
725 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
726 * array(1 => array("Whiz", "String")));
729 * @param array $params
730 * @param string $message
732 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
736 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
737 $this->assertEquals($expected, $actual,
738 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
739 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
745 * Assert that two array-trees are exactly equal, notwithstanding
746 * the sorting of keys
748 * @param array $expected
749 * @param array $actual
751 public function assertTreeEquals($expected, $actual) {
754 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
755 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
759 $this->assertEquals($e, $a);
763 * Assert that two numbers are approximately equal.
765 * @param int|float $expected
766 * @param int|float $actual
767 * @param int|float $tolerance
768 * @param string $message
770 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
771 if ($message === NULL) {
772 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
774 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
778 * Assert attributes are equal.
780 * @param $expectedValues
781 * @param $actualValues
782 * @param string $message
784 * @throws PHPUnit_Framework_AssertionFailedError
786 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
787 foreach ($expectedValues as $paramName => $paramValue) {
788 if (isset($actualValues[$paramName])) {
789 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
792 $this->fail("Attribute '$paramName' not present in actual array.");
801 public function assertArrayKeyExists($key, &$list) {
802 $result = isset($list[$key]) ?
TRUE : FALSE;
803 $this->assertTrue($result, ts("%1 element exists?",
812 public function assertArrayValueNotNull($key, &$list) {
813 $this->assertArrayKeyExists($key, $list);
815 $value = isset($list[$key]) ?
$list[$key] : NULL;
816 $this->assertTrue($value,
817 ts("%1 element not null?",
824 * Check that api returned 'is_error' => 0.
826 * @param array $apiResult
828 * @param string $prefix
829 * Extra test to add to message.
831 public function assertAPISuccess($apiResult, $prefix = '') {
832 if (!empty($prefix)) {
835 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
837 if (!empty($apiResult['debug_information'])) {
838 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
840 if (!empty($apiResult['trace'])) {
841 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
843 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
847 * Check that api returned 'is_error' => 1.
849 * @param array $apiResult
851 * @param string $prefix
852 * Extra test to add to message.
853 * @param null $expectedError
855 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
856 if (!empty($prefix)) {
859 if ($expectedError && !empty($apiResult['is_error'])) {
860 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
862 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
863 $this->assertNotEmpty($apiResult['error_message']);
869 * @param string $message
871 public function assertType($expected, $actual, $message = '') {
872 return $this->assertInternalType($expected, $actual, $message);
876 * Check that a deleted item has been deleted.
881 public function assertAPIDeleted($entity, $id) {
882 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
887 * Check that api returned 'is_error' => 1
888 * else provide full message
889 * @param array $result
891 * @param array $valuesToExclude
892 * @param string $prefix
893 * Extra test to add to message.
895 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
896 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
897 foreach ($valuesToExclude as $value) {
898 if (isset($result[$value])) {
899 unset($result[$value]);
901 if (isset($expected[$value])) {
902 unset($expected[$value]);
905 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
909 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
913 * @param array $params
916 public function civicrm_api($entity, $action, $params) {
917 return civicrm_api($entity, $action, $params);
921 * Create a batch of external API calls which can
922 * be executed concurrently.
925 * $calls = $this->createExternalAPI()
926 * ->addCall('Contact', 'get', ...)
927 * ->addCall('Contact', 'get', ...)
933 * @return \Civi\API\ExternalBatch
934 * @throws PHPUnit_Framework_SkippedTestError
936 public function createExternalAPI() {
937 global $civicrm_root;
938 $defaultParams = array(
939 'version' => $this->_apiversion
,
943 $calls = new \Civi\API\
ExternalBatch($defaultParams);
944 $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
946 if (!$calls->isSupported()) {
947 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
954 * wrap api functions.
955 * so we can ensure they succeed & throw exceptions without litterering the test with checks
957 * @param string $entity
958 * @param string $action
959 * @param array $params
960 * @param mixed $checkAgainst
961 * Optional value to check result against, implemented for getvalue,.
962 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
963 * for getsingle the array is compared against an array passed in - the id is not compared (for
968 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
969 $params = array_merge(array(
970 'version' => $this->_apiversion
,
975 switch (strtolower($action)) {
977 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
980 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
983 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
985 $result = $this->civicrm_api($entity, $action, $params);
986 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
991 * This function exists to wrap api getValue function & check the result
992 * so we can ensure they succeed & throw exceptions without litterering the test with checks
993 * There is a type check in this
995 * @param string $entity
996 * @param array $params
997 * @param string $type
998 * Per http://php.net/manual/en/function.gettype.php possible types.
1008 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
1010 'version' => $this->_apiversion
,
1013 $result = $this->civicrm_api($entity, 'getvalue', $params);
1015 if ($type == 'integer') {
1016 // api seems to return integers as strings
1017 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
1020 $this->assertType($type, $result, "returned result should have been of type $type but was ");
1027 * This function exists to wrap api getsingle function & check the result
1028 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1030 * @param string $entity
1031 * @param array $params
1032 * @param array $checkAgainst
1033 * Array to compare result against.
1044 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
1046 'version' => $this->_apiversion
,
1049 $result = $this->civicrm_api($entity, 'getsingle', $params);
1050 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1051 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1053 if ($checkAgainst) {
1054 // @todo - have gone with the fn that unsets id? should we check id?
1055 $this->checkArrayEquals($result, $checkAgainst);
1061 * This function exists to wrap api getValue function & check the result
1062 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1063 * There is a type check in this
1064 * @param string $entity
1065 * @param array $params
1066 * @param null $count
1070 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1072 'version' => $this->_apiversion
,
1075 $result = $this->civicrm_api($entity, 'getcount', $params);
1076 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1077 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1079 if (is_int($count)) {
1080 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1086 * This function exists to wrap api functions.
1087 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1089 * @param string $entity
1090 * @param string $action
1091 * @param array $params
1092 * @param string $function
1093 * Pass this in to create a generated example.
1094 * @param string $file
1095 * Pass this in to create a generated example.
1096 * @param string $description
1097 * @param string|null $exampleName
1101 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1102 $params['version'] = $this->_apiversion
;
1103 $result = $this->callAPISuccess($entity, $action, $params);
1104 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1109 * This function exists to wrap api functions.
1110 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1111 * @param string $entity
1112 * @param string $action
1113 * @param array $params
1114 * @param string $expectedErrorMessage
1116 * @param null $extraOutput
1119 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1120 if (is_array($params)) {
1122 'version' => $this->_apiversion
,
1125 $result = $this->civicrm_api($entity, $action, $params);
1126 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1131 * Create required data based on $this->entity & $this->params
1132 * This is just a way to set up the test data for delete & get functions
1133 * so the distinction between set
1134 * up & tested functions is clearer
1139 public function createTestEntity() {
1140 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1144 * Generic function to create Organisation, to be used in test cases
1146 * @param array $params
1147 * parameters for civicrm_contact_add api function call
1149 * sequence number if creating multiple organizations
1152 * id of Organisation created
1154 public function organizationCreate($params = array(), $seq = 0) {
1158 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1159 return $this->_contactCreate($params);
1163 * Generic function to create Individual, to be used in test cases
1165 * @param array $params
1166 * parameters for civicrm_contact_add api function call
1168 * sequence number if creating multiple individuals
1171 * id of Individual created
1173 public function individualCreate($params = array(), $seq = 0) {
1174 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1175 return $this->_contactCreate($params);
1179 * Generic function to create Household, to be used in test cases
1181 * @param array $params
1182 * parameters for civicrm_contact_add api function call
1184 * sequence number if creating multiple households
1187 * id of Household created
1189 public function householdCreate($params = array(), $seq = 0) {
1190 $params = array_merge($this->sampleContact('Household', $seq), $params);
1191 return $this->_contactCreate($params);
1195 * Helper function for getting sample contact properties.
1197 * @param string $contact_type
1198 * enum contact type: Individual, Organization
1200 * sequence number for the values of this type
1203 * properties of sample contact (ie. $params for API call)
1205 public function sampleContact($contact_type, $seq = 0) {
1207 'Individual' => array(
1208 // The number of values in each list need to be coprime numbers to not have duplicates
1209 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1210 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1211 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1213 'Organization' => array(
1214 'organization_name' => array(
1215 'Unit Test Organization',
1222 'Household' => array(
1223 'household_name' => array('Unit Test household'),
1226 $params = array('contact_type' => $contact_type);
1227 foreach ($samples[$contact_type] as $key => $values) {
1228 $params[$key] = $values[$seq %
count($values)];
1230 if ($contact_type == 'Individual') {
1231 $params['email'] = strtolower(
1232 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1234 $params['prefix_id'] = 3;
1235 $params['suffix_id'] = 3;
1241 * Private helper function for calling civicrm_contact_add.
1243 * @param array $params
1244 * For civicrm_contact_add api function call.
1249 * id of Household created
1251 private function _contactCreate($params) {
1252 $result = $this->callAPISuccess('contact', 'create', $params);
1253 if (!empty($result['is_error']) ||
empty($result['id'])) {
1254 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1256 return $result['id'];
1260 * Delete contact, ensuring it is not the domain contact
1262 * @param int $contactID
1263 * Contact ID to delete
1265 public function contactDelete($contactID) {
1266 $domain = new CRM_Core_BAO_Domain();
1267 $domain->contact_id
= $contactID;
1268 if (!$domain->find(TRUE)) {
1269 $this->callAPISuccess('contact', 'delete', array(
1271 'skip_undelete' => 1,
1277 * @param int $contactTypeId
1281 public function contactTypeDelete($contactTypeId) {
1282 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1284 throw new Exception('Could not delete contact type');
1289 * @param array $params
1293 public function membershipTypeCreate($params = array()) {
1294 CRM_Member_PseudoConstant
::flush('membershipType');
1295 CRM_Core_Config
::clearDBCache();
1296 $memberOfOrganization = $this->organizationCreate();
1297 $params = array_merge(array(
1298 'name' => 'General',
1299 'duration_unit' => 'year',
1300 'duration_interval' => 1,
1301 'period_type' => 'rolling',
1302 'member_of_contact_id' => $memberOfOrganization,
1304 'financial_type_id' => 1,
1307 'visibility' => 'Public',
1310 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1312 CRM_Member_PseudoConstant
::flush('membershipType');
1313 CRM_Utils_Cache
::singleton()->flush();
1315 return $result['id'];
1319 * @param array $params
1323 public function contactMembershipCreate($params) {
1325 'join_date' => '2007-01-21',
1326 'start_date' => '2007-01-21',
1327 'end_date' => '2007-12-21',
1328 'source' => 'Payment',
1331 foreach ($pre as $key => $val) {
1332 if (!isset($params[$key])) {
1333 $params[$key] = $val;
1337 $result = $this->callAPISuccess('Membership', 'create', $params);
1338 return $result['id'];
1342 * Delete Membership Type.
1344 * @param array $params
1346 public function membershipTypeDelete($params) {
1347 $this->callAPISuccess('MembershipType', 'Delete', $params);
1351 * @param int $membershipID
1353 public function membershipDelete($membershipID) {
1354 $deleteParams = array('id' => $membershipID);
1355 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1359 * @param string $name
1363 public function membershipStatusCreate($name = 'test member status') {
1364 $params['name'] = $name;
1365 $params['start_event'] = 'start_date';
1366 $params['end_event'] = 'end_date';
1367 $params['is_current_member'] = 1;
1368 $params['is_active'] = 1;
1370 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1371 CRM_Member_PseudoConstant
::flush('membershipStatus');
1372 return $result['id'];
1376 * @param int $membershipStatusID
1378 public function membershipStatusDelete($membershipStatusID) {
1379 if (!$membershipStatusID) {
1382 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1386 * @param array $params
1390 public function relationshipTypeCreate($params = array()) {
1391 $params = array_merge(array(
1392 'name_a_b' => 'Relation 1 for relationship type create',
1393 'name_b_a' => 'Relation 2 for relationship type create',
1394 'contact_type_a' => 'Individual',
1395 'contact_type_b' => 'Organization',
1402 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1403 CRM_Core_PseudoConstant
::flush('relationshipType');
1405 return $result['id'];
1409 * Delete Relatinship Type.
1411 * @param int $relationshipTypeID
1413 public function relationshipTypeDelete($relationshipTypeID) {
1414 $params['id'] = $relationshipTypeID;
1415 $this->callAPISuccess('relationship_type', 'delete', $params);
1419 * @param array $params
1423 public function paymentProcessorTypeCreate($params = NULL) {
1424 if (is_null($params)) {
1426 'name' => 'API_Test_PP',
1427 'title' => 'API Test Payment Processor',
1428 'class_name' => 'CRM_Core_Payment_APITest',
1429 'billing_mode' => 'form',
1435 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1437 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1439 return $result['id'];
1443 * Create test Authorize.net instance.
1445 * @param array $params
1449 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1450 $params = array_merge(array(
1451 'name' => 'Authorize',
1452 'domain_id' => CRM_Core_Config
::domainID(),
1453 'payment_processor_type_id' => 'AuthNet',
1454 'title' => 'AuthNet',
1459 'user_name' => '4y5BfuW7jm',
1460 'password' => '4cAmW927n8uLf5J8',
1461 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1462 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1463 'class_name' => 'Payment_AuthorizeNet',
1464 'billing_mode' => 1,
1467 $result = $this->callAPISuccess('payment_processor', 'create', $params);
1468 return $result['id'];
1472 * Create Participant.
1474 * @param array $params
1475 * Array of contact id and event id values.
1478 * $id of participant created
1480 public function participantCreate($params) {
1481 if (empty($params['contact_id'])) {
1482 $params['contact_id'] = $this->individualCreate();
1484 if (empty($params['event_id'])) {
1485 $event = $this->eventCreate();
1486 $params['event_id'] = $event['id'];
1491 'register_date' => 20070219,
1492 'source' => 'Wimbeldon',
1493 'event_level' => 'Payment',
1497 $params = array_merge($defaults, $params);
1498 $result = $this->callAPISuccess('Participant', 'create', $params);
1499 return $result['id'];
1503 * Create Payment Processor.
1505 * @return CRM_Financial_DAO_PaymentProcessor
1506 * instance of Payment Processsor
1508 public function processorCreate() {
1509 $processorParams = array(
1512 'payment_processor_type_id' => 10,
1513 'financial_account_id' => 12,
1517 'url_site' => 'http://dummy.com',
1518 'url_recur' => 'http://dummy.com',
1519 'billing_mode' => 1,
1521 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1522 return $paymentProcessor;
1526 * Create contribution page.
1528 * @param array $params
1530 * Array of contribution page
1532 public function contributionPageCreate($params) {
1533 $this->_pageParams
= array(
1534 'title' => 'Test Contribution Page',
1535 'financial_type_id' => 1,
1536 'currency' => 'USD',
1537 'financial_account_id' => 1,
1538 'payment_processor' => $params['processor_id'],
1540 'is_allow_other_amount' => 1,
1542 'max_amount' => 1000,
1544 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1545 return $contributionPage;
1551 * @param array $params
1553 * result of created tag
1555 public function tagCreate($params = array()) {
1557 'name' => 'New Tag3',
1558 'description' => 'This is description for Our New Tag ',
1561 $params = array_merge($defaults, $params);
1562 $result = $this->callAPISuccess('Tag', 'create', $params);
1563 return $result['values'][$result['id']];
1570 * Id of the tag to be deleted.
1574 public function tagDelete($tagId) {
1575 require_once 'api/api.php';
1579 $result = $this->callAPISuccess('Tag', 'delete', $params);
1580 return $result['id'];
1584 * Add entity(s) to the tag
1586 * @param array $params
1590 public function entityTagAdd($params) {
1591 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1596 * Create contribution.
1602 * id of created contribution
1604 public function pledgeCreate($cID) {
1606 'contact_id' => $cID,
1607 'pledge_create_date' => date('Ymd'),
1608 'start_date' => date('Ymd'),
1609 'scheduled_date' => date('Ymd'),
1611 'pledge_status_id' => '2',
1612 'financial_type_id' => '1',
1613 'pledge_original_installment_amount' => 20,
1614 'frequency_interval' => 5,
1615 'frequency_unit' => 'year',
1616 'frequency_day' => 15,
1617 'installments' => 5,
1620 $result = $this->callAPISuccess('Pledge', 'create', $params);
1621 return $result['id'];
1625 * Delete contribution.
1627 * @param int $pledgeId
1629 public function pledgeDelete($pledgeId) {
1631 'pledge_id' => $pledgeId,
1633 $this->callAPISuccess('Pledge', 'delete', $params);
1637 * Create contribution.
1639 * @param int|array $params
1640 * Array of parameters or Contact_id (legacy) .
1641 * @param int $cTypeID
1642 * Id of financial type.
1643 * @param int $invoiceID
1644 * @param int $trxnID
1645 * @param int $paymentInstrumentID
1646 * @param bool $isFee
1649 * id of created contribution
1651 public function contributionCreate($params, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345,
1652 $paymentInstrumentID = 1, $isFee = TRUE) {
1653 if (!is_array($params)) {
1654 $params = array('contact_id' => $params);
1656 $params = array_merge(array(
1658 'receive_date' => date('Ymd'),
1659 'total_amount' => 100.00,
1660 'financial_type_id' => $cTypeID,
1661 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1662 'non_deductible_amount' => 10.00,
1663 'trxn_id' => $trxnID,
1664 'invoice_id' => $invoiceID,
1666 'contribution_status_id' => 1,
1670 $params['fee_amount'] = 5.00;
1671 $params['net_amount'] = 95.00;
1674 $result = $this->callAPISuccess('contribution', 'create', $params);
1675 return $result['id'];
1679 * Create online contribution.
1681 * @param array $params
1682 * @param int $financialType
1683 * Id of financial type.
1684 * @param int $invoiceID
1685 * @param int $trxnID
1688 * id of created contribution
1690 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1691 $contribParams = array(
1692 'contact_id' => $params['contact_id'],
1693 'receive_date' => date('Ymd'),
1694 'total_amount' => 100.00,
1695 'financial_type_id' => $financialType,
1696 'contribution_page_id' => $params['contribution_page_id'],
1698 'invoice_id' => 67890,
1701 $contribParams = array_merge($contribParams, $params);
1702 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1704 return $result['id'];
1708 * Delete contribution.
1710 * @param int $contributionId
1714 public function contributionDelete($contributionId) {
1716 'contribution_id' => $contributionId,
1718 $result = $this->callAPISuccess('contribution', 'delete', $params);
1725 * @param array $params
1726 * Name-value pair for an event.
1730 public function eventCreate($params = array()) {
1731 // if no contact was passed, make up a dummy event creator
1732 if (!isset($params['contact_id'])) {
1733 $params['contact_id'] = $this->_contactCreate(array(
1734 'contact_type' => 'Individual',
1735 'first_name' => 'Event',
1736 'last_name' => 'Creator',
1740 // set defaults for missing params
1741 $params = array_merge(array(
1742 'title' => 'Annual CiviCRM meet',
1743 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1744 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1745 'event_type_id' => 1,
1747 'start_date' => 20081021,
1748 'end_date' => 20081023,
1749 'is_online_registration' => 1,
1750 'registration_start_date' => 20080601,
1751 'registration_end_date' => 20081015,
1752 'max_participants' => 100,
1753 'event_full_text' => 'Sorry! We are already full',
1756 'is_show_location' => 0,
1759 return $this->callAPISuccess('Event', 'create', $params);
1770 public function eventDelete($id) {
1774 return $this->callAPISuccess('event', 'delete', $params);
1778 * Delete participant.
1780 * @param int $participantID
1784 public function participantDelete($participantID) {
1786 'id' => $participantID,
1788 return $this->callAPISuccess('Participant', 'delete', $params);
1792 * Create participant payment.
1794 * @param int $participantID
1795 * @param int $contributionID
1797 * $id of created payment
1799 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1800 //Create Participant Payment record With Values
1802 'participant_id' => $participantID,
1803 'contribution_id' => $contributionID,
1806 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1807 return $result['id'];
1811 * Delete participant payment.
1813 * @param int $paymentID
1815 public function participantPaymentDelete($paymentID) {
1819 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1825 * @param int $contactID
1827 * location id of created location
1829 public function locationAdd($contactID) {
1832 'location_type' => 'New Location Type',
1834 'name' => 'Saint Helier St',
1835 'county' => 'Marin',
1836 'country' => 'United States',
1837 'state_province' => 'Michigan',
1838 'supplemental_address_1' => 'Hallmark Ct',
1839 'supplemental_address_2' => 'Jersey Village',
1844 'contact_id' => $contactID,
1845 'address' => $address,
1846 'location_format' => '2.0',
1847 'location_type' => 'New Location Type',
1850 $result = $this->callAPISuccess('Location', 'create', $params);
1855 * Delete Locations of contact.
1857 * @param array $params
1860 public function locationDelete($params) {
1861 $this->callAPISuccess('Location', 'delete', $params);
1865 * Add a Location Type.
1867 * @param array $params
1868 * @return CRM_Core_DAO_LocationType
1869 * location id of created location
1871 public function locationTypeCreate($params = NULL) {
1872 if ($params === NULL) {
1874 'name' => 'New Location Type',
1875 'vcard_name' => 'New Location Type',
1876 'description' => 'Location Type for Delete',
1881 $locationType = new CRM_Core_DAO_LocationType();
1882 $locationType->copyValues($params);
1883 $locationType->save();
1884 // clear getfields cache
1885 CRM_Core_PseudoConstant
::flush();
1886 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1887 return $locationType;
1891 * Delete a Location Type.
1893 * @param int $locationTypeId
1895 public function locationTypeDelete($locationTypeId) {
1896 $locationType = new CRM_Core_DAO_LocationType();
1897 $locationType->id
= $locationTypeId;
1898 $locationType->delete();
1904 * @param array $params
1906 * groupId of created group
1908 public function groupCreate($params = array()) {
1909 $params = array_merge(array(
1910 'name' => 'Test Group 1',
1912 'title' => 'New Test Group Created',
1913 'description' => 'New Test Group Created',
1915 'visibility' => 'Public Pages',
1916 'group_type' => array(
1922 $result = $this->callAPISuccess('Group', 'create', $params);
1923 return $result['id'];
1928 * Function to add a Group.
1930 * @params array to add group
1932 * @param int $groupID
1933 * @param int $totalCount
1935 * groupId of created group
1937 public function groupContactCreate($groupID, $totalCount = 10) {
1938 $params = array('group_id' => $groupID);
1939 for ($i = 1; $i <= $totalCount; $i++
) {
1940 $contactID = $this->individualCreate();
1942 $params +
= array('contact_id' => $contactID);
1945 $params +
= array("contact_id.$i" => $contactID);
1948 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1958 public function groupDelete($gid) {
1964 $this->callAPISuccess('Group', 'delete', $params);
1969 * @param array $params
1971 public function uFFieldCreate($params = array()) {
1972 $params = array_merge(array(
1974 'field_name' => 'first_name',
1977 'visibility' => 'Public Pages and Listings',
1978 'is_searchable' => '1',
1979 'label' => 'first_name',
1980 'field_type' => 'Individual',
1983 $this->callAPISuccess('uf_field', 'create', $params);
1987 * Add a UF Join Entry.
1989 * @param array $params
1991 * $id of created UF Join
1993 public function ufjoinCreate($params = NULL) {
1994 if ($params === NULL) {
1997 'module' => 'CiviEvent',
1998 'entity_table' => 'civicrm_event',
2004 $result = $this->callAPISuccess('uf_join', 'create', $params);
2009 * Delete a UF Join Entry.
2011 * @param array $params
2012 * with missing uf_group_id
2014 public function ufjoinDelete($params = NULL) {
2015 if ($params === NULL) {
2018 'module' => 'CiviEvent',
2019 'entity_table' => 'civicrm_event',
2022 'uf_group_id' => '',
2026 crm_add_uf_join($params);
2030 * @param array $params
2031 * Optional parameters.
2036 public function campaignCreate($params = array()) {
2037 $this->enableCiviCampaign();
2038 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2039 'name' => 'big_campaign',
2040 'title' => 'Campaign',
2042 return $campaign['id'];
2046 * Create Group for a contact.
2048 * @param int $contactId
2050 public function contactGroupCreate($contactId) {
2052 'contact_id.1' => $contactId,
2056 $this->callAPISuccess('GroupContact', 'Create', $params);
2060 * Delete Group for a contact.
2062 * @param int $contactId
2064 public function contactGroupDelete($contactId) {
2066 'contact_id.1' => $contactId,
2069 $this->civicrm_api('GroupContact', 'Delete', $params);
2075 * @param array $params
2078 public function activityCreate($params = NULL) {
2080 if ($params === NULL) {
2081 $individualSourceID = $this->individualCreate();
2083 $contactParams = array(
2084 'first_name' => 'Julia',
2085 'Last_name' => 'Anderson',
2087 'email' => 'julia_anderson@civicrm.org',
2088 'contact_type' => 'Individual',
2091 $individualTargetID = $this->individualCreate($contactParams);
2094 'source_contact_id' => $individualSourceID,
2095 'target_contact_id' => array($individualTargetID),
2096 'assignee_contact_id' => array($individualTargetID),
2097 'subject' => 'Discussion on warm beer',
2098 'activity_date_time' => date('Ymd'),
2099 'duration_hours' => 30,
2100 'duration_minutes' => 20,
2101 'location' => 'Baker Street',
2102 'details' => 'Lets schedule a meeting',
2104 'activity_name' => 'Meeting',
2108 $result = $this->callAPISuccess('Activity', 'create', $params);
2110 $result['target_contact_id'] = $individualTargetID;
2111 $result['assignee_contact_id'] = $individualTargetID;
2116 * Create an activity type.
2118 * @param array $params
2122 public function activityTypeCreate($params) {
2123 return $this->callAPISuccess('ActivityType', 'create', $params);
2127 * Delete activity type.
2129 * @param int $activityTypeId
2130 * Id of the activity type.
2133 public function activityTypeDelete($activityTypeId) {
2134 $params['activity_type_id'] = $activityTypeId;
2135 return $this->callAPISuccess('ActivityType', 'delete', $params);
2139 * Create custom group.
2141 * @param array $params
2144 public function customGroupCreate($params = array()) {
2146 'title' => 'new custom group',
2147 'extends' => 'Contact',
2149 'style' => 'Inline',
2153 $params = array_merge($defaults, $params);
2155 if (strlen($params['title']) > 13) {
2156 $params['title'] = substr($params['title'], 0, 13);
2159 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2160 $this->callAPISuccess('custom_group', 'get', array(
2161 'title' => $params['title'],
2162 array('api.custom_group.delete' => 1),
2165 return $this->callAPISuccess('custom_group', 'create', $params);
2169 * Existing function doesn't allow params to be over-ridden so need a new one
2170 * this one allows you to only pass in the params you want to change
2171 * @param array $params
2174 public function CustomGroupCreateByParams($params = array()) {
2176 'title' => "API Custom Group",
2177 'extends' => 'Contact',
2179 'style' => 'Inline',
2182 $params = array_merge($defaults, $params);
2183 return $this->callAPISuccess('custom_group', 'create', $params);
2187 * Create custom group with multi fields.
2188 * @param array $params
2191 public function CustomGroupMultipleCreateByParams($params = array()) {
2196 $params = array_merge($defaults, $params);
2197 return $this->CustomGroupCreateByParams($params);
2201 * Create custom group with multi fields.
2202 * @param array $params
2205 public function CustomGroupMultipleCreateWithFields($params = array()) {
2206 // also need to pass on $params['custom_field'] if not set but not in place yet
2208 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2209 $ids['custom_group_id'] = $customGroup['id'];
2211 $customField = $this->customFieldCreate(array(
2212 'custom_group_id' => $ids['custom_group_id'],
2213 'label' => 'field_1' . $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_2' . $ids['custom_group_id'],
2223 $ids['custom_field_id'][] = $customField['id'];
2225 $customField = $this->customFieldCreate(array(
2226 'custom_group_id' => $ids['custom_group_id'],
2227 'default_value' => '',
2228 'label' => 'field_3' . $ids['custom_group_id'],
2230 $ids['custom_field_id'][] = $customField['id'];
2236 * Create a custom group with a single text custom field. See
2237 * participant:testCreateWithCustom for how to use this
2239 * @param string $function
2241 * @param string $filename
2245 * ids of created objects
2247 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2248 $params = array('title' => $function);
2249 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2250 $params['extends'] = $entity ?
$entity : 'Contact';
2251 $customGroup = $this->CustomGroupCreate($params);
2252 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2253 CRM_Core_PseudoConstant
::flush();
2255 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2259 * Delete custom group.
2261 * @param int $customGroupID
2265 public function customGroupDelete($customGroupID) {
2266 $params['id'] = $customGroupID;
2267 return $this->callAPISuccess('custom_group', 'delete', $params);
2271 * Create custom field.
2273 * @param array $params
2274 * (custom_group_id) is required.
2277 public function customFieldCreate($params) {
2278 $params = array_merge(array(
2279 'label' => 'Custom Field',
2280 'data_type' => 'String',
2281 'html_type' => 'Text',
2282 'is_searchable' => 1,
2284 'default_value' => 'defaultValue',
2287 $result = $this->callAPISuccess('custom_field', 'create', $params);
2288 // these 2 functions are called with force to flush static caches
2289 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2290 CRM_Core_Component
::getEnabledComponents(1);
2295 * Delete custom field.
2297 * @param int $customFieldID
2301 public function customFieldDelete($customFieldID) {
2303 $params['id'] = $customFieldID;
2304 return $this->callAPISuccess('custom_field', 'delete', $params);
2313 public function noteCreate($cId) {
2315 'entity_table' => 'civicrm_contact',
2316 'entity_id' => $cId,
2317 'note' => 'hello I am testing Note',
2318 'contact_id' => $cId,
2319 'modified_date' => date('Ymd'),
2320 'subject' => 'Test Note',
2323 return $this->callAPISuccess('Note', 'create', $params);
2327 * Enable CiviCampaign Component.
2329 public function enableCiviCampaign() {
2330 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2331 // force reload of config object
2332 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2333 //flush cache by calling with reset
2334 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2338 * Create test generated example in api/v3/examples.
2340 * To turn this off (e.g. on the server) set
2341 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2342 * in your settings file
2344 * @param string $entity
2345 * @param string $action
2346 * @param array $params
2347 * Array as passed to civicrm_api function.
2348 * @param array $result
2349 * Array as received from the civicrm_api function.
2350 * @param string $testFunction
2351 * Calling function - generally __FUNCTION__.
2352 * @param string $testFile
2353 * Called from file - generally __FILE__.
2354 * @param string $description
2355 * Descriptive text for the example file.
2356 * @param string $exampleName
2357 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2359 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2360 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2363 $entity = _civicrm_api_get_camel_name($entity);
2364 $action = strtolower($action);
2366 if (empty($exampleName)) {
2367 // Attempt to convert lowercase action name to CamelCase.
2368 // This is clunky/imperfect due to the convention of all lowercase actions.
2369 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2370 $knownPrefixes = array(
2377 foreach ($knownPrefixes as $prefix) {
2378 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2379 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2384 $this->tidyExampleResult($result);
2385 if (isset($params['version'])) {
2386 unset($params['version']);
2388 // Format multiline description as array
2390 if (is_string($description) && strlen($description)) {
2391 foreach (explode("\n", $description) as $line) {
2392 $desc[] = trim($line);
2395 $smarty = CRM_Core_Smarty
::singleton();
2396 $smarty->assign('testFunction', $testFunction);
2397 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2398 $smarty->assign('params', $params);
2399 $smarty->assign('entity', $entity);
2400 $smarty->assign('testFile', basename($testFile));
2401 $smarty->assign('description', $desc);
2402 $smarty->assign('result', $result);
2403 $smarty->assign('action', $action);
2405 if (file_exists('../tests/templates/documentFunction.tpl')) {
2406 if (!is_dir("../api/v3/examples/$entity")) {
2407 mkdir("../api/v3/examples/$entity");
2409 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2410 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2416 * Tidy up examples array so that fields that change often ..don't
2417 * and debug related fields are unset
2419 * @param array $result
2421 public function tidyExampleResult(&$result) {
2422 if (!is_array($result)) {
2425 $fieldsToChange = array(
2426 'hash' => '67eac7789eaee00',
2427 'modified_date' => '2012-11-14 16:02:35',
2428 'created_date' => '2013-07-28 08:49:19',
2429 'create_date' => '20120130621222105',
2430 'application_received_date' => '20130728084957',
2431 'in_date' => '2013-07-28 08:50:19',
2432 'scheduled_date' => '20130728085413',
2433 'approval_date' => '20130728085413',
2434 'pledge_start_date_high' => '20130726090416',
2435 'start_date' => '2013-07-29 00:00:00',
2436 'event_start_date' => '2013-07-29 00:00:00',
2437 'end_date' => '2013-08-04 00:00:00',
2438 'event_end_date' => '2013-08-04 00:00:00',
2439 'decision_date' => '20130805000000',
2442 $keysToUnset = array('xdebug', 'undefined_fields');
2443 foreach ($keysToUnset as $unwantedKey) {
2444 if (isset($result[$unwantedKey])) {
2445 unset($result[$unwantedKey]);
2448 if (isset($result['values'])) {
2449 if (!is_array($result['values'])) {
2452 $resultArray = &$result['values'];
2454 elseif (is_array($result)) {
2455 $resultArray = &$result;
2461 foreach ($resultArray as $index => &$values) {
2462 if (!is_array($values)) {
2465 foreach ($values as $key => &$value) {
2466 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2467 if (isset($value['is_error'])) {
2468 // we have a std nested result format
2469 $this->tidyExampleResult($value);
2472 foreach ($value as &$nestedResult) {
2473 // this is an alternative syntax for nested results a keyed array of results
2474 $this->tidyExampleResult($nestedResult);
2478 if (in_array($key, $keysToUnset)) {
2479 unset($values[$key]);
2482 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2483 $value = $fieldsToChange[$key];
2485 if (is_string($value)) {
2486 $value = addslashes($value);
2495 * @param array $params
2499 public function noteDelete($params) {
2500 return $this->callAPISuccess('Note', 'delete', $params);
2504 * Create custom field with Option Values.
2506 * @param array $customGroup
2507 * @param string $name
2508 * Name of custom field.
2512 public function customFieldOptionValueCreate($customGroup, $name) {
2513 $fieldParams = array(
2514 'custom_group_id' => $customGroup['id'],
2515 'name' => 'test_custom_group',
2516 'label' => 'Country',
2517 'html_type' => 'Select',
2518 'data_type' => 'String',
2521 'is_searchable' => 0,
2525 $optionGroup = array(
2527 'name' => 'option_group1',
2528 'label' => 'option_group_label1',
2531 $optionValue = array(
2532 'option_label' => array('Label1', 'Label2'),
2533 'option_value' => array('value1', 'value2'),
2534 'option_name' => array($name . '_1', $name . '_2'),
2535 'option_weight' => array(1, 2),
2536 'option_status' => 1,
2539 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2541 return $this->callAPISuccess('custom_field', 'create', $params);
2549 public function confirmEntitiesDeleted($entities) {
2550 foreach ($entities as $entity) {
2552 $result = $this->callAPISuccess($entity, 'Get', array());
2553 if ($result['error'] == 1 ||
$result['count'] > 0) {
2554 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2562 * @param $tablesToTruncate
2563 * @param bool $dropCustomValueTables
2564 * @throws \Exception
2566 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2568 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2570 if ($dropCustomValueTables) {
2571 $tablesToTruncate[] = 'civicrm_custom_group';
2572 $tablesToTruncate[] = 'civicrm_custom_field';
2575 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2577 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2578 foreach ($tablesToTruncate as $table) {
2579 $sql = "TRUNCATE TABLE $table";
2580 CRM_Core_DAO
::executeQuery($sql);
2582 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2584 if ($dropCustomValueTables) {
2585 $dbName = self
::getDBName();
2587 SELECT TABLE_NAME as tableName
2588 FROM INFORMATION_SCHEMA.TABLES
2589 WHERE TABLE_SCHEMA = '{$dbName}'
2590 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2593 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2594 while ($tableDAO->fetch()) {
2595 $sql = "DROP TABLE {$tableDAO->tableName}";
2596 CRM_Core_DAO
::executeQuery($sql);
2602 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2604 public function quickCleanUpFinancialEntities() {
2605 $tablesToTruncate = array(
2607 'civicrm_activity_contact',
2608 'civicrm_contribution',
2609 'civicrm_contribution_soft',
2610 'civicrm_contribution_product',
2611 'civicrm_financial_trxn',
2612 'civicrm_financial_item',
2613 'civicrm_contribution_recur',
2614 'civicrm_line_item',
2615 'civicrm_contribution_page',
2616 'civicrm_payment_processor',
2617 'civicrm_entity_financial_trxn',
2618 'civicrm_membership',
2619 'civicrm_membership_type',
2620 'civicrm_membership_payment',
2621 'civicrm_membership_log',
2622 'civicrm_membership_block',
2624 'civicrm_participant',
2625 'civicrm_participant_payment',
2627 'civicrm_price_set_entity',
2628 'civicrm_price_field_value',
2629 'civicrm_price_field',
2631 $this->quickCleanup($tablesToTruncate);
2632 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2633 $this->restoreDefaultPriceSetConfig();
2635 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2636 Civi\Payment\System
::singleton()->flushProcessors();
2639 public function restoreDefaultPriceSetConfig() {
2640 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2641 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)");
2642 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)");
2645 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2646 * Default behaviour is to also delete the entity
2647 * @param array $params
2648 * Params array to check against.
2650 * Id of the entity concerned.
2651 * @param string $entity
2652 * Name of entity concerned (e.g. membership).
2653 * @param bool $delete
2654 * Should the entity be deleted as part of this check.
2655 * @param string $errorText
2656 * Text to print on error.
2659 * @param array $params
2662 * @param int $delete
2663 * @param string $errorText
2667 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2669 $result = $this->callAPISuccessGetSingle($entity, array(
2674 $this->callAPISuccess($entity, 'Delete', array(
2678 $dateFields = $keys = $dateTimeFields = array();
2679 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2680 foreach ($fields['values'] as $field => $settings) {
2681 if (array_key_exists($field, $result)) {
2682 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2685 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2687 $type = CRM_Utils_Array
::value('type', $settings);
2688 if ($type == CRM_Utils_Type
::T_DATE
) {
2689 $dateFields[] = $settings['name'];
2690 // we should identify both real names & unique names as dates
2691 if ($field != $settings['name']) {
2692 $dateFields[] = $field;
2695 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2696 $dateTimeFields[] = $settings['name'];
2697 // we should identify both real names & unique names as dates
2698 if ($field != $settings['name']) {
2699 $dateTimeFields[] = $field;
2704 if (strtolower($entity) == 'contribution') {
2705 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2706 // this is not returned in id format
2707 unset($params['payment_instrument_id']);
2708 $params['contribution_source'] = $params['source'];
2709 unset($params['source']);
2712 foreach ($params as $key => $value) {
2713 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2716 if (in_array($key, $dateFields)) {
2717 $value = date('Y-m-d', strtotime($value));
2718 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2720 if (in_array($key, $dateTimeFields)) {
2721 $value = date('Y-m-d H:i:s', strtotime($value));
2722 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2724 $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);
2729 * Get formatted values in the actual and expected result.
2730 * @param array $actual
2731 * Actual calculated values.
2732 * @param array $expected
2735 public function checkArrayEquals(&$actual, &$expected) {
2736 self
::unsetId($actual);
2737 self
::unsetId($expected);
2738 $this->assertEquals($actual, $expected);
2742 * Unset the key 'id' from the array
2743 * @param array $unformattedArray
2744 * The array from which the 'id' has to be unset.
2746 public static function unsetId(&$unformattedArray) {
2747 $formattedArray = array();
2748 if (array_key_exists('id', $unformattedArray)) {
2749 unset($unformattedArray['id']);
2751 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2752 foreach ($unformattedArray['values'] as $key => $value) {
2753 if (is_array($value)) {
2754 foreach ($value as $k => $v) {
2760 elseif ($key == 'id') {
2761 $unformattedArray[$key];
2763 $formattedArray = array($value);
2765 $unformattedArray['values'] = $formattedArray;
2770 * Helper to enable/disable custom directory support
2772 * @param array $customDirs
2774 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2775 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2777 public function customDirectories($customDirs) {
2778 require_once 'CRM/Core/Config.php';
2779 $config = CRM_Core_Config
::singleton();
2781 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2782 unset($config->customPHPPathDir
);
2784 elseif ($customDirs['php_path'] === TRUE) {
2785 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2788 $config->customPHPPathDir
= $php_path;
2791 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2792 unset($config->customTemplateDir
);
2794 elseif ($customDirs['template_path'] === TRUE) {
2795 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2798 $config->customTemplateDir
= $template_path;
2803 * Generate a temporary folder.
2805 * @param string $prefix
2808 public function createTempDir($prefix = 'test-') {
2809 $tempDir = CRM_Utils_File
::tempdir($prefix);
2810 $this->tempDirs
[] = $tempDir;
2814 public function cleanTempDirs() {
2815 if (!is_array($this->tempDirs
)) {
2816 // fix test errors where this is not set
2819 foreach ($this->tempDirs
as $tempDir) {
2820 if (is_dir($tempDir)) {
2821 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2827 * Temporarily replace the singleton extension with a different one.
2828 * @param \CRM_Extension_System $system
2830 public function setExtensionSystem(CRM_Extension_System
$system) {
2831 if ($this->origExtensionSystem
== NULL) {
2832 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2834 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2837 public function unsetExtensionSystem() {
2838 if ($this->origExtensionSystem
!== NULL) {
2839 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2840 $this->origExtensionSystem
= NULL;
2845 * Temporarily alter the settings-metadata to add a mock setting.
2847 * WARNING: The setting metadata will disappear on the next cache-clear.
2852 public function setMockSettingsMetaData($extras) {
2853 CRM_Core_BAO_Setting
::$_cache = array();
2854 $this->callAPISuccess('system', 'flush', array());
2855 CRM_Core_BAO_Setting
::$_cache = array();
2857 CRM_Utils_Hook
::singleton()
2858 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2859 $metadata = array_merge($metadata, $extras);
2862 $fields = $this->callAPISuccess('setting', 'getfields', array());
2863 foreach ($extras as $key => $spec) {
2864 $this->assertNotEmpty($spec['title']);
2865 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2870 * @param string $name
2872 public function financialAccountDelete($name) {
2873 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2874 $financialAccount->name
= $name;
2875 if ($financialAccount->find(TRUE)) {
2876 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2877 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2878 $entityFinancialType->delete();
2879 $financialAccount->delete();
2884 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2885 * (NB unclear if this is still required)
2887 public function _sethtmlGlobals() {
2888 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2889 'required' => array(
2890 'html_quickform_rule_required',
2891 'HTML/QuickForm/Rule/Required.php',
2893 'maxlength' => array(
2894 'html_quickform_rule_range',
2895 'HTML/QuickForm/Rule/Range.php',
2897 'minlength' => array(
2898 'html_quickform_rule_range',
2899 'HTML/QuickForm/Rule/Range.php',
2901 'rangelength' => array(
2902 'html_quickform_rule_range',
2903 'HTML/QuickForm/Rule/Range.php',
2906 'html_quickform_rule_email',
2907 'HTML/QuickForm/Rule/Email.php',
2910 'html_quickform_rule_regex',
2911 'HTML/QuickForm/Rule/Regex.php',
2913 'lettersonly' => array(
2914 'html_quickform_rule_regex',
2915 'HTML/QuickForm/Rule/Regex.php',
2917 'alphanumeric' => array(
2918 'html_quickform_rule_regex',
2919 'HTML/QuickForm/Rule/Regex.php',
2922 'html_quickform_rule_regex',
2923 'HTML/QuickForm/Rule/Regex.php',
2925 'nopunctuation' => array(
2926 'html_quickform_rule_regex',
2927 'HTML/QuickForm/Rule/Regex.php',
2930 'html_quickform_rule_regex',
2931 'HTML/QuickForm/Rule/Regex.php',
2933 'callback' => array(
2934 'html_quickform_rule_callback',
2935 'HTML/QuickForm/Rule/Callback.php',
2938 'html_quickform_rule_compare',
2939 'HTML/QuickForm/Rule/Compare.php',
2942 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2943 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2945 'HTML/QuickForm/group.php',
2946 'HTML_QuickForm_group',
2949 'HTML/QuickForm/hidden.php',
2950 'HTML_QuickForm_hidden',
2953 'HTML/QuickForm/reset.php',
2954 'HTML_QuickForm_reset',
2956 'checkbox' => array(
2957 'HTML/QuickForm/checkbox.php',
2958 'HTML_QuickForm_checkbox',
2961 'HTML/QuickForm/file.php',
2962 'HTML_QuickForm_file',
2965 'HTML/QuickForm/image.php',
2966 'HTML_QuickForm_image',
2968 'password' => array(
2969 'HTML/QuickForm/password.php',
2970 'HTML_QuickForm_password',
2973 'HTML/QuickForm/radio.php',
2974 'HTML_QuickForm_radio',
2977 'HTML/QuickForm/button.php',
2978 'HTML_QuickForm_button',
2981 'HTML/QuickForm/submit.php',
2982 'HTML_QuickForm_submit',
2985 'HTML/QuickForm/select.php',
2986 'HTML_QuickForm_select',
2988 'hiddenselect' => array(
2989 'HTML/QuickForm/hiddenselect.php',
2990 'HTML_QuickForm_hiddenselect',
2993 'HTML/QuickForm/text.php',
2994 'HTML_QuickForm_text',
2996 'textarea' => array(
2997 'HTML/QuickForm/textarea.php',
2998 'HTML_QuickForm_textarea',
3000 'fckeditor' => array(
3001 'HTML/QuickForm/fckeditor.php',
3002 'HTML_QuickForm_FCKEditor',
3005 'HTML/QuickForm/tinymce.php',
3006 'HTML_QuickForm_TinyMCE',
3008 'dojoeditor' => array(
3009 'HTML/QuickForm/dojoeditor.php',
3010 'HTML_QuickForm_dojoeditor',
3013 'HTML/QuickForm/link.php',
3014 'HTML_QuickForm_link',
3016 'advcheckbox' => array(
3017 'HTML/QuickForm/advcheckbox.php',
3018 'HTML_QuickForm_advcheckbox',
3021 'HTML/QuickForm/date.php',
3022 'HTML_QuickForm_date',
3025 'HTML/QuickForm/static.php',
3026 'HTML_QuickForm_static',
3029 'HTML/QuickForm/header.php',
3030 'HTML_QuickForm_header',
3033 'HTML/QuickForm/html.php',
3034 'HTML_QuickForm_html',
3036 'hierselect' => array(
3037 'HTML/QuickForm/hierselect.php',
3038 'HTML_QuickForm_hierselect',
3040 'autocomplete' => array(
3041 'HTML/QuickForm/autocomplete.php',
3042 'HTML_QuickForm_autocomplete',
3045 'HTML/QuickForm/xbutton.php',
3046 'HTML_QuickForm_xbutton',
3048 'advmultiselect' => array(
3049 'HTML/QuickForm/advmultiselect.php',
3050 'HTML_QuickForm_advmultiselect',
3056 * Set up an acl allowing contact to see 2 specified groups
3057 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3059 * You need to have pre-created these groups & created the user e.g
3060 * $this->createLoggedInUser();
3061 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3062 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3064 public function setupACL($isProfile = FALSE) {
3066 $_REQUEST = $this->_params
;
3068 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3069 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3070 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3071 'option_group_id' => $optionGroupID,
3072 'label' => 'pick me',
3076 CRM_Core_DAO
::executeQuery("
3077 TRUNCATE civicrm_acl_cache
3080 CRM_Core_DAO
::executeQuery("
3081 TRUNCATE civicrm_acl_contact_cache
3084 CRM_Core_DAO
::executeQuery("
3085 INSERT INTO civicrm_acl_entity_role (
3086 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3087 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3091 CRM_Core_DAO
::executeQuery("
3092 INSERT INTO civicrm_acl (
3093 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3096 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3101 CRM_Core_DAO
::executeQuery("
3102 INSERT INTO civicrm_acl (
3103 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3106 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3110 CRM_Core_DAO
::executeQuery("
3111 INSERT INTO civicrm_acl (
3112 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3115 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3119 CRM_ACL_BAO_Cache
::resetCache();
3120 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3121 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3124 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3125 $this->callAPISuccess('group_contact', 'create', array(
3126 'group_id' => $this->_permissionedGroup
,
3127 'contact_id' => $this->_loggedInUser
,
3132 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3134 public function offsetDefaultPriceSet() {
3135 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3136 $firstID = $contributionPriceSet['id'];
3137 $this->callAPISuccess('price_set', 'create', array(
3138 'id' => $contributionPriceSet['id'],
3142 unset($contributionPriceSet['id']);
3143 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3144 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3145 'price_set_id' => $firstID,
3146 'options' => array('limit' => 1),
3148 unset($priceField['id']);
3149 $priceField['price_set_id'] = $newPriceSet['id'];
3150 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3151 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3152 'price_set_id' => $firstID,
3154 'options' => array('limit' => 1),
3157 unset($priceFieldValue['id']);
3158 //create some padding to use up ids
3159 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3160 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3161 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3165 * Create an instance of the paypal processor.
3166 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3167 * this parent class & we don't have a structure for that yet
3168 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3169 * & the best protection against that is the functions this class affords
3170 * @param array $params
3171 * @return int $result['id'] payment processor id
3173 public function paymentProcessorCreate($params = array()) {
3174 $params = array_merge(array(
3176 'domain_id' => CRM_Core_Config
::domainID(),
3177 'payment_processor_type_id' => 'PayPal',
3181 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3182 'password' => '1183377788',
3183 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3184 'url_site' => 'https://www.sandbox.paypal.com/',
3185 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3186 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3187 'class_name' => 'Payment_PayPalImpl',
3188 'billing_mode' => 3,
3189 'financial_type_id' => 1,
3192 if (!is_numeric($params['payment_processor_type_id'])) {
3193 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3195 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3196 'name' => $params['payment_processor_type_id'],
3200 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3201 return $result['id'];
3205 * Set up initial recurring payment allowing subsequent IPN payments.
3207 public function setupRecurringPaymentProcessorTransaction() {
3208 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3209 'contact_id' => $this->_contactID
,
3212 'installments' => 5,
3213 'frequency_unit' => 'Month',
3214 'frequency_interval' => 1,
3215 'invoice_id' => $this->_invoiceID
,
3216 'contribution_status_id' => 2,
3217 'processor_id' => $this->_paymentProcessorID
,
3218 'api.contribution.create' => array(
3219 'total_amount' => '200',
3220 'invoice_id' => $this->_invoiceID
,
3221 'financial_type_id' => 1,
3222 'contribution_status_id' => 'Pending',
3223 'contact_id' => $this->_contactID
,
3224 'contribution_page_id' => $this->_contributionPageID
,
3225 'payment_processor_id' => $this->_paymentProcessorID
,
3229 $this->_contributionRecurID
= $contributionRecur['id'];
3230 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3234 * 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
3236 public function setupMembershipRecurringPaymentProcessorTransaction() {
3237 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3238 //create a contribution so our membership & contribution don't both have id = 1
3239 $this->contributionCreate(array(
3240 'contact_id' => $this->_contactID
,
3243 $this->setupRecurringPaymentProcessorTransaction();
3245 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3246 'contact_id' => $this->_contactID
,
3247 'membership_type_id' => $this->ids
['membership_type'],
3248 'contribution_recur_id' => $this->_contributionRecurID
,
3249 'format.only_id' => TRUE,
3251 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3252 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3254 $this->callAPISuccess('line_item', 'create', array(
3255 'entity_table' => 'civicrm_membership',
3256 'entity_id' => $this->ids
['membership'],
3257 'contribution_id' => $this->_contributionID
,
3258 'label' => 'General',
3260 'unit_price' => 200,
3261 'line_total' => 200,
3262 'financial_type_id' => 1,
3263 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3265 'label' => 'Membership Amount',
3267 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3269 'label' => 'General',
3272 $this->callAPISuccess('membership_payment', 'create', array(
3273 'contribution_id' => $this->_contributionID
,
3274 'membership_id' => $this->ids
['membership'],
3283 public function CiviUnitTestCase_fatalErrorHandler($message) {
3284 throw new Exception("{$message['message']}: {$message['code']}");
3288 * Helper function to create new mailing.
3291 public function createMailing() {
3293 'subject' => 'maild' . rand(),
3294 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3295 'name' => 'mailing name' . rand(),
3299 $result = $this->callAPISuccess('Mailing', 'create', $params);
3300 return $result['id'];
3304 * Helper function to delete mailing.
3307 public function deleteMailing($id) {
3312 $this->callAPISuccess('Mailing', 'delete', $params);
3316 * Wrap the entire test case in a transaction.
3318 * Only subsequent DB statements will be wrapped in TX -- this cannot
3319 * retroactively wrap old DB statements. Therefore, it makes sense to
3320 * call this at the beginning of setUp().
3322 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3323 * this option does not work with, e.g., custom-data.
3325 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3326 * if TRUNCATE or ALTER is called while using a transaction.
3329 * Whether to use nesting or reference-counting.
3331 public function useTransaction($nest = TRUE) {
3333 $this->tx
= new CRM_Core_Transaction($nest);
3334 $this->tx
->rollback();
3338 public function clearOutputBuffer() {
3339 while (ob_get_level() > 0) {
3346 * @param array $apiResult
3348 protected function assertAttachmentExistence($exists, $apiResult) {
3349 $fileId = $apiResult['id'];
3350 $this->assertTrue(is_numeric($fileId));
3351 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3352 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3353 1 => array($fileId, 'Int'),
3355 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3356 1 => array($fileId, 'Int'),