3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
30 * Include configuration
32 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
33 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
38 require_once CIVICRM_SETTINGS_PATH
;
40 * Include class definitions
42 require_once 'tests/phpunit/Utils.php';
43 require_once 'api/api.php';
44 require_once 'CRM/Financial/BAO/FinancialType.php';
45 define('API_LATEST_VERSION', 3);
48 * Base class for CiviCRM unit tests
50 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
51 * may opt for one or neither:
53 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
54 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
55 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
56 * 2. useTransaction() executes the test inside a transaction. It's easier to use
57 * (because you don't need to identify specific tables), but it doesn't work for tests
58 * which manipulate schema or truncate data -- and could behave inconsistently
59 * for tests which specifically examine DB transactions.
61 * Common functions for unit tests
64 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
67 * Api version - easier to override than just a define
69 protected $_apiversion = API_LATEST_VERSION
;
71 * Database has been initialized
75 private static $dbInit = FALSE;
80 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
89 static protected $_dbName;
92 * Track tables we have modified during a test
94 protected $_tablesToTruncate = array();
97 * @var array of temporary directory names
102 * @var Utils instance
104 public static $utils;
107 * @var boolean populateOnce allows to skip db resets in setUp
109 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
110 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
113 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
115 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
117 public static $populateOnce = FALSE;
120 * Allow classes to state E-notice compliance
122 public $_eNoticeCompliant = TRUE;
125 * @var boolean DBResetRequired allows skipping DB reset
126 * in specific test case. If you still need
127 * to reset single test (method) of such case, call
128 * $this->cleanDB() in the first line of this
131 public $DBResetRequired = TRUE;
134 * @var CRM_Core_Transaction|NULL
139 * @var CRM_Utils_Hook_UnitTests hookClass
140 * example of setting a method for a hook
141 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
143 public $hookClass = NULL;
146 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
148 protected $_params = array();
151 * @var CRM_Extension_System
153 protected $origExtensionSystem;
158 * Because we are overriding the parent class constructor, we
159 * need to show the same arguments as exist in the constructor of
160 * PHPUnit_Framework_TestCase, since
161 * PHPUnit_Framework_TestSuite::createTest() creates a
162 * ReflectionClass of the Test class and checks the constructor
163 * of that class to decide how to set up the test.
165 * @param string $name
167 * @param string $dataName
169 public function __construct($name = NULL, array$data = array(), $dataName = '') {
170 parent
::__construct($name, $data, $dataName);
172 // we need full error reporting
173 error_reporting(E_ALL
& ~E_NOTICE
);
175 if (!empty($GLOBALS['mysql_db'])) {
176 self
::$_dbName = $GLOBALS['mysql_db'];
179 self
::$_dbName = 'civicrm_tests_dev';
182 // create test database
183 self
::$utils = new Utils($GLOBALS['mysql_host'],
184 $GLOBALS['mysql_port'],
185 $GLOBALS['mysql_user'],
186 $GLOBALS['mysql_pass']
189 // also load the class loader
190 require_once 'CRM/Core/ClassLoader.php';
191 CRM_Core_ClassLoader
::singleton()->register();
192 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
193 _civix_phpunit_setUp();
197 protected function runTest() {
199 return parent
::runTest();
201 catch (PEAR_Exception
$e) {
202 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
203 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
210 public function requireDBReset() {
211 return $this->DBResetRequired
;
217 public static function getDBName() {
218 $dbName = !empty($GLOBALS['mysql_db']) ?
$GLOBALS['mysql_db'] : 'civicrm_tests_dev';
223 * Create database connection for this instance
225 * Initialize the test database if it hasn't been initialized
227 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
229 protected function getConnection() {
230 $dbName = self
::$_dbName;
231 if (!self
::$dbInit) {
232 $dbName = self
::getDBName();
234 // install test database
235 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
237 static::_populateDB(FALSE, $this);
239 self
::$dbInit = TRUE;
241 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
245 * Required implementation of abstract method
247 protected function getDataSet() {
251 * @param bool $perClass
252 * @param null $object
254 * TRUE if the populate logic runs; FALSE if it is skipped
256 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
258 if ($perClass ||
$object == NULL) {
262 $dbreset = $object->requireDBReset();
265 if (self
::$populateOnce ||
!$dbreset) {
268 self
::$populateOnce = NULL;
270 $dbName = self
::getDBName();
271 $pdo = self
::$utils->pdo
;
272 // only consider real tables and not views
273 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
274 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
276 $truncates = array();
278 foreach ($tables as $table) {
280 if (substr($table['table_name'], 0, 4) == 'log_') {
284 // don't change list of installed extensions
285 if ($table['table_name'] == 'civicrm_extension') {
289 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
290 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
293 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
299 "SET foreign_key_checks = 0",
300 // SQL mode needs to be strict, that's our standard
301 "SET SQL_MODE='STRICT_ALL_TABLES';",
302 "SET global innodb_flush_log_at_trx_commit = 2;",
304 $queries = array_merge($queries, $truncates);
305 $queries = array_merge($queries, $drops);
306 foreach ($queries as $query) {
307 if (self
::$utils->do_query($query) === FALSE) {
308 // failed to create test database
309 echo "failed to create test db.";
314 // initialize test database
315 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
316 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
317 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
319 $query2 = file_get_contents($sql_file2);
320 $query3 = file_get_contents($sql_file3);
321 $query4 = file_get_contents($sql_file4);
322 if (self
::$utils->do_query($query2) === FALSE) {
323 echo "Cannot load civicrm_data.mysql. Aborting.";
326 if (self
::$utils->do_query($query3) === FALSE) {
327 echo "Cannot load test_data.mysql. Aborting.";
330 if (self
::$utils->do_query($query4) === FALSE) {
331 echo "Cannot load test_data.mysql. Aborting.";
335 // done with all the loading, get transactions back
336 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
337 echo "Cannot set global? Huh?";
341 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
342 echo "Cannot get foreign keys back? Huh?";
346 unset($query, $query2, $query3);
349 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
351 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
363 public static function setUpBeforeClass() {
364 static::_populateDB(TRUE);
366 // also set this global hack
367 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
369 $env = new CRM_Utils_Check_Env();
370 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
374 * Common setup functions for all unit tests
376 protected function setUp() {
377 $session = CRM_Core_Session
::singleton();
378 $session->set('userID', NULL);
380 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
381 // Use a temporary file for STDIN
382 $GLOBALS['stdin'] = tmpfile();
383 if ($GLOBALS['stdin'] === FALSE) {
384 echo "Couldn't open temporary file\n";
388 // Get and save a connection to the database
389 $this->_dbconn
= $this->getConnection();
391 // reload database before each test
392 // $this->_populateDB();
394 // "initialize" CiviCRM to avoid problems when running single tests
395 // FIXME: look at it closer in second stage
397 // initialize the object once db is loaded
398 CRM_Core_Config
::$_mail = NULL;
399 $config = CRM_Core_Config
::singleton();
401 // when running unit tests, use mockup user framework
402 $config->setUserFramework('UnitTests');
403 $this->hookClass
= CRM_Utils_Hook
::singleton(TRUE);
404 // also fix the fatal error handler to throw exceptions,
406 $config->fatalErrorHandler
= 'CiviUnitTestCase_fatalErrorHandler';
408 // enable backtrace to get meaningful errors
409 $config->backtrace
= 1;
411 // disable any left-over test extensions
412 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
414 // reset all the caches
415 CRM_Utils_System
::flushCache();
417 // clear permissions stub to not check permissions
418 $config = CRM_Core_Config
::singleton();
419 $config->userPermissionClass
->permissions
= NULL;
421 //flush component settings
422 CRM_Core_Component
::getEnabledComponents(TRUE);
424 if ($this->_eNoticeCompliant
) {
425 error_reporting(E_ALL
);
428 error_reporting(E_ALL
& ~E_NOTICE
);
430 $this->_sethtmlGlobals();
434 * Read everything from the datasets directory and insert into the db
436 public function loadAllFixtures() {
437 $fixturesDir = __DIR__
. '/../../fixtures';
439 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
441 $xmlFiles = glob($fixturesDir . '/*.xml');
442 foreach ($xmlFiles as $xmlFixture) {
443 $op = new PHPUnit_Extensions_Database_Operation_Insert();
444 $dataset = $this->createXMLDataSet($xmlFixture);
445 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
446 $op->execute($this->_dbconn
, $dataset);
449 $yamlFiles = glob($fixturesDir . '/*.yaml');
450 foreach ($yamlFiles as $yamlFixture) {
451 $op = new PHPUnit_Extensions_Database_Operation_Insert();
452 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
453 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
454 $op->execute($this->_dbconn
, $dataset);
457 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
461 * Emulate a logged in user since certain functions use that
462 * value to store a record in the DB (like activity)
465 public function createLoggedInUser() {
467 'first_name' => 'Logged In',
468 'last_name' => 'User ' . rand(),
469 'contact_type' => 'Individual',
471 $contactID = $this->individualCreate($params);
473 $session = CRM_Core_Session
::singleton();
474 $session->set('userID', $contactID);
477 public function cleanDB() {
478 self
::$populateOnce = NULL;
479 $this->DBResetRequired
= TRUE;
481 $this->_dbconn
= $this->getConnection();
482 static::_populateDB();
483 $this->tempDirs
= array();
487 * Create default domain contacts for the two domains added during test class
488 * database population.
490 public function createDomainContacts() {
491 $default_domain_contact = $this->organizationCreate();
492 $second_domain_contact = $this->organizationCreate();
496 * Common teardown functions for all unit tests
498 protected function tearDown() {
499 error_reporting(E_ALL
& ~E_NOTICE
);
500 CRM_Utils_Hook
::singleton()->reset();
501 $this->hookClass
->reset();
502 $session = CRM_Core_Session
::singleton();
503 $session->set('userID', NULL);
506 $this->tx
->rollback()->commit();
509 CRM_Core_Transaction
::forceRollbackIfEnabled();
510 \Civi\Core\Transaction\Manager
::singleton(TRUE);
513 CRM_Core_Transaction
::forceRollbackIfEnabled();
514 \Civi\Core\Transaction\Manager
::singleton(TRUE);
516 $tablesToTruncate = array('civicrm_contact');
517 $this->quickCleanup($tablesToTruncate);
518 $this->createDomainContacts();
521 $this->cleanTempDirs();
522 $this->unsetExtensionSystem();
523 $this->clearOutputBuffer();
527 * FIXME: Maybe a better way to do it
529 public function foreignKeyChecksOff() {
530 self
::$utils = new Utils($GLOBALS['mysql_host'],
531 $GLOBALS['mysql_port'],
532 $GLOBALS['mysql_user'],
533 $GLOBALS['mysql_pass']
535 $dbName = self
::getDBName();
536 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
537 if (self
::$utils->do_query($query) === FALSE) {
539 echo 'Cannot set foreign_key_checks = 0';
545 public function foreignKeyChecksOn() {
546 // FIXME: might not be needed if previous fixme implemented
550 * Generic function to compare expected values after an api call to retrieved
553 * @daoName string DAO Name of object we're evaluating.
554 * @id int Id of object
555 * @match array Associative array of field name => expected value. Empty if asserting
556 * that a DELETE occurred
557 * @delete boolean True if we're checking that a DELETE action occurred.
559 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
561 // adding this here since developers forget to check for an id
562 // and hence we get the first value in the db
563 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
566 $object = new $daoName();
570 // If we're asserting successful record deletion, make sure object is NOT found.
572 if ($object->find(TRUE)) {
573 $this->fail("Object not deleted by delete operation: $daoName, $id");
578 // Otherwise check matches of DAO field values against expected values in $match.
579 if ($object->find(TRUE)) {
580 $fields = &$object->fields();
581 foreach ($fields as $name => $value) {
582 $dbName = $value['name'];
583 if (isset($match[$name])) {
585 $this->assertEquals($object->$dbName, $match[$name]);
587 elseif (isset($match[$dbName])) {
589 $this->assertEquals($object->$dbName, $match[$dbName]);
594 $this->fail("Could not retrieve object: $daoName, $id");
597 $matchSize = count($match);
598 if ($verifiedCount != $matchSize) {
599 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
604 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
605 * @param string $daoName
606 * @param $searchValue
607 * @param $returnColumn
608 * @param $searchColumn
611 * @return null|string
612 * @throws PHPUnit_Framework_AssertionFailedError
614 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
615 if (empty($searchValue)) {
616 $this->fail("empty value passed to assertDBNotNull");
618 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
619 $this->assertNotNull($value, $message);
625 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
626 * @param string $daoName
627 * @param $searchValue
628 * @param $returnColumn
629 * @param $searchColumn
632 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
633 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
634 $this->assertNull($value, $message);
638 * Request a record from the DB by id. Success if row not found.
639 * @param string $daoName
641 * @param null $message
643 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
644 $message = $message ?
$message : "$daoName (#$id) should not exist";
645 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
646 $this->assertNull($value, $message);
650 * Request a record from the DB by id. Success if row not found.
651 * @param string $daoName
653 * @param null $message
655 public function assertDBRowExist($daoName, $id, $message = NULL) {
656 $message = $message ?
$message : "$daoName (#$id) should exist";
657 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
658 $this->assertEquals($id, $value, $message);
662 * Compare a single column value in a retrieved DB record to an expected value
663 * @param string $daoName
664 * @param $searchValue
665 * @param $returnColumn
666 * @param $searchColumn
667 * @param $expectedValue
670 function assertDBCompareValue(
671 $daoName, $searchValue, $returnColumn, $searchColumn,
672 $expectedValue, $message
674 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
675 $this->assertEquals($value, $expectedValue, $message);
679 * Compare all values in a single retrieved DB record to an array of expected values
680 * @param string $daoName
681 * @param array $searchParams
682 * @param $expectedValues
684 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
685 //get the values from db
687 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
689 // compare db values with expected values
690 self
::assertAttributesEquals($expectedValues, $dbValues);
694 * Assert that a SQL query returns a given value
696 * The first argument is an expected value. The remaining arguments are passed
697 * to CRM_Core_DAO::singleValueQuery
699 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
700 * array(1 => array("Whiz", "String")));
702 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
706 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
707 $this->assertEquals($expected, $actual,
708 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
709 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
715 * Assert that two array-trees are exactly equal, notwithstanding
716 * the sorting of keys
718 * @param array $expected
719 * @param array $actual
721 public function assertTreeEquals($expected, $actual) {
724 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
725 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
729 $this->assertEquals($e, $a);
733 * Assert that two numbers are approximately equal
735 * @param int|float $expected
736 * @param int|float $actual
737 * @param int|float $tolerance
738 * @param string $message
740 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
741 if ($message === NULL) {
742 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
744 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
748 * @param $expectedValues
749 * @param $actualValues
750 * @param null $message
752 * @throws PHPUnit_Framework_AssertionFailedError
754 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
755 foreach ($expectedValues as $paramName => $paramValue) {
756 if (isset($actualValues[$paramName])) {
757 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
760 $this->fail("Attribute '$paramName' not present in actual array.");
769 public function assertArrayKeyExists($key, &$list) {
770 $result = isset($list[$key]) ?
TRUE : FALSE;
771 $this->assertTrue($result, ts("%1 element exists?",
780 public function assertArrayValueNotNull($key, &$list) {
781 $this->assertArrayKeyExists($key, $list);
783 $value = isset($list[$key]) ?
$list[$key] : NULL;
784 $this->assertTrue($value,
785 ts("%1 element not null?",
792 * Check that api returned 'is_error' => 0
793 * else provide full message
794 * @param array $apiResult
796 * @param string $prefix
797 * Extra test to add to message.
799 public function assertAPISuccess($apiResult, $prefix = '') {
800 if (!empty($prefix)) {
803 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
805 if (!empty($apiResult['debug_information'])) {
806 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
808 if (!empty($apiResult['trace'])) {
809 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
811 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
815 * Check that api returned 'is_error' => 1
816 * else provide full message
818 * @param array $apiResult
820 * @param string $prefix
821 * Extra test to add to message.
822 * @param null $expectedError
824 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
825 if (!empty($prefix)) {
828 if ($expectedError && !empty($apiResult['is_error'])) {
829 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
831 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
832 $this->assertNotEmpty($apiResult['error_message']);
838 * @param string $message
840 public function assertType($expected, $actual, $message = '') {
841 return $this->assertInternalType($expected, $actual, $message);
845 * Check that a deleted item has been deleted
847 public function assertAPIDeleted($entity, $id) {
848 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
853 * Check that api returned 'is_error' => 1
854 * else provide full message
855 * @param array $result
857 * @param array $valuesToExclude
858 * @param string $prefix
859 * Extra test to add to message.
861 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
862 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
863 foreach ($valuesToExclude as $value) {
864 if (isset($result[$value])) {
865 unset($result[$value]);
867 if (isset($expected[$value])) {
868 unset($expected[$value]);
871 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
875 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
879 * @param array $params
882 public function civicrm_api($entity, $action, $params) {
883 return civicrm_api($entity, $action, $params);
888 * so we can ensure they succeed & throw exceptions without litterering the test with checks
890 * @param string $entity
891 * @param string $action
892 * @param array $params
893 * @param mixed $checkAgainst
894 * Optional value to check result against, implemented for getvalue,.
895 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
896 * for getsingle the array is compared against an array passed in - the id is not compared (for
901 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
902 $params = array_merge(array(
903 'version' => $this->_apiversion
,
908 switch (strtolower($action)) {
910 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
913 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
916 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
918 $result = $this->civicrm_api($entity, $action, $params);
919 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
924 * This function exists to wrap api getValue function & check the result
925 * so we can ensure they succeed & throw exceptions without litterering the test with checks
926 * There is a type check in this
928 * @param string $entity
929 * @param array $params
930 * @param string $type
931 * Per http://php.net/manual/en/function.gettype.php possible types.
941 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
943 'version' => $this->_apiversion
,
946 $result = $this->civicrm_api($entity, 'getvalue', $params);
948 if ($type == 'integer') {
949 // api seems to return integers as strings
950 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
953 $this->assertType($type, $result, "returned result should have been of type $type but was ");
960 * This function exists to wrap api getsingle function & check the result
961 * so we can ensure they succeed & throw exceptions without litterering the test with checks
963 * @param string $entity
964 * @param array $params
965 * @param array $checkAgainst
966 * Array to compare result against.
977 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
979 'version' => $this->_apiversion
,
982 $result = $this->civicrm_api($entity, 'getsingle', $params);
983 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
984 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
987 // @todo - have gone with the fn that unsets id? should we check id?
988 $this->checkArrayEquals($result, $checkAgainst);
994 * This function exists to wrap api getValue function & check the result
995 * so we can ensure they succeed & throw exceptions without litterering the test with checks
996 * There is a type check in this
997 * @param string $entity
998 * @param array $params
1003 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1005 'version' => $this->_apiversion
,
1008 $result = $this->civicrm_api($entity, 'getcount', $params);
1009 if (!is_integer($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1010 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1012 if (is_int($count)) {
1013 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1019 * This function exists to wrap api functions
1020 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1022 * @param string $entity
1023 * @param string $action
1024 * @param array $params
1025 * @param string $function
1026 * Pass this in to create a generated example.
1027 * @param string $file
1028 * Pass this in to create a generated example.
1029 * @param string $description
1030 * @param string|null $subfile
1031 * @param string|null $actionName
1034 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL) {
1035 $params['version'] = $this->_apiversion
;
1036 $result = $this->callAPISuccess($entity, $action, $params);
1037 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
1042 * This function exists to wrap api functions
1043 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1044 * @param string $entity
1045 * @param string $action
1046 * @param array $params
1047 * @param string $expectedErrorMessage
1049 * @param null $extraOutput
1052 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1053 if (is_array($params)) {
1055 'version' => $this->_apiversion
,
1058 $result = $this->civicrm_api($entity, $action, $params);
1059 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1064 * Create required data based on $this->entity & $this->params
1065 * This is just a way to set up the test data for delete & get functions
1066 * so the distinction between set
1067 * up & tested functions is clearer
1072 public function createTestEntity() {
1073 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1077 * Generic function to create Organisation, to be used in test cases
1079 * @param array $params
1080 * parameters for civicrm_contact_add api function call
1082 * sequence number if creating multiple organizations
1085 * id of Organisation created
1087 public function organizationCreate($params = array(), $seq = 0) {
1091 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1092 return $this->_contactCreate($params);
1096 * Generic function to create Individual, to be used in test cases
1098 * @param array $params
1099 * parameters for civicrm_contact_add api function call
1101 * sequence number if creating multiple individuals
1104 * id of Individual created
1106 public function individualCreate($params = array(), $seq = 0) {
1107 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1108 return $this->_contactCreate($params);
1112 * Generic function to create Household, to be used in test cases
1114 * @param array $params
1115 * parameters for civicrm_contact_add api function call
1117 * sequence number if creating multiple households
1120 * id of Household created
1122 public function householdCreate($params = array(), $seq = 0) {
1123 $params = array_merge($this->sampleContact('Household', $seq), $params);
1124 return $this->_contactCreate($params);
1128 * Helper function for getting sample contact properties
1130 * @param string $contact_type
1131 * enum contact type: Individual, Organization
1133 * sequence number for the values of this type
1136 * properties of sample contact (ie. $params for API call)
1138 public function sampleContact($contact_type, $seq = 0) {
1140 'Individual' => array(
1141 // The number of values in each list need to be coprime numbers to not have duplicates
1142 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1143 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1144 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1146 'Organization' => array(
1147 'organization_name' => array(
1148 'Unit Test Organization',
1155 'Household' => array(
1156 'household_name' => array('Unit Test household'),
1159 $params = array('contact_type' => $contact_type);
1160 foreach ($samples[$contact_type] as $key => $values) {
1161 $params[$key] = $values[$seq %
sizeof($values)];
1163 if ($contact_type == 'Individual') {
1164 $params['email'] = strtolower(
1165 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1167 $params['prefix_id'] = 3;
1168 $params['suffix_id'] = 3;
1174 * Private helper function for calling civicrm_contact_add
1176 * @param array $params
1177 * For civicrm_contact_add api function call.
1182 * id of Household created
1184 private function _contactCreate($params) {
1185 $result = $this->callAPISuccess('contact', 'create', $params);
1186 if (!empty($result['is_error']) ||
empty($result['id'])) {
1187 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1189 return $result['id'];
1193 * @param int $contactID
1197 public function contactDelete($contactID) {
1200 'skip_undelete' => 1,
1203 $domain = new CRM_Core_BAO_Domain
;
1204 $domain->contact_id
= $contactID;
1205 if ($domain->find(TRUE)) {
1206 // we are finding tests trying to delete the domain contact in cleanup
1207 //since this is mainly for cleanup lets put a safeguard here
1210 $result = $this->callAPISuccess('contact', 'delete', $params);
1215 * @param int $contactTypeId
1219 public function contactTypeDelete($contactTypeId) {
1220 require_once 'CRM/Contact/BAO/ContactType.php';
1221 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1223 throw new Exception('Could not delete contact type');
1228 * @param array $params
1232 public function membershipTypeCreate($params = array()) {
1233 CRM_Member_PseudoConstant
::flush('membershipType');
1234 CRM_Core_Config
::clearDBCache();
1235 $memberOfOrganization = $this->organizationCreate();
1236 $params = array_merge(array(
1237 'name' => 'General',
1238 'duration_unit' => 'year',
1239 'duration_interval' => 1,
1240 'period_type' => 'rolling',
1241 'member_of_contact_id' => $memberOfOrganization,
1243 'financial_type_id' => 1,
1246 'visibility' => 'Public',
1249 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1251 CRM_Member_PseudoConstant
::flush('membershipType');
1252 CRM_Utils_Cache
::singleton()->flush();
1254 return $result['id'];
1258 * @param array $params
1262 public function contactMembershipCreate($params) {
1264 'join_date' => '2007-01-21',
1265 'start_date' => '2007-01-21',
1266 'end_date' => '2007-12-21',
1267 'source' => 'Payment',
1270 foreach ($pre as $key => $val) {
1271 if (!isset($params[$key])) {
1272 $params[$key] = $val;
1276 $result = $this->callAPISuccess('Membership', 'create', $params);
1277 return $result['id'];
1281 * Delete Membership Type
1283 * @param array $params
1285 public function membershipTypeDelete($params) {
1286 $this->callAPISuccess('MembershipType', 'Delete', $params);
1290 * @param int $membershipID
1292 public function membershipDelete($membershipID) {
1293 $deleteParams = array('id' => $membershipID);
1294 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1299 * @param string $name
1303 public function membershipStatusCreate($name = 'test member status') {
1304 $params['name'] = $name;
1305 $params['start_event'] = 'start_date';
1306 $params['end_event'] = 'end_date';
1307 $params['is_current_member'] = 1;
1308 $params['is_active'] = 1;
1310 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1311 CRM_Member_PseudoConstant
::flush('membershipStatus');
1312 return $result['id'];
1316 * @param int $membershipStatusID
1318 public function membershipStatusDelete($membershipStatusID) {
1319 if (!$membershipStatusID) {
1322 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1327 * @param array $params
1331 public function relationshipTypeCreate($params = array()) {
1332 $params = array_merge(array(
1333 'name_a_b' => 'Relation 1 for relationship type create',
1334 'name_b_a' => 'Relation 2 for relationship type create',
1335 'contact_type_a' => 'Individual',
1336 'contact_type_b' => 'Organization',
1343 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1344 CRM_Core_PseudoConstant
::flush('relationshipType');
1346 return $result['id'];
1350 * Delete Relatinship Type
1352 * @param int $relationshipTypeID
1354 public function relationshipTypeDelete($relationshipTypeID) {
1355 $params['id'] = $relationshipTypeID;
1356 $this->callAPISuccess('relationship_type', 'delete', $params);
1360 * @param array $params
1364 public function paymentProcessorTypeCreate($params = NULL) {
1365 if (is_null($params)) {
1367 'name' => 'API_Test_PP',
1368 'title' => 'API Test Payment Processor',
1369 'class_name' => 'CRM_Core_Payment_APITest',
1370 'billing_mode' => 'form',
1376 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1378 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1380 return $result['id'];
1384 * Create Participant
1386 * @param array $params
1387 * Array of contact id and event id values.
1390 * $id of participant created
1392 public function participantCreate($params) {
1393 if (empty($params['contact_id'])) {
1394 $params['contact_id'] = $this->individualCreate();
1396 if (empty($params['event_id'])) {
1397 $event = $this->eventCreate();
1398 $params['event_id'] = $event['id'];
1403 'register_date' => 20070219,
1404 'source' => 'Wimbeldon',
1405 'event_level' => 'Payment',
1409 $params = array_merge($defaults, $params);
1410 $result = $this->callAPISuccess('Participant', 'create', $params);
1411 return $result['id'];
1415 * Create Payment Processor
1417 * @return CRM_Financial_DAO_PaymentProcessor
1418 * instance of Payment Processsor
1420 public function processorCreate() {
1421 $processorParams = array(
1424 'payment_processor_type_id' => 10,
1425 'financial_account_id' => 12,
1428 'url_site' => 'http://dummy.com',
1429 'url_recur' => 'http://dummy.com',
1430 'billing_mode' => 1,
1432 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::create($processorParams);
1433 return $paymentProcessor;
1437 * Create contribution page
1439 * @param array $params
1441 * Array of contribution page
1443 public function contributionPageCreate($params) {
1444 $this->_pageParams
= array(
1445 'title' => 'Test Contribution Page',
1446 'financial_type_id' => 1,
1447 'currency' => 'USD',
1448 'financial_account_id' => 1,
1449 'payment_processor' => $params['processor_id'],
1451 'is_allow_other_amount' => 1,
1453 'max_amount' => 1000,
1455 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1456 return $contributionPage;
1462 * @param array $params
1464 * result of created tag
1466 public function tagCreate($params = array()) {
1468 'name' => 'New Tag3',
1469 'description' => 'This is description for Our New Tag ',
1472 $params = array_merge($defaults, $params);
1473 $result = $this->callAPISuccess('Tag', 'create', $params);
1474 return $result['values'][$result['id']];
1481 * Id of the tag to be deleted.
1485 public function tagDelete($tagId) {
1486 require_once 'api/api.php';
1490 $result = $this->callAPISuccess('Tag', 'delete', $params);
1491 return $result['id'];
1495 * Add entity(s) to the tag
1497 * @param array $params
1501 public function entityTagAdd($params) {
1502 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1507 * Create contribution
1513 * id of created contribution
1515 public function pledgeCreate($cID) {
1517 'contact_id' => $cID,
1518 'pledge_create_date' => date('Ymd'),
1519 'start_date' => date('Ymd'),
1520 'scheduled_date' => date('Ymd'),
1522 'pledge_status_id' => '2',
1523 'financial_type_id' => '1',
1524 'pledge_original_installment_amount' => 20,
1525 'frequency_interval' => 5,
1526 'frequency_unit' => 'year',
1527 'frequency_day' => 15,
1528 'installments' => 5,
1531 $result = $this->callAPISuccess('Pledge', 'create', $params);
1532 return $result['id'];
1536 * Delete contribution
1538 * @param int $pledgeId
1540 public function pledgeDelete($pledgeId) {
1542 'pledge_id' => $pledgeId,
1544 $this->callAPISuccess('Pledge', 'delete', $params);
1548 * Create contribution
1552 * @param int $cTypeID
1553 * Id of financial type.
1554 * @param int $invoiceID
1555 * @param int $trxnID
1556 * @param int $paymentInstrumentID
1557 * @param bool $isFee
1560 * id of created contribution
1562 public function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1565 'contact_id' => $cID,
1566 'receive_date' => date('Ymd'),
1567 'total_amount' => 100.00,
1568 'financial_type_id' => empty($cTypeID) ?
1 : $cTypeID,
1569 'payment_instrument_id' => empty($paymentInstrumentID) ?
1 : $paymentInstrumentID,
1570 'non_deductible_amount' => 10.00,
1571 'trxn_id' => $trxnID,
1572 'invoice_id' => $invoiceID,
1574 'contribution_status_id' => 1,
1575 // 'note' => 'Donating for Nobel Cause', *Fixme
1579 $params['fee_amount'] = 5.00;
1580 $params['net_amount'] = 95.00;
1583 $result = $this->callAPISuccess('contribution', 'create', $params);
1584 return $result['id'];
1588 * Create online contribution
1590 * @param array $params
1591 * @param int $financialType
1592 * Id of financial type.
1593 * @param int $invoiceID
1594 * @param int $trxnID
1597 * id of created contribution
1599 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1600 $contribParams = array(
1601 'contact_id' => $params['contact_id'],
1602 'receive_date' => date('Ymd'),
1603 'total_amount' => 100.00,
1604 'financial_type_id' => $financialType,
1605 'contribution_page_id' => $params['contribution_page_id'],
1607 'invoice_id' => 67890,
1610 $contribParams = array_merge($contribParams, $params);
1611 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1613 return $result['id'];
1617 * Delete contribution
1619 * @param int $contributionId
1623 public function contributionDelete($contributionId) {
1625 'contribution_id' => $contributionId,
1627 $result = $this->callAPISuccess('contribution', 'delete', $params);
1634 * @param array $params
1635 * Name-value pair for an event.
1639 public function eventCreate($params = array()) {
1640 // if no contact was passed, make up a dummy event creator
1641 if (!isset($params['contact_id'])) {
1642 $params['contact_id'] = $this->_contactCreate(array(
1643 'contact_type' => 'Individual',
1644 'first_name' => 'Event',
1645 'last_name' => 'Creator',
1649 // set defaults for missing params
1650 $params = array_merge(array(
1651 'title' => 'Annual CiviCRM meet',
1652 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1653 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1654 'event_type_id' => 1,
1656 'start_date' => 20081021,
1657 'end_date' => 20081023,
1658 'is_online_registration' => 1,
1659 'registration_start_date' => 20080601,
1660 'registration_end_date' => 20081015,
1661 'max_participants' => 100,
1662 'event_full_text' => 'Sorry! We are already full',
1665 'is_show_location' => 0,
1668 return $this->callAPISuccess('Event', 'create', $params);
1679 public function eventDelete($id) {
1683 return $this->callAPISuccess('event', 'delete', $params);
1687 * Delete participant
1689 * @param int $participantID
1693 public function participantDelete($participantID) {
1695 'id' => $participantID,
1697 return $this->callAPISuccess('Participant', 'delete', $params);
1701 * Create participant payment
1703 * @param int $participantID
1704 * @param int $contributionID
1706 * $id of created payment
1708 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1709 //Create Participant Payment record With Values
1711 'participant_id' => $participantID,
1712 'contribution_id' => $contributionID,
1715 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1716 return $result['id'];
1720 * Delete participant payment
1722 * @param int $paymentID
1724 public function participantPaymentDelete($paymentID) {
1728 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1734 * @param int $contactID
1736 * location id of created location
1738 public function locationAdd($contactID) {
1741 'location_type' => 'New Location Type',
1743 'name' => 'Saint Helier St',
1744 'county' => 'Marin',
1745 'country' => 'United States',
1746 'state_province' => 'Michigan',
1747 'supplemental_address_1' => 'Hallmark Ct',
1748 'supplemental_address_2' => 'Jersey Village',
1753 'contact_id' => $contactID,
1754 'address' => $address,
1755 'location_format' => '2.0',
1756 'location_type' => 'New Location Type',
1759 $result = $this->callAPISuccess('Location', 'create', $params);
1764 * Delete Locations of contact
1766 * @param array $params
1769 public function locationDelete($params) {
1770 $this->callAPISuccess('Location', 'delete', $params);
1774 * Add a Location Type
1776 * @param array $params
1777 * @return CRM_Core_DAO_LocationType
1778 * location id of created location
1780 public function locationTypeCreate($params = NULL) {
1781 if ($params === NULL) {
1783 'name' => 'New Location Type',
1784 'vcard_name' => 'New Location Type',
1785 'description' => 'Location Type for Delete',
1790 $locationType = new CRM_Core_DAO_LocationType();
1791 $locationType->copyValues($params);
1792 $locationType->save();
1793 // clear getfields cache
1794 CRM_Core_PseudoConstant
::flush();
1795 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1796 return $locationType;
1800 * Delete a Location Type
1802 * @param int location type id
1804 public function locationTypeDelete($locationTypeId) {
1805 $locationType = new CRM_Core_DAO_LocationType();
1806 $locationType->id
= $locationTypeId;
1807 $locationType->delete();
1813 * @param array $params
1815 * groupId of created group
1817 public function groupCreate($params = array()) {
1818 $params = array_merge(array(
1819 'name' => 'Test Group 1',
1821 'title' => 'New Test Group Created',
1822 'description' => 'New Test Group Created',
1824 'visibility' => 'Public Pages',
1825 'group_type' => array(
1831 $result = $this->callAPISuccess('Group', 'create', $params);
1832 return $result['id'];
1837 * Function to add a Group
1839 * @params array to add group
1841 * @param array $params
1843 * groupId of created group
1845 public function groupContactCreate($groupID, $totalCount = 10) {
1846 $params = array('group_id' => $groupID);
1847 for ($i = 1; $i <= $totalCount; $i++
) {
1848 $contactID = $this->individualCreate();
1850 $params +
= array('contact_id' => $contactID);
1853 $params +
= array("contact_id.$i" => $contactID);
1856 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1866 public function groupDelete($gid) {
1872 $this->callAPISuccess('Group', 'delete', $params);
1877 * @param array $params
1879 public function uFFieldCreate($params = array()) {
1880 $params = array_merge(array(
1882 'field_name' => 'first_name',
1885 'visibility' => 'Public Pages and Listings',
1886 'is_searchable' => '1',
1887 'label' => 'first_name',
1888 'field_type' => 'Individual',
1891 $this->callAPISuccess('uf_field', 'create', $params);
1895 * Add a UF Join Entry
1897 * @param array $params
1899 * $id of created UF Join
1901 public function ufjoinCreate($params = NULL) {
1902 if ($params === NULL) {
1905 'module' => 'CiviEvent',
1906 'entity_table' => 'civicrm_event',
1912 $result = $this->callAPISuccess('uf_join', 'create', $params);
1917 * Delete a UF Join Entry
1919 * @param array with missing uf_group_id
1921 public function ufjoinDelete($params = NULL) {
1922 if ($params === NULL) {
1925 'module' => 'CiviEvent',
1926 'entity_table' => 'civicrm_event',
1929 'uf_group_id' => '',
1933 crm_add_uf_join($params);
1937 * Create Group for a contact
1939 * @param int $contactId
1941 public function contactGroupCreate($contactId) {
1943 'contact_id.1' => $contactId,
1947 $this->callAPISuccess('GroupContact', 'Create', $params);
1951 * Delete Group for a contact
1953 * @param int $contactId
1955 public function contactGroupDelete($contactId) {
1957 'contact_id.1' => $contactId,
1960 $this->civicrm_api('GroupContact', 'Delete', $params);
1966 * @param array $params
1969 public function activityCreate($params = NULL) {
1971 if ($params === NULL) {
1972 $individualSourceID = $this->individualCreate();
1974 $contactParams = array(
1975 'first_name' => 'Julia',
1976 'Last_name' => 'Anderson',
1978 'email' => 'julia_anderson@civicrm.org',
1979 'contact_type' => 'Individual',
1982 $individualTargetID = $this->individualCreate($contactParams);
1985 'source_contact_id' => $individualSourceID,
1986 'target_contact_id' => array($individualTargetID),
1987 'assignee_contact_id' => array($individualTargetID),
1988 'subject' => 'Discussion on warm beer',
1989 'activity_date_time' => date('Ymd'),
1990 'duration_hours' => 30,
1991 'duration_minutes' => 20,
1992 'location' => 'Baker Street',
1993 'details' => 'Lets schedule a meeting',
1995 'activity_name' => 'Meeting',
1999 $result = $this->callAPISuccess('Activity', 'create', $params);
2001 $result['target_contact_id'] = $individualTargetID;
2002 $result['assignee_contact_id'] = $individualTargetID;
2007 * Create an activity type
2009 * @param array $params
2012 public function activityTypeCreate($params) {
2013 $result = $this->callAPISuccess('ActivityType', 'create', $params);
2018 * Delete activity type
2020 * @param int $activityTypeId
2021 * Id of the activity type.
2023 public function activityTypeDelete($activityTypeId) {
2024 $params['activity_type_id'] = $activityTypeId;
2025 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
2030 * Create custom group
2032 * @param array $params
2035 public function customGroupCreate($params = array()) {
2037 'title' => 'new custom group',
2038 'extends' => 'Contact',
2040 'style' => 'Inline',
2044 $params = array_merge($defaults, $params);
2046 if (strlen($params['title']) > 13) {
2047 $params['title'] = substr($params['title'], 0, 13);
2050 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2051 $this->callAPISuccess('custom_group', 'get', array(
2052 'title' => $params['title'],
2053 array('api.custom_group.delete' => 1),
2056 return $this->callAPISuccess('custom_group', 'create', $params);
2060 * Existing function doesn't allow params to be over-ridden so need a new one
2061 * this one allows you to only pass in the params you want to change
2063 public function CustomGroupCreateByParams($params = array()) {
2065 'title' => "API Custom Group",
2066 'extends' => 'Contact',
2068 'style' => 'Inline',
2071 $params = array_merge($defaults, $params);
2072 return $this->callAPISuccess('custom_group', 'create', $params);
2076 * Create custom group with multi fields
2078 public function CustomGroupMultipleCreateByParams($params = array()) {
2083 $params = array_merge($defaults, $params);
2084 return $this->CustomGroupCreateByParams($params);
2088 * Create custom group with multi fields
2090 public function CustomGroupMultipleCreateWithFields($params = array()) {
2091 // also need to pass on $params['custom_field'] if not set but not in place yet
2093 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2094 $ids['custom_group_id'] = $customGroup['id'];
2096 $customField = $this->customFieldCreate(array(
2097 'custom_group_id' => $ids['custom_group_id'],
2098 'label' => 'field_1' . $ids['custom_group_id'],
2101 $ids['custom_field_id'][] = $customField['id'];
2103 $customField = $this->customFieldCreate(array(
2104 'custom_group_id' => $ids['custom_group_id'],
2105 'default_value' => '',
2106 'label' => 'field_2' . $ids['custom_group_id'],
2108 $ids['custom_field_id'][] = $customField['id'];
2110 $customField = $this->customFieldCreate(array(
2111 'custom_group_id' => $ids['custom_group_id'],
2112 'default_value' => '',
2113 'label' => 'field_3' . $ids['custom_group_id'],
2115 $ids['custom_field_id'][] = $customField['id'];
2121 * Create a custom group with a single text custom field. See
2122 * participant:testCreateWithCustom for how to use this
2124 * @param string $function
2126 * @param string $filename
2130 * ids of created objects
2132 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2133 $params = array('title' => $function);
2134 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2135 $params['extends'] = $entity ?
$entity : 'Contact';
2136 $customGroup = $this->CustomGroupCreate($params);
2137 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2138 CRM_Core_PseudoConstant
::flush();
2140 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2144 * Delete custom group
2146 * @param int $customGroupID
2150 public function customGroupDelete($customGroupID) {
2151 $params['id'] = $customGroupID;
2152 return $this->callAPISuccess('custom_group', 'delete', $params);
2156 * Create custom field
2158 * @param array $params
2159 * (custom_group_id) is required.
2162 public function customFieldCreate($params) {
2163 $params = array_merge(array(
2164 'label' => 'Custom Field',
2165 'data_type' => 'String',
2166 'html_type' => 'Text',
2167 'is_searchable' => 1,
2169 'default_value' => 'defaultValue',
2172 $result = $this->callAPISuccess('custom_field', 'create', $params);
2174 if ($result['is_error'] == 0 && isset($result['id'])) {
2175 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2176 // force reset of enabled components to help grab custom fields
2177 CRM_Core_Component
::getEnabledComponents(1);
2183 * Delete custom field
2185 * @param int $customFieldID
2189 public function customFieldDelete($customFieldID) {
2191 $params['id'] = $customFieldID;
2192 return $this->callAPISuccess('custom_field', 'delete', $params);
2201 public function noteCreate($cId) {
2203 'entity_table' => 'civicrm_contact',
2204 'entity_id' => $cId,
2205 'note' => 'hello I am testing Note',
2206 'contact_id' => $cId,
2207 'modified_date' => date('Ymd'),
2208 'subject' => 'Test Note',
2211 return $this->callAPISuccess('Note', 'create', $params);
2215 * Enable CiviCampaign Component
2217 public function enableCiviCampaign() {
2218 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2219 // force reload of config object
2220 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2221 //flush cache by calling with reset
2222 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2226 * Create test generated example in api/v3/examples.
2227 * To turn this off (e.g. on the server) set
2228 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2229 * in your settings file
2230 * @param array $params
2231 * Array as passed to civicrm_api function.
2232 * @param array $result
2233 * Array as received from the civicrm_api function.
2234 * @param string $function
2235 * Calling function - generally __FUNCTION__.
2236 * @param string $filename
2237 * Called from file - generally __FILE__.
2238 * @param string $description
2239 * Descriptive text for the example file.
2240 * @param string $subfile
2241 * Name for subfile - if this is completed the example will be put in a subfolder (named by the entity).
2242 * @param string $action
2243 * Optional action - otherwise taken from function name.
2245 public function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2246 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2249 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2250 //todo - this is a bit cludgey
2251 if (empty($action)) {
2252 if (strstr($function, 'Create')) {
2253 $action = empty($action) ?
'create' : $action;
2254 $entityAction = 'Create';
2256 elseif (strstr($function, 'GetSingle')) {
2257 $action = empty($action) ?
'getsingle' : $action;
2258 $entityAction = 'GetSingle';
2260 elseif (strstr($function, 'GetValue')) {
2261 $action = empty($action) ?
'getvalue' : $action;
2262 $entityAction = 'GetValue';
2264 elseif (strstr($function, 'GetCount')) {
2265 $action = empty($action) ?
'getcount' : $action;
2266 $entityAction = 'GetCount';
2268 elseif (strstr($function, 'GetFields')) {
2269 $action = empty($action) ?
'getfields' : $action;
2270 $entityAction = 'GetFields';
2272 elseif (strstr($function, 'GetList')) {
2273 $action = empty($action) ?
'getlist' : $action;
2274 $entityAction = 'GetList';
2276 elseif (strstr($function, 'GetActions')) {
2277 $action = empty($action) ?
'getactions' : $action;
2278 $entityAction = 'GetActions';
2280 elseif (strstr($function, 'Get')) {
2281 $action = empty($action) ?
'get' : $action;
2282 $entityAction = 'Get';
2284 elseif (strstr($function, 'Delete')) {
2285 $action = empty($action) ?
'delete' : $action;
2286 $entityAction = 'Delete';
2288 elseif (strstr($function, 'Update')) {
2289 $action = empty($action) ?
'update' : $action;
2290 $entityAction = 'Update';
2292 elseif (strstr($function, 'Subscribe')) {
2293 $action = empty($action) ?
'subscribe' : $action;
2294 $entityAction = 'Subscribe';
2296 elseif (strstr($function, 'Submit')) {
2297 $action = empty($action) ?
'submit' : $action;
2298 $entityAction = 'Submit';
2300 elseif (strstr($function, 'Apply')) {
2301 $action = empty($action) ?
'apply' : $action;
2302 $entityAction = 'Apply';
2304 elseif (strstr($function, 'Replace')) {
2305 $action = empty($action) ?
'replace' : $action;
2306 $entityAction = 'Replace';
2310 $entityAction = ucwords($action);
2313 $this->tidyExampleResult($result);
2314 if (isset($params['version'])) {
2315 unset($params['version']);
2317 // a cleverer person than me would do it in a single regex
2318 if (strstr($entity, 'UF')) {
2319 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2322 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2324 $smarty = CRM_Core_Smarty
::singleton();
2325 $smarty->assign('testfunction', $function);
2326 $function = $fnPrefix . "_" . strtolower($action);
2327 $smarty->assign('function', $function);
2328 $smarty->assign('fnPrefix', $fnPrefix);
2329 $smarty->assign('params', $params);
2330 $smarty->assign('entity', $entity);
2331 $smarty->assign('filename', basename($filename));
2332 $smarty->assign('description', $description);
2333 $smarty->assign('result', $result);
2335 $smarty->assign('action', $action);
2336 if (empty($subfile)) {
2337 $subfile = $entityAction;
2339 if (file_exists('../tests/templates/documentFunction.tpl')) {
2340 if (!is_dir("../api/v3/examples/$entity")) {
2341 mkdir("../api/v3/examples/$entity");
2343 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2344 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2350 * Tidy up examples array so that fields that change often ..don't
2351 * and debug related fields are unset
2353 * @param array $result
2355 public function tidyExampleResult(&$result) {
2356 if (!is_array($result)) {
2359 $fieldsToChange = array(
2360 'hash' => '67eac7789eaee00',
2361 'modified_date' => '2012-11-14 16:02:35',
2362 'created_date' => '2013-07-28 08:49:19',
2363 'create_date' => '20120130621222105',
2364 'application_received_date' => '20130728084957',
2365 'in_date' => '2013-07-28 08:50:19',
2366 'scheduled_date' => '20130728085413',
2367 'approval_date' => '20130728085413',
2368 'pledge_start_date_high' => '20130726090416',
2369 'start_date' => '2013-07-29 00:00:00',
2370 'event_start_date' => '2013-07-29 00:00:00',
2371 'end_date' => '2013-08-04 00:00:00',
2372 'event_end_date' => '2013-08-04 00:00:00',
2373 'decision_date' => '20130805000000',
2376 $keysToUnset = array('xdebug', 'undefined_fields');
2377 foreach ($keysToUnset as $unwantedKey) {
2378 if (isset($result[$unwantedKey])) {
2379 unset($result[$unwantedKey]);
2382 if (isset($result['values'])) {
2383 if (!is_array($result['values'])) {
2386 $resultArray = &$result['values'];
2388 elseif (is_array($result)) {
2389 $resultArray = &$result;
2395 foreach ($resultArray as $index => &$values) {
2396 if (!is_array($values)) {
2399 foreach ($values as $key => &$value) {
2400 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2401 if (isset($value['is_error'])) {
2402 // we have a std nested result format
2403 $this->tidyExampleResult($value);
2406 foreach ($value as &$nestedResult) {
2407 // this is an alternative syntax for nested results a keyed array of results
2408 $this->tidyExampleResult($nestedResult);
2412 if (in_array($key, $keysToUnset)) {
2413 unset($values[$key]);
2416 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2417 $value = $fieldsToChange[$key];
2419 if (is_string($value)) {
2420 $value = addslashes($value);
2429 * @param array $params
2433 public function noteDelete($params) {
2434 return $this->callAPISuccess('Note', 'delete', $params);
2438 * Create custom field with Option Values
2440 * @param array $customGroup
2441 * @param string $name
2442 * Name of custom field.
2446 public function customFieldOptionValueCreate($customGroup, $name) {
2447 $fieldParams = array(
2448 'custom_group_id' => $customGroup['id'],
2449 'name' => 'test_custom_group',
2450 'label' => 'Country',
2451 'html_type' => 'Select',
2452 'data_type' => 'String',
2455 'is_searchable' => 0,
2459 $optionGroup = array(
2461 'name' => 'option_group1',
2462 'label' => 'option_group_label1',
2465 $optionValue = array(
2466 'option_label' => array('Label1', 'Label2'),
2467 'option_value' => array('value1', 'value2'),
2468 'option_name' => array($name . '_1', $name . '_2'),
2469 'option_weight' => array(1, 2),
2470 'option_status' => 1,
2473 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2475 return $this->callAPISuccess('custom_field', 'create', $params);
2483 public function confirmEntitiesDeleted($entities) {
2484 foreach ($entities as $entity) {
2486 $result = $this->callAPISuccess($entity, 'Get', array());
2487 if ($result['error'] == 1 ||
$result['count'] > 0) {
2488 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2495 * @param $tablesToTruncate
2496 * @param bool $dropCustomValueTables
2498 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2500 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2502 if ($dropCustomValueTables) {
2503 $tablesToTruncate[] = 'civicrm_custom_group';
2504 $tablesToTruncate[] = 'civicrm_custom_field';
2507 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2509 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2510 foreach ($tablesToTruncate as $table) {
2511 $sql = "TRUNCATE TABLE $table";
2512 CRM_Core_DAO
::executeQuery($sql);
2514 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2516 if ($dropCustomValueTables) {
2517 $dbName = self
::getDBName();
2519 SELECT TABLE_NAME as tableName
2520 FROM INFORMATION_SCHEMA.TABLES
2521 WHERE TABLE_SCHEMA = '{$dbName}'
2522 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2525 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2526 while ($tableDAO->fetch()) {
2527 $sql = "DROP TABLE {$tableDAO->tableName}";
2528 CRM_Core_DAO
::executeQuery($sql);
2534 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2536 public function quickCleanUpFinancialEntities() {
2537 $tablesToTruncate = array(
2538 'civicrm_contribution',
2539 'civicrm_contribution_soft',
2540 'civicrm_financial_trxn',
2541 'civicrm_financial_item',
2542 'civicrm_contribution_recur',
2543 'civicrm_line_item',
2544 'civicrm_contribution_page',
2545 'civicrm_payment_processor',
2546 'civicrm_entity_financial_trxn',
2547 'civicrm_membership',
2548 'civicrm_membership_type',
2549 'civicrm_membership_payment',
2550 'civicrm_membership_log',
2551 'civicrm_membership_block',
2553 'civicrm_participant',
2554 'civicrm_participant_payment',
2556 'civicrm_price_set_entity',
2557 'civicrm_price_field_value',
2558 'civicrm_price_field',
2560 $this->quickCleanup($tablesToTruncate);
2561 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2562 $this->restoreDefaultPriceSetConfig();
2564 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2567 public function restoreDefaultPriceSetConfig() {
2568 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)");
2569 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)");
2572 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2573 * Default behaviour is to also delete the entity
2574 * @param array $params
2575 * Params array to check agains.
2577 * Id of the entity concerned.
2578 * @param string $entity
2579 * Name of entity concerned (e.g. membership).
2580 * @param bool $delete
2581 * Should the entity be deleted as part of this check.
2582 * @param string $errorText
2583 * Text to print on error.
2586 * @param array $params
2589 * @param int $delete
2590 * @param string $errorText
2594 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2596 $result = $this->callAPISuccessGetSingle($entity, array(
2601 $this->callAPISuccess($entity, 'Delete', array(
2605 $dateFields = $keys = $dateTimeFields = array();
2606 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2607 foreach ($fields['values'] as $field => $settings) {
2608 if (array_key_exists($field, $result)) {
2609 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2612 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2614 $type = CRM_Utils_Array
::value('type', $settings);
2615 if ($type == CRM_Utils_Type
::T_DATE
) {
2616 $dateFields[] = $settings['name'];
2617 // we should identify both real names & unique names as dates
2618 if ($field != $settings['name']) {
2619 $dateFields[] = $field;
2622 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2623 $dateTimeFields[] = $settings['name'];
2624 // we should identify both real names & unique names as dates
2625 if ($field != $settings['name']) {
2626 $dateTimeFields[] = $field;
2631 if (strtolower($entity) == 'contribution') {
2632 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2633 // this is not returned in id format
2634 unset($params['payment_instrument_id']);
2635 $params['contribution_source'] = $params['source'];
2636 unset($params['source']);
2639 foreach ($params as $key => $value) {
2640 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2643 if (in_array($key, $dateFields)) {
2644 $value = date('Y-m-d', strtotime($value));
2645 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2647 if (in_array($key, $dateTimeFields)) {
2648 $value = date('Y-m-d H:i:s', strtotime($value));
2649 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2651 $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);
2656 * Get formatted values in the actual and expected result
2657 * @param array $actual
2658 * Actual calculated values.
2659 * @param array $expected
2662 public function checkArrayEquals(&$actual, &$expected) {
2663 self
::unsetId($actual);
2664 self
::unsetId($expected);
2665 $this->assertEquals($actual, $expected);
2669 * Unset the key 'id' from the array
2670 * @param array $unformattedArray
2671 * The array from which the 'id' has to be unset.
2673 public static function unsetId(&$unformattedArray) {
2674 $formattedArray = array();
2675 if (array_key_exists('id', $unformattedArray)) {
2676 unset($unformattedArray['id']);
2678 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2679 foreach ($unformattedArray['values'] as $key => $value) {
2680 if (is_array($value)) {
2681 foreach ($value as $k => $v) {
2687 elseif ($key == 'id') {
2688 $unformattedArray[$key];
2690 $formattedArray = array($value);
2692 $unformattedArray['values'] = $formattedArray;
2697 * Helper to enable/disable custom directory support
2699 * @param array $customDirs
2701 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2702 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2704 public function customDirectories($customDirs) {
2705 require_once 'CRM/Core/Config.php';
2706 $config = CRM_Core_Config
::singleton();
2708 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2709 unset($config->customPHPPathDir
);
2711 elseif ($customDirs['php_path'] === TRUE) {
2712 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2715 $config->customPHPPathDir
= $php_path;
2718 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2719 unset($config->customTemplateDir
);
2721 elseif ($customDirs['template_path'] === TRUE) {
2722 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2725 $config->customTemplateDir
= $template_path;
2730 * Generate a temporary folder
2732 * @param string $prefix
2735 public function createTempDir($prefix = 'test-') {
2736 $tempDir = CRM_Utils_File
::tempdir($prefix);
2737 $this->tempDirs
[] = $tempDir;
2741 public function cleanTempDirs() {
2742 if (!is_array($this->tempDirs
)) {
2743 // fix test errors where this is not set
2746 foreach ($this->tempDirs
as $tempDir) {
2747 if (is_dir($tempDir)) {
2748 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2754 * Temporarily replace the singleton extension with a different one
2756 public function setExtensionSystem(CRM_Extension_System
$system) {
2757 if ($this->origExtensionSystem
== NULL) {
2758 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2760 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2763 public function unsetExtensionSystem() {
2764 if ($this->origExtensionSystem
!== NULL) {
2765 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2766 $this->origExtensionSystem
= NULL;
2771 * Temporarily alter the settings-metadata to add a mock setting.
2773 * WARNING: The setting metadata will disappear on the next cache-clear.
2778 public function setMockSettingsMetaData($extras) {
2779 CRM_Core_BAO_Setting
::$_cache = array();
2780 $this->callAPISuccess('system', 'flush', array());
2781 CRM_Core_BAO_Setting
::$_cache = array();
2783 CRM_Utils_Hook
::singleton()
2784 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2785 $metadata = array_merge($metadata, $extras);
2788 $fields = $this->callAPISuccess('setting', 'getfields', array());
2789 foreach ($extras as $key => $spec) {
2790 $this->assertNotEmpty($spec['title']);
2791 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2796 * @param string $name
2798 public function financialAccountDelete($name) {
2799 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2800 $financialAccount->name
= $name;
2801 if ($financialAccount->find(TRUE)) {
2802 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2803 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2804 $entityFinancialType->delete();
2805 $financialAccount->delete();
2810 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2811 * (NB unclear if this is still required)
2813 public function _sethtmlGlobals() {
2814 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2815 'required' => array(
2816 'html_quickform_rule_required',
2817 'HTML/QuickForm/Rule/Required.php',
2819 'maxlength' => array(
2820 'html_quickform_rule_range',
2821 'HTML/QuickForm/Rule/Range.php',
2823 'minlength' => array(
2824 'html_quickform_rule_range',
2825 'HTML/QuickForm/Rule/Range.php',
2827 'rangelength' => array(
2828 'html_quickform_rule_range',
2829 'HTML/QuickForm/Rule/Range.php',
2832 'html_quickform_rule_email',
2833 'HTML/QuickForm/Rule/Email.php',
2836 'html_quickform_rule_regex',
2837 'HTML/QuickForm/Rule/Regex.php',
2839 'lettersonly' => array(
2840 'html_quickform_rule_regex',
2841 'HTML/QuickForm/Rule/Regex.php',
2843 'alphanumeric' => array(
2844 'html_quickform_rule_regex',
2845 'HTML/QuickForm/Rule/Regex.php',
2848 'html_quickform_rule_regex',
2849 'HTML/QuickForm/Rule/Regex.php',
2851 'nopunctuation' => array(
2852 'html_quickform_rule_regex',
2853 'HTML/QuickForm/Rule/Regex.php',
2856 'html_quickform_rule_regex',
2857 'HTML/QuickForm/Rule/Regex.php',
2859 'callback' => array(
2860 'html_quickform_rule_callback',
2861 'HTML/QuickForm/Rule/Callback.php',
2864 'html_quickform_rule_compare',
2865 'HTML/QuickForm/Rule/Compare.php',
2868 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2869 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2871 'HTML/QuickForm/group.php',
2872 'HTML_QuickForm_group',
2875 'HTML/QuickForm/hidden.php',
2876 'HTML_QuickForm_hidden',
2879 'HTML/QuickForm/reset.php',
2880 'HTML_QuickForm_reset',
2882 'checkbox' => array(
2883 'HTML/QuickForm/checkbox.php',
2884 'HTML_QuickForm_checkbox',
2887 'HTML/QuickForm/file.php',
2888 'HTML_QuickForm_file',
2891 'HTML/QuickForm/image.php',
2892 'HTML_QuickForm_image',
2894 'password' => array(
2895 'HTML/QuickForm/password.php',
2896 'HTML_QuickForm_password',
2899 'HTML/QuickForm/radio.php',
2900 'HTML_QuickForm_radio',
2903 'HTML/QuickForm/button.php',
2904 'HTML_QuickForm_button',
2907 'HTML/QuickForm/submit.php',
2908 'HTML_QuickForm_submit',
2911 'HTML/QuickForm/select.php',
2912 'HTML_QuickForm_select',
2914 'hiddenselect' => array(
2915 'HTML/QuickForm/hiddenselect.php',
2916 'HTML_QuickForm_hiddenselect',
2919 'HTML/QuickForm/text.php',
2920 'HTML_QuickForm_text',
2922 'textarea' => array(
2923 'HTML/QuickForm/textarea.php',
2924 'HTML_QuickForm_textarea',
2926 'fckeditor' => array(
2927 'HTML/QuickForm/fckeditor.php',
2928 'HTML_QuickForm_FCKEditor',
2931 'HTML/QuickForm/tinymce.php',
2932 'HTML_QuickForm_TinyMCE',
2934 'dojoeditor' => array(
2935 'HTML/QuickForm/dojoeditor.php',
2936 'HTML_QuickForm_dojoeditor',
2939 'HTML/QuickForm/link.php',
2940 'HTML_QuickForm_link',
2942 'advcheckbox' => array(
2943 'HTML/QuickForm/advcheckbox.php',
2944 'HTML_QuickForm_advcheckbox',
2947 'HTML/QuickForm/date.php',
2948 'HTML_QuickForm_date',
2951 'HTML/QuickForm/static.php',
2952 'HTML_QuickForm_static',
2955 'HTML/QuickForm/header.php',
2956 'HTML_QuickForm_header',
2959 'HTML/QuickForm/html.php',
2960 'HTML_QuickForm_html',
2962 'hierselect' => array(
2963 'HTML/QuickForm/hierselect.php',
2964 'HTML_QuickForm_hierselect',
2966 'autocomplete' => array(
2967 'HTML/QuickForm/autocomplete.php',
2968 'HTML_QuickForm_autocomplete',
2971 'HTML/QuickForm/xbutton.php',
2972 'HTML_QuickForm_xbutton',
2974 'advmultiselect' => array(
2975 'HTML/QuickForm/advmultiselect.php',
2976 'HTML_QuickForm_advmultiselect',
2982 * Set up an acl allowing contact to see 2 specified groups
2983 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2985 * You need to have pre-created these groups & created the user e.g
2986 * $this->createLoggedInUser();
2987 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2988 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2990 public function setupACL() {
2992 $_REQUEST = $this->_params
;
2994 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2995 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2996 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2997 'option_group_id' => $optionGroupID,
2998 'label' => 'pick me',
3002 CRM_Core_DAO
::executeQuery("
3003 TRUNCATE civicrm_acl_cache
3006 CRM_Core_DAO
::executeQuery("
3007 TRUNCATE civicrm_acl_contact_cache
3010 CRM_Core_DAO
::executeQuery("
3011 INSERT INTO civicrm_acl_entity_role (
3012 `acl_role_id`, `entity_table`, `entity_id`
3013 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
3016 CRM_Core_DAO
::executeQuery("
3017 INSERT INTO civicrm_acl (
3018 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3021 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3025 CRM_Core_DAO
::executeQuery("
3026 INSERT INTO civicrm_acl (
3027 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3030 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3033 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3034 $this->callAPISuccess('group_contact', 'create', array(
3035 'group_id' => $this->_permissionedGroup
,
3036 'contact_id' => $this->_loggedInUser
,
3039 CRM_ACL_BAO_Cache
::resetCache();
3040 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3041 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3045 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3047 public function offsetDefaultPriceSet() {
3048 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3049 $firstID = $contributionPriceSet['id'];
3050 $this->callAPISuccess('price_set', 'create', array(
3051 'id' => $contributionPriceSet['id'],
3055 unset($contributionPriceSet['id']);
3056 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3057 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3058 'price_set_id' => $firstID,
3059 'options' => array('limit' => 1),
3061 unset($priceField['id']);
3062 $priceField['price_set_id'] = $newPriceSet['id'];
3063 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3064 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3065 'price_set_id' => $firstID,
3067 'options' => array('limit' => 1),
3070 unset($priceFieldValue['id']);
3071 //create some padding to use up ids
3072 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3073 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3074 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3078 * Create an instance of the paypal processor
3079 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3080 * this parent class & we don't have a structure for that yet
3081 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3082 * & the best protection agains that is the functions this class affords
3084 public function paymentProcessorCreate($params = array()) {
3085 $params = array_merge(array(
3087 'domain_id' => CRM_Core_Config
::domainID(),
3088 'payment_processor_type_id' => 'PayPal',
3092 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3093 'password' => '1183377788',
3094 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3095 'url_site' => 'https://www.sandbox.paypal.com/',
3096 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3097 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3098 'class_name' => 'Payment_PayPalImpl',
3099 'billing_mode' => 3,
3100 'financial_type_id' => 1,
3103 if (!is_numeric($params['payment_processor_type_id'])) {
3104 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3106 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3107 'name' => $params['payment_processor_type_id'],
3111 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3112 return $result['id'];
3116 * Set up initial recurring payment allowing subsequent IPN payments
3118 public function setupRecurringPaymentProcessorTransaction() {
3119 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3120 'contact_id' => $this->_contactID
,
3123 'installments' => 5,
3124 'frequency_unit' => 'Month',
3125 'frequency_interval' => 1,
3126 'invoice_id' => $this->_invoiceID
,
3127 'contribution_status_id' => 2,
3128 'processor_id' => $this->_paymentProcessorID
,
3129 'api.contribution.create' => array(
3130 'total_amount' => '200',
3131 'invoice_id' => $this->_invoiceID
,
3132 'financial_type_id' => 1,
3133 'contribution_status_id' => 'Pending',
3134 'contact_id' => $this->_contactID
,
3135 'contribution_page_id' => $this->_contributionPageID
,
3136 'payment_processor_id' => $this->_paymentProcessorID
,
3139 $this->_contributionRecurID
= $contributionRecur['id'];
3140 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3144 * 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
3146 public function setupMembershipRecurringPaymentProcessorTransaction() {
3147 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3148 //create a contribution so our membership & contribution don't both have id = 1
3149 $this->contributionCreate($this->_contactID
, 1, 'abcd', '345j');
3150 $this->setupRecurringPaymentProcessorTransaction();
3152 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3153 'contact_id' => $this->_contactID
,
3154 'membership_type_id' => $this->ids
['membership_type'],
3155 'contribution_recur_id' => $this->_contributionRecurID
,
3156 'format.only_id' => TRUE,
3158 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3159 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3161 $this->callAPISuccess('line_item', 'create', array(
3162 'entity_table' => 'civicrm_membership',
3163 'entity_id' => $this->ids
['membership'],
3164 'contribution_id' => $this->_contributionID
,
3165 'label' => 'General',
3167 'unit_price' => 200,
3168 'line_total' => 200,
3169 'financial_type_id' => 1,
3170 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3172 'label' => 'Membership Amount',
3174 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3176 'label' => 'General',
3179 $this->callAPISuccess('membership_payment', 'create', array(
3180 'contribution_id' => $this->_contributionID
,
3181 'membership_id' => $this->ids
['membership'],
3190 public function CiviUnitTestCase_fatalErrorHandler($message) {
3191 throw new Exception("{$message['message']}: {$message['code']}");
3195 * Helper function to create new mailing
3198 public function createMailing() {
3200 'subject' => 'maild' . rand(),
3201 'body_text' => 'bdkfhdskfhduew',
3202 'name' => 'mailing name' . rand(),
3204 'api.mailing_job.create' => 0,
3207 $result = $this->callAPISuccess('Mailing', 'create', $params);
3208 return $result['id'];
3212 * Helper function to delete mailing
3215 public function deleteMailing($id) {
3220 $this->callAPISuccess('Mailing', 'delete', $params);
3224 * Wrap the entire test case in a transaction
3226 * Only subsequent DB statements will be wrapped in TX -- this cannot
3227 * retroactively wrap old DB statements. Therefore, it makes sense to
3228 * call this at the beginning of setUp().
3230 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3231 * this option does not work with, e.g., custom-data.
3233 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3234 * if TRUNCATE or ALTER is called while using a transaction.
3237 * Whether to use nesting or reference-counting.
3239 public function useTransaction($nest = TRUE) {
3241 $this->tx
= new CRM_Core_Transaction($nest);
3242 $this->tx
->rollback();
3246 public function clearOutputBuffer() {
3247 while (ob_get_level() > 0) {