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 class definitions
34 require_once 'tests/phpunit/Utils.php';
35 require_once 'api/api.php';
36 require_once 'CRM/Financial/BAO/FinancialType.php';
37 define('API_LATEST_VERSION', 3);
40 * Base class for CiviCRM unit tests
42 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
43 * may opt for one or neither:
45 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
46 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
47 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
48 * 2. useTransaction() executes the test inside a transaction. It's easier to use
49 * (because you don't need to identify specific tables), but it doesn't work for tests
50 * which manipulate schema or truncate data -- and could behave inconsistently
51 * for tests which specifically examine DB transactions.
53 * Common functions for unit tests
56 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
59 * Api version - easier to override than just a define
61 protected $_apiversion = API_LATEST_VERSION
;
63 * Database has been initialized.
67 private static $dbInit = FALSE;
70 * Database connection.
72 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
81 static protected $_dbName;
84 * Track tables we have modified during a test.
86 protected $_tablesToTruncate = array();
89 * @var array of temporary directory names
99 * @var boolean populateOnce allows to skip db resets in setUp
101 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
102 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
105 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
107 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
109 public static $populateOnce = FALSE;
112 * @var boolean DBResetRequired allows skipping DB reset
113 * in specific test case. If you still need
114 * to reset single test (method) of such case, call
115 * $this->cleanDB() in the first line of this
118 public $DBResetRequired = TRUE;
121 * @var CRM_Core_Transaction|NULL
126 * @var CRM_Utils_Hook_UnitTests hookClass
127 * example of setting a method for a hook
128 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
130 public $hookClass = NULL;
133 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
135 protected $_params = array();
138 * @var CRM_Extension_System
140 protected $origExtensionSystem;
145 * Because we are overriding the parent class constructor, we
146 * need to show the same arguments as exist in the constructor of
147 * PHPUnit_Framework_TestCase, since
148 * PHPUnit_Framework_TestSuite::createTest() creates a
149 * ReflectionClass of the Test class and checks the constructor
150 * of that class to decide how to set up the test.
152 * @param string $name
154 * @param string $dataName
156 public function __construct($name = NULL, array$data = array(), $dataName = '') {
157 parent
::__construct($name, $data, $dataName);
159 // we need full error reporting
160 error_reporting(E_ALL
& ~E_NOTICE
);
162 self
::$_dbName = self
::getDBName();
164 // create test database
165 self
::$utils = new Utils(CIVICRM_DSN
);
167 // also load the class loader
168 require_once 'CRM/Core/ClassLoader.php';
169 CRM_Core_ClassLoader
::singleton()->register();
170 if (function_exists('_civix_phpunit_setUp')) {
171 // FIXME: loosen coupling
172 _civix_phpunit_setUp();
177 * Override to run the test and assert its state.
180 * @throws \PHPUnit_Framework_IncompleteTest
181 * @throws \PHPUnit_Framework_SkippedTest
183 protected function runTest() {
185 return parent
::runTest();
187 catch (PEAR_Exception
$e) {
188 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
189 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
196 public function requireDBReset() {
197 return $this->DBResetRequired
;
203 public static function getDBName() {
204 static $dbName = NULL;
205 if ($dbName === NULL ) {
206 require_once "DB.php";
207 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
208 $dbName = $dsninfo['database'];
214 * Create database connection for this instance.
216 * Initialize the test database if it hasn't been initialized
218 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
220 protected function getConnection() {
221 $dbName = self
::$_dbName;
222 if (!self
::$dbInit) {
223 $dbName = self
::getDBName();
225 // install test database
226 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
228 static::_populateDB(FALSE, $this);
230 self
::$dbInit = TRUE;
232 return $this->createDefaultDBConnection(self
::$utils->pdo
, $dbName);
236 * Required implementation of abstract method.
238 protected function getDataSet() {
242 * @param bool $perClass
243 * @param null $object
245 * TRUE if the populate logic runs; FALSE if it is skipped
247 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
248 if (CIVICRM_UF
!== 'UnitTests') {
249 throw new \
RuntimeException("_populateDB requirs CIVICRM_UF=UnitTests");
252 if ($perClass ||
$object == NULL) {
256 $dbreset = $object->requireDBReset();
259 if (self
::$populateOnce ||
!$dbreset) {
262 self
::$populateOnce = NULL;
264 $dbName = self
::getDBName();
265 $pdo = self
::$utils->pdo
;
266 // only consider real tables and not views
267 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
268 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
270 $truncates = array();
272 foreach ($tables as $table) {
274 if (substr($table['table_name'], 0, 4) == 'log_') {
278 // don't change list of installed extensions
279 if ($table['table_name'] == 'civicrm_extension') {
283 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
284 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
287 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
293 "SET foreign_key_checks = 0",
294 // SQL mode needs to be strict, that's our standard
295 "SET SQL_MODE='STRICT_ALL_TABLES';",
296 "SET global innodb_flush_log_at_trx_commit = 2;",
298 $queries = array_merge($queries, $truncates);
299 $queries = array_merge($queries, $drops);
300 foreach ($queries as $query) {
301 if (self
::$utils->do_query($query) === FALSE) {
302 // failed to create test database
303 echo "failed to create test db.";
308 // initialize test database
309 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/civicrm_data.mysql";
310 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data.mysql";
311 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__
)))) . "/sql/test_data_second_domain.mysql";
313 $query2 = file_get_contents($sql_file2);
314 $query3 = file_get_contents($sql_file3);
315 $query4 = file_get_contents($sql_file4);
316 if (self
::$utils->do_query($query2) === FALSE) {
317 echo "Cannot load civicrm_data.mysql. Aborting.";
320 if (self
::$utils->do_query($query3) === FALSE) {
321 echo "Cannot load test_data.mysql. Aborting.";
324 if (self
::$utils->do_query($query4) === FALSE) {
325 echo "Cannot load test_data.mysql. Aborting.";
329 // done with all the loading, get transactions back
330 if (self
::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
331 echo "Cannot set global? Huh?";
335 if (self
::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
336 echo "Cannot get foreign keys back? Huh?";
340 unset($query, $query2, $query3);
343 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
345 CRM_Core_BAO_ConfigSetting
::setEnabledComponents(array(
357 public static function setUpBeforeClass() {
358 static::_populateDB(TRUE);
360 // also set this global hack
361 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
365 * Common setup functions for all unit tests.
367 protected function setUp() {
368 $session = CRM_Core_Session
::singleton();
369 $session->set('userID', NULL);
371 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
372 // Use a temporary file for STDIN
373 $GLOBALS['stdin'] = tmpfile();
374 if ($GLOBALS['stdin'] === FALSE) {
375 echo "Couldn't open temporary file\n";
379 // Get and save a connection to the database
380 $this->_dbconn
= $this->getConnection();
382 // reload database before each test
383 // $this->_populateDB();
385 // "initialize" CiviCRM to avoid problems when running single tests
386 // FIXME: look at it closer in second stage
388 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
389 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
391 // disable any left-over test extensions
392 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
394 // reset all the caches
395 CRM_Utils_System
::flushCache();
397 // initialize the object once db is loaded
399 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
401 // when running unit tests, use mockup user framework
402 $this->hookClass
= CRM_Utils_Hook
::singleton();
404 // Make sure the DB connection is setup properly
405 $config->userSystem
->setMySQLTimeZone();
406 $env = new CRM_Utils_Check_Component_Env();
407 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
409 // clear permissions stub to not check permissions
410 $config->userPermissionClass
->permissions
= NULL;
412 //flush component settings
413 CRM_Core_Component
::getEnabledComponents(TRUE);
415 error_reporting(E_ALL
);
417 $this->_sethtmlGlobals();
421 * Read everything from the datasets directory and insert into the db.
423 public function loadAllFixtures() {
424 $fixturesDir = __DIR__
. '/../../fixtures';
426 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
428 $xmlFiles = glob($fixturesDir . '/*.xml');
429 foreach ($xmlFiles as $xmlFixture) {
430 $op = new PHPUnit_Extensions_Database_Operation_Insert();
431 $dataset = $this->createXMLDataSet($xmlFixture);
432 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
433 $op->execute($this->_dbconn
, $dataset);
436 $yamlFiles = glob($fixturesDir . '/*.yaml');
437 foreach ($yamlFiles as $yamlFixture) {
438 $op = new PHPUnit_Extensions_Database_Operation_Insert();
439 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
440 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
441 $op->execute($this->_dbconn
, $dataset);
444 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
448 * Emulate a logged in user since certain functions use that.
449 * value to store a record in the DB (like activity)
453 * Contact ID of the created user.
455 public function createLoggedInUser() {
457 'first_name' => 'Logged In',
458 'last_name' => 'User ' . rand(),
459 'contact_type' => 'Individual',
461 $contactID = $this->individualCreate($params);
462 $this->callAPISuccess('UFMatch', 'create', array(
463 'contact_id' => $contactID,
464 'uf_name' => 'superman',
468 $session = CRM_Core_Session
::singleton();
469 $session->set('userID', $contactID);
473 public function cleanDB() {
474 self
::$populateOnce = NULL;
475 $this->DBResetRequired
= TRUE;
477 $this->_dbconn
= $this->getConnection();
478 static::_populateDB();
479 $this->tempDirs
= array();
483 * Create default domain contacts for the two domains added during test class.
484 * database population.
486 public function createDomainContacts() {
487 $default_domain_contact = $this->organizationCreate();
488 $second_domain_contact = $this->organizationCreate();
492 * Common teardown functions for all unit tests.
494 protected function tearDown() {
495 error_reporting(E_ALL
& ~E_NOTICE
);
496 CRM_Utils_Hook
::singleton()->reset();
497 $this->hookClass
->reset();
498 $session = CRM_Core_Session
::singleton();
499 $session->set('userID', NULL);
502 $this->tx
->rollback()->commit();
505 CRM_Core_Transaction
::forceRollbackIfEnabled();
506 \Civi\Core\Transaction\Manager
::singleton(TRUE);
509 CRM_Core_Transaction
::forceRollbackIfEnabled();
510 \Civi\Core\Transaction\Manager
::singleton(TRUE);
512 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
513 $this->quickCleanup($tablesToTruncate);
514 $this->createDomainContacts();
517 $this->cleanTempDirs();
518 $this->unsetExtensionSystem();
519 $this->clearOutputBuffer();
523 * Generic function to compare expected values after an api call to retrieved.
526 * @daoName string DAO Name of object we're evaluating.
527 * @id int Id of object
528 * @match array Associative array of field name => expected value. Empty if asserting
529 * that a DELETE occurred
530 * @delete boolean True if we're checking that a DELETE action occurred.
534 * @param bool $delete
535 * @throws \PHPUnit_Framework_AssertionFailedError
537 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
539 // adding this here since developers forget to check for an id
540 // and hence we get the first value in the db
541 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
544 $object = new $daoName();
548 // If we're asserting successful record deletion, make sure object is NOT found.
550 if ($object->find(TRUE)) {
551 $this->fail("Object not deleted by delete operation: $daoName, $id");
556 // Otherwise check matches of DAO field values against expected values in $match.
557 if ($object->find(TRUE)) {
558 $fields = &$object->fields();
559 foreach ($fields as $name => $value) {
560 $dbName = $value['name'];
561 if (isset($match[$name])) {
563 $this->assertEquals($object->$dbName, $match[$name]);
565 elseif (isset($match[$dbName])) {
567 $this->assertEquals($object->$dbName, $match[$dbName]);
572 $this->fail("Could not retrieve object: $daoName, $id");
575 $matchSize = count($match);
576 if ($verifiedCount != $matchSize) {
577 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
582 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
583 * @param string $daoName
584 * @param $searchValue
585 * @param $returnColumn
586 * @param $searchColumn
589 * @return null|string
590 * @throws PHPUnit_Framework_AssertionFailedError
592 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
593 if (empty($searchValue)) {
594 $this->fail("empty value passed to assertDBNotNull");
596 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
597 $this->assertNotNull($value, $message);
603 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
604 * @param string $daoName
605 * @param $searchValue
606 * @param $returnColumn
607 * @param $searchColumn
610 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
611 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
612 $this->assertNull($value, $message);
616 * Request a record from the DB by id. Success if row not found.
617 * @param string $daoName
619 * @param null $message
621 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
622 $message = $message ?
$message : "$daoName (#$id) should not exist";
623 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
624 $this->assertNull($value, $message);
628 * Request a record from the DB by id. Success if row not found.
629 * @param string $daoName
631 * @param null $message
633 public function assertDBRowExist($daoName, $id, $message = NULL) {
634 $message = $message ?
$message : "$daoName (#$id) should exist";
635 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
636 $this->assertEquals($id, $value, $message);
640 * Compare a single column value in a retrieved DB record to an expected value.
641 * @param string $daoName
642 * @param $searchValue
643 * @param $returnColumn
644 * @param $searchColumn
645 * @param $expectedValue
648 public function assertDBCompareValue(
649 $daoName, $searchValue, $returnColumn, $searchColumn,
650 $expectedValue, $message
652 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
653 $this->assertEquals($value, $expectedValue, $message);
657 * Compare all values in a single retrieved DB record to an array of expected values.
658 * @param string $daoName
659 * @param array $searchParams
660 * @param $expectedValues
662 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
663 //get the values from db
665 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
667 // compare db values with expected values
668 self
::assertAttributesEquals($expectedValues, $dbValues);
672 * Assert that a SQL query returns a given value.
674 * The first argument is an expected value. The remaining arguments are passed
675 * to CRM_Core_DAO::singleValueQuery
677 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
678 * array(1 => array("Whiz", "String")));
681 * @param array $params
682 * @param string $message
684 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
688 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
689 $this->assertEquals($expected, $actual,
690 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
691 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
697 * Assert that two array-trees are exactly equal, notwithstanding
698 * the sorting of keys
700 * @param array $expected
701 * @param array $actual
703 public function assertTreeEquals($expected, $actual) {
706 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
707 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
711 $this->assertEquals($e, $a);
715 * Assert that two numbers are approximately equal.
717 * @param int|float $expected
718 * @param int|float $actual
719 * @param int|float $tolerance
720 * @param string $message
722 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
723 if ($message === NULL) {
724 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
726 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
730 * Assert attributes are equal.
732 * @param $expectedValues
733 * @param $actualValues
734 * @param string $message
736 * @throws PHPUnit_Framework_AssertionFailedError
738 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
739 foreach ($expectedValues as $paramName => $paramValue) {
740 if (isset($actualValues[$paramName])) {
741 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
744 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
753 public function assertArrayKeyExists($key, &$list) {
754 $result = isset($list[$key]) ?
TRUE : FALSE;
755 $this->assertTrue($result, ts("%1 element exists?",
764 public function assertArrayValueNotNull($key, &$list) {
765 $this->assertArrayKeyExists($key, $list);
767 $value = isset($list[$key]) ?
$list[$key] : NULL;
768 $this->assertTrue($value,
769 ts("%1 element not null?",
776 * Check that api returned 'is_error' => 0.
778 * @param array $apiResult
780 * @param string $prefix
781 * Extra test to add to message.
783 public function assertAPISuccess($apiResult, $prefix = '') {
784 if (!empty($prefix)) {
787 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
789 if (!empty($apiResult['debug_information'])) {
790 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
792 if (!empty($apiResult['trace'])) {
793 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
795 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
799 * Check that api returned 'is_error' => 1.
801 * @param array $apiResult
803 * @param string $prefix
804 * Extra test to add to message.
805 * @param null $expectedError
807 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
808 if (!empty($prefix)) {
811 if ($expectedError && !empty($apiResult['is_error'])) {
812 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
814 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
815 $this->assertNotEmpty($apiResult['error_message']);
821 * @param string $message
823 public function assertType($expected, $actual, $message = '') {
824 return $this->assertInternalType($expected, $actual, $message);
828 * Check that a deleted item has been deleted.
833 public function assertAPIDeleted($entity, $id) {
834 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
839 * Check that api returned 'is_error' => 1
840 * else provide full message
841 * @param array $result
843 * @param array $valuesToExclude
844 * @param string $prefix
845 * Extra test to add to message.
847 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
848 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
849 foreach ($valuesToExclude as $value) {
850 if (isset($result[$value])) {
851 unset($result[$value]);
853 if (isset($expected[$value])) {
854 unset($expected[$value]);
857 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
861 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
865 * @param array $params
868 public function civicrm_api($entity, $action, $params) {
869 return civicrm_api($entity, $action, $params);
873 * Create a batch of external API calls which can
874 * be executed concurrently.
877 * $calls = $this->createExternalAPI()
878 * ->addCall('Contact', 'get', ...)
879 * ->addCall('Contact', 'get', ...)
885 * @return \Civi\API\ExternalBatch
886 * @throws PHPUnit_Framework_SkippedTestError
888 public function createExternalAPI() {
889 global $civicrm_root;
890 $defaultParams = array(
891 'version' => $this->_apiversion
,
895 $calls = new \Civi\API\
ExternalBatch($defaultParams);
897 if (!$calls->isSupported()) {
898 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
905 * wrap api functions.
906 * so we can ensure they succeed & throw exceptions without litterering the test with checks
908 * @param string $entity
909 * @param string $action
910 * @param array $params
911 * @param mixed $checkAgainst
912 * Optional value to check result against, implemented for getvalue,.
913 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
914 * for getsingle the array is compared against an array passed in - the id is not compared (for
919 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
920 $params = array_merge(array(
921 'version' => $this->_apiversion
,
926 switch (strtolower($action)) {
928 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
931 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
934 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
936 $result = $this->civicrm_api($entity, $action, $params);
937 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
942 * This function exists to wrap api getValue function & check the result
943 * so we can ensure they succeed & throw exceptions without litterering the test with checks
944 * There is a type check in this
946 * @param string $entity
947 * @param array $params
948 * @param string $type
949 * Per http://php.net/manual/en/function.gettype.php possible types.
959 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
961 'version' => $this->_apiversion
,
964 $result = $this->civicrm_api($entity, 'getvalue', $params);
966 if ($type == 'integer') {
967 // api seems to return integers as strings
968 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
971 $this->assertType($type, $result, "returned result should have been of type $type but was ");
978 * This function exists to wrap api getsingle function & check the result
979 * so we can ensure they succeed & throw exceptions without litterering the test with checks
981 * @param string $entity
982 * @param array $params
983 * @param array $checkAgainst
984 * Array to compare result against.
995 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
997 'version' => $this->_apiversion
,
1000 $result = $this->civicrm_api($entity, 'getsingle', $params);
1001 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1002 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
1004 if ($checkAgainst) {
1005 // @todo - have gone with the fn that unsets id? should we check id?
1006 $this->checkArrayEquals($result, $checkAgainst);
1012 * This function exists to wrap api getValue function & check the result
1013 * so we can ensure they succeed & throw exceptions without litterering the test with checks
1014 * There is a type check in this
1015 * @param string $entity
1016 * @param array $params
1017 * @param null $count
1021 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
1023 'version' => $this->_apiversion
,
1026 $result = $this->civicrm_api($entity, 'getcount', $params);
1027 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
1028 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
1030 if (is_int($count)) {
1031 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
1037 * This function exists to wrap api functions.
1038 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
1040 * @param string $entity
1041 * @param string $action
1042 * @param array $params
1043 * @param string $function
1044 * Pass this in to create a generated example.
1045 * @param string $file
1046 * Pass this in to create a generated example.
1047 * @param string $description
1048 * @param string|null $exampleName
1052 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
1053 $params['version'] = $this->_apiversion
;
1054 $result = $this->callAPISuccess($entity, $action, $params);
1055 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
1060 * This function exists to wrap api functions.
1061 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
1062 * @param string $entity
1063 * @param string $action
1064 * @param array $params
1065 * @param string $expectedErrorMessage
1067 * @param null $extraOutput
1070 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
1071 if (is_array($params)) {
1073 'version' => $this->_apiversion
,
1076 $result = $this->civicrm_api($entity, $action, $params);
1077 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
1082 * Create required data based on $this->entity & $this->params
1083 * This is just a way to set up the test data for delete & get functions
1084 * so the distinction between set
1085 * up & tested functions is clearer
1090 public function createTestEntity() {
1091 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
1095 * Generic function to create Organisation, to be used in test cases
1097 * @param array $params
1098 * parameters for civicrm_contact_add api function call
1100 * sequence number if creating multiple organizations
1103 * id of Organisation created
1105 public function organizationCreate($params = array(), $seq = 0) {
1109 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1110 return $this->_contactCreate($params);
1114 * Generic function to create Individual, to be used in test cases
1116 * @param array $params
1117 * parameters for civicrm_contact_add api function call
1119 * sequence number if creating multiple individuals
1122 * id of Individual created
1124 public function individualCreate($params = array(), $seq = 0) {
1125 $params = array_merge($this->sampleContact('Individual', $seq), $params);
1126 return $this->_contactCreate($params);
1130 * Generic function to create Household, to be used in test cases
1132 * @param array $params
1133 * parameters for civicrm_contact_add api function call
1135 * sequence number if creating multiple households
1138 * id of Household created
1140 public function householdCreate($params = array(), $seq = 0) {
1141 $params = array_merge($this->sampleContact('Household', $seq), $params);
1142 return $this->_contactCreate($params);
1146 * Helper function for getting sample contact properties.
1148 * @param string $contact_type
1149 * enum contact type: Individual, Organization
1151 * sequence number for the values of this type
1154 * properties of sample contact (ie. $params for API call)
1156 public function sampleContact($contact_type, $seq = 0) {
1158 'Individual' => array(
1159 // The number of values in each list need to be coprime numbers to not have duplicates
1160 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1161 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1162 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1164 'Organization' => array(
1165 'organization_name' => array(
1166 'Unit Test Organization',
1173 'Household' => array(
1174 'household_name' => array('Unit Test household'),
1177 $params = array('contact_type' => $contact_type);
1178 foreach ($samples[$contact_type] as $key => $values) {
1179 $params[$key] = $values[$seq %
count($values)];
1181 if ($contact_type == 'Individual') {
1182 $params['email'] = strtolower(
1183 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1185 $params['prefix_id'] = 3;
1186 $params['suffix_id'] = 3;
1192 * Private helper function for calling civicrm_contact_add.
1194 * @param array $params
1195 * For civicrm_contact_add api function call.
1200 * id of Household created
1202 private function _contactCreate($params) {
1203 $result = $this->callAPISuccess('contact', 'create', $params);
1204 if (!empty($result['is_error']) ||
empty($result['id'])) {
1205 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
1207 return $result['id'];
1211 * Delete contact, ensuring it is not the domain contact
1213 * @param int $contactID
1214 * Contact ID to delete
1216 public function contactDelete($contactID) {
1217 $domain = new CRM_Core_BAO_Domain();
1218 $domain->contact_id
= $contactID;
1219 if (!$domain->find(TRUE)) {
1220 $this->callAPISuccess('contact', 'delete', array(
1222 'skip_undelete' => 1,
1228 * @param int $contactTypeId
1232 public function contactTypeDelete($contactTypeId) {
1233 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
1235 throw new Exception('Could not delete contact type');
1240 * @param array $params
1244 public function membershipTypeCreate($params = array()) {
1245 CRM_Member_PseudoConstant
::flush('membershipType');
1246 CRM_Core_Config
::clearDBCache();
1247 $memberOfOrganization = $this->organizationCreate();
1248 $params = array_merge(array(
1249 'name' => 'General',
1250 'duration_unit' => 'year',
1251 'duration_interval' => 1,
1252 'period_type' => 'rolling',
1253 'member_of_contact_id' => $memberOfOrganization,
1255 'financial_type_id' => 1,
1258 'visibility' => 'Public',
1261 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1263 CRM_Member_PseudoConstant
::flush('membershipType');
1264 CRM_Utils_Cache
::singleton()->flush();
1266 return $result['id'];
1270 * @param array $params
1274 public function contactMembershipCreate($params) {
1276 'join_date' => '2007-01-21',
1277 'start_date' => '2007-01-21',
1278 'end_date' => '2007-12-21',
1279 'source' => 'Payment',
1282 foreach ($pre as $key => $val) {
1283 if (!isset($params[$key])) {
1284 $params[$key] = $val;
1288 $result = $this->callAPISuccess('Membership', 'create', $params);
1289 return $result['id'];
1293 * Delete Membership Type.
1295 * @param array $params
1297 public function membershipTypeDelete($params) {
1298 $this->callAPISuccess('MembershipType', 'Delete', $params);
1302 * @param int $membershipID
1304 public function membershipDelete($membershipID) {
1305 $deleteParams = array('id' => $membershipID);
1306 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1310 * @param string $name
1314 public function membershipStatusCreate($name = 'test member status') {
1315 $params['name'] = $name;
1316 $params['start_event'] = 'start_date';
1317 $params['end_event'] = 'end_date';
1318 $params['is_current_member'] = 1;
1319 $params['is_active'] = 1;
1321 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1322 CRM_Member_PseudoConstant
::flush('membershipStatus');
1323 return $result['id'];
1327 * @param int $membershipStatusID
1329 public function membershipStatusDelete($membershipStatusID) {
1330 if (!$membershipStatusID) {
1333 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1337 * @param array $params
1341 public function relationshipTypeCreate($params = array()) {
1342 $params = array_merge(array(
1343 'name_a_b' => 'Relation 1 for relationship type create',
1344 'name_b_a' => 'Relation 2 for relationship type create',
1345 'contact_type_a' => 'Individual',
1346 'contact_type_b' => 'Organization',
1353 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1354 CRM_Core_PseudoConstant
::flush('relationshipType');
1356 return $result['id'];
1360 * Delete Relatinship Type.
1362 * @param int $relationshipTypeID
1364 public function relationshipTypeDelete($relationshipTypeID) {
1365 $params['id'] = $relationshipTypeID;
1366 $this->callAPISuccess('relationship_type', 'delete', $params);
1370 * @param array $params
1374 public function paymentProcessorTypeCreate($params = NULL) {
1375 if (is_null($params)) {
1377 'name' => 'API_Test_PP',
1378 'title' => 'API Test Payment Processor',
1379 'class_name' => 'CRM_Core_Payment_APITest',
1380 'billing_mode' => 'form',
1386 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1388 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1390 return $result['id'];
1394 * Create test Authorize.net instance.
1396 * @param array $params
1400 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1401 $params = array_merge(array(
1402 'name' => 'Authorize',
1403 'domain_id' => CRM_Core_Config
::domainID(),
1404 'payment_processor_type_id' => 'AuthNet',
1405 'title' => 'AuthNet',
1410 'user_name' => '4y5BfuW7jm',
1411 'password' => '4cAmW927n8uLf5J8',
1412 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1413 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1414 'class_name' => 'Payment_AuthorizeNet',
1415 'billing_mode' => 1,
1418 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1419 return $result['id'];
1423 * Create Participant.
1425 * @param array $params
1426 * Array of contact id and event id values.
1429 * $id of participant created
1431 public function participantCreate($params) {
1432 if (empty($params['contact_id'])) {
1433 $params['contact_id'] = $this->individualCreate();
1435 if (empty($params['event_id'])) {
1436 $event = $this->eventCreate();
1437 $params['event_id'] = $event['id'];
1442 'register_date' => 20070219,
1443 'source' => 'Wimbeldon',
1444 'event_level' => 'Payment',
1448 $params = array_merge($defaults, $params);
1449 $result = $this->callAPISuccess('Participant', 'create', $params);
1450 return $result['id'];
1454 * Create Payment Processor.
1457 * Id Payment Processor
1459 public function processorCreate() {
1460 $processorParams = array(
1463 'payment_processor_type_id' => 'Dummy',
1464 'financial_account_id' => 12,
1468 'url_site' => 'http://dummy.com',
1469 'url_recur' => 'http://dummy.com',
1470 'billing_mode' => 1,
1473 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1474 return $processor['id'];
1478 * Create Payment Processor.
1480 * @param array $processorParams
1482 * @return \CRM_Core_Payment_Dummy
1483 * Instance of Dummy Payment Processor
1485 public function dummyProcessorCreate($processorParams = array()) {
1486 $paymentProcessorID = $this->processorCreate($processorParams);
1487 return System
::singleton()->getById($paymentProcessorID);
1491 * Create contribution page.
1493 * @param array $params
1495 * Array of contribution page
1497 public function contributionPageCreate($params) {
1498 $this->_pageParams
= array(
1499 'title' => 'Test Contribution Page',
1500 'financial_type_id' => 1,
1501 'currency' => 'USD',
1502 'financial_account_id' => 1,
1503 'payment_processor' => $params['processor_id'],
1505 'is_allow_other_amount' => 1,
1507 'max_amount' => 1000,
1509 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1510 return $contributionPage;
1514 * Create a sample batch.
1516 public function batchCreate() {
1517 $params = $this->_params
;
1518 $params['name'] = $params['title'] = 'Batch_433397';
1519 $params['status_id'] = 1;
1520 $result = $this->callAPISuccess('batch', 'create', $params);
1521 return $result['id'];
1527 * @param array $params
1529 * result of created tag
1531 public function tagCreate($params = array()) {
1533 'name' => 'New Tag3',
1534 'description' => 'This is description for Our New Tag ',
1537 $params = array_merge($defaults, $params);
1538 $result = $this->callAPISuccess('Tag', 'create', $params);
1539 return $result['values'][$result['id']];
1546 * Id of the tag to be deleted.
1550 public function tagDelete($tagId) {
1551 require_once 'api/api.php';
1555 $result = $this->callAPISuccess('Tag', 'delete', $params);
1556 return $result['id'];
1560 * Add entity(s) to the tag
1562 * @param array $params
1566 public function entityTagAdd($params) {
1567 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1572 * Create contribution.
1578 * id of created contribution
1580 public function pledgeCreate($cID) {
1582 'contact_id' => $cID,
1583 'pledge_create_date' => date('Ymd'),
1584 'start_date' => date('Ymd'),
1585 'scheduled_date' => date('Ymd'),
1587 'pledge_status_id' => '2',
1588 'financial_type_id' => '1',
1589 'pledge_original_installment_amount' => 20,
1590 'frequency_interval' => 5,
1591 'frequency_unit' => 'year',
1592 'frequency_day' => 15,
1593 'installments' => 5,
1596 $result = $this->callAPISuccess('Pledge', 'create', $params);
1597 return $result['id'];
1601 * Delete contribution.
1603 * @param int $pledgeId
1605 public function pledgeDelete($pledgeId) {
1607 'pledge_id' => $pledgeId,
1609 $this->callAPISuccess('Pledge', 'delete', $params);
1613 * Create contribution.
1615 * @param array $params
1616 * Array of parameters.
1619 * id of created contribution
1621 public function contributionCreate($params) {
1623 $params = array_merge(array(
1625 'receive_date' => date('Ymd'),
1626 'total_amount' => 100.00,
1627 'fee_amount' => 5.00,
1628 'net_ammount' => 95.00,
1629 'financial_type_id' => 1,
1630 'payment_instrument_id' => 1,
1631 'non_deductible_amount' => 10.00,
1633 'invoice_id' => 67890,
1635 'contribution_status_id' => 1,
1638 $result = $this->callAPISuccess('contribution', 'create', $params);
1639 return $result['id'];
1643 * Delete contribution.
1645 * @param int $contributionId
1649 public function contributionDelete($contributionId) {
1651 'contribution_id' => $contributionId,
1653 $result = $this->callAPISuccess('contribution', 'delete', $params);
1660 * @param array $params
1661 * Name-value pair for an event.
1665 public function eventCreate($params = array()) {
1666 // if no contact was passed, make up a dummy event creator
1667 if (!isset($params['contact_id'])) {
1668 $params['contact_id'] = $this->_contactCreate(array(
1669 'contact_type' => 'Individual',
1670 'first_name' => 'Event',
1671 'last_name' => 'Creator',
1675 // set defaults for missing params
1676 $params = array_merge(array(
1677 'title' => 'Annual CiviCRM meet',
1678 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1679 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1680 'event_type_id' => 1,
1682 'start_date' => 20081021,
1683 'end_date' => 20081023,
1684 'is_online_registration' => 1,
1685 'registration_start_date' => 20080601,
1686 'registration_end_date' => 20081015,
1687 'max_participants' => 100,
1688 'event_full_text' => 'Sorry! We are already full',
1691 'is_show_location' => 0,
1694 return $this->callAPISuccess('Event', 'create', $params);
1705 public function eventDelete($id) {
1709 return $this->callAPISuccess('event', 'delete', $params);
1713 * Delete participant.
1715 * @param int $participantID
1719 public function participantDelete($participantID) {
1721 'id' => $participantID,
1723 return $this->callAPISuccess('Participant', 'delete', $params);
1727 * Create participant payment.
1729 * @param int $participantID
1730 * @param int $contributionID
1732 * $id of created payment
1734 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1735 //Create Participant Payment record With Values
1737 'participant_id' => $participantID,
1738 'contribution_id' => $contributionID,
1741 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1742 return $result['id'];
1746 * Delete participant payment.
1748 * @param int $paymentID
1750 public function participantPaymentDelete($paymentID) {
1754 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1760 * @param int $contactID
1762 * location id of created location
1764 public function locationAdd($contactID) {
1767 'location_type' => 'New Location Type',
1769 'name' => 'Saint Helier St',
1770 'county' => 'Marin',
1771 'country' => 'UNITED STATES',
1772 'state_province' => 'Michigan',
1773 'supplemental_address_1' => 'Hallmark Ct',
1774 'supplemental_address_2' => 'Jersey Village',
1779 'contact_id' => $contactID,
1780 'address' => $address,
1781 'location_format' => '2.0',
1782 'location_type' => 'New Location Type',
1785 $result = $this->callAPISuccess('Location', 'create', $params);
1790 * Delete Locations of contact.
1792 * @param array $params
1795 public function locationDelete($params) {
1796 $this->callAPISuccess('Location', 'delete', $params);
1800 * Add a Location Type.
1802 * @param array $params
1803 * @return CRM_Core_DAO_LocationType
1804 * location id of created location
1806 public function locationTypeCreate($params = NULL) {
1807 if ($params === NULL) {
1809 'name' => 'New Location Type',
1810 'vcard_name' => 'New Location Type',
1811 'description' => 'Location Type for Delete',
1816 $locationType = new CRM_Core_DAO_LocationType();
1817 $locationType->copyValues($params);
1818 $locationType->save();
1819 // clear getfields cache
1820 CRM_Core_PseudoConstant
::flush();
1821 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1822 return $locationType;
1826 * Delete a Location Type.
1828 * @param int $locationTypeId
1830 public function locationTypeDelete($locationTypeId) {
1831 $locationType = new CRM_Core_DAO_LocationType();
1832 $locationType->id
= $locationTypeId;
1833 $locationType->delete();
1839 * @param array $params
1840 * @return CRM_Core_DAO_Mapping
1841 * Mapping id of created mapping
1843 public function mappingCreate($params = NULL) {
1844 if ($params === NULL) {
1846 'name' => 'Mapping name',
1847 'description' => 'Mapping description',
1848 // 'Export Contact' mapping.
1849 'mapping_type_id' => 7,
1853 $mapping = new CRM_Core_DAO_Mapping();
1854 $mapping->copyValues($params);
1856 // clear getfields cache
1857 CRM_Core_PseudoConstant
::flush();
1858 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1865 * @param int $mappingId
1867 public function mappingDelete($mappingId) {
1868 $mapping = new CRM_Core_DAO_Mapping();
1869 $mapping->id
= $mappingId;
1876 * @param array $params
1878 * groupId of created group
1880 public function groupCreate($params = array()) {
1881 $params = array_merge(array(
1882 'name' => 'Test Group 1',
1884 'title' => 'New Test Group Created',
1885 'description' => 'New Test Group Created',
1887 'visibility' => 'Public Pages',
1888 'group_type' => array(
1894 $result = $this->callAPISuccess('Group', 'create', $params);
1895 return $result['id'];
1900 * Function to add a Group.
1902 * @params array to add group
1904 * @param int $groupID
1905 * @param int $totalCount
1907 * groupId of created group
1909 public function groupContactCreate($groupID, $totalCount = 10) {
1910 $params = array('group_id' => $groupID);
1911 for ($i = 1; $i <= $totalCount; $i++
) {
1912 $contactID = $this->individualCreate();
1914 $params +
= array('contact_id' => $contactID);
1917 $params +
= array("contact_id.$i" => $contactID);
1920 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1930 public function groupDelete($gid) {
1936 $this->callAPISuccess('Group', 'delete', $params);
1941 * @param array $params
1943 public function uFFieldCreate($params = array()) {
1944 $params = array_merge(array(
1946 'field_name' => 'first_name',
1949 'visibility' => 'Public Pages and Listings',
1950 'is_searchable' => '1',
1951 'label' => 'first_name',
1952 'field_type' => 'Individual',
1955 $this->callAPISuccess('uf_field', 'create', $params);
1959 * Add a UF Join Entry.
1961 * @param array $params
1963 * $id of created UF Join
1965 public function ufjoinCreate($params = NULL) {
1966 if ($params === NULL) {
1969 'module' => 'CiviEvent',
1970 'entity_table' => 'civicrm_event',
1976 $result = $this->callAPISuccess('uf_join', 'create', $params);
1981 * Delete a UF Join Entry.
1983 * @param array $params
1984 * with missing uf_group_id
1986 public function ufjoinDelete($params = NULL) {
1987 if ($params === NULL) {
1990 'module' => 'CiviEvent',
1991 'entity_table' => 'civicrm_event',
1994 'uf_group_id' => '',
1998 crm_add_uf_join($params);
2002 * @param array $params
2003 * Optional parameters.
2008 public function campaignCreate($params = array()) {
2009 $this->enableCiviCampaign();
2010 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
2011 'name' => 'big_campaign',
2012 'title' => 'Campaign',
2014 return $campaign['id'];
2018 * Create Group for a contact.
2020 * @param int $contactId
2022 public function contactGroupCreate($contactId) {
2024 'contact_id.1' => $contactId,
2028 $this->callAPISuccess('GroupContact', 'Create', $params);
2032 * Delete Group for a contact.
2034 * @param int $contactId
2036 public function contactGroupDelete($contactId) {
2038 'contact_id.1' => $contactId,
2041 $this->civicrm_api('GroupContact', 'Delete', $params);
2047 * @param array $params
2050 public function activityCreate($params = NULL) {
2052 if ($params === NULL) {
2053 $individualSourceID = $this->individualCreate();
2055 $contactParams = array(
2056 'first_name' => 'Julia',
2057 'Last_name' => 'Anderson',
2059 'email' => 'julia_anderson@civicrm.org',
2060 'contact_type' => 'Individual',
2063 $individualTargetID = $this->individualCreate($contactParams);
2066 'source_contact_id' => $individualSourceID,
2067 'target_contact_id' => array($individualTargetID),
2068 'assignee_contact_id' => array($individualTargetID),
2069 'subject' => 'Discussion on warm beer',
2070 'activity_date_time' => date('Ymd'),
2071 'duration_hours' => 30,
2072 'duration_minutes' => 20,
2073 'location' => 'Baker Street',
2074 'details' => 'Lets schedule a meeting',
2076 'activity_name' => 'Meeting',
2080 $result = $this->callAPISuccess('Activity', 'create', $params);
2082 $result['target_contact_id'] = $individualTargetID;
2083 $result['assignee_contact_id'] = $individualTargetID;
2088 * Create an activity type.
2090 * @param array $params
2094 public function activityTypeCreate($params) {
2095 return $this->callAPISuccess('ActivityType', 'create', $params);
2099 * Delete activity type.
2101 * @param int $activityTypeId
2102 * Id of the activity type.
2105 public function activityTypeDelete($activityTypeId) {
2106 $params['activity_type_id'] = $activityTypeId;
2107 return $this->callAPISuccess('ActivityType', 'delete', $params);
2111 * Create custom group.
2113 * @param array $params
2116 public function customGroupCreate($params = array()) {
2118 'title' => 'new custom group',
2119 'extends' => 'Contact',
2121 'style' => 'Inline',
2125 $params = array_merge($defaults, $params);
2127 if (strlen($params['title']) > 13) {
2128 $params['title'] = substr($params['title'], 0, 13);
2131 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2132 $this->callAPISuccess('custom_group', 'get', array(
2133 'title' => $params['title'],
2134 array('api.custom_group.delete' => 1),
2137 return $this->callAPISuccess('custom_group', 'create', $params);
2141 * Existing function doesn't allow params to be over-ridden so need a new one
2142 * this one allows you to only pass in the params you want to change
2143 * @param array $params
2146 public function CustomGroupCreateByParams($params = array()) {
2148 'title' => "API Custom Group",
2149 'extends' => 'Contact',
2151 'style' => 'Inline',
2154 $params = array_merge($defaults, $params);
2155 return $this->callAPISuccess('custom_group', 'create', $params);
2159 * Create custom group with multi fields.
2160 * @param array $params
2163 public function CustomGroupMultipleCreateByParams($params = array()) {
2168 $params = array_merge($defaults, $params);
2169 return $this->CustomGroupCreateByParams($params);
2173 * Create custom group with multi fields.
2174 * @param array $params
2177 public function CustomGroupMultipleCreateWithFields($params = array()) {
2178 // also need to pass on $params['custom_field'] if not set but not in place yet
2180 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2181 $ids['custom_group_id'] = $customGroup['id'];
2183 $customField = $this->customFieldCreate(array(
2184 'custom_group_id' => $ids['custom_group_id'],
2185 'label' => 'field_1' . $ids['custom_group_id'],
2188 $ids['custom_field_id'][] = $customField['id'];
2190 $customField = $this->customFieldCreate(array(
2191 'custom_group_id' => $ids['custom_group_id'],
2192 'default_value' => '',
2193 'label' => 'field_2' . $ids['custom_group_id'],
2195 $ids['custom_field_id'][] = $customField['id'];
2197 $customField = $this->customFieldCreate(array(
2198 'custom_group_id' => $ids['custom_group_id'],
2199 'default_value' => '',
2200 'label' => 'field_3' . $ids['custom_group_id'],
2202 $ids['custom_field_id'][] = $customField['id'];
2208 * Create a custom group with a single text custom field. See
2209 * participant:testCreateWithCustom for how to use this
2211 * @param string $function
2213 * @param string $filename
2217 * ids of created objects
2219 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2220 $params = array('title' => $function);
2221 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2222 $params['extends'] = $entity ?
$entity : 'Contact';
2223 $customGroup = $this->CustomGroupCreate($params);
2224 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2225 CRM_Core_PseudoConstant
::flush();
2227 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2231 * Delete custom group.
2233 * @param int $customGroupID
2237 public function customGroupDelete($customGroupID) {
2238 $params['id'] = $customGroupID;
2239 return $this->callAPISuccess('custom_group', 'delete', $params);
2243 * Create custom field.
2245 * @param array $params
2246 * (custom_group_id) is required.
2249 public function customFieldCreate($params) {
2250 $params = array_merge(array(
2251 'label' => 'Custom Field',
2252 'data_type' => 'String',
2253 'html_type' => 'Text',
2254 'is_searchable' => 1,
2256 'default_value' => 'defaultValue',
2259 $result = $this->callAPISuccess('custom_field', 'create', $params);
2260 // these 2 functions are called with force to flush static caches
2261 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2262 CRM_Core_Component
::getEnabledComponents(1);
2267 * Delete custom field.
2269 * @param int $customFieldID
2273 public function customFieldDelete($customFieldID) {
2275 $params['id'] = $customFieldID;
2276 return $this->callAPISuccess('custom_field', 'delete', $params);
2285 public function noteCreate($cId) {
2287 'entity_table' => 'civicrm_contact',
2288 'entity_id' => $cId,
2289 'note' => 'hello I am testing Note',
2290 'contact_id' => $cId,
2291 'modified_date' => date('Ymd'),
2292 'subject' => 'Test Note',
2295 return $this->callAPISuccess('Note', 'create', $params);
2299 * Enable CiviCampaign Component.
2301 public function enableCiviCampaign() {
2302 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2303 // force reload of config object
2304 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2305 //flush cache by calling with reset
2306 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2310 * Create test generated example in api/v3/examples.
2312 * To turn this off (e.g. on the server) set
2313 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2314 * in your settings file
2316 * @param string $entity
2317 * @param string $action
2318 * @param array $params
2319 * Array as passed to civicrm_api function.
2320 * @param array $result
2321 * Array as received from the civicrm_api function.
2322 * @param string $testFunction
2323 * Calling function - generally __FUNCTION__.
2324 * @param string $testFile
2325 * Called from file - generally __FILE__.
2326 * @param string $description
2327 * Descriptive text for the example file.
2328 * @param string $exampleName
2329 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2331 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2332 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG
) {
2335 $entity = _civicrm_api_get_camel_name($entity);
2336 $action = strtolower($action);
2338 if (empty($exampleName)) {
2339 // Attempt to convert lowercase action name to CamelCase.
2340 // This is clunky/imperfect due to the convention of all lowercase actions.
2341 $exampleName = CRM_Utils_String
::convertStringToCamel($action);
2342 $knownPrefixes = array(
2349 foreach ($knownPrefixes as $prefix) {
2350 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2351 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2356 $this->tidyExampleResult($result);
2357 if (isset($params['version'])) {
2358 unset($params['version']);
2360 // Format multiline description as array
2362 if (is_string($description) && strlen($description)) {
2363 foreach (explode("\n", $description) as $line) {
2364 $desc[] = trim($line);
2367 $smarty = CRM_Core_Smarty
::singleton();
2368 $smarty->assign('testFunction', $testFunction);
2369 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2370 $smarty->assign('params', $params);
2371 $smarty->assign('entity', $entity);
2372 $smarty->assign('testFile', basename($testFile));
2373 $smarty->assign('description', $desc);
2374 $smarty->assign('result', $result);
2375 $smarty->assign('action', $action);
2377 if (file_exists('../tests/templates/documentFunction.tpl')) {
2378 if (!is_dir("../api/v3/examples/$entity")) {
2379 mkdir("../api/v3/examples/$entity");
2381 $f = fopen("../api/v3/examples/$entity/$exampleName.php", "w+b");
2382 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2388 * Tidy up examples array so that fields that change often ..don't
2389 * and debug related fields are unset
2391 * @param array $result
2393 public function tidyExampleResult(&$result) {
2394 if (!is_array($result)) {
2397 $fieldsToChange = array(
2398 'hash' => '67eac7789eaee00',
2399 'modified_date' => '2012-11-14 16:02:35',
2400 'created_date' => '2013-07-28 08:49:19',
2401 'create_date' => '20120130621222105',
2402 'application_received_date' => '20130728084957',
2403 'in_date' => '2013-07-28 08:50:19',
2404 'scheduled_date' => '20130728085413',
2405 'approval_date' => '20130728085413',
2406 'pledge_start_date_high' => '20130726090416',
2407 'start_date' => '2013-07-29 00:00:00',
2408 'event_start_date' => '2013-07-29 00:00:00',
2409 'end_date' => '2013-08-04 00:00:00',
2410 'event_end_date' => '2013-08-04 00:00:00',
2411 'decision_date' => '20130805000000',
2414 $keysToUnset = array('xdebug', 'undefined_fields');
2415 foreach ($keysToUnset as $unwantedKey) {
2416 if (isset($result[$unwantedKey])) {
2417 unset($result[$unwantedKey]);
2420 if (isset($result['values'])) {
2421 if (!is_array($result['values'])) {
2424 $resultArray = &$result['values'];
2426 elseif (is_array($result)) {
2427 $resultArray = &$result;
2433 foreach ($resultArray as $index => &$values) {
2434 if (!is_array($values)) {
2437 foreach ($values as $key => &$value) {
2438 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2439 if (isset($value['is_error'])) {
2440 // we have a std nested result format
2441 $this->tidyExampleResult($value);
2444 foreach ($value as &$nestedResult) {
2445 // this is an alternative syntax for nested results a keyed array of results
2446 $this->tidyExampleResult($nestedResult);
2450 if (in_array($key, $keysToUnset)) {
2451 unset($values[$key]);
2454 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2455 $value = $fieldsToChange[$key];
2457 if (is_string($value)) {
2458 $value = addslashes($value);
2467 * @param array $params
2471 public function noteDelete($params) {
2472 return $this->callAPISuccess('Note', 'delete', $params);
2476 * Create custom field with Option Values.
2478 * @param array $customGroup
2479 * @param string $name
2480 * Name of custom field.
2484 public function customFieldOptionValueCreate($customGroup, $name) {
2485 $fieldParams = array(
2486 'custom_group_id' => $customGroup['id'],
2487 'name' => 'test_custom_group',
2488 'label' => 'Country',
2489 'html_type' => 'Select',
2490 'data_type' => 'String',
2493 'is_searchable' => 0,
2497 $optionGroup = array(
2499 'name' => 'option_group1',
2500 'label' => 'option_group_label1',
2503 $optionValue = array(
2504 'option_label' => array('Label1', 'Label2'),
2505 'option_value' => array('value1', 'value2'),
2506 'option_name' => array($name . '_1', $name . '_2'),
2507 'option_weight' => array(1, 2),
2508 'option_status' => 1,
2511 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2513 return $this->callAPISuccess('custom_field', 'create', $params);
2521 public function confirmEntitiesDeleted($entities) {
2522 foreach ($entities as $entity) {
2524 $result = $this->callAPISuccess($entity, 'Get', array());
2525 if ($result['error'] == 1 ||
$result['count'] > 0) {
2526 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2534 * Quick clean by emptying tables created for the test.
2536 * @param array $tablesToTruncate
2537 * @param bool $dropCustomValueTables
2538 * @throws \Exception
2540 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2542 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2544 if ($dropCustomValueTables) {
2545 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2546 while ($optionGroupResult->fetch()) {
2547 if (!empty($optionGroupResult->option_group_id
)) {
2548 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2551 $tablesToTruncate[] = 'civicrm_custom_group';
2552 $tablesToTruncate[] = 'civicrm_custom_field';
2555 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2557 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2558 foreach ($tablesToTruncate as $table) {
2559 $sql = "TRUNCATE TABLE $table";
2560 CRM_Core_DAO
::executeQuery($sql);
2562 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2564 if ($dropCustomValueTables) {
2565 $dbName = self
::getDBName();
2567 SELECT TABLE_NAME as tableName
2568 FROM INFORMATION_SCHEMA.TABLES
2569 WHERE TABLE_SCHEMA = '{$dbName}'
2570 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2573 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2574 while ($tableDAO->fetch()) {
2575 $sql = "DROP TABLE {$tableDAO->tableName}";
2576 CRM_Core_DAO
::executeQuery($sql);
2582 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2584 public function quickCleanUpFinancialEntities() {
2585 $tablesToTruncate = array(
2587 'civicrm_activity_contact',
2588 'civicrm_contribution',
2589 'civicrm_contribution_soft',
2590 'civicrm_contribution_product',
2591 'civicrm_financial_trxn',
2592 'civicrm_financial_item',
2593 'civicrm_contribution_recur',
2594 'civicrm_line_item',
2595 'civicrm_contribution_page',
2596 'civicrm_payment_processor',
2597 'civicrm_entity_financial_trxn',
2598 'civicrm_membership',
2599 'civicrm_membership_type',
2600 'civicrm_membership_payment',
2601 'civicrm_membership_log',
2602 'civicrm_membership_block',
2604 'civicrm_participant',
2605 'civicrm_participant_payment',
2607 'civicrm_price_set_entity',
2608 'civicrm_price_field_value',
2609 'civicrm_price_field',
2611 $this->quickCleanup($tablesToTruncate);
2612 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2613 $this->restoreDefaultPriceSetConfig();
2615 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2616 System
::singleton()->flushProcessors();
2619 public function restoreDefaultPriceSetConfig() {
2620 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2621 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)");
2622 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)");
2625 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2626 * Default behaviour is to also delete the entity
2627 * @param array $params
2628 * Params array to check against.
2630 * Id of the entity concerned.
2631 * @param string $entity
2632 * Name of entity concerned (e.g. membership).
2633 * @param bool $delete
2634 * Should the entity be deleted as part of this check.
2635 * @param string $errorText
2636 * Text to print on error.
2639 * @param array $params
2642 * @param int $delete
2643 * @param string $errorText
2647 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2649 $result = $this->callAPISuccessGetSingle($entity, array(
2654 $this->callAPISuccess($entity, 'Delete', array(
2658 $dateFields = $keys = $dateTimeFields = array();
2659 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2660 foreach ($fields['values'] as $field => $settings) {
2661 if (array_key_exists($field, $result)) {
2662 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2665 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2667 $type = CRM_Utils_Array
::value('type', $settings);
2668 if ($type == CRM_Utils_Type
::T_DATE
) {
2669 $dateFields[] = $settings['name'];
2670 // we should identify both real names & unique names as dates
2671 if ($field != $settings['name']) {
2672 $dateFields[] = $field;
2675 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2676 $dateTimeFields[] = $settings['name'];
2677 // we should identify both real names & unique names as dates
2678 if ($field != $settings['name']) {
2679 $dateTimeFields[] = $field;
2684 if (strtolower($entity) == 'contribution') {
2685 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2686 // this is not returned in id format
2687 unset($params['payment_instrument_id']);
2688 $params['contribution_source'] = $params['source'];
2689 unset($params['source']);
2692 foreach ($params as $key => $value) {
2693 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2696 if (in_array($key, $dateFields)) {
2697 $value = date('Y-m-d', strtotime($value));
2698 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2700 if (in_array($key, $dateTimeFields)) {
2701 $value = date('Y-m-d H:i:s', strtotime($value));
2702 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2704 $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);
2709 * Get formatted values in the actual and expected result.
2710 * @param array $actual
2711 * Actual calculated values.
2712 * @param array $expected
2715 public function checkArrayEquals(&$actual, &$expected) {
2716 self
::unsetId($actual);
2717 self
::unsetId($expected);
2718 $this->assertEquals($actual, $expected);
2722 * Unset the key 'id' from the array
2723 * @param array $unformattedArray
2724 * The array from which the 'id' has to be unset.
2726 public static function unsetId(&$unformattedArray) {
2727 $formattedArray = array();
2728 if (array_key_exists('id', $unformattedArray)) {
2729 unset($unformattedArray['id']);
2731 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2732 foreach ($unformattedArray['values'] as $key => $value) {
2733 if (is_array($value)) {
2734 foreach ($value as $k => $v) {
2740 elseif ($key == 'id') {
2741 $unformattedArray[$key];
2743 $formattedArray = array($value);
2745 $unformattedArray['values'] = $formattedArray;
2750 * Helper to enable/disable custom directory support
2752 * @param array $customDirs
2754 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2755 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2757 public function customDirectories($customDirs) {
2758 require_once 'CRM/Core/Config.php';
2759 $config = CRM_Core_Config
::singleton();
2761 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2762 unset($config->customPHPPathDir
);
2764 elseif ($customDirs['php_path'] === TRUE) {
2765 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2768 $config->customPHPPathDir
= $php_path;
2771 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2772 unset($config->customTemplateDir
);
2774 elseif ($customDirs['template_path'] === TRUE) {
2775 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2778 $config->customTemplateDir
= $template_path;
2783 * Generate a temporary folder.
2785 * @param string $prefix
2788 public function createTempDir($prefix = 'test-') {
2789 $tempDir = CRM_Utils_File
::tempdir($prefix);
2790 $this->tempDirs
[] = $tempDir;
2794 public function cleanTempDirs() {
2795 if (!is_array($this->tempDirs
)) {
2796 // fix test errors where this is not set
2799 foreach ($this->tempDirs
as $tempDir) {
2800 if (is_dir($tempDir)) {
2801 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2807 * Temporarily replace the singleton extension with a different one.
2808 * @param \CRM_Extension_System $system
2810 public function setExtensionSystem(CRM_Extension_System
$system) {
2811 if ($this->origExtensionSystem
== NULL) {
2812 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2814 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2817 public function unsetExtensionSystem() {
2818 if ($this->origExtensionSystem
!== NULL) {
2819 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2820 $this->origExtensionSystem
= NULL;
2825 * Temporarily alter the settings-metadata to add a mock setting.
2827 * WARNING: The setting metadata will disappear on the next cache-clear.
2832 public function setMockSettingsMetaData($extras) {
2833 Civi
::service('settings_manager')->flush();
2835 CRM_Utils_Hook
::singleton()
2836 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2837 $metadata = array_merge($metadata, $extras);
2840 $fields = $this->callAPISuccess('setting', 'getfields', array());
2841 foreach ($extras as $key => $spec) {
2842 $this->assertNotEmpty($spec['title']);
2843 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2848 * @param string $name
2850 public function financialAccountDelete($name) {
2851 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2852 $financialAccount->name
= $name;
2853 if ($financialAccount->find(TRUE)) {
2854 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2855 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2856 $entityFinancialType->delete();
2857 $financialAccount->delete();
2862 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2863 * (NB unclear if this is still required)
2865 public function _sethtmlGlobals() {
2866 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2867 'required' => array(
2868 'html_quickform_rule_required',
2869 'HTML/QuickForm/Rule/Required.php',
2871 'maxlength' => array(
2872 'html_quickform_rule_range',
2873 'HTML/QuickForm/Rule/Range.php',
2875 'minlength' => array(
2876 'html_quickform_rule_range',
2877 'HTML/QuickForm/Rule/Range.php',
2879 'rangelength' => array(
2880 'html_quickform_rule_range',
2881 'HTML/QuickForm/Rule/Range.php',
2884 'html_quickform_rule_email',
2885 'HTML/QuickForm/Rule/Email.php',
2888 'html_quickform_rule_regex',
2889 'HTML/QuickForm/Rule/Regex.php',
2891 'lettersonly' => array(
2892 'html_quickform_rule_regex',
2893 'HTML/QuickForm/Rule/Regex.php',
2895 'alphanumeric' => array(
2896 'html_quickform_rule_regex',
2897 'HTML/QuickForm/Rule/Regex.php',
2900 'html_quickform_rule_regex',
2901 'HTML/QuickForm/Rule/Regex.php',
2903 'nopunctuation' => array(
2904 'html_quickform_rule_regex',
2905 'HTML/QuickForm/Rule/Regex.php',
2908 'html_quickform_rule_regex',
2909 'HTML/QuickForm/Rule/Regex.php',
2911 'callback' => array(
2912 'html_quickform_rule_callback',
2913 'HTML/QuickForm/Rule/Callback.php',
2916 'html_quickform_rule_compare',
2917 'HTML/QuickForm/Rule/Compare.php',
2920 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2921 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2923 'HTML/QuickForm/group.php',
2924 'HTML_QuickForm_group',
2927 'HTML/QuickForm/hidden.php',
2928 'HTML_QuickForm_hidden',
2931 'HTML/QuickForm/reset.php',
2932 'HTML_QuickForm_reset',
2934 'checkbox' => array(
2935 'HTML/QuickForm/checkbox.php',
2936 'HTML_QuickForm_checkbox',
2939 'HTML/QuickForm/file.php',
2940 'HTML_QuickForm_file',
2943 'HTML/QuickForm/image.php',
2944 'HTML_QuickForm_image',
2946 'password' => array(
2947 'HTML/QuickForm/password.php',
2948 'HTML_QuickForm_password',
2951 'HTML/QuickForm/radio.php',
2952 'HTML_QuickForm_radio',
2955 'HTML/QuickForm/button.php',
2956 'HTML_QuickForm_button',
2959 'HTML/QuickForm/submit.php',
2960 'HTML_QuickForm_submit',
2963 'HTML/QuickForm/select.php',
2964 'HTML_QuickForm_select',
2966 'hiddenselect' => array(
2967 'HTML/QuickForm/hiddenselect.php',
2968 'HTML_QuickForm_hiddenselect',
2971 'HTML/QuickForm/text.php',
2972 'HTML_QuickForm_text',
2974 'textarea' => array(
2975 'HTML/QuickForm/textarea.php',
2976 'HTML_QuickForm_textarea',
2978 'fckeditor' => array(
2979 'HTML/QuickForm/fckeditor.php',
2980 'HTML_QuickForm_FCKEditor',
2983 'HTML/QuickForm/tinymce.php',
2984 'HTML_QuickForm_TinyMCE',
2986 'dojoeditor' => array(
2987 'HTML/QuickForm/dojoeditor.php',
2988 'HTML_QuickForm_dojoeditor',
2991 'HTML/QuickForm/link.php',
2992 'HTML_QuickForm_link',
2994 'advcheckbox' => array(
2995 'HTML/QuickForm/advcheckbox.php',
2996 'HTML_QuickForm_advcheckbox',
2999 'HTML/QuickForm/date.php',
3000 'HTML_QuickForm_date',
3003 'HTML/QuickForm/static.php',
3004 'HTML_QuickForm_static',
3007 'HTML/QuickForm/header.php',
3008 'HTML_QuickForm_header',
3011 'HTML/QuickForm/html.php',
3012 'HTML_QuickForm_html',
3014 'hierselect' => array(
3015 'HTML/QuickForm/hierselect.php',
3016 'HTML_QuickForm_hierselect',
3018 'autocomplete' => array(
3019 'HTML/QuickForm/autocomplete.php',
3020 'HTML_QuickForm_autocomplete',
3023 'HTML/QuickForm/xbutton.php',
3024 'HTML_QuickForm_xbutton',
3026 'advmultiselect' => array(
3027 'HTML/QuickForm/advmultiselect.php',
3028 'HTML_QuickForm_advmultiselect',
3034 * Set up an acl allowing contact to see 2 specified groups
3035 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
3037 * You need to have pre-created these groups & created the user e.g
3038 * $this->createLoggedInUser();
3039 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3040 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
3042 * @param bool $isProfile
3044 public function setupACL($isProfile = FALSE) {
3046 $_REQUEST = $this->_params
;
3048 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
3049 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
3050 $optionValue = $this->callAPISuccess('option_value', 'create', array(
3051 'option_group_id' => $optionGroupID,
3052 'label' => 'pick me',
3056 CRM_Core_DAO
::executeQuery("
3057 TRUNCATE civicrm_acl_cache
3060 CRM_Core_DAO
::executeQuery("
3061 TRUNCATE civicrm_acl_contact_cache
3064 CRM_Core_DAO
::executeQuery("
3065 INSERT INTO civicrm_acl_entity_role (
3066 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3067 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
3071 CRM_Core_DAO
::executeQuery("
3072 INSERT INTO civicrm_acl (
3073 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3076 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3081 CRM_Core_DAO
::executeQuery("
3082 INSERT INTO civicrm_acl (
3083 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3086 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3090 CRM_Core_DAO
::executeQuery("
3091 INSERT INTO civicrm_acl (
3092 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3095 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3100 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
3101 $this->callAPISuccess('group_contact', 'create', array(
3102 'group_id' => $this->_permissionedGroup
,
3103 'contact_id' => $this->_loggedInUser
,
3108 CRM_ACL_BAO_Cache
::resetCache();
3109 CRM_Contact_BAO_Group
::getPermissionClause(TRUE);
3110 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3115 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3117 public function offsetDefaultPriceSet() {
3118 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3119 $firstID = $contributionPriceSet['id'];
3120 $this->callAPISuccess('price_set', 'create', array(
3121 'id' => $contributionPriceSet['id'],
3125 unset($contributionPriceSet['id']);
3126 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3127 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3128 'price_set_id' => $firstID,
3129 'options' => array('limit' => 1),
3131 unset($priceField['id']);
3132 $priceField['price_set_id'] = $newPriceSet['id'];
3133 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3134 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3135 'price_set_id' => $firstID,
3137 'options' => array('limit' => 1),
3140 unset($priceFieldValue['id']);
3141 //create some padding to use up ids
3142 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3143 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3144 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3148 * Create an instance of the paypal processor.
3149 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3150 * this parent class & we don't have a structure for that yet
3151 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3152 * & the best protection against that is the functions this class affords
3153 * @param array $params
3154 * @return int $result['id'] payment processor id
3156 public function paymentProcessorCreate($params = array()) {
3157 $params = array_merge(array(
3159 'domain_id' => CRM_Core_Config
::domainID(),
3160 'payment_processor_type_id' => 'PayPal',
3164 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3165 'password' => '1183377788',
3166 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3167 'url_site' => 'https://www.sandbox.paypal.com/',
3168 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3169 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3170 'class_name' => 'Payment_PayPalImpl',
3171 'billing_mode' => 3,
3172 'financial_type_id' => 1,
3175 if (!is_numeric($params['payment_processor_type_id'])) {
3176 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3178 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3179 'name' => $params['payment_processor_type_id'],
3183 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3184 return $result['id'];
3188 * Set up initial recurring payment allowing subsequent IPN payments.
3190 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3191 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3192 'contact_id' => $this->_contactID
,
3195 'installments' => 5,
3196 'frequency_unit' => 'Month',
3197 'frequency_interval' => 1,
3198 'invoice_id' => $this->_invoiceID
,
3199 'contribution_status_id' => 2,
3200 'payment_processor_id' => $this->_paymentProcessorID
,
3201 // processor provided ID - use contact ID as proxy.
3202 'processor_id' => $this->_contactID
,
3203 'api.contribution.create' => array(
3204 'total_amount' => '200',
3205 'invoice_id' => $this->_invoiceID
,
3206 'financial_type_id' => 1,
3207 'contribution_status_id' => 'Pending',
3208 'contact_id' => $this->_contactID
,
3209 'contribution_page_id' => $this->_contributionPageID
,
3210 'payment_processor_id' => $this->_paymentProcessorID
,
3214 $this->_contributionRecurID
= $contributionRecur['id'];
3215 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
3219 * 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
3221 public function setupMembershipRecurringPaymentProcessorTransaction() {
3222 $this->ids
['membership_type'] = $this->membershipTypeCreate();
3223 //create a contribution so our membership & contribution don't both have id = 1
3224 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3225 $this->contributionCreate(array(
3226 'contact_id' => $this->_contactID
,
3228 'financial_type_id' => 1,
3229 'invoice_id' => 'abcd',
3233 $this->setupRecurringPaymentProcessorTransaction();
3235 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
3236 'contact_id' => $this->_contactID
,
3237 'membership_type_id' => $this->ids
['membership_type'],
3238 'contribution_recur_id' => $this->_contributionRecurID
,
3239 'format.only_id' => TRUE,
3241 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3242 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
3244 $this->callAPISuccess('line_item', 'create', array(
3245 'entity_table' => 'civicrm_membership',
3246 'entity_id' => $this->ids
['membership'],
3247 'contribution_id' => $this->_contributionID
,
3248 'label' => 'General',
3250 'unit_price' => 200,
3251 'line_total' => 200,
3252 'financial_type_id' => 1,
3253 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3255 'label' => 'Membership Amount',
3256 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3258 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3260 'label' => 'General',
3261 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3264 $this->callAPISuccess('membership_payment', 'create', array(
3265 'contribution_id' => $this->_contributionID
,
3266 'membership_id' => $this->ids
['membership'],
3275 public function CiviUnitTestCase_fatalErrorHandler($message) {
3276 throw new Exception("{$message['message']}: {$message['code']}");
3280 * Helper function to create new mailing.
3283 public function createMailing() {
3285 'subject' => 'maild' . rand(),
3286 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3287 'name' => 'mailing name' . rand(),
3291 $result = $this->callAPISuccess('Mailing', 'create', $params);
3292 return $result['id'];
3296 * Helper function to delete mailing.
3299 public function deleteMailing($id) {
3304 $this->callAPISuccess('Mailing', 'delete', $params);
3308 * Wrap the entire test case in a transaction.
3310 * Only subsequent DB statements will be wrapped in TX -- this cannot
3311 * retroactively wrap old DB statements. Therefore, it makes sense to
3312 * call this at the beginning of setUp().
3314 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3315 * this option does not work with, e.g., custom-data.
3317 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3318 * if TRUNCATE or ALTER is called while using a transaction.
3321 * Whether to use nesting or reference-counting.
3323 public function useTransaction($nest = TRUE) {
3325 $this->tx
= new CRM_Core_Transaction($nest);
3326 $this->tx
->rollback();
3330 public function clearOutputBuffer() {
3331 while (ob_get_level() > 0) {
3337 * Assert the attachment exists.
3339 * @param bool $exists
3340 * @param array $apiResult
3342 protected function assertAttachmentExistence($exists, $apiResult) {
3343 $fileId = $apiResult['id'];
3344 $this->assertTrue(is_numeric($fileId));
3345 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3346 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3347 1 => array($fileId, 'Int'),
3349 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3350 1 => array($fileId, 'Int'),
3355 * Create a price set for an event.
3357 * @param int $feeTotal
3362 protected function eventPriceSetCreate($feeTotal) {
3363 // creating price set, price field
3364 $paramsSet['title'] = 'Price Set';
3365 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3366 $paramsSet['is_active'] = FALSE;
3367 $paramsSet['extends'] = 1;
3369 $priceset = CRM_Price_BAO_PriceSet
::create($paramsSet);
3370 $priceSetId = $priceset->id
;
3372 //Checking for priceset added in the table.
3373 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3374 'id', $paramsSet['title'], 'Check DB for created priceset'
3376 $paramsField = array(
3377 'label' => 'Price Field',
3378 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3379 'html_type' => 'Text',
3380 'price' => $feeTotal,
3381 'option_label' => array('1' => 'Price Field'),
3382 'option_value' => array('1' => $feeTotal),
3383 'option_name' => array('1' => $feeTotal),
3384 'option_weight' => array('1' => 1),
3385 'option_amount' => array('1' => 1),
3386 'is_display_amounts' => 1,
3388 'options_per_line' => 1,
3389 'is_active' => array('1' => 1),
3390 'price_set_id' => $priceset->id
,
3391 'is_enter_qty' => 1,
3392 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3394 CRM_Price_BAO_PriceField
::create($paramsField);
3400 * Add a profile to a contribution page.
3402 * @param string $name
3403 * @param int $contributionPageID
3405 protected function addProfile($name, $contributionPageID) {
3406 $this->callAPISuccess('UFJoin', 'create', array(
3407 'uf_group_id' => $name,
3408 'module' => 'CiviContribute',
3409 'entity_table' => 'civicrm_contribution_page',
3410 'entity_id' => $contributionPageID,
3416 * Add participant with contribution
3420 protected function createParticipantWithContribution() {
3421 // creating price set, price field
3422 require_once 'CiviTest/Event.php';
3423 require_once 'CiviTest/Contact.php';
3424 $this->_contactId
= Contact
::createIndividual();
3425 $this->_eventId
= Event
::create($this->_contactId
);
3426 $eventParams = array(
3427 'id' => $this->_eventId
,
3428 'financial_type_id' => 4,
3431 $this->callAPISuccess('event', 'create', $eventParams);
3432 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3433 $participantParams = array(
3434 'financial_type_id' => 4,
3435 'event_id' => $this->_eventId
,
3438 'fee_currency' => 'USD',
3439 'contact_id' => $this->_contactId
,
3441 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3442 $contributionParams = array(
3443 'total_amount' => 150,
3444 'currency' => 'USD',
3445 'contact_id' => $this->_contactId
,
3446 'financial_type_id' => 4,
3447 'contribution_status_id' => 1,
3448 'partial_payment_total' => 300.00,
3449 'partial_amount_pay' => 150,
3450 'contribution_mode' => 'participant',
3451 'participant_id' => $participant['id'],
3453 foreach ($priceFields['values'] as $key => $priceField) {
3454 $lineItems[1][$key] = array(
3455 'price_field_id' => $priceField['price_field_id'],
3456 'price_field_value_id' => $priceField['id'],
3457 'label' => $priceField['label'],
3458 'field_title' => $priceField['label'],
3460 'unit_price' => $priceField['amount'],
3461 'line_total' => $priceField['amount'],
3462 'financial_type_id' => $priceField['financial_type_id'],
3465 $contributionParams['line_item'] = $lineItems;
3466 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3467 $paymentParticipant = array(
3468 'participant_id' => $participant['id'],
3469 'contribution_id' => $contribution['id'],
3472 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3473 return array($lineItems, $contribution);
3479 * @param string $component
3480 * @param int $componentId
3484 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3485 $paramsSet['title'] = 'Price Set';
3486 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3487 $paramsSet['is_active'] = TRUE;
3488 $paramsSet['financial_type_id'] = 4;
3489 $paramsSet['extends'] = 1;
3490 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3491 $priceSetId = $priceSet['id'];
3492 //Checking for priceset added in the table.
3493 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3494 'id', $paramsSet['title'], 'Check DB for created priceset'
3496 $paramsField = array(
3497 'label' => 'Price Field',
3498 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3499 'html_type' => 'CheckBox',
3500 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3501 'option_value' => array('1' => 100, '2' => 200),
3502 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3503 'option_weight' => array('1' => 1, '2' => 2),
3504 'option_amount' => array('1' => 100, '2' => 200),
3505 'is_display_amounts' => 1,
3507 'options_per_line' => 1,
3508 'is_active' => array('1' => 1, '2' => 1),
3509 'price_set_id' => $priceSet['id'],
3510 'is_enter_qty' => 1,
3511 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3513 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3515 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3517 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));