Merge pull request #3207 from totten/master-alerts
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
1 <?php
2 /**
3 * File for the CiviUnitTestCase class
4 *
5 * (PHP 5)
6 *
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
10 * @package CiviCRM
11 *
12 * This file is part of CiviCRM
13 *
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.
18 *
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.
23 *
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/>.
27 */
28
29 /**
30 * Include configuration
31 */
32 define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
33 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
34
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH;
37 }
38 require_once CIVICRM_SETTINGS_PATH;
39 /**
40 * Include class definitions
41 */
42 require_once 'PHPUnit/Extensions/Database/TestCase.php';
43 require_once 'PHPUnit/Framework/TestResult.php';
44 require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45 require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46 require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47 require_once 'tests/phpunit/Utils.php';
48 require_once 'api/api.php';
49 require_once 'CRM/Financial/BAO/FinancialType.php';
50 define('API_LATEST_VERSION', 3);
51
52 /**
53 * Base class for CiviCRM unit tests
54 *
55 * Common functions for unit tests
56 * @package CiviCRM
57 */
58 class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
59
60 /**
61 * api version - easier to override than just a defin
62 */
63 protected $_apiversion = API_LATEST_VERSION;
64 /**
65 * Database has been initialized
66 *
67 * @var boolean
68 */
69 private static $dbInit = FALSE;
70
71 /**
72 * Database connection
73 *
74 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
75 */
76 protected $_dbconn;
77
78 /**
79 * The database name
80 *
81 * @var string
82 */
83 static protected $_dbName;
84
85 /**
86 * Track tables we have modified during a test
87 */
88 protected $_tablesToTruncate = array();
89
90 /**
91 * @var array of temporary directory names
92 */
93 protected $tempDirs;
94
95 /**
96 * @var Utils instance
97 */
98 public static $utils;
99
100 /**
101 * @var boolean populateOnce allows to skip db resets in setUp
102 *
103 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
104 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
105 * "CHECK RUNS" ONLY!
106 *
107 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
108 *
109 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
110 */
111 public static $populateOnce = FALSE;
112
113 /**
114 * Allow classes to state E-notice compliance
115 */
116 public $_eNoticeCompliant = TRUE;
117
118 /**
119 * @var boolean DBResetRequired allows skipping DB reset
120 * in specific test case. If you still need
121 * to reset single test (method) of such case, call
122 * $this->cleanDB() in the first line of this
123 * test (method).
124 */
125 public $DBResetRequired = TRUE;
126
127 /**
128 * Constructor
129 *
130 * Because we are overriding the parent class constructor, we
131 * need to show the same arguments as exist in the constructor of
132 * PHPUnit_Framework_TestCase, since
133 * PHPUnit_Framework_TestSuite::createTest() creates a
134 * ReflectionClass of the Test class and checks the constructor
135 * of that class to decide how to set up the test.
136 *
137 * @param string $name
138 * @param array $data
139 * @param string $dataName
140 */
141 function __construct($name = NULL, array$data = array(), $dataName = '') {
142 parent::__construct($name, $data, $dataName);
143
144 // we need full error reporting
145 error_reporting(E_ALL & ~E_NOTICE);
146
147 if (!empty($GLOBALS['mysql_db'])) {
148 self::$_dbName = $GLOBALS['mysql_db'];
149 }
150 else {
151 self::$_dbName = 'civicrm_tests_dev';
152 }
153
154 // create test database
155 self::$utils = new Utils($GLOBALS['mysql_host'],
156 $GLOBALS['mysql_port'],
157 $GLOBALS['mysql_user'],
158 $GLOBALS['mysql_pass']
159 );
160
161 // also load the class loader
162 require_once 'CRM/Core/ClassLoader.php';
163 CRM_Core_ClassLoader::singleton()->register();
164 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
165 _civix_phpunit_setUp();
166 }
167 }
168
169 function requireDBReset() {
170 return $this->DBResetRequired;
171 }
172
173 static function getDBName() {
174 $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
175 return $dbName;
176 }
177
178 /**
179 * Create database connection for this instance
180 *
181 * Initialize the test database if it hasn't been initialized
182 *
183 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
184 */
185 protected function getConnection() {
186 $dbName = self::$_dbName;
187 if (!self::$dbInit) {
188 $dbName = self::getDBName();
189
190 // install test database
191 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
192
193 static::_populateDB(FALSE, $this);
194
195 self::$dbInit = TRUE;
196 }
197 return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
198 }
199
200 /**
201 * Required implementation of abstract method
202 */
203 protected function getDataSet() {
204 }
205
206 /**
207 * @param bool $perClass
208 * @param null $object
209 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
210 */
211 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
212
213 if ($perClass || $object == NULL) {
214 $dbreset = TRUE;
215 }
216 else {
217 $dbreset = $object->requireDBReset();
218 }
219
220 if (self::$populateOnce || !$dbreset) {
221 return FALSE;
222 }
223 self::$populateOnce = NULL;
224
225 $dbName = self::getDBName();
226 $pdo = self::$utils->pdo;
227 // only consider real tables and not views
228 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
229 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
230
231 $truncates = array();
232 $drops = array();
233 foreach ($tables as $table) {
234 // skip log tables
235 if (substr($table['table_name'], 0, 4) == 'log_') {
236 continue;
237 }
238
239 // don't change list of installed extensions
240 if ($table['table_name'] == 'civicrm_extension') {
241 continue;
242 }
243
244 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
245 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
246 }
247 else {
248 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
249 }
250 }
251
252 $queries = array(
253 "USE {$dbName};",
254 "SET foreign_key_checks = 0",
255 // SQL mode needs to be strict, that's our standard
256 "SET SQL_MODE='STRICT_ALL_TABLES';",
257 "SET global innodb_flush_log_at_trx_commit = 2;",
258 );
259 $queries = array_merge($queries, $truncates);
260 $queries = array_merge($queries, $drops);
261 foreach ($queries as $query) {
262 if (self::$utils->do_query($query) === FALSE) {
263 // failed to create test database
264 echo "failed to create test db.";
265 exit;
266 }
267 }
268
269 // initialize test database
270 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
271 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
272 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
273
274 $query2 = file_get_contents($sql_file2);
275 $query3 = file_get_contents($sql_file3);
276 $query4 = file_get_contents($sql_file4);
277 if (self::$utils->do_query($query2) === FALSE) {
278 echo "Cannot load civicrm_data.mysql. Aborting.";
279 exit;
280 }
281 if (self::$utils->do_query($query3) === FALSE) {
282 echo "Cannot load test_data.mysql. Aborting.";
283 exit;
284 }
285 if (self::$utils->do_query($query4) === FALSE) {
286 echo "Cannot load test_data.mysql. Aborting.";
287 exit;
288 }
289
290 // done with all the loading, get transactions back
291 if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
292 echo "Cannot set global? Huh?";
293 exit;
294 }
295
296 if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
297 echo "Cannot get foreign keys back? Huh?";
298 exit;
299 }
300
301 unset($query, $query2, $query3);
302
303 // Rebuild triggers
304 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
305
306 return TRUE;
307 }
308
309 public static function setUpBeforeClass() {
310 static::_populateDB(TRUE);
311
312 // also set this global hack
313 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
314
315 $env = new CRM_Utils_Check_Env();
316 CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
317 }
318
319 /**
320 * Common setup functions for all unit tests
321 */
322 protected function setUp() {
323 CRM_Utils_Hook::singleton(TRUE);
324 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
325 // Use a temporary file for STDIN
326 $GLOBALS['stdin'] = tmpfile();
327 if ($GLOBALS['stdin'] === FALSE) {
328 echo "Couldn't open temporary file\n";
329 exit(1);
330 }
331
332 // Get and save a connection to the database
333 $this->_dbconn = $this->getConnection();
334
335 // reload database before each test
336 // $this->_populateDB();
337
338 // "initialize" CiviCRM to avoid problems when running single tests
339 // FIXME: look at it closer in second stage
340
341 // initialize the object once db is loaded
342 CRM_Core_Config::$_mail = NULL;
343 $config = CRM_Core_Config::singleton();
344
345 // when running unit tests, use mockup user framework
346 $config->setUserFramework('UnitTests');
347
348 // also fix the fatal error handler to throw exceptions,
349 // rather than exit
350 $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
351
352 // enable backtrace to get meaningful errors
353 $config->backtrace = 1;
354
355 // disable any left-over test extensions
356 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
357
358 // reset all the caches
359 CRM_Utils_System::flushCache();
360
361 // clear permissions stub to not check permissions
362 $config = CRM_Core_Config::singleton();
363 $config->userPermissionClass->permissions = NULL;
364
365 //flush component settings
366 CRM_Core_Component::getEnabledComponents(TRUE);
367
368 if ($this->_eNoticeCompliant) {
369 error_reporting(E_ALL);
370 }
371 else {
372 error_reporting(E_ALL & ~E_NOTICE);
373 }
374 }
375
376 /**
377 * Read everything from the datasets directory and insert into the db
378 */
379 public function loadAllFixtures() {
380 $fixturesDir = __DIR__ . '/../../fixtures';
381
382 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
383
384 $xmlFiles = glob($fixturesDir . '/*.xml');
385 foreach ($xmlFiles as $xmlFixture) {
386 $op = new PHPUnit_Extensions_Database_Operation_Insert();
387 $dataset = new PHPUnit_Extensions_Database_DataSet_XMLDataSet($xmlFixture);
388 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
389 $op->execute($this->_dbconn, $dataset);
390 }
391
392 $yamlFiles = glob($fixturesDir . '/*.yaml');
393 foreach ($yamlFiles as $yamlFixture) {
394 $op = new PHPUnit_Extensions_Database_Operation_Insert();
395 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
396 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
397 $op->execute($this->_dbconn, $dataset);
398 }
399
400 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
401 }
402
403 /**
404 * emulate a logged in user since certain functions use that
405 * value to store a record in the DB (like activity)
406 * CRM-8180
407 */
408 public function createLoggedInUser() {
409 $params = array(
410 'first_name' => 'Logged In',
411 'last_name' => 'User ' . rand(),
412 'contact_type' => 'Individual',
413 );
414 $contactID = $this->individualCreate($params);
415
416 $session = CRM_Core_Session::singleton();
417 $session->set('userID', $contactID);
418 }
419
420 public function cleanDB() {
421 self::$populateOnce = NULL;
422 $this->DBResetRequired = TRUE;
423
424 $this->_dbconn = $this->getConnection();
425 static::_populateDB();
426 $this->tempDirs = array();
427 }
428
429 /**
430 * Common teardown functions for all unit tests
431 */
432 protected function tearDown() {
433 error_reporting(E_ALL & ~E_NOTICE);
434 $tablesToTruncate = array('civicrm_contact');
435 $this->quickCleanup($tablesToTruncate);
436 $this->cleanTempDirs();
437 $this->unsetExtensionSystem();
438 }
439
440 /**
441 * FIXME: Maybe a better way to do it
442 */
443 function foreignKeyChecksOff() {
444 self::$utils = new Utils($GLOBALS['mysql_host'],
445 $GLOBALS['mysql_port'],
446 $GLOBALS['mysql_user'],
447 $GLOBALS['mysql_pass']
448 );
449 $dbName = self::getDBName();
450 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
451 if (self::$utils->do_query($query) === FALSE) {
452 // fail happens
453 echo 'Cannot set foreign_key_checks = 0';
454 exit(1);
455 }
456 return TRUE;
457 }
458
459 function foreignKeyChecksOn() {
460 // FIXME: might not be needed if previous fixme implemented
461 }
462
463 /**
464 * Generic function to compare expected values after an api call to retrieved
465 * DB values.
466 *
467 * @daoName string DAO Name of object we're evaluating.
468 * @id int Id of object
469 * @match array Associative array of field name => expected value. Empty if asserting
470 * that a DELETE occurred
471 * @delete boolean True if we're checking that a DELETE action occurred.
472 */
473 function assertDBState($daoName, $id, $match, $delete = FALSE) {
474 if (empty($id)) {
475 // adding this here since developers forget to check for an id
476 // and hence we get the first value in the db
477 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
478 }
479
480 $object = new $daoName();
481 $object->id = $id;
482 $verifiedCount = 0;
483
484 // If we're asserting successful record deletion, make sure object is NOT found.
485 if ($delete) {
486 if ($object->find(TRUE)) {
487 $this->fail("Object not deleted by delete operation: $daoName, $id");
488 }
489 return;
490 }
491
492 // Otherwise check matches of DAO field values against expected values in $match.
493 if ($object->find(TRUE)) {
494 $fields = & $object->fields();
495 foreach ($fields as $name => $value) {
496 $dbName = $value['name'];
497 if (isset($match[$name])) {
498 $verifiedCount++;
499 $this->assertEquals($object->$dbName, $match[$name]);
500 }
501 elseif (isset($match[$dbName])) {
502 $verifiedCount++;
503 $this->assertEquals($object->$dbName, $match[$dbName]);
504 }
505 }
506 }
507 else {
508 $this->fail("Could not retrieve object: $daoName, $id");
509 }
510 $object->free();
511 $matchSize = count($match);
512 if ($verifiedCount != $matchSize) {
513 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
514 }
515 }
516
517 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
518 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
519 if (empty($searchValue)) {
520 $this->fail("empty value passed to assertDBNotNull");
521 }
522 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
523 $this->assertNotNull($value, $message);
524
525 return $value;
526 }
527
528 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
529 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
530 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
531 $this->assertNull($value, $message);
532 }
533
534 // Request a record from the DB by id. Success if row not found.
535 function assertDBRowNotExist($daoName, $id, $message = NULL) {
536 $message = $message ? $message : "$daoName (#$id) should not exist";
537 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
538 $this->assertNull($value, $message);
539 }
540
541 // Request a record from the DB by id. Success if row not found.
542 function assertDBRowExist($daoName, $id, $message = NULL) {
543 $message = $message ? $message : "$daoName (#$id) should exist";
544 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
545 $this->assertEquals($id, $value, $message);
546 }
547
548 // Compare a single column value in a retrieved DB record to an expected value
549 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
550 $expectedValue, $message
551 ) {
552 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
553 $this->assertEquals($value, $expectedValue, $message);
554 }
555
556 // Compare all values in a single retrieved DB record to an array of expected values
557 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
558 //get the values from db
559 $dbValues = array();
560 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
561
562 // compare db values with expected values
563 self::assertAttributesEquals($expectedValues, $dbValues);
564 }
565
566 /**
567 * Assert that a SQL query returns a given value
568 *
569 * The first argument is an expected value. The remaining arguments are passed
570 * to CRM_Core_DAO::singleValueQuery
571 *
572 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
573 * array(1 => array("Whiz", "String")));
574 */
575 function assertDBQuery($expected, $query, $params = array()) {
576 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
577 $this->assertEquals($expected, $actual,
578 sprintf('expected=[%s] actual=[%s] query=[%s]',
579 $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
580 )
581 );
582 }
583
584 /**
585 * Assert that two array-trees are exactly equal, notwithstanding
586 * the sorting of keys
587 *
588 * @param array $expected
589 * @param array $actual
590 */
591 function assertTreeEquals($expected, $actual) {
592 $e = array();
593 $a = array();
594 CRM_Utils_Array::flatten($expected, $e, '', ':::');
595 CRM_Utils_Array::flatten($actual, $a, '', ':::');
596 ksort($e);
597 ksort($a);
598
599 $this->assertEquals($e, $a);
600 }
601
602 /**
603 * Assert that two numbers are approximately equal
604 *
605 * @param int|float $expected
606 * @param int|float $actual
607 * @param int|float $tolerance
608 * @param string $message
609 */
610 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
611 if ($message === NULL) {
612 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
613 }
614 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
615 }
616
617 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
618 foreach ($expectedValues as $paramName => $paramValue) {
619 if (isset($actualValues[$paramName])) {
620 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
621 }
622 else {
623 $this->fail("Attribute '$paramName' not present in actual array.");
624 }
625 }
626 }
627
628 function assertArrayKeyExists($key, &$list) {
629 $result = isset($list[$key]) ? TRUE : FALSE;
630 $this->assertTrue($result, ts("%1 element exists?",
631 array(1 => $key)
632 ));
633 }
634
635 function assertArrayValueNotNull($key, &$list) {
636 $this->assertArrayKeyExists($key, $list);
637
638 $value = isset($list[$key]) ? $list[$key] : NULL;
639 $this->assertTrue($value,
640 ts("%1 element not null?",
641 array(1 => $key)
642 )
643 );
644 }
645
646 /**
647 * check that api returned 'is_error' => 0
648 * else provide full message
649 * @param array $apiResult api result
650 * @param string $prefix extra test to add to message
651 */
652 function assertAPISuccess($apiResult, $prefix = '') {
653 if (!empty($prefix)) {
654 $prefix .= ': ';
655 }
656 $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
657
658 if(!empty($apiResult['debug_information'])) {
659 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
660 }
661 if(!empty($apiResult['trace'])){
662 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
663 }
664 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
665 }
666
667 /**
668 * check that api returned 'is_error' => 1
669 * else provide full message
670 *
671 * @param array $apiResult api result
672 * @param string $prefix extra test to add to message
673 * @param null $expectedError
674 */
675 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
676 if (!empty($prefix)) {
677 $prefix .= ': ';
678 }
679 if($expectedError && !empty($apiResult['is_error'])){
680 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
681 }
682 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
683 $this->assertNotEmpty($apiResult['error_message']);
684 }
685
686 function assertType($expected, $actual, $message = '') {
687 return $this->assertInternalType($expected, $actual, $message);
688 }
689
690 /**
691 * check that a deleted item has been deleted
692 */
693 function assertAPIDeleted($entity, $id) {
694 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
695 }
696
697
698 /**
699 * check that api returned 'is_error' => 1
700 * else provide full message
701 * @param $result
702 * @param $expected
703 * @param array $valuesToExclude
704 * @param string $prefix extra test to add to message
705 * @internal param array $apiResult api result
706 */
707 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
708 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
709 foreach ($valuesToExclude as $value) {
710 if(isset($result[$value])) {
711 unset($result[$value]);
712 }
713 if(isset($expected[$value])) {
714 unset($expected[$value]);
715 }
716 }
717 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
718 }
719
720 /**
721 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
722 *
723 * @param $entity
724 * @param $action
725 * @param $params
726 * @return array|int
727 */
728 function civicrm_api($entity, $action, $params) {
729 return civicrm_api($entity, $action, $params);
730 }
731
732 /**
733 * This function exists to wrap api functions
734 * so we can ensure they succeed & throw exceptions without litterering the test with checks
735 *
736 * @param string $entity
737 * @param string $action
738 * @param array $params
739 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
740 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
741 * for getsingle the array is compared against an array passed in - the id is not compared (for
742 * better or worse )
743 *
744 * @return array|int
745 */
746 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
747 $params = array_merge(array(
748 'version' => $this->_apiversion,
749 'debug' => 1,
750 ),
751 $params
752 );
753 switch (strtolower($action)) {
754 case 'getvalue' :
755 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
756 case 'getsingle' :
757 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
758 case 'getcount' :
759 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
760 }
761 $result = $this->civicrm_api($entity, $action, $params);
762 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
763 return $result;
764 }
765
766 /**
767 * This function exists to wrap api getValue function & check the result
768 * so we can ensure they succeed & throw exceptions without litterering the test with checks
769 * There is a type check in this
770 *
771 * @param string $entity
772 * @param array $params
773 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
774 * - boolean
775 * - integer
776 * - double
777 * - string
778 * - array
779 * - object
780 *
781 * @return array|int
782 */
783 function callAPISuccessGetValue($entity, $params, $type = NULL) {
784 $params += array(
785 'version' => $this->_apiversion,
786 'debug' => 1,
787 );
788 $result = $this->civicrm_api($entity, 'getvalue', $params);
789 if($type){
790 if($type == 'integer'){
791 // api seems to return integers as strings
792 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
793 }
794 else{
795 $this->assertType($type, $result, "returned result should have been of type $type but was " );
796 }
797 }
798 return $result;
799 }
800
801 /**
802 * This function exists to wrap api getsingle function & check the result
803 * so we can ensure they succeed & throw exceptions without litterering the test with checks
804 *
805 * @param string $entity
806 * @param array $params
807 * @param array $checkAgainst - array to compare result against
808 * - boolean
809 * - integer
810 * - double
811 * - string
812 * - array
813 * - object
814 *
815 * @return array|int
816 */
817 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
818 $params += array(
819 'version' => $this->_apiversion,
820 'debug' => 1,
821 );
822 $result = $this->civicrm_api($entity, 'getsingle', $params);
823 if(!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
824 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
825 }
826 if($checkAgainst){
827 // @todo - have gone with the fn that unsets id? should we check id?
828 $this->checkArrayEquals($result, $checkAgainst);
829 }
830 return $result;
831 }
832
833 /**
834 * This function exists to wrap api getValue function & check the result
835 * so we can ensure they succeed & throw exceptions without litterering the test with checks
836 * There is a type check in this
837 * @param string $entity
838 * @param array $params
839 * @param null $count
840 * @throws Exception
841 * @return array|int
842 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
843 * - boolean
844 * - integer
845 * - double
846 * - string
847 * - array
848 * - object
849 */
850 function callAPISuccessGetCount($entity, $params, $count = NULL) {
851 $params += array(
852 'version' => $this->_apiversion,
853 'debug' => 1,
854 );
855 $result = $this->civicrm_api($entity, 'getcount', $params);
856 if(!is_integer($result) || !empty($result['is_error']) || isset($result['values'])) {
857 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
858 }
859 if(is_int($count)){
860 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
861 }
862 return $result;
863 }
864
865 /**
866 * This function exists to wrap api functions
867 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
868 *
869 * @param string $entity
870 * @param string $action
871 * @param array $params
872 * @param string $function - pass this in to create a generated example
873 * @param string $file - pass this in to create a generated example
874 * @param string $description
875 * @param string|null $subfile
876 * @param string|null $actionName
877 * @return array|int
878 */
879 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
880 $params['version'] = $this->_apiversion;
881 $result = $this->callAPISuccess($entity, $action, $params);
882 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
883 return $result;
884 }
885
886 /**
887 * This function exists to wrap api functions
888 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
889 * @param string $entity
890 * @param string $action
891 * @param array $params
892 * @param string $expectedErrorMessage error
893 * @param null $extraOutput
894 * @return array|int
895 */
896 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
897 if (is_array($params)) {
898 $params += array(
899 'version' => $this->_apiversion,
900 );
901 }
902 $result = $this->civicrm_api($entity, $action, $params);
903 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
904 return $result;
905 }
906
907 /**
908 * Create required data based on $this->entity & $this->params
909 * This is just a way to set up the test data for delete & get functions
910 * so the distinction between set
911 * up & tested functions is clearer
912 *
913 * @return array api Result
914 */
915 public function createTestEntity(){
916 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
917 }
918
919 /**
920 * Generic function to create Organisation, to be used in test cases
921 *
922 * @param array parameters for civicrm_contact_add api function call
923 *
924 * @return int id of Organisation created
925 */
926 function organizationCreate($params = array()) {
927 if (!$params) {
928 $params = array();
929 }
930 $orgParams = array(
931 'organization_name' => 'Unit Test Organization',
932 'contact_type' => 'Organization',
933 );
934 return $this->_contactCreate(array_merge($orgParams, $params));
935 }
936
937 /**
938 * Generic function to create Individual, to be used in test cases
939 *
940 * @param array parameters for civicrm_contact_add api function call
941 *
942 * @return int id of Individual created
943 */
944 function individualCreate($params = array()) {
945 $params = array_merge(array(
946 'first_name' => 'Anthony',
947 'middle_name' => 'J.',
948 'last_name' => 'Anderson',
949 'prefix_id' => 3,
950 'suffix_id' => 3,
951 'email' => 'anthony_anderson@civicrm.org',
952 'contact_type' => 'Individual',
953 ), $params);
954
955 return $this->_contactCreate($params);
956 }
957
958 /**
959 * Generic function to create Household, to be used in test cases
960 *
961 * @param array parameters for civicrm_contact_add api function call
962 *
963 * @return int id of Household created
964 */
965 function householdCreate($params = array()) {
966 $params = array_merge(array(
967 'household_name' => 'Unit Test household',
968 'contact_type' => 'Household',
969 ), $params);
970 return $this->_contactCreate($params);
971 }
972
973 /**
974 * Private helper function for calling civicrm_contact_add
975 *
976 * @param $params
977 *
978 * @throws Exception
979 * @internal param \parameters $array for civicrm_contact_add api function call
980 *
981 * @return int id of Household created
982 */
983 private function _contactCreate($params) {
984 $result = $this->callAPISuccess('contact', 'create', $params);
985 if (!empty($result['is_error']) || empty($result['id'])) {
986 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array::value('trace', $result));
987 }
988 return $result['id'];
989 }
990
991 function contactDelete($contactID) {
992 $params = array(
993 'id' => $contactID,
994 'skip_undelete' => 1,
995 'debug' => 1,
996 );
997 $domain = new CRM_Core_BAO_Domain;
998 $domain->contact_id = $contactID;
999 if ($domain->find(TRUE)) {
1000 // we are finding tests trying to delete the domain contact in cleanup
1001 //since this is mainly for cleanup lets put a safeguard here
1002 return;
1003 }
1004 $result = $this->callAPISuccess('contact', 'delete', $params);
1005 return $result;
1006 }
1007
1008 function contactTypeDelete($contactTypeId) {
1009 require_once 'CRM/Contact/BAO/ContactType.php';
1010 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1011 if (!$result) {
1012 throw new Exception('Could not delete contact type');
1013 }
1014 }
1015
1016 function membershipTypeCreate($params = array()) {
1017 CRM_Member_PseudoConstant::flush('membershipType');
1018 CRM_Core_Config::clearDBCache();
1019 $memberOfOrganization = $this->organizationCreate();
1020 $params = array_merge(array(
1021 'name' => 'General',
1022 'duration_unit' => 'year',
1023 'duration_interval' => 1,
1024 'period_type' => 'rolling',
1025 'member_of_contact_id' => $memberOfOrganization,
1026 'domain_id' => 1,
1027 'financial_type_id' => 1,
1028 'is_active' => 1,
1029 'sequential' => 1,
1030 'visibility' => 1,
1031 ), $params);
1032
1033 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1034
1035 CRM_Member_PseudoConstant::flush('membershipType');
1036 CRM_Utils_Cache::singleton()->flush();
1037
1038 return $result['id'];
1039 }
1040
1041 function contactMembershipCreate($params) {
1042 $pre = array(
1043 'join_date' => '2007-01-21',
1044 'start_date' => '2007-01-21',
1045 'end_date' => '2007-12-21',
1046 'source' => 'Payment',
1047 );
1048
1049 foreach ($pre as $key => $val) {
1050 if (!isset($params[$key])) {
1051 $params[$key] = $val;
1052 }
1053 }
1054
1055 $result = $this->callAPISuccess('Membership', 'create', $params);
1056 return $result['id'];
1057 }
1058
1059 /**
1060 * Function to delete Membership Type
1061 *
1062 * @param $params
1063 * @internal param int $membershipTypeID
1064 */
1065 function membershipTypeDelete($params) {
1066 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
1067 return;
1068 }
1069
1070 function membershipDelete($membershipID) {
1071 $deleteParams = array('id' => $membershipID);
1072 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1073 return;
1074 }
1075
1076 function membershipStatusCreate($name = 'test member status') {
1077 $params['name'] = $name;
1078 $params['start_event'] = 'start_date';
1079 $params['end_event'] = 'end_date';
1080 $params['is_current_member'] = 1;
1081 $params['is_active'] = 1;
1082
1083 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1084 CRM_Member_PseudoConstant::flush('membershipStatus');
1085 return $result['id'];
1086 }
1087
1088 function membershipStatusDelete($membershipStatusID) {
1089 if (!$membershipStatusID) {
1090 return;
1091 }
1092 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1093 return;
1094 }
1095
1096 function relationshipTypeCreate($params = array()) {
1097 $params = array_merge(array(
1098 'name_a_b' => 'Relation 1 for relationship type create',
1099 'name_b_a' => 'Relation 2 for relationship type create',
1100 'contact_type_a' => 'Individual',
1101 'contact_type_b' => 'Organization',
1102 'is_reserved' => 1,
1103 'is_active' => 1,
1104 ),
1105 $params
1106 );
1107
1108 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1109 CRM_Core_PseudoConstant::flush('relationshipType');
1110
1111 return $result['id'];
1112 }
1113
1114 /**
1115 * Function to delete Relatinship Type
1116 *
1117 * @param int $relationshipTypeID
1118 */
1119 function relationshipTypeDelete($relationshipTypeID) {
1120 $params['id'] = $relationshipTypeID;
1121 $this->callAPISuccess('relationship_type', 'delete', $params);
1122 }
1123
1124 function paymentProcessorTypeCreate($params = NULL) {
1125 if (is_null($params)) {
1126 $params = array(
1127 'name' => 'API_Test_PP',
1128 'title' => 'API Test Payment Processor',
1129 'class_name' => 'CRM_Core_Payment_APITest',
1130 'billing_mode' => 'form',
1131 'is_recur' => 0,
1132 'is_reserved' => 1,
1133 'is_active' => 1,
1134 );
1135 }
1136 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1137
1138 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1139
1140 return $result['id'];
1141 }
1142
1143 /**
1144 * Function to create Participant
1145 *
1146 * @param array $params array of contact id and event id values
1147 *
1148 * @return int $id of participant created
1149 */
1150 function participantCreate($params) {
1151 if(empty($params['contact_id'])){
1152 $params['contact_id'] = $this->individualCreate();
1153 }
1154 if(empty($params['event_id'])){
1155 $event = $this->eventCreate();
1156 $params['event_id'] = $event['id'];
1157 }
1158 $defaults = array(
1159 'status_id' => 2,
1160 'role_id' => 1,
1161 'register_date' => 20070219,
1162 'source' => 'Wimbeldon',
1163 'event_level' => 'Payment',
1164 'debug' => 1,
1165 );
1166
1167 $params = array_merge($defaults, $params);
1168 $result = $this->callAPISuccess('Participant', 'create', $params);
1169 return $result['id'];
1170 }
1171
1172 /**
1173 * Function to create Payment Processor
1174 *
1175 * @return object of Payment Processsor
1176 */
1177 function processorCreate() {
1178 $processorParams = array(
1179 'domain_id' => 1,
1180 'name' => 'Dummy',
1181 'payment_processor_type_id' => 10,
1182 'financial_account_id' => 12,
1183 'is_active' => 1,
1184 'user_name' => '',
1185 'url_site' => 'http://dummy.com',
1186 'url_recur' => 'http://dummy.com',
1187 'billing_mode' => 1,
1188 );
1189 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1190 return $paymentProcessor;
1191 }
1192
1193 /**
1194 * Function to create contribution page
1195 *
1196 * @param $params
1197 * @return object of contribution page
1198 */
1199 function contributionPageCreate($params) {
1200 $this->_pageParams = array(
1201 'title' => 'Test Contribution Page',
1202 'financial_type_id' => 1,
1203 'currency' => 'USD',
1204 'financial_account_id' => 1,
1205 'payment_processor' => $params['processor_id'],
1206 'is_active' => 1,
1207 'is_allow_other_amount' => 1,
1208 'min_amount' => 10,
1209 'max_amount' => 1000,
1210 );
1211 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1212 return $contributionPage;
1213 }
1214
1215 /**
1216 * Function to create Tag
1217 *
1218 * @param array $params
1219 * @return array result of created tag
1220 */
1221 function tagCreate($params = array()) {
1222 $defaults = array(
1223 'name' => 'New Tag3',
1224 'description' => 'This is description for Our New Tag ',
1225 'domain_id' => '1',
1226 );
1227 $params = array_merge($defaults, $params);
1228 $result = $this->callAPISuccess('Tag', 'create', $params);
1229 return $result['values'][$result['id']];
1230 }
1231
1232 /**
1233 * Function to delete Tag
1234 *
1235 * @param int $tagId id of the tag to be deleted
1236 */
1237 function tagDelete($tagId) {
1238 require_once 'api/api.php';
1239 $params = array(
1240 'tag_id' => $tagId,
1241 );
1242 $result = $this->callAPISuccess('Tag', 'delete', $params);
1243 return $result['id'];
1244 }
1245
1246 /**
1247 * Add entity(s) to the tag
1248 *
1249 * @param array $params
1250 *
1251 * @return bool
1252 */
1253 function entityTagAdd($params) {
1254 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1255 return TRUE;
1256 }
1257
1258 /**
1259 * Function to create contribution
1260 *
1261 * @param int $cID contact_id
1262 *
1263 * @internal param int $cTypeID id of financial type
1264 *
1265 * @return int id of created contribution
1266 */
1267 function pledgeCreate($cID) {
1268 $params = array(
1269 'contact_id' => $cID,
1270 'pledge_create_date' => date('Ymd'),
1271 'start_date' => date('Ymd'),
1272 'scheduled_date' => date('Ymd'),
1273 'amount' => 100.00,
1274 'pledge_status_id' => '2',
1275 'financial_type_id' => '1',
1276 'pledge_original_installment_amount' => 20,
1277 'frequency_interval' => 5,
1278 'frequency_unit' => 'year',
1279 'frequency_day' => 15,
1280 'installments' => 5,
1281 );
1282
1283 $result = $this->callAPISuccess('Pledge', 'create', $params);
1284 return $result['id'];
1285 }
1286
1287 /**
1288 * Function to delete contribution
1289 *
1290 * @param $pledgeId
1291 * @internal param int $contributionId
1292 */
1293 function pledgeDelete($pledgeId) {
1294 $params = array(
1295 'pledge_id' => $pledgeId,
1296 );
1297 $this->callAPISuccess('Pledge', 'delete', $params);
1298 }
1299
1300 /**
1301 * Function to create contribution
1302 *
1303 * @param int $cID contact_id
1304 * @param int $cTypeID id of financial type
1305 *
1306 * @param int $invoiceID
1307 * @param int $trxnID
1308 * @param int $paymentInstrumentID
1309 * @param bool $isFee
1310 * @return int id of created contribution
1311 */
1312 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1313 $params = array(
1314 'domain_id' => 1,
1315 'contact_id' => $cID,
1316 'receive_date' => date('Ymd'),
1317 'total_amount' => 100.00,
1318 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1319 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1320 'non_deductible_amount' => 10.00,
1321 'trxn_id' => $trxnID,
1322 'invoice_id' => $invoiceID,
1323 'source' => 'SSF',
1324 'contribution_status_id' => 1,
1325 // 'note' => 'Donating for Nobel Cause', *Fixme
1326 );
1327
1328 if ($isFee) {
1329 $params['fee_amount'] = 5.00;
1330 $params['net_amount'] = 95.00;
1331 }
1332
1333 $result = $this->callAPISuccess('contribution', 'create', $params);
1334 return $result['id'];
1335 }
1336
1337 /**
1338 * Function to create online contribution
1339 *
1340 * @param $params
1341 * @param int $financialType id of financial type
1342 *
1343 * @param int $invoiceID
1344 * @param int $trxnID
1345 * @return int id of created contribution
1346 */
1347 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1348 $contribParams = array(
1349 'contact_id' => $params['contact_id'],
1350 'receive_date' => date('Ymd'),
1351 'total_amount' => 100.00,
1352 'financial_type_id' => $financialType,
1353 'contribution_page_id' => $params['contribution_page_id'],
1354 'trxn_id' => 12345,
1355 'invoice_id' => 67890,
1356 'source' => 'SSF',
1357 );
1358 $contribParams = array_merge($contribParams, $params);
1359 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1360
1361 return $result['id'];
1362 }
1363
1364 /**
1365 * Function to delete contribution
1366 *
1367 * @param int $contributionId
1368 *
1369 * @return array|int
1370 */
1371 function contributionDelete($contributionId) {
1372 $params = array(
1373 'contribution_id' => $contributionId,
1374 );
1375 $result = $this->callAPISuccess('contribution', 'delete', $params);
1376 return $result;
1377 }
1378
1379 /**
1380 * Function to create an Event
1381 *
1382 * @param array $params name-value pair for an event
1383 *
1384 * @return array $event
1385 */
1386 function eventCreate($params = array()) {
1387 // if no contact was passed, make up a dummy event creator
1388 if (!isset($params['contact_id'])) {
1389 $params['contact_id'] = $this->_contactCreate(array(
1390 'contact_type' => 'Individual',
1391 'first_name' => 'Event',
1392 'last_name' => 'Creator',
1393 ));
1394 }
1395
1396 // set defaults for missing params
1397 $params = array_merge(array(
1398 'title' => 'Annual CiviCRM meet',
1399 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1400 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1401 'event_type_id' => 1,
1402 'is_public' => 1,
1403 'start_date' => 20081021,
1404 'end_date' => 20081023,
1405 'is_online_registration' => 1,
1406 'registration_start_date' => 20080601,
1407 'registration_end_date' => 20081015,
1408 'max_participants' => 100,
1409 'event_full_text' => 'Sorry! We are already full',
1410 'is_monetory' => 0,
1411 'is_active' => 1,
1412 'is_show_location' => 0,
1413 ), $params);
1414
1415 return $this->callAPISuccess('Event', 'create', $params);
1416 }
1417
1418 /**
1419 * Function to delete event
1420 *
1421 * @param int $id ID of the event
1422 *
1423 * @return array|int
1424 */
1425 function eventDelete($id) {
1426 $params = array(
1427 'event_id' => $id,
1428 );
1429 return $this->callAPISuccess('event', 'delete', $params);
1430 }
1431
1432 /**
1433 * Function to delete participant
1434 *
1435 * @param int $participantID
1436 *
1437 * @return array|int
1438 */
1439 function participantDelete($participantID) {
1440 $params = array(
1441 'id' => $participantID,
1442 );
1443 return $this->callAPISuccess('Participant', 'delete', $params);
1444 }
1445
1446 /**
1447 * Function to create participant payment
1448 *
1449 * @param $participantID
1450 * @param null $contributionID
1451 * @return int $id of created payment
1452 */
1453 function participantPaymentCreate($participantID, $contributionID = NULL) {
1454 //Create Participant Payment record With Values
1455 $params = array(
1456 'participant_id' => $participantID,
1457 'contribution_id' => $contributionID,
1458 );
1459
1460 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1461 return $result['id'];
1462 }
1463
1464 /**
1465 * Function to delete participant payment
1466 *
1467 * @param int $paymentID
1468 */
1469 function participantPaymentDelete($paymentID) {
1470 $params = array(
1471 'id' => $paymentID,
1472 );
1473 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1474 }
1475
1476 /**
1477 * Function to add a Location
1478 *
1479 * @param $contactID
1480 * @return int location id of created location
1481 */
1482 function locationAdd($contactID) {
1483 $address = array(
1484 1 => array(
1485 'location_type' => 'New Location Type',
1486 'is_primary' => 1,
1487 'name' => 'Saint Helier St',
1488 'county' => 'Marin',
1489 'country' => 'United States',
1490 'state_province' => 'Michigan',
1491 'supplemental_address_1' => 'Hallmark Ct',
1492 'supplemental_address_2' => 'Jersey Village',
1493 )
1494 );
1495
1496 $params = array(
1497 'contact_id' => $contactID,
1498 'address' => $address,
1499 'location_format' => '2.0',
1500 'location_type' => 'New Location Type',
1501 );
1502
1503 $result = $this->callAPISuccess('Location', 'create', $params);
1504 return $result;
1505 }
1506
1507 /**
1508 * Function to delete Locations of contact
1509 *
1510 * @params array $pamars parameters
1511 */
1512 function locationDelete($params) {
1513 $result = $this->callAPISuccess('Location', 'delete', $params);
1514 }
1515
1516 /**
1517 * Function to add a Location Type
1518 *
1519 * @param null $params
1520 * @return int location id of created location
1521 */
1522 function locationTypeCreate($params = NULL) {
1523 if ($params === NULL) {
1524 $params = array(
1525 'name' => 'New Location Type',
1526 'vcard_name' => 'New Location Type',
1527 'description' => 'Location Type for Delete',
1528 'is_active' => 1,
1529 );
1530 }
1531
1532 $locationType = new CRM_Core_DAO_LocationType();
1533 $locationType->copyValues($params);
1534 $locationType->save();
1535 // clear getfields cache
1536 CRM_Core_PseudoConstant::flush();
1537 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1538 return $locationType;
1539 }
1540
1541 /**
1542 * Function to delete a Location Type
1543 *
1544 * @param int location type id
1545 */
1546 function locationTypeDelete($locationTypeId) {
1547 $locationType = new CRM_Core_DAO_LocationType();
1548 $locationType->id = $locationTypeId;
1549 $locationType->delete();
1550 }
1551
1552 /**
1553 * Function to add a Group
1554 *
1555 * @params array to add group
1556 *
1557 * @param array $params
1558 * @return int groupId of created group
1559 */
1560 function groupCreate($params = array()) {
1561 $params = array_merge(array(
1562 'name' => 'Test Group 1',
1563 'domain_id' => 1,
1564 'title' => 'New Test Group Created',
1565 'description' => 'New Test Group Created',
1566 'is_active' => 1,
1567 'visibility' => 'Public Pages',
1568 'group_type' => array(
1569 '1' => 1,
1570 '2' => 1,
1571 ),
1572 ), $params);
1573
1574 $result = $this->callAPISuccess('Group', 'create', $params);
1575 return $result['id'];
1576 }
1577
1578 /**
1579 * Function to delete a Group
1580 *
1581 * @param $gid
1582 * @internal param int $id
1583 */
1584 function groupDelete($gid) {
1585
1586 $params = array(
1587 'id' => $gid,
1588 );
1589
1590 $this->callAPISuccess('Group', 'delete', $params);
1591 }
1592
1593 /**
1594 * Create a UFField
1595 * @param array $params
1596 */
1597 function uFFieldCreate($params = array()) {
1598 $params = array_merge(array(
1599 'uf_group_id' => 1,
1600 'field_name' => 'first_name',
1601 'is_active' => 1,
1602 'is_required' => 1,
1603 'visibility' => 'Public Pages and Listings',
1604 'is_searchable' => '1',
1605 'label' => 'first_name',
1606 'field_type' => 'Individual',
1607 'weight' => 1,
1608 ), $params);
1609 $this->callAPISuccess('uf_field', 'create', $params);
1610 }
1611
1612 /**
1613 * Function to add a UF Join Entry
1614 *
1615 * @param null $params
1616 * @return int $id of created UF Join
1617 */
1618 function ufjoinCreate($params = NULL) {
1619 if ($params === NULL) {
1620 $params = array(
1621 'is_active' => 1,
1622 'module' => 'CiviEvent',
1623 'entity_table' => 'civicrm_event',
1624 'entity_id' => 3,
1625 'weight' => 1,
1626 'uf_group_id' => 1,
1627 );
1628 }
1629 $result = $this->callAPISuccess('uf_join', 'create', $params);
1630 return $result;
1631 }
1632
1633 /**
1634 * Function to delete a UF Join Entry
1635 *
1636 * @param array with missing uf_group_id
1637 */
1638 function ufjoinDelete($params = NULL) {
1639 if ($params === NULL) {
1640 $params = array(
1641 'is_active' => 1,
1642 'module' => 'CiviEvent',
1643 'entity_table' => 'civicrm_event',
1644 'entity_id' => 3,
1645 'weight' => 1,
1646 'uf_group_id' => '',
1647 );
1648 }
1649
1650 crm_add_uf_join($params);
1651 }
1652
1653 /**
1654 * Function to create Group for a contact
1655 *
1656 * @param int $contactId
1657 */
1658 function contactGroupCreate($contactId) {
1659 $params = array(
1660 'contact_id.1' => $contactId,
1661 'group_id' => 1,
1662 );
1663
1664 $this->callAPISuccess('GroupContact', 'Create', $params);
1665 }
1666
1667 /**
1668 * Function to delete Group for a contact
1669 *
1670 * @param $contactId
1671 * @internal param array $params
1672 */
1673 function contactGroupDelete($contactId) {
1674 $params = array(
1675 'contact_id.1' => $contactId,
1676 'group_id' => 1,
1677 );
1678 $this->civicrm_api('GroupContact', 'Delete', $params);
1679 }
1680
1681 /**
1682 * Function to create Activity
1683 *
1684 * @param null $params
1685 * @return array|int
1686 * @internal param int $contactId
1687 */
1688 function activityCreate($params = NULL) {
1689
1690 if ($params === NULL) {
1691 $individualSourceID = $this->individualCreate();
1692
1693 $contactParams = array(
1694 'first_name' => 'Julia',
1695 'Last_name' => 'Anderson',
1696 'prefix' => 'Ms.',
1697 'email' => 'julia_anderson@civicrm.org',
1698 'contact_type' => 'Individual',
1699 );
1700
1701 $individualTargetID = $this->individualCreate($contactParams);
1702
1703 $params = array(
1704 'source_contact_id' => $individualSourceID,
1705 'target_contact_id' => array($individualTargetID),
1706 'assignee_contact_id' => array($individualTargetID),
1707 'subject' => 'Discussion on warm beer',
1708 'activity_date_time' => date('Ymd'),
1709 'duration_hours' => 30,
1710 'duration_minutes' => 20,
1711 'location' => 'Baker Street',
1712 'details' => 'Lets schedule a meeting',
1713 'status_id' => 1,
1714 'activity_name' => 'Meeting',
1715 );
1716 }
1717
1718 $result = $this->callAPISuccess('Activity', 'create', $params);
1719
1720 $result['target_contact_id'] = $individualTargetID;
1721 $result['assignee_contact_id'] = $individualTargetID;
1722 return $result;
1723 }
1724
1725 /**
1726 * Function to create an activity type
1727 *
1728 * @params array $params parameters
1729 */
1730 function activityTypeCreate($params) {
1731 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1732 return $result;
1733 }
1734
1735 /**
1736 * Function to delete activity type
1737 *
1738 * @params Integer $activityTypeId id of the activity type
1739 */
1740 function activityTypeDelete($activityTypeId) {
1741 $params['activity_type_id'] = $activityTypeId;
1742 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1743 return $result;
1744 }
1745
1746 /**
1747 * Function to create custom group
1748 *
1749 * @param array $params
1750 * @return array|int
1751 * @internal param string $className
1752 * @internal param string $title name of custom group
1753 */
1754 function customGroupCreate($params = array()) {
1755 $defaults = array(
1756 'title' => 'new custom group',
1757 'extends' => 'Contact',
1758 'domain_id' => 1,
1759 'style' => 'Inline',
1760 'is_active' => 1,
1761 );
1762
1763 $params = array_merge($defaults, $params);
1764
1765 if (strlen($params['title']) > 13) {
1766 $params['title'] = substr($params['title'], 0, 13);
1767 }
1768
1769 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1770 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1771
1772 return $this->callAPISuccess('custom_group', 'create', $params);
1773 }
1774
1775 /**
1776 * existing function doesn't allow params to be over-ridden so need a new one
1777 * this one allows you to only pass in the params you want to change
1778 */
1779 function CustomGroupCreateByParams($params = array()) {
1780 $defaults = array(
1781 'title' => "API Custom Group",
1782 'extends' => 'Contact',
1783 'domain_id' => 1,
1784 'style' => 'Inline',
1785 'is_active' => 1,
1786 );
1787 $params = array_merge($defaults, $params);
1788 return $this->callAPISuccess('custom_group', 'create', $params);
1789 }
1790
1791 /**
1792 * Create custom group with multi fields
1793 */
1794 function CustomGroupMultipleCreateByParams($params = array()) {
1795 $defaults = array(
1796 'style' => 'Tab',
1797 'is_multiple' => 1,
1798 );
1799 $params = array_merge($defaults, $params);
1800 return $this->CustomGroupCreateByParams($params);
1801 }
1802
1803 /**
1804 * Create custom group with multi fields
1805 */
1806 function CustomGroupMultipleCreateWithFields($params = array()) {
1807 // also need to pass on $params['custom_field'] if not set but not in place yet
1808 $ids = array();
1809 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1810 $ids['custom_group_id'] = $customGroup['id'];
1811
1812 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1813
1814 $ids['custom_field_id'][] = $customField['id'];
1815
1816 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1817 $ids['custom_field_id'][] = $customField['id'];
1818
1819 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1820 $ids['custom_field_id'][] = $customField['id'];
1821
1822 return $ids;
1823 }
1824
1825 /**
1826 * Create a custom group with a single text custom field. See
1827 * participant:testCreateWithCustom for how to use this
1828 *
1829 * @param string $function __FUNCTION__
1830 * @param $filename
1831 * @internal param string $file __FILE__
1832 *
1833 * @return array $ids ids of created objects
1834 */
1835 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1836 $params = array('title' => $function);
1837 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1838 $params['extends'] = $entity ? $entity : 'Contact';
1839 $customGroup = $this->CustomGroupCreate($params);
1840 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1841 CRM_Core_PseudoConstant::flush();
1842
1843 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1844 }
1845
1846 /**
1847 * Function to delete custom group
1848 *
1849 * @param int $customGroupID
1850 *
1851 * @return array|int
1852 */
1853 function customGroupDelete($customGroupID) {
1854 $params['id'] = $customGroupID;
1855 return $this->callAPISuccess('custom_group', 'delete', $params);
1856 }
1857
1858 /**
1859 * Function to create custom field
1860 *
1861 * @param array $params (custom_group_id) is required
1862 * @return array|int
1863 * @internal param string $name name of custom field
1864 * @internal param int $apiversion API version to use
1865 */
1866 function customFieldCreate($params) {
1867 $params = array_merge(array(
1868 'label' => 'Custom Field',
1869 'data_type' => 'String',
1870 'html_type' => 'Text',
1871 'is_searchable' => 1,
1872 'is_active' => 1,
1873 'default_value' => 'defaultValue',
1874 ), $params);
1875
1876 $result = $this->callAPISuccess('custom_field', 'create', $params);
1877
1878 if ($result['is_error'] == 0 && isset($result['id'])) {
1879 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1880 // force reset of enabled components to help grab custom fields
1881 CRM_Core_Component::getEnabledComponents(1);
1882 return $result;
1883 }
1884 }
1885
1886 /**
1887 * Function to delete custom field
1888 *
1889 * @param int $customFieldID
1890 *
1891 * @return array|int
1892 */
1893 function customFieldDelete($customFieldID) {
1894
1895 $params['id'] = $customFieldID;
1896 return $this->callAPISuccess('custom_field', 'delete', $params);
1897 }
1898
1899 /**
1900 * Function to create note
1901 *
1902 * @params array $params name-value pair for an event
1903 *
1904 * @param $cId
1905 * @return array $note
1906 */
1907 function noteCreate($cId) {
1908 $params = array(
1909 'entity_table' => 'civicrm_contact',
1910 'entity_id' => $cId,
1911 'note' => 'hello I am testing Note',
1912 'contact_id' => $cId,
1913 'modified_date' => date('Ymd'),
1914 'subject' => 'Test Note',
1915 );
1916
1917 return $this->callAPISuccess('Note', 'create', $params);
1918 }
1919
1920 /**
1921 * Enable CiviCampaign Component
1922 */
1923 function enableCiviCampaign() {
1924 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
1925 // force reload of config object
1926 $config = CRM_Core_Config::singleton(TRUE, TRUE);
1927 //flush cache by calling with reset
1928 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1929 }
1930
1931 /**
1932 * Create test generated example in api/v3/examples.
1933 * To turn this off (e.g. on the server) set
1934 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1935 * in your settings file
1936 * @param array $params array as passed to civicrm_api function
1937 * @param array $result array as received from the civicrm_api function
1938 * @param string $function calling function - generally __FUNCTION__
1939 * @param string $filename called from file - generally __FILE__
1940 * @param string $description descriptive text for the example file
1941 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1942 * @param string $action - optional action - otherwise taken from function name
1943 */
1944 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1945 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1946 return;
1947 }
1948 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1949 //todo - this is a bit cludgey
1950 if (empty($action)) {
1951 if (strstr($function, 'Create')) {
1952 $action = empty($action) ? 'create' : $action;
1953 $entityAction = 'Create';
1954 }
1955 elseif (strstr($function, 'GetSingle')) {
1956 $action = empty($action) ? 'getsingle' : $action;
1957 $entityAction = 'GetSingle';
1958 }
1959 elseif (strstr($function, 'GetValue')) {
1960 $action = empty($action) ? 'getvalue' : $action;
1961 $entityAction = 'GetValue';
1962 }
1963 elseif (strstr($function, 'GetCount')) {
1964 $action = empty($action) ? 'getcount' : $action;
1965 $entityAction = 'GetCount';
1966 }
1967 elseif (strstr($function, 'GetFields')) {
1968 $action = empty($action) ? 'getfields' : $action;
1969 $entityAction = 'GetFields';
1970 }
1971 elseif (strstr($function, 'GetList')) {
1972 $action = empty($action) ? 'getlist' : $action;
1973 $entityAction = 'GetList';
1974 }
1975 elseif (strstr($function, 'Get')) {
1976 $action = empty($action) ? 'get' : $action;
1977 $entityAction = 'Get';
1978 }
1979 elseif (strstr($function, 'Delete')) {
1980 $action = empty($action) ? 'delete' : $action;
1981 $entityAction = 'Delete';
1982 }
1983 elseif (strstr($function, 'Update')) {
1984 $action = empty($action) ? 'update' : $action;
1985 $entityAction = 'Update';
1986 }
1987 elseif (strstr($function, 'Subscribe')) {
1988 $action = empty($action) ? 'subscribe' : $action;
1989 $entityAction = 'Subscribe';
1990 }
1991 elseif (strstr($function, 'Submit')) {
1992 $action = empty($action) ? 'submit' : $action;
1993 $entityAction = 'Submit';
1994 }
1995 elseif (strstr($function, 'Apply')) {
1996 $action = empty($action) ? 'apply' : $action;
1997 $entityAction = 'Apply';
1998 }
1999 elseif (strstr($function, 'Replace')) {
2000 $action = empty($action) ? 'replace' : $action;
2001 $entityAction = 'Replace';
2002 }
2003 }
2004 else {
2005 $entityAction = ucwords($action);
2006 }
2007
2008 $this->tidyExampleResult($result);
2009 if(isset($params['version'])) {
2010 unset($params['version']);
2011 }
2012 // a cleverer person than me would do it in a single regex
2013 if (strstr($entity, 'UF')) {
2014 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2015 }
2016 else {
2017 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2018 }
2019 $smarty = CRM_Core_Smarty::singleton();
2020 $smarty->assign('testfunction', $function);
2021 $function = $fnPrefix . "_" . strtolower($action);
2022 $smarty->assign('function', $function);
2023 $smarty->assign('fnPrefix', $fnPrefix);
2024 $smarty->assign('params', $params);
2025 $smarty->assign('entity', $entity);
2026 $smarty->assign('filename', basename($filename));
2027 $smarty->assign('description', $description);
2028 $smarty->assign('result', $result);
2029
2030 $smarty->assign('action', $action);
2031 if (empty($subfile)) {
2032 $subfile = $entityAction;
2033 }
2034 if (file_exists('../tests/templates/documentFunction.tpl')) {
2035 if (!is_dir("../api/v3/examples/$entity")) {
2036 mkdir("../api/v3/examples/$entity");
2037 }
2038 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2039 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2040 fclose($f);
2041 }
2042 }
2043
2044 /**
2045 * Tidy up examples array so that fields that change often ..don't
2046 * and debug related fields are unset
2047 *
2048 * @param $result
2049 *
2050 * @internal param array $params
2051 */
2052 function tidyExampleResult(&$result){
2053 if(!is_array($result)) {
2054 return;
2055 }
2056 $fieldsToChange = array(
2057 'hash' => '67eac7789eaee00',
2058 'modified_date' => '2012-11-14 16:02:35',
2059 'created_date' => '2013-07-28 08:49:19',
2060 'create_date' => '20120130621222105',
2061 'application_received_date' => '20130728084957',
2062 'in_date' => '2013-07-28 08:50:19',
2063 'scheduled_date' => '20130728085413',
2064 'approval_date' => '20130728085413',
2065 'pledge_start_date_high' => '20130726090416',
2066 'start_date' => '2013-07-29 00:00:00',
2067 'event_start_date' => '2013-07-29 00:00:00',
2068 'end_date' => '2013-08-04 00:00:00',
2069 'event_end_date' => '2013-08-04 00:00:00',
2070 'decision_date' => '20130805000000',
2071 );
2072
2073 $keysToUnset = array('xdebug', 'undefined_fields',);
2074 foreach ($keysToUnset as $unwantedKey) {
2075 if(isset($result[$unwantedKey])) {
2076 unset($result[$unwantedKey]);
2077 }
2078 }
2079 if (isset($result['values'])) {
2080 if(!is_array($result['values'])) {
2081 return;
2082 }
2083 $resultArray = &$result['values'];
2084 }
2085 elseif(is_array($result)) {
2086 $resultArray = &$result;
2087 }
2088 else {
2089 return;
2090 }
2091
2092 foreach ($resultArray as $index => &$values) {
2093 if(!is_array($values)) {
2094 continue;
2095 }
2096 foreach($values as $key => &$value) {
2097 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2098 if(isset($value['is_error'])) {
2099 // we have a std nested result format
2100 $this->tidyExampleResult($value);
2101 }
2102 else{
2103 foreach ($value as &$nestedResult) {
2104 // this is an alternative syntax for nested results a keyed array of results
2105 $this->tidyExampleResult($nestedResult);
2106 }
2107 }
2108 }
2109 if(in_array($key, $keysToUnset)) {
2110 unset($values[$key]);
2111 break;
2112 }
2113 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2114 $value = $fieldsToChange[$key];
2115 }
2116 if(is_string($value)) {
2117 $value = addslashes($value);
2118 }
2119 }
2120 }
2121 }
2122
2123 /**
2124 * Function to delete note
2125 *
2126 * @params int $noteID
2127 *
2128 */
2129 function noteDelete($params) {
2130 return $this->callAPISuccess('Note', 'delete', $params);
2131 }
2132
2133 /**
2134 * Function to create custom field with Option Values
2135 *
2136 * @param array $customGroup
2137 * @param string $name name of custom field
2138 *
2139 * @return array|int
2140 */
2141 function customFieldOptionValueCreate($customGroup, $name) {
2142 $fieldParams = array(
2143 'custom_group_id' => $customGroup['id'],
2144 'name' => 'test_custom_group',
2145 'label' => 'Country',
2146 'html_type' => 'Select',
2147 'data_type' => 'String',
2148 'weight' => 4,
2149 'is_required' => 1,
2150 'is_searchable' => 0,
2151 'is_active' => 1,
2152 );
2153
2154 $optionGroup = array(
2155 'domain_id' => 1,
2156 'name' => 'option_group1',
2157 'label' => 'option_group_label1',
2158 );
2159
2160 $optionValue = array(
2161 'option_label' => array('Label1', 'Label2'),
2162 'option_value' => array('value1', 'value2'),
2163 'option_name' => array($name . '_1', $name . '_2'),
2164 'option_weight' => array(1, 2),
2165 'option_status' => 1,
2166 );
2167
2168 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2169
2170 return $this->callAPISuccess('custom_field', 'create', $params);
2171 }
2172
2173 function confirmEntitiesDeleted($entities) {
2174 foreach ($entities as $entity) {
2175
2176 $result = $this->callAPISuccess($entity, 'Get', array());
2177 if ($result['error'] == 1 || $result['count'] > 0) {
2178 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2179 return TRUE;
2180 }
2181 }
2182 }
2183
2184 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2185 if ($dropCustomValueTables) {
2186 $tablesToTruncate[] = 'civicrm_custom_group';
2187 $tablesToTruncate[] = 'civicrm_custom_field';
2188 }
2189
2190 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2191
2192 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2193 foreach ($tablesToTruncate as $table) {
2194 $sql = "TRUNCATE TABLE $table";
2195 CRM_Core_DAO::executeQuery($sql);
2196 }
2197 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2198
2199 if ($dropCustomValueTables) {
2200 $dbName = self::getDBName();
2201 $query = "
2202 SELECT TABLE_NAME as tableName
2203 FROM INFORMATION_SCHEMA.TABLES
2204 WHERE TABLE_SCHEMA = '{$dbName}'
2205 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2206 ";
2207
2208 $tableDAO = CRM_Core_DAO::executeQuery($query);
2209 while ($tableDAO->fetch()) {
2210 $sql = "DROP TABLE {$tableDAO->tableName}";
2211 CRM_Core_DAO::executeQuery($sql);
2212 }
2213 }
2214 }
2215
2216 /**
2217 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2218 */
2219 function quickCleanUpFinancialEntities() {
2220 $tablesToTruncate = array(
2221 'civicrm_contribution',
2222 'civicrm_financial_trxn',
2223 'civicrm_contribution_recur',
2224 'civicrm_line_item',
2225 'civicrm_contribution_page',
2226 'civicrm_payment_processor',
2227 'civicrm_entity_financial_trxn',
2228 'civicrm_membership',
2229 'civicrm_membership_type',
2230 'civicrm_membership_payment',
2231 'civicrm_membership_status',
2232 'civicrm_event',
2233 'civicrm_participant',
2234 'civicrm_participant_payment',
2235 'civicrm_pledge',
2236 );
2237 $this->quickCleanup($tablesToTruncate);
2238 }
2239 /*
2240 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2241 * Default behaviour is to also delete the entity
2242 * @param array $params params array to check agains
2243 * @param int $id id of the entity concerned
2244 * @param string $entity name of entity concerned (e.g. membership)
2245 * @param bool $delete should the entity be deleted as part of this check
2246 * @param string $errorText text to print on error
2247 *
2248 */
2249 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2250
2251 $result = $this->callAPISuccessGetSingle($entity, array(
2252 'id' => $id,
2253 ));
2254
2255 if ($delete) {
2256 $this->callAPISuccess($entity, 'Delete', array(
2257 'id' => $id,
2258 ));
2259 }
2260 $dateFields = $keys = $dateTimeFields = array();
2261 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2262 foreach ($fields['values'] as $field => $settings) {
2263 if (array_key_exists($field, $result)) {
2264 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2265 }
2266 else {
2267 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2268 }
2269 $type = CRM_Utils_Array::value('type', $settings);
2270 if ($type == CRM_Utils_Type::T_DATE) {
2271 $dateFields[] = $settings['name'];
2272 // we should identify both real names & unique names as dates
2273 if($field != $settings['name']) {
2274 $dateFields[] = $field;
2275 }
2276 }
2277 if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2278 $dateTimeFields[] = $settings['name'];
2279 // we should identify both real names & unique names as dates
2280 if($field != $settings['name']) {
2281 $dateTimeFields[] = $field;
2282 }
2283 }
2284 }
2285
2286 if (strtolower($entity) == 'contribution') {
2287 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2288 // this is not returned in id format
2289 unset($params['payment_instrument_id']);
2290 $params['contribution_source'] = $params['source'];
2291 unset($params['source']);
2292 }
2293
2294 foreach ($params as $key => $value) {
2295 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2296 continue;
2297 }
2298 if (in_array($key, $dateFields)) {
2299 $value = date('Y-m-d', strtotime($value));
2300 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2301 }
2302 if (in_array($key, $dateTimeFields)) {
2303 $value = date('Y-m-d H:i:s', strtotime($value));
2304 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2305 }
2306 $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);
2307 }
2308 }
2309
2310 /**
2311 * Function to get formatted values in the actual and expected result
2312 * @param array $actual actual calculated values
2313 * @param array $expected expected values
2314 *
2315 */
2316 function checkArrayEquals(&$actual, &$expected) {
2317 self::unsetId($actual);
2318 self::unsetId($expected);
2319 $this->assertEquals($actual, $expected);
2320 }
2321
2322 /**
2323 * Function to unset the key 'id' from the array
2324 * @param array $unformattedArray The array from which the 'id' has to be unset
2325 *
2326 */
2327 static function unsetId(&$unformattedArray) {
2328 $formattedArray = array();
2329 if (array_key_exists('id', $unformattedArray)) {
2330 unset($unformattedArray['id']);
2331 }
2332 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2333 foreach ($unformattedArray['values'] as $key => $value) {
2334 if (is_Array($value)) {
2335 foreach ($value as $k => $v) {
2336 if ($k == 'id') {
2337 unset($value[$k]);
2338 }
2339 }
2340 }
2341 elseif ($key == 'id') {
2342 $unformattedArray[$key];
2343 }
2344 $formattedArray = array($value);
2345 }
2346 $unformattedArray['values'] = $formattedArray;
2347 }
2348 }
2349
2350 /**
2351 * Helper to enable/disable custom directory support
2352 *
2353 * @param array $customDirs with members:
2354 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2355 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2356 */
2357 function customDirectories($customDirs) {
2358 require_once 'CRM/Core/Config.php';
2359 $config = CRM_Core_Config::singleton();
2360
2361 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2362 unset($config->customPHPPathDir);
2363 }
2364 elseif ($customDirs['php_path'] === TRUE) {
2365 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2366 }
2367 else {
2368 $config->customPHPPathDir = $php_path;
2369 }
2370
2371 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2372 unset($config->customTemplateDir);
2373 }
2374 elseif ($customDirs['template_path'] === TRUE) {
2375 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2376 }
2377 else {
2378 $config->customTemplateDir = $template_path;
2379 }
2380 }
2381
2382 /**
2383 * Generate a temporary folder
2384 *
2385 * @param string $prefix
2386 * @return string $string
2387 */
2388 function createTempDir($prefix = 'test-') {
2389 $tempDir = CRM_Utils_File::tempdir($prefix);
2390 $this->tempDirs[] = $tempDir;
2391 return $tempDir;
2392 }
2393
2394 function cleanTempDirs() {
2395 if (!is_array($this->tempDirs)) {
2396 // fix test errors where this is not set
2397 return;
2398 }
2399 foreach ($this->tempDirs as $tempDir) {
2400 if (is_dir($tempDir)) {
2401 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2402 }
2403 }
2404 }
2405
2406 /**
2407 * Temporarily replace the singleton extension with a different one
2408 */
2409 function setExtensionSystem(CRM_Extension_System $system) {
2410 if ($this->origExtensionSystem == NULL) {
2411 $this->origExtensionSystem = CRM_Extension_System::singleton();
2412 }
2413 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2414 }
2415
2416 function unsetExtensionSystem() {
2417 if ($this->origExtensionSystem !== NULL) {
2418 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2419 $this->origExtensionSystem = NULL;
2420 }
2421 }
2422
2423 /**
2424 * Temporarily alter the settings-metadata to add a mock setting.
2425 *
2426 * WARNING: The setting metadata will disappear on the next cache-clear.
2427 *
2428 * @param $extras
2429 * @return void
2430 */
2431 function setMockSettingsMetaData($extras) {
2432 CRM_Core_BAO_Setting::$_cache = array();
2433 $this->callAPISuccess('system','flush', array());
2434 CRM_Core_BAO_Setting::$_cache = array();
2435
2436 CRM_Utils_Hook::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2437 $metadata = array_merge($metadata, $extras);
2438 });
2439
2440 $fields = $this->callAPISuccess('setting', 'getfields', array());
2441 foreach ($extras as $key => $spec) {
2442 $this->assertNotEmpty($spec['title']);
2443 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2444 }
2445 }
2446
2447 function financialAccountDelete($name) {
2448 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2449 $financialAccount->name = $name;
2450 if($financialAccount->find(TRUE)) {
2451 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2452 $entityFinancialType->financial_account_id = $financialAccount->id;
2453 $entityFinancialType->delete();
2454 $financialAccount->delete();
2455 }
2456 }
2457
2458 /**
2459 * Use $ids as an instruction to do test cleanup
2460 */
2461 function deleteFromIDSArray() {
2462 foreach ($this->ids as $entity => $ids) {
2463 foreach ($ids as $id) {
2464 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2465 }
2466 }
2467 }
2468
2469 /**
2470 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2471 * (NB unclear if this is still required)
2472 */
2473 function _sethtmlGlobals() {
2474 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2475 'required' => array(
2476 'html_quickform_rule_required',
2477 'HTML/QuickForm/Rule/Required.php'
2478 ),
2479 'maxlength' => array(
2480 'html_quickform_rule_range',
2481 'HTML/QuickForm/Rule/Range.php'
2482 ),
2483 'minlength' => array(
2484 'html_quickform_rule_range',
2485 'HTML/QuickForm/Rule/Range.php'
2486 ),
2487 'rangelength' => array(
2488 'html_quickform_rule_range',
2489 'HTML/QuickForm/Rule/Range.php'
2490 ),
2491 'email' => array(
2492 'html_quickform_rule_email',
2493 'HTML/QuickForm/Rule/Email.php'
2494 ),
2495 'regex' => array(
2496 'html_quickform_rule_regex',
2497 'HTML/QuickForm/Rule/Regex.php'
2498 ),
2499 'lettersonly' => array(
2500 'html_quickform_rule_regex',
2501 'HTML/QuickForm/Rule/Regex.php'
2502 ),
2503 'alphanumeric' => array(
2504 'html_quickform_rule_regex',
2505 'HTML/QuickForm/Rule/Regex.php'
2506 ),
2507 'numeric' => array(
2508 'html_quickform_rule_regex',
2509 'HTML/QuickForm/Rule/Regex.php'
2510 ),
2511 'nopunctuation' => array(
2512 'html_quickform_rule_regex',
2513 'HTML/QuickForm/Rule/Regex.php'
2514 ),
2515 'nonzero' => array(
2516 'html_quickform_rule_regex',
2517 'HTML/QuickForm/Rule/Regex.php'
2518 ),
2519 'callback' => array(
2520 'html_quickform_rule_callback',
2521 'HTML/QuickForm/Rule/Callback.php'
2522 ),
2523 'compare' => array(
2524 'html_quickform_rule_compare',
2525 'HTML/QuickForm/Rule/Compare.php'
2526 )
2527 );
2528 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2529 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2530 'group' => array(
2531 'HTML/QuickForm/group.php',
2532 'HTML_QuickForm_group'
2533 ),
2534 'hidden' => array(
2535 'HTML/QuickForm/hidden.php',
2536 'HTML_QuickForm_hidden'
2537 ),
2538 'reset' => array(
2539 'HTML/QuickForm/reset.php',
2540 'HTML_QuickForm_reset'
2541 ),
2542 'checkbox' => array(
2543 'HTML/QuickForm/checkbox.php',
2544 'HTML_QuickForm_checkbox'
2545 ),
2546 'file' => array(
2547 'HTML/QuickForm/file.php',
2548 'HTML_QuickForm_file'
2549 ),
2550 'image' => array(
2551 'HTML/QuickForm/image.php',
2552 'HTML_QuickForm_image'
2553 ),
2554 'password' => array(
2555 'HTML/QuickForm/password.php',
2556 'HTML_QuickForm_password'
2557 ),
2558 'radio' => array(
2559 'HTML/QuickForm/radio.php',
2560 'HTML_QuickForm_radio'
2561 ),
2562 'button' => array(
2563 'HTML/QuickForm/button.php',
2564 'HTML_QuickForm_button'
2565 ),
2566 'submit' => array(
2567 'HTML/QuickForm/submit.php',
2568 'HTML_QuickForm_submit'
2569 ),
2570 'select' => array(
2571 'HTML/QuickForm/select.php',
2572 'HTML_QuickForm_select'
2573 ),
2574 'hiddenselect' => array(
2575 'HTML/QuickForm/hiddenselect.php',
2576 'HTML_QuickForm_hiddenselect'
2577 ),
2578 'text' => array(
2579 'HTML/QuickForm/text.php',
2580 'HTML_QuickForm_text'
2581 ),
2582 'textarea' => array(
2583 'HTML/QuickForm/textarea.php',
2584 'HTML_QuickForm_textarea'
2585 ),
2586 'fckeditor' => array(
2587 'HTML/QuickForm/fckeditor.php',
2588 'HTML_QuickForm_FCKEditor'
2589 ),
2590 'tinymce' => array(
2591 'HTML/QuickForm/tinymce.php',
2592 'HTML_QuickForm_TinyMCE'
2593 ),
2594 'dojoeditor' => array(
2595 'HTML/QuickForm/dojoeditor.php',
2596 'HTML_QuickForm_dojoeditor'
2597 ),
2598 'link' => array(
2599 'HTML/QuickForm/link.php',
2600 'HTML_QuickForm_link'
2601 ),
2602 'advcheckbox' => array(
2603 'HTML/QuickForm/advcheckbox.php',
2604 'HTML_QuickForm_advcheckbox'
2605 ),
2606 'date' => array(
2607 'HTML/QuickForm/date.php',
2608 'HTML_QuickForm_date'
2609 ),
2610 'static' => array(
2611 'HTML/QuickForm/static.php',
2612 'HTML_QuickForm_static'
2613 ),
2614 'header' => array(
2615 'HTML/QuickForm/header.php',
2616 'HTML_QuickForm_header'
2617 ),
2618 'html' => array(
2619 'HTML/QuickForm/html.php',
2620 'HTML_QuickForm_html'
2621 ),
2622 'hierselect' => array(
2623 'HTML/QuickForm/hierselect.php',
2624 'HTML_QuickForm_hierselect'
2625 ),
2626 'autocomplete' => array(
2627 'HTML/QuickForm/autocomplete.php',
2628 'HTML_QuickForm_autocomplete'
2629 ),
2630 'xbutton' => array(
2631 'HTML/QuickForm/xbutton.php',
2632 'HTML_QuickForm_xbutton'
2633 ),
2634 'advmultiselect' => array(
2635 'HTML/QuickForm/advmultiselect.php',
2636 'HTML_QuickForm_advmultiselect'
2637 )
2638 );
2639 }
2640
2641 /**
2642 * Set up an acl allowing contact to see 2 specified groups
2643 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2644 *
2645 * You need to have precreated these groups & created the user e.g
2646 * $this->createLoggedInUser();
2647 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2648 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2649 *
2650 */
2651 function setupACL() {
2652 global $_REQUEST;
2653 $_REQUEST = $this->_params;
2654 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2655 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2656 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2657 'label' => 'pick me',
2658 'value' => 55,
2659 ));
2660
2661
2662 CRM_Core_DAO::executeQuery("
2663 TRUNCATE civicrm_acl_cache
2664 ");
2665
2666 CRM_Core_DAO::executeQuery("
2667 TRUNCATE civicrm_acl_contact_cache
2668 ");
2669
2670
2671 CRM_Core_DAO::executeQuery("
2672 INSERT INTO civicrm_acl_entity_role (
2673 `acl_role_id`, `entity_table`, `entity_id`
2674 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2675 ");
2676
2677 CRM_Core_DAO::executeQuery("
2678 INSERT INTO civicrm_acl (
2679 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2680 )
2681 VALUES (
2682 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2683 );
2684 ");
2685
2686 CRM_Core_DAO::executeQuery("
2687 INSERT INTO civicrm_acl (
2688 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2689 )
2690 VALUES (
2691 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2692 );
2693 ");
2694 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2695 $this->callAPISuccess('group_contact', 'create', array(
2696 'group_id' => $this->_permissionedGroup,
2697 'contact_id' => $this->_loggedInUser,
2698 ));
2699 //flush cache
2700 CRM_ACL_BAO_Cache::resetCache();
2701 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
2702 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2703 }
2704
2705 /**
2706 * Create an instance of the paypal processor
2707 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2708 * this parent class & we don't have a structure for that yet
2709 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2710 * & the best protection agains that is the functions this class affords
2711 */
2712 function paymentProcessorCreate($params = array()) {
2713 $params = array_merge(array(
2714 'name' => 'demo',
2715 'domain_id' => CRM_Core_Config::domainID(),
2716 'payment_processor_type_id' => 'PayPal',
2717 'is_active' => 1,
2718 'is_default' => 0,
2719 'is_test' => 1,
2720 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2721 'password' => '1183377788',
2722 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2723 'url_site' => 'https://www.sandbox.paypal.com/',
2724 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2725 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2726 'class_name' => 'Payment_PayPalImpl',
2727 'billing_mode' => 3,
2728 'financial_type_id' => 1,
2729 ),
2730 $params);
2731 if(!is_numeric($params['payment_processor_type_id'])) {
2732 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2733 //here
2734 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2735 'name' => $params['payment_processor_type_id'],
2736 'return' => 'id',
2737 ), 'integer');
2738 }
2739 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2740 return $result['id'];
2741 }
2742
2743
2744 function CiviUnitTestCase_fatalErrorHandler($message) {
2745 throw new Exception("{$message['message']}: {$message['code']}");
2746 }
2747 }