CRM-13072 mark tests non-enotice compliant
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
CommitLineData
6a488035
TO
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 */
32define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
33define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
34
35if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH;
37}
38require_once CIVICRM_SETTINGS_PATH;
39/**
40 * Include class definitions
41 */
42require_once 'PHPUnit/Extensions/Database/TestCase.php';
43require_once 'PHPUnit/Framework/TestResult.php';
44require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47require_once 'tests/phpunit/Utils.php';
48require_once 'api/api.php';
49require_once 'CRM/Financial/BAO/FinancialType.php';
50define('API_LATEST_VERSION', 3);
51
52/**
53 * Base class for CiviCRM unit tests
54 *
55 * Common functions for unit tests
56 * @package CiviCRM
57 */
58class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
59
f6722559 60 /**
61 * api version - easier to override than just a defin
62 */
63 protected $_apiversion = API_LATEST_VERSION;
6a488035
TO
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 * @var array of temporary directory names
87 */
88 protected $tempDirs;
89
90 /**
91 * @var Utils instance
92 */
93 public static $utils;
94
95 /**
96 * @var boolean populateOnce allows to skip db resets in setUp
97 *
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
100 * "CHECK RUNS" ONLY!
101 *
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
103 *
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
105 */
106 public static $populateOnce = FALSE;
107
108 /**
109 * Allow classes to state E-notice compliance
110 */
111 public $_eNoticeCompliant = FALSE;
112
113 /**
114 * @var boolean DBResetRequired allows skipping DB reset
115 * in specific test case. If you still need
116 * to reset single test (method) of such case, call
117 * $this->cleanDB() in the first line of this
118 * test (method).
119 */
120 public $DBResetRequired = TRUE;
121
122 /**
123 * Constructor
124 *
125 * Because we are overriding the parent class constructor, we
126 * need to show the same arguments as exist in the constructor of
127 * PHPUnit_Framework_TestCase, since
128 * PHPUnit_Framework_TestSuite::createTest() creates a
129 * ReflectionClass of the Test class and checks the constructor
130 * of that class to decide how to set up the test.
131 *
132 * @param string $name
133 * @param array $data
134 * @param string $dataName
135 */
136 function __construct($name = NULL, array$data = array(), $dataName = '') {
137 parent::__construct($name, $data, $dataName);
138
139 // we need full error reporting
140 error_reporting(E_ALL & ~E_NOTICE);
141
142 if (!empty($GLOBALS['mysql_db'])) {
143 self::$_dbName = $GLOBALS['mysql_db'];
144 }
145 else {
146 self::$_dbName = 'civicrm_tests_dev';
147 }
148
149 // create test database
150 self::$utils = new Utils($GLOBALS['mysql_host'],
151 $GLOBALS['mysql_user'],
152 $GLOBALS['mysql_pass']
153 );
154
155 // also load the class loader
156 require_once 'CRM/Core/ClassLoader.php';
157 CRM_Core_ClassLoader::singleton()->register();
158 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
159 _civix_phpunit_setUp();
160 }
161 }
162
163 function requireDBReset() {
164 return $this->DBResetRequired;
165 }
166
167 static function getDBName() {
168 $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
169 return $dbName;
170 }
171
172 /**
173 * Create database connection for this instance
174 *
175 * Initialize the test database if it hasn't been initialized
176 *
177 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
178 */
179 protected function getConnection() {
180 $dbName = self::$_dbName;
181 if (!self::$dbInit) {
182 $dbName = self::getDBName();
183
184 // install test database
185 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
186
99117745 187 static::_populateDB(FALSE, $this);
6a488035
TO
188
189 self::$dbInit = TRUE;
190 }
191 return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
192 }
193
194 /**
195 * Required implementation of abstract method
196 */
197 protected function getDataSet() {
198 }
199
99117745
TO
200 /**
201 * @param bool $perClass
202 * @param null $object
203 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
204 */
205 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
6a488035
TO
206
207 if ($perClass || $object == NULL) {
208 $dbreset = TRUE;
209 }
210 else {
211 $dbreset = $object->requireDBReset();
212 }
213
214 if (self::$populateOnce || !$dbreset) {
99117745 215 return FALSE;
6a488035
TO
216 }
217 self::$populateOnce = NULL;
218
219 $dbName = self::getDBName();
220 $pdo = self::$utils->pdo;
221 // only consider real tables and not views
222 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
223 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
224
225 $truncates = array();
226 $drops = array();
227 foreach ($tables as $table) {
228 // skip log tables
229 if (substr($table['table_name'], 0, 4) == 'log_') {
230 continue;
231 }
232
233 // don't change list of installed extensions
234 if ($table['table_name'] == 'civicrm_extension') {
235 continue;
236 }
237
238 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
239 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
240 }
241 else {
242 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
243 }
244 }
245
246 $queries = array(
247 "USE {$dbName};",
248 "SET foreign_key_checks = 0",
249 // SQL mode needs to be strict, that's our standard
250 "SET SQL_MODE='STRICT_ALL_TABLES';",
251 "SET global innodb_flush_log_at_trx_commit = 2;",
252 );
253 $queries = array_merge($queries, $truncates);
254 $queries = array_merge($queries, $drops);
255 foreach ($queries as $query) {
256 if (self::$utils->do_query($query) === FALSE) {
257 // failed to create test database
258 echo "failed to create test db.";
259 exit;
260 }
261 }
262
263 // initialize test database
264 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
265 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
266 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
267
268 $query2 = file_get_contents($sql_file2);
269 $query3 = file_get_contents($sql_file3);
270 $query4 = file_get_contents($sql_file4);
271 if (self::$utils->do_query($query2) === FALSE) {
272 echo "Cannot load civicrm_data.mysql. Aborting.";
273 exit;
274 }
275 if (self::$utils->do_query($query3) === FALSE) {
276 echo "Cannot load test_data.mysql. Aborting.";
277 exit;
278 }
279 if (self::$utils->do_query($query4) === FALSE) {
280 echo "Cannot load test_data.mysql. Aborting.";
281 exit;
282 }
283
284 // done with all the loading, get transactions back
285 if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
286 echo "Cannot set global? Huh?";
287 exit;
288 }
289
290 if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
291 echo "Cannot get foreign keys back? Huh?";
292 exit;
293 }
294
295 unset($query, $query2, $query3);
296
297 // Rebuild triggers
298 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
99117745
TO
299
300 return TRUE;
6a488035
TO
301 }
302
303 public static function setUpBeforeClass() {
99117745 304 static::_populateDB(TRUE);
6a488035
TO
305
306 // also set this global hack
307 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
308 }
309
310 /**
311 * Common setup functions for all unit tests
312 */
313 protected function setUp() {
314 CRM_Utils_Hook::singleton(TRUE);
315 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
316 // Use a temporary file for STDIN
317 $GLOBALS['stdin'] = tmpfile();
318 if ($GLOBALS['stdin'] === FALSE) {
319 echo "Couldn't open temporary file\n";
320 exit(1);
321 }
322
323 // Get and save a connection to the database
324 $this->_dbconn = $this->getConnection();
325
326 // reload database before each test
327 // $this->_populateDB();
328
329 // "initialize" CiviCRM to avoid problems when running single tests
330 // FIXME: look at it closer in second stage
331
332 // initialize the object once db is loaded
6a488035
TO
333 $config = CRM_Core_Config::singleton();
334
335 // when running unit tests, use mockup user framework
336 $config->setUserFramework('UnitTests');
337
338 // also fix the fatal error handler to throw exceptions,
339 // rather than exit
340 $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
341
342 // enable backtrace to get meaningful errors
343 $config->backtrace = 1;
344
345 // disable any left-over test extensions
346 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
347
348 // reset all the caches
349 CRM_Utils_System::flushCache();
350
351 // clear permissions stub to not check permissions
352 $config = CRM_Core_Config::singleton();
353 $config->userPermissionClass->permissions = NULL;
354
355 //flush component settings
356 CRM_Core_Component::getEnabledComponents(TRUE);
357
358 if ($this->_eNoticeCompliant) {
359 error_reporting(E_ALL);
360 }
361 else {
362 error_reporting(E_ALL & ~E_NOTICE);
363 }
364 }
365
366 /**
367 * emulate a logged in user since certain functions use that
368 * value to store a record in the DB (like activity)
369 * CRM-8180
370 */
371 public function createLoggedInUser() {
372 $params = array(
373 'first_name' => 'Logged In',
374 'last_name' => 'User ' . rand(),
375 'contact_type' => 'Individual',
376 );
377 $contactID = $this->individualCreate($params);
378
379 $session = CRM_Core_Session::singleton();
380 $session->set('userID', $contactID);
381 }
382
383 public function cleanDB() {
384 self::$populateOnce = NULL;
385 $this->DBResetRequired = TRUE;
386
387 $this->_dbconn = $this->getConnection();
99117745 388 static::_populateDB();
6a488035
TO
389 $this->tempDirs = array();
390 }
391
392 /**
393 * Common teardown functions for all unit tests
394 */
395 protected function tearDown() {
396 error_reporting(E_ALL & ~E_NOTICE);
397 $tablesToTruncate = array('civicrm_contact');
398 $this->quickCleanup($tablesToTruncate);
399 $this->cleanTempDirs();
400 $this->unsetExtensionSystem();
401 }
402
403 /**
404 * FIXME: Maybe a better way to do it
405 */
406 function foreignKeyChecksOff() {
407 self::$utils = new Utils($GLOBALS['mysql_host'],
408 $GLOBALS['mysql_user'],
409 $GLOBALS['mysql_pass']
410 );
411 $dbName = self::getDBName();
412 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
413 if (self::$utils->do_query($query) === FALSE) {
414 // fail happens
415 echo 'Cannot set foreign_key_checks = 0';
416 exit(1);
417 }
418 return TRUE;
419 }
420
421 function foreignKeyChecksOn() {
422 // FIXME: might not be needed if previous fixme implemented
423 }
424
425 /**
426 * Generic function to compare expected values after an api call to retrieved
427 * DB values.
428 *
429 * @daoName string DAO Name of object we're evaluating.
430 * @id int Id of object
431 * @match array Associative array of field name => expected value. Empty if asserting
432 * that a DELETE occurred
433 * @delete boolean True if we're checking that a DELETE action occurred.
434 */
435 function assertDBState($daoName, $id, $match, $delete = FALSE) {
436 if (empty($id)) {
437 // adding this here since developers forget to check for an id
438 // and hence we get the first value in the db
439 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
440 }
441
4d5c2eb5 442 $object = new $daoName();
6a488035
TO
443 $object->id = $id;
444 $verifiedCount = 0;
445
446 // If we're asserting successful record deletion, make sure object is NOT found.
447 if ($delete) {
448 if ($object->find(TRUE)) {
449 $this->fail("Object not deleted by delete operation: $daoName, $id");
450 }
451 return;
452 }
453
454 // Otherwise check matches of DAO field values against expected values in $match.
455 if ($object->find(TRUE)) {
456 $fields = & $object->fields();
457 foreach ($fields as $name => $value) {
458 $dbName = $value['name'];
459 if (isset($match[$name])) {
460 $verifiedCount++;
461 $this->assertEquals($object->$dbName, $match[$name]);
462 }
463 elseif (isset($match[$dbName])) {
464 $verifiedCount++;
465 $this->assertEquals($object->$dbName, $match[$dbName]);
466 }
467 }
468 }
469 else {
470 $this->fail("Could not retrieve object: $daoName, $id");
471 }
472 $object->free();
473 $matchSize = count($match);
474 if ($verifiedCount != $matchSize) {
475 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
476 }
477 }
478
479 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
480 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
481 if (empty($searchValue)) {
482 $this->fail("empty value passed to assertDBNotNull");
483 }
484 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
485 $this->assertNotNull($value, $message);
486
487 return $value;
488 }
489
490 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
491 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
492 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
493 $this->assertNull($value, $message);
494 }
495
496 // Request a record from the DB by id. Success if row not found.
497 function assertDBRowNotExist($daoName, $id, $message = NULL) {
498 $message = $message ? $message : "$daoName (#$id) should not exist";
499 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
500 $this->assertNull($value, $message);
501 }
502
503 // Request a record from the DB by id. Success if row not found.
504 function assertDBRowExist($daoName, $id, $message = NULL) {
505 $message = $message ? $message : "$daoName (#$id) should exist";
506 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
507 $this->assertEquals($id, $value, $message);
508 }
509
510 // Compare a single column value in a retrieved DB record to an expected value
511 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
512 $expectedValue, $message
513 ) {
514 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
515 $this->assertEquals($value, $expectedValue, $message);
516 }
517
518 // Compare all values in a single retrieved DB record to an array of expected values
519 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
520 //get the values from db
521 $dbValues = array();
522 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
523
524 // compare db values with expected values
525 self::assertAttributesEquals($expectedValues, $dbValues);
526 }
527
528 /**
529 * Assert that a SQL query returns a given value
530 *
531 * The first argument is an expected value. The remaining arguments are passed
532 * to CRM_Core_DAO::singleValueQuery
533 *
534 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
535 * array(1 => array("Whiz", "String")));
536 */
537 function assertDBQuery($expected, $query, $params = array()) {
538 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
539 $this->assertEquals($expected, $actual,
540 sprintf('expected=[%s] actual=[%s] query=[%s]',
541 $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
542 )
543 );
544 }
545
546 /**
547 * Assert that two array-trees are exactly equal, notwithstanding
548 * the sorting of keys
549 *
550 * @param array $expected
551 * @param array $actual
552 */
553 function assertTreeEquals($expected, $actual) {
554 $e = array();
555 $a = array();
556 CRM_Utils_Array::flatten($expected, $e, '', ':::');
557 CRM_Utils_Array::flatten($actual, $a, '', ':::');
558 ksort($e);
559 ksort($a);
560
561 $this->assertEquals($e, $a);
562 }
563
dc92f2f8
TO
564 /**
565 * Assert that two numbers are approximately equal
566 *
567 * @param int|float $expected
568 * @param int|float $actual
569 * @param int|float $tolerance
570 * @param string $message
571 */
572 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
573 if ($message === NULL) {
574 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
575 }
576 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
577 }
578
6a488035
TO
579 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
580 foreach ($expectedValues as $paramName => $paramValue) {
581 if (isset($actualValues[$paramName])) {
582 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is $paramValue value 2 is {$actualValues[$paramName]}");
583 }
584 else {
585 $this->fail("Attribute '$paramName' not present in actual array.");
586 }
587 }
588 }
589
590 function assertArrayKeyExists($key, &$list) {
591 $result = isset($list[$key]) ? TRUE : FALSE;
592 $this->assertTrue($result, ts("%1 element exists?",
593 array(1 => $key)
594 ));
595 }
596
597 function assertArrayValueNotNull($key, &$list) {
598 $this->assertArrayKeyExists($key, $list);
599
600 $value = isset($list[$key]) ? $list[$key] : NULL;
601 $this->assertTrue($value,
602 ts("%1 element not null?",
603 array(1 => $key)
604 )
605 );
606 }
607
c8950569
KJ
608 /**
609 * check that api returned 'is_error' => 0
610 * else provide full message
611 * @param array $apiResult api result
612 * @param string $prefix extra test to add to message
613 */
6a488035
TO
614 function assertAPISuccess($apiResult, $prefix = '') {
615 if (!empty($prefix)) {
616 $prefix .= ': ';
617 }
7681ca91 618 $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
f6722559 619
620 if(!empty($apiResult['debug_information'])) {
621 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
622 }
7681ca91 623 if(!empty($apiResult['trace'])){
624 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
625 }
f6722559 626
7681ca91 627 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
6a488035
TO
628 }
629
feb2a730 630 /**
631 * check that api returned 'is_error' => 1
632 * else provide full message
633 * @param array $apiResult api result
634 * @param string $prefix extra test to add to message
635 */
64fe97da 636 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
feb2a730 637 if (!empty($prefix)) {
638 $prefix .= ': ';
639 }
64fe97da 640 if($expectedError && !empty($apiResult['is_error'])){
641 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
642 }
feb2a730 643 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
f6722559 644 $this->assertNotEmpty($apiResult['error_message']);
feb2a730 645 }
646
6a488035
TO
647 function assertType($expected, $actual, $message = '') {
648 return $this->assertInternalType($expected, $actual, $message);
649 }
54bd1003 650
c43d01f3 651 /**
652 * check that a deleted item has been deleted
653 */
654 function assertAPIDeleted($entity, $id) {
655 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
656 }
657
658
f6722559 659 /**
660 * check that api returned 'is_error' => 1
661 * else provide full message
662 * @param array $apiResult api result
663 * @param string $prefix extra test to add to message
664 */
665 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
666 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
667 foreach ($valuesToExclude as $value) {
668 if(isset($result[$value])) {
669 unset($result[$value]);
670 }
671 if(isset($expected[$value])) {
672 unset($expected[$value]);
673 }
674 }
675 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
676 }
677
54bd1003 678 /**
679 * This function exists to wrap api functions
791c263c 680 * so we can ensure they succeed & throw exceptions without litterering the test with checks
681 * @param string $entity
682 * @param string $action
683 * @param array $params
f6722559 684 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue, getcount, getsingle
791c263c 685 */
f6722559 686 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
fbda92d3 687 $params = array_merge(array(
f6722559 688 'version' => $this->_apiversion,
fbda92d3 689 'debug' => 1,
690 ),
691 $params
9443c775 692 );
f6722559 693 switch (strtolower($action)) {
694 case 'getvalue' :
695 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
696 case 'getsingle' :
697 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
698 case 'getcount' :
699 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
700 }
791c263c 701 $result = civicrm_api($entity, $action, $params);
54bd1003 702 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
703 return $result;
704 }
705
fbda92d3 706 /**
707 * This function exists to wrap api getValue function & check the result
708 * so we can ensure they succeed & throw exceptions without litterering the test with checks
709 * There is a type check in this
710 * @param string $entity
711 * @param array $params
712 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
c8950569
KJ
713 * - boolean
714 * - integer
715 * - double
716 * - string
717 * - array
718 * - object
fbda92d3 719 */
720 function callAPISuccessGetValue($entity, $params, $type = NULL) {
721 $params += array(
f6722559 722 'version' => $this->_apiversion,
fbda92d3 723 'debug' => 1,
724 );
725 $result = civicrm_api($entity, 'getvalue', $params);
726 if($type){
727 if($type == 'integer'){
728 // api seems to return integers as strings
729 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
730 }
731 else{
732 $this->assertType($type, $result, "returned result should have been of type $type but was " );
733 }
734 }
735 return $result;
736 }
c8950569 737
f6722559 738 /**
739 * This function exists to wrap api getsingle function & check the result
740 * so we can ensure they succeed & throw exceptions without litterering the test with checks
741 * @param string $entity
742 * @param array $params
743 * @param array $checkAgainst - array to compare result against
744 * - boolean
745 * - integer
746 * - double
747 * - string
748 * - array
749 * - object
750 */
751 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
752 $params += array(
753 'version' => $this->_apiversion,
754 'debug' => 1,
755 );
756 $result = civicrm_api($entity, 'getsingle', $params);
757 if(!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
758 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
759 }
760 if($checkAgainst){
761 // @todo - have gone with the fn that unsets id? should we check id?
762 $this->checkArrayEquals($result, $checkAgainst);
763 }
764 return $result;
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 * @param string $entity
771 * @param array $params
772 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
773 * - boolean
774 * - integer
775 * - double
776 * - string
777 * - array
778 * - object
779 */
780 function callAPISuccessGetCount($entity, $params, $count = NULL) {
781 $params += array(
782 'version' => $this->_apiversion,
783 'debug' => 1,
784 );
785 $result = civicrm_api($entity, 'getcount', $params);
786 if(!is_integer($result) || !empty($result['is_error']) || isset($result['values'])) {
787 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
788 }
789 if(is_int($count)){
790 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
791 }
792 return $result;
793 }
54bd1003 794 /**
795 * This function exists to wrap api functions
796 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
797 *
798 * @param string $entity
799 * @param string $action
800 * @param array $params
801 * @param string $function - pass this in to create a generated example
802 * @param string $file - pass this in to create a generated example
803 */
9443c775 804 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
f6722559 805 $params['version'] = $this->_apiversion;
fbda92d3 806 if(!isset($params['debug'])){
807 // don't debug by default to keep examples tidy
808 $params['debug'] = 0;
809 }
f6722559 810 try{
811 $result = $this->callAPISuccess($entity, $action, $params);
812 }
813 catch (EXCEPTION $e) {
814 // but if it fails call again with debug on for better error message
815 $params['debug'] = 1;
816 $result = $this->callAPISuccess($entity, $action, $params);
817
818 }
9443c775 819 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
54bd1003 820 return $result;
821 }
822
823 /**
824 * This function exists to wrap api functions
825 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
826 * @param string $entity
827 * @param string $action
828 * @param array $params
64fe97da 829 * @param string $expectedErrorMessage error
54bd1003 830 */
64fe97da 831 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
9443c775
CW
832 if (is_array($params)) {
833 $params += array(
f6722559 834 'version' => $this->_apiversion,
9443c775
CW
835 );
836 }
54bd1003 837 $result = civicrm_api($entity, $action, $params);
838 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
791c263c 839 return $result;
840 }
9443c775 841
fbda92d3 842 /**
843 * Create required data based on $this->entity & $this->params
844 * This is just a way to set up the test data for delete & get functions
845 * so the distinction between set
846 * up & tested functions is clearer
847 *
848 * @return array api Result
849 */
850 public function createTestEntity(){
851 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
852 }
853
6a488035
TO
854 /**
855 * Generic function to create Organisation, to be used in test cases
856 *
857 * @param array parameters for civicrm_contact_add api function call
858 *
859 * @return int id of Organisation created
860 */
861 function organizationCreate($params = array()) {
862 if (!$params) {
863 $params = array();
864 }
865 $orgParams = array(
866 'organization_name' => 'Unit Test Organization',
867 'contact_type' => 'Organization',
6a488035
TO
868 );
869 return $this->_contactCreate(array_merge($orgParams, $params));
870 }
871
872 /**
873 * Generic function to create Individual, to be used in test cases
874 *
875 * @param array parameters for civicrm_contact_add api function call
876 *
877 * @return int id of Individual created
878 */
879 function individualCreate($params = NULL) {
880 if ($params === NULL) {
881 $params = array(
882 'first_name' => 'Anthony',
883 'middle_name' => 'J.',
884 'last_name' => 'Anderson',
885 'prefix_id' => 3,
886 'suffix_id' => 3,
887 'email' => 'anthony_anderson@civicrm.org',
888 'contact_type' => 'Individual',
889 );
890 }
6a488035
TO
891 return $this->_contactCreate($params);
892 }
893
894 /**
895 * Generic function to create Household, to be used in test cases
896 *
897 * @param array parameters for civicrm_contact_add api function call
898 *
899 * @return int id of Household created
900 */
901 function householdCreate($params = NULL) {
902 if ($params === NULL) {
903 $params = array(
904 'household_name' => 'Unit Test household',
905 'contact_type' => 'Household',
906 );
907 }
6a488035
TO
908 return $this->_contactCreate($params);
909 }
910
911 /**
912 * Private helper function for calling civicrm_contact_add
913 *
914 * @param array parameters for civicrm_contact_add api function call
915 *
916 * @return int id of Household created
917 */
918 private function _contactCreate($params) {
4732bb2f 919 $result = $this->callAPISuccess('contact', 'create', $params);
6a488035
TO
920 if (CRM_Utils_Array::value('is_error', $result) ||
921 !CRM_Utils_Array::value('id', $result)
922 ) {
ace01fda 923 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array::value('trace', $result));
6a488035
TO
924 }
925 return $result['id'];
926 }
927
928 function contactDelete($contactID) {
ace01fda
CW
929 $params = array(
930 'id' => $contactID,
ace01fda
CW
931 'skip_undelete' => 1,
932 'debug' => 1,
933 );
6a488035
TO
934 $domain = new CRM_Core_BAO_Domain;
935 $domain->contact_id = $contactID;
936 if ($domain->find(TRUE)) {
937 // we are finding tests trying to delete the domain contact in cleanup
938 //since this is mainly for cleanup lets put a safeguard here
939 return;
940 }
f6722559 941 $result = $this->callAPISuccess('contact', 'delete', $params);
942 return $result;
6a488035
TO
943 }
944
945 function contactTypeDelete($contactTypeId) {
946 require_once 'CRM/Contact/BAO/ContactType.php';
947 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
948 if (!$result) {
949 throw new Exception('Could not delete contact type');
950 }
951 }
952
953 function membershipTypeCreate($contactID, $contributionTypeID = 1, $version = 3) {
954 require_once 'CRM/Member/PseudoConstant.php';
955 CRM_Member_PseudoConstant::flush('membershipType');
956 CRM_Core_Config::clearDBCache();
957 $params = array(
958 'name' => 'General',
959 'duration_unit' => 'year',
960 'duration_interval' => 1,
961 'period_type' => 'rolling',
962 'member_of_contact_id' => $contactID,
963 'domain_id' => 1,
964 // FIXME: I know it's 1, cause it was loaded directly to the db.
965 // FIXME: when we load all the data, we'll need to address this to
966 // FIXME: avoid hunting numbers around.
967 'financial_type_id' => $contributionTypeID,
968 'is_active' => 1,
969 'version' => $version,
970 'sequential' => 1,
971 'visibility' => 1,
972 );
973
974 $result = civicrm_api('MembershipType', 'Create', $params);
975 require_once 'CRM/Member/PseudoConstant.php';
976 CRM_Member_PseudoConstant::flush('membershipType');
977 CRM_Utils_Cache::singleton()->flush();
978 if (CRM_Utils_Array::value('is_error', $result) ||
979 (!CRM_Utils_Array::value('id', $result) && !CRM_Utils_Array::value('id', $result['values'][0]))
980 ) {
981 throw new Exception('Could not create membership type, with message: ' . CRM_Utils_Array::value('error_message', $result));
982 }
983
984 return $result['id'];
985 }
986
987 function contactMembershipCreate($params) {
988 $pre = array(
989 'join_date' => '2007-01-21',
990 'start_date' => '2007-01-21',
991 'end_date' => '2007-12-21',
992 'source' => 'Payment',
6a488035
TO
993 );
994
995 foreach ($pre as $key => $val) {
996 if (!isset($params[$key])) {
997 $params[$key] = $val;
998 }
999 }
1000
f6722559 1001 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
1002 return $result['id'];
1003 }
1004
1005 /**
1006 * Function to delete Membership Type
1007 *
1008 * @param int $membershipTypeID
1009 */
1010 function membershipTypeDelete($params) {
f6722559 1011 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
1012 return;
1013 }
1014
1015 function membershipDelete($membershipID) {
f6722559 1016 $deleteParams = array('id' => $membershipID);
1017 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
1018 return;
1019 }
1020
1021 function membershipStatusCreate($name = 'test member status') {
1022 $params['name'] = $name;
1023 $params['start_event'] = 'start_date';
1024 $params['end_event'] = 'end_date';
1025 $params['is_current_member'] = 1;
1026 $params['is_active'] = 1;
6a488035 1027
f6722559 1028 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 1029 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
1030 return $result['id'];
1031 }
1032
1033 function membershipStatusDelete($membershipStatusID) {
1034 if (!$membershipStatusID) {
1035 return;
1036 }
4732bb2f 1037 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
1038 return;
1039 }
1040
1041 function relationshipTypeCreate($params = NULL) {
1042 if (is_null($params)) {
1043 $params = array(
1044 'name_a_b' => 'Relation 1 for relationship type create',
1045 'name_b_a' => 'Relation 2 for relationship type create',
1046 'contact_type_a' => 'Individual',
1047 'contact_type_b' => 'Organization',
1048 'is_reserved' => 1,
1049 'is_active' => 1,
1050 );
1051 }
1052
f6722559 1053 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
1054 CRM_Core_PseudoConstant::flush('relationshipType');
1055
1056 return $result['id'];
1057 }
1058
1059 /**
1060 * Function to delete Relatinship Type
1061 *
1062 * @param int $relationshipTypeID
1063 */
1064 function relationshipTypeDelete($relationshipTypeID) {
1065 $params['id'] = $relationshipTypeID;
f6722559 1066 $this->callAPISuccess('relationship_type', 'delete', $params);
6a488035
TO
1067 }
1068
1069 function paymentProcessorTypeCreate($params = NULL) {
1070 if (is_null($params)) {
1071 $params = array(
1072 'name' => 'API_Test_PP',
1073 'title' => 'API Test Payment Processor',
1074 'class_name' => 'CRM_Core_Payment_APITest',
1075 'billing_mode' => 'form',
1076 'is_recur' => 0,
1077 'is_reserved' => 1,
1078 'is_active' => 1,
1079 );
1080 }
f6722559 1081 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 1082
6a488035
TO
1083 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1084
1085 return $result['id'];
1086 }
1087
1088 /**
1089 * Function to create Participant
1090 *
1091 * @param array $params array of contact id and event id values
1092 *
1093 * @return int $id of participant created
1094 */
1095 function participantCreate($params) {
94692f2d 1096 if(empty($params['contact_id'])){
1097 $params['contact_id'] = $this->individualCreate();
1098 }
1099 if(empty($params['event_id'])){
1100 $event = $this->eventCreate();
1101 $params['event_id'] = $event['id'];
1102 }
6a488035 1103 $defaults = array(
6a488035
TO
1104 'status_id' => 2,
1105 'role_id' => 1,
1106 'register_date' => 20070219,
1107 'source' => 'Wimbeldon',
1108 'event_level' => 'Payment',
94692f2d 1109 'debug' => 1,
6a488035
TO
1110 );
1111
1112 $params = array_merge($defaults, $params);
f6722559 1113 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
1114 return $result['id'];
1115 }
1116
1117 /**
1118 * Function to create Payment Processor
1119 *
1120 * @return object of Payment Processsor
1121 */
1122 function processorCreate() {
1123 $processorParams = array(
1124 'domain_id' => 1,
1125 'name' => 'Dummy',
1126 'payment_processor_type_id' => 10,
1127 'financial_account_id' => 12,
1128 'is_active' => 1,
1129 'user_name' => '',
1130 'url_site' => 'http://dummy.com',
1131 'url_recur' => 'http://dummy.com',
1132 'billing_mode' => 1,
1133 );
1134 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1135 return $paymentProcessor;
1136 }
1137
1138 /**
1139 * Function to create contribution page
1140 *
1141 * @return object of contribution page
1142 */
1143 function contributionPageCreate($params) {
1144 $this->_pageParams = array(
6a488035
TO
1145 'title' => 'Test Contribution Page',
1146 'financial_type_id' => 1,
1147 'currency' => 'USD',
1148 'financial_account_id' => 1,
1149 'payment_processor' => $params['processor_id'],
1150 'is_active' => 1,
1151 'is_allow_other_amount' => 1,
1152 'min_amount' => 10,
1153 'max_amount' => 1000,
1154 );
f6722559 1155 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
1156 return $contributionPage;
1157 }
1158
6a488035
TO
1159 /**
1160 * Function to create Tag
1161 *
1162 * @return int tag_id of created tag
1163 */
1164 function tagCreate($params = NULL) {
1165 if ($params === NULL) {
1166 $params = array(
1167 'name' => 'New Tag3' . rand(),
1168 'description' => 'This is description for New Tag ' . rand(),
1169 'domain_id' => '1',
6a488035
TO
1170 );
1171 }
1172
f6722559 1173 $result = $this->callAPISuccess('Tag', 'create', $params);
6a488035
TO
1174 return $result;
1175 }
1176
1177 /**
1178 * Function to delete Tag
1179 *
1180 * @param int $tagId id of the tag to be deleted
1181 */
1182 function tagDelete($tagId) {
1183 require_once 'api/api.php';
1184 $params = array(
1185 'tag_id' => $tagId,
6a488035 1186 );
f6722559 1187 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
1188 return $result['id'];
1189 }
1190
1191 /**
1192 * Add entity(s) to the tag
1193 *
1194 * @param array $params
6a488035
TO
1195 */
1196 function entityTagAdd($params) {
f6722559 1197 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
1198 return TRUE;
1199 }
1200
1201 /**
1202 * Function to create contribution
1203 *
1204 * @param int $cID contact_id
1205 * @param int $cTypeID id of financial type
1206 *
1207 * @return int id of created contribution
1208 */
1209 function pledgeCreate($cID) {
1210 $params = array(
1211 'contact_id' => $cID,
1212 'pledge_create_date' => date('Ymd'),
1213 'start_date' => date('Ymd'),
1214 'scheduled_date' => date('Ymd'),
1215 'amount' => 100.00,
1216 'pledge_status_id' => '2',
1217 'financial_type_id' => '1',
1218 'pledge_original_installment_amount' => 20,
1219 'frequency_interval' => 5,
1220 'frequency_unit' => 'year',
1221 'frequency_day' => 15,
1222 'installments' => 5,
6a488035
TO
1223 );
1224
f6722559 1225 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
1226 return $result['id'];
1227 }
1228
1229 /**
1230 * Function to delete contribution
1231 *
1232 * @param int $contributionId
1233 */
1234 function pledgeDelete($pledgeId) {
1235 $params = array(
1236 'pledge_id' => $pledgeId,
6a488035 1237 );
f6722559 1238 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
1239 }
1240
1241 /**
1242 * Function to create contribution
1243 *
1244 * @param int $cID contact_id
1245 * @param int $cTypeID id of financial type
1246 *
1247 * @return int id of created contribution
1248 */
1249 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1250 $params = array(
1251 'domain_id' => 1,
1252 'contact_id' => $cID,
1253 'receive_date' => date('Ymd'),
1254 'total_amount' => 100.00,
1255 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1256 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1257 'non_deductible_amount' => 10.00,
1258 'trxn_id' => $trxnID,
1259 'invoice_id' => $invoiceID,
1260 'source' => 'SSF',
6a488035
TO
1261 'contribution_status_id' => 1,
1262 // 'note' => 'Donating for Nobel Cause', *Fixme
1263 );
1264
1265 if ($isFee) {
1266 $params['fee_amount'] = 5.00;
1267 $params['net_amount'] = 95.00;
1268 }
1269
f6722559 1270 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
1271 return $result['id'];
1272 }
1273
1274 /**
1275 * Function to create online contribution
1276 *
1277 * @param int $financialType id of financial type
1278 *
1279 * @return int id of created contribution
1280 */
1281 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1282 $contribParams = array(
1283 'contact_id' => $params['contact_id'],
1284 'receive_date' => date('Ymd'),
1285 'total_amount' => 100.00,
1286 'financial_type_id' => $financialType,
1287 'contribution_page_id' => $params['contribution_page_id'],
1288 'trxn_id' => 12345,
1289 'invoice_id' => 67890,
1290 'source' => 'SSF',
6a488035 1291 );
f6722559 1292 $contribParams = array_merge($contribParams, $params);
1293 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
6a488035
TO
1294
1295 return $result['id'];
1296 }
1297
1298 /**
1299 * Function to delete contribution
1300 *
1301 * @param int $contributionId
1302 */
1303 function contributionDelete($contributionId) {
1304 $params = array(
1305 'contribution_id' => $contributionId,
6a488035 1306 );
f6722559 1307 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
1308 return $result;
1309 }
1310
1311 /**
1312 * Function to create an Event
1313 *
1314 * @param array $params name-value pair for an event
1315 *
1316 * @return array $event
1317 */
1318 function eventCreate($params = array()) {
1319 // if no contact was passed, make up a dummy event creator
1320 if (!isset($params['contact_id'])) {
1321 $params['contact_id'] = $this->_contactCreate(array(
1322 'contact_type' => 'Individual',
1323 'first_name' => 'Event',
1324 'last_name' => 'Creator',
6a488035
TO
1325 ));
1326 }
1327
1328 // set defaults for missing params
1329 $params = array_merge(array(
1330 'title' => 'Annual CiviCRM meet',
1331 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1332 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1333 'event_type_id' => 1,
1334 'is_public' => 1,
1335 'start_date' => 20081021,
1336 'end_date' => 20081023,
1337 'is_online_registration' => 1,
1338 'registration_start_date' => 20080601,
1339 'registration_end_date' => 20081015,
1340 'max_participants' => 100,
1341 'event_full_text' => 'Sorry! We are already full',
1342 'is_monetory' => 0,
1343 'is_active' => 1,
6a488035
TO
1344 'is_show_location' => 0,
1345 ), $params);
1346
8cba5814 1347 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1348 }
1349
1350 /**
1351 * Function to delete event
1352 *
1353 * @param int $id ID of the event
1354 */
1355 function eventDelete($id) {
1356 $params = array(
1357 'event_id' => $id,
6a488035 1358 );
8cba5814 1359 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1360 }
1361
1362 /**
1363 * Function to delete participant
1364 *
1365 * @param int $participantID
1366 */
1367 function participantDelete($participantID) {
1368 $params = array(
1369 'id' => $participantID,
6a488035 1370 );
8cba5814 1371 return $this->callAPISuccess('Participant', 'delete', $params);
6a488035
TO
1372 }
1373
1374 /**
1375 * Function to create participant payment
1376 *
1377 * @return int $id of created payment
1378 */
1379 function participantPaymentCreate($participantID, $contributionID = NULL) {
1380 //Create Participant Payment record With Values
1381 $params = array(
1382 'participant_id' => $participantID,
1383 'contribution_id' => $contributionID,
6a488035
TO
1384 );
1385
f6722559 1386 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1387 return $result['id'];
1388 }
1389
1390 /**
1391 * Function to delete participant payment
1392 *
1393 * @param int $paymentID
1394 */
1395 function participantPaymentDelete($paymentID) {
1396 $params = array(
1397 'id' => $paymentID,
6a488035 1398 );
f6722559 1399 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1400 }
1401
1402 /**
1403 * Function to add a Location
1404 *
1405 * @return int location id of created location
1406 */
1407 function locationAdd($contactID) {
1408 $address = array(
1409 1 => array(
1410 'location_type' => 'New Location Type',
1411 'is_primary' => 1,
1412 'name' => 'Saint Helier St',
1413 'county' => 'Marin',
1414 'country' => 'United States',
1415 'state_province' => 'Michigan',
1416 'supplemental_address_1' => 'Hallmark Ct',
1417 'supplemental_address_2' => 'Jersey Village',
1418 )
1419 );
1420
1421 $params = array(
1422 'contact_id' => $contactID,
1423 'address' => $address,
6a488035
TO
1424 'location_format' => '2.0',
1425 'location_type' => 'New Location Type',
1426 );
1427
f6722559 1428 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1429 return $result;
1430 }
1431
1432 /**
1433 * Function to delete Locations of contact
1434 *
1435 * @params array $pamars parameters
1436 */
1437 function locationDelete($params) {
f6722559 1438 $result = $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1439 }
1440
1441 /**
1442 * Function to add a Location Type
1443 *
1444 * @return int location id of created location
1445 */
1446 function locationTypeCreate($params = NULL) {
1447 if ($params === NULL) {
1448 $params = array(
1449 'name' => 'New Location Type',
1450 'vcard_name' => 'New Location Type',
1451 'description' => 'Location Type for Delete',
1452 'is_active' => 1,
1453 );
1454 }
1455
6a488035
TO
1456 $locationType = new CRM_Core_DAO_LocationType();
1457 $locationType->copyValues($params);
1458 $locationType->save();
1459 // clear getfields cache
2683ce94 1460 CRM_Core_PseudoConstant::flush();
f6722559 1461 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1462 return $locationType;
1463 }
1464
1465 /**
1466 * Function to delete a Location Type
1467 *
1468 * @param int location type id
1469 */
1470 function locationTypeDelete($locationTypeId) {
6a488035
TO
1471 $locationType = new CRM_Core_DAO_LocationType();
1472 $locationType->id = $locationTypeId;
1473 $locationType->delete();
1474 }
1475
1476 /**
1477 * Function to add a Group
1478 *
1479 * @params array to add group
1480 *
1481 * @return int groupId of created group
1482 *
1483 */
1484 function groupCreate($params = NULL) {
1485 if ($params === NULL) {
1486 $params = array(
1487 'name' => 'Test Group 1',
1488 'domain_id' => 1,
1489 'title' => 'New Test Group Created',
1490 'description' => 'New Test Group Created',
1491 'is_active' => 1,
1492 'visibility' => 'Public Pages',
1493 'group_type' => array(
1494 '1' => 1,
1495 '2' => 1,
1496 ),
6a488035
TO
1497 );
1498 }
1499
f6722559 1500 $result = $this->callAPISuccess('Group', 'create', $params);
1501 return $result['id'];
6a488035
TO
1502 }
1503
1504 /**
1505 * Function to delete a Group
1506 *
1507 * @param int $id
1508 */
1509 function groupDelete($gid) {
1510
1511 $params = array(
1512 'id' => $gid,
6a488035
TO
1513 );
1514
f6722559 1515 $this->callAPISuccess('Group', 'delete', $params);
6a488035
TO
1516 }
1517
1518 /**
1519 * Function to add a UF Join Entry
1520 *
1521 * @return int $id of created UF Join
1522 */
1523 function ufjoinCreate($params = NULL) {
1524 if ($params === NULL) {
1525 $params = array(
1526 'is_active' => 1,
1527 'module' => 'CiviEvent',
1528 'entity_table' => 'civicrm_event',
1529 'entity_id' => 3,
1530 'weight' => 1,
1531 'uf_group_id' => 1,
1532 );
1533 }
f6722559 1534 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1535 return $result;
1536 }
1537
1538 /**
1539 * Function to delete a UF Join Entry
1540 *
1541 * @param array with missing uf_group_id
1542 */
1543 function ufjoinDelete($params = NULL) {
1544 if ($params === NULL) {
1545 $params = array(
1546 'is_active' => 1,
1547 'module' => 'CiviEvent',
1548 'entity_table' => 'civicrm_event',
1549 'entity_id' => 3,
1550 'weight' => 1,
1551 'uf_group_id' => '',
1552 );
1553 }
1554
1555 crm_add_uf_join($params);
1556 }
1557
1558 /**
1559 * Function to create Group for a contact
1560 *
1561 * @param int $contactId
1562 */
1563 function contactGroupCreate($contactId) {
1564 $params = array(
1565 'contact_id.1' => $contactId,
1566 'group_id' => 1,
1567 );
1568
f6722559 1569 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
1570 }
1571
1572 /**
1573 * Function to delete Group for a contact
1574 *
1575 * @param array $params
1576 */
1577 function contactGroupDelete($contactId) {
1578 $params = array(
1579 'contact_id.1' => $contactId,
1580 'group_id' => 1,
1581 );
1582 civicrm_api('GroupContact', 'Delete', $params);
1583 }
1584
1585 /**
1586 * Function to create Activity
1587 *
1588 * @param int $contactId
1589 */
1590 function activityCreate($params = NULL) {
1591
1592 if ($params === NULL) {
1593 $individualSourceID = $this->individualCreate(NULL);
1594
1595 $contactParams = array(
1596 'first_name' => 'Julia',
1597 'Last_name' => 'Anderson',
1598 'prefix' => 'Ms.',
1599 'email' => 'julia_anderson@civicrm.org',
1600 'contact_type' => 'Individual',
6a488035
TO
1601 );
1602
1603 $individualTargetID = $this->individualCreate($contactParams);
1604
1605 $params = array(
1606 'source_contact_id' => $individualSourceID,
1607 'target_contact_id' => array($individualTargetID),
1608 'assignee_contact_id' => array($individualTargetID),
1609 'subject' => 'Discussion on warm beer',
1610 'activity_date_time' => date('Ymd'),
1611 'duration_hours' => 30,
1612 'duration_minutes' => 20,
1613 'location' => 'Baker Street',
1614 'details' => 'Lets schedule a meeting',
1615 'status_id' => 1,
1616 'activity_name' => 'Meeting',
6a488035
TO
1617 );
1618 }
1619
f6722559 1620 $result = $this->callAPISuccess('Activity', 'create', $params);
6a488035
TO
1621
1622 $result['target_contact_id'] = $individualTargetID;
1623 $result['assignee_contact_id'] = $individualTargetID;
1624 return $result;
1625 }
1626
1627 /**
1628 * Function to create an activity type
1629 *
1630 * @params array $params parameters
1631 */
1632 function activityTypeCreate($params) {
f6722559 1633 $result = $this->callAPISuccess('ActivityType', 'create', $params);
6a488035
TO
1634 return $result;
1635 }
1636
1637 /**
1638 * Function to delete activity type
1639 *
1640 * @params Integer $activityTypeId id of the activity type
1641 */
1642 function activityTypeDelete($activityTypeId) {
1643 $params['activity_type_id'] = $activityTypeId;
f6722559 1644 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
6a488035
TO
1645 return $result;
1646 }
1647
1648 /**
1649 * Function to create custom group
1650 *
1651 * @param string $className
1652 * @param string $title name of custom group
1653 */
f6722559 1654 function customGroupCreate($params = array()) {
1655 $defaults = array(
1656 'title' => 'new custom group',
1657 'extends' => 'Contact',
1658 'domain_id' => 1,
1659 'style' => 'Inline',
1660 'is_active' => 1,
1661 );
6a488035 1662
f6722559 1663 $params = array_merge($defaults, $params);
1664
1665 if (strlen($params['title']) > 13) {
1666 $params['title'] = substr($params['title'], 0, 13);
6a488035 1667 }
6a488035 1668
f6722559 1669 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1670 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
6a488035 1671
f6722559 1672 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1673 }
1674
1675 /**
1676 * existing function doesn't allow params to be over-ridden so need a new one
1677 * this one allows you to only pass in the params you want to change
1678 */
1679 function CustomGroupCreateByParams($params = array()) {
1680 $defaults = array(
1681 'title' => "API Custom Group",
1682 'extends' => 'Contact',
1683 'domain_id' => 1,
1684 'style' => 'Inline',
1685 'is_active' => 1,
6a488035
TO
1686 );
1687 $params = array_merge($defaults, $params);
f6722559 1688 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1689 }
1690
1691 /**
1692 * Create custom group with multi fields
1693 */
1694 function CustomGroupMultipleCreateByParams($params = array()) {
1695 $defaults = array(
1696 'style' => 'Tab',
1697 'is_multiple' => 1,
1698 );
1699 $params = array_merge($defaults, $params);
f6722559 1700 return $this->CustomGroupCreateByParams($params);
6a488035
TO
1701 }
1702
1703 /**
1704 * Create custom group with multi fields
1705 */
1706 function CustomGroupMultipleCreateWithFields($params = array()) {
1707 // also need to pass on $params['custom_field'] if not set but not in place yet
1708 $ids = array();
1709 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1710 $ids['custom_group_id'] = $customGroup['id'];
6a488035
TO
1711
1712 $customField = $this->customFieldCreate($ids['custom_group_id']);
1713
1714 $ids['custom_field_id'][] = $customField['id'];
f6722559 1715
6a488035
TO
1716 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_2');
1717 $ids['custom_field_id'][] = $customField['id'];
f6722559 1718
6a488035
TO
1719 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_3');
1720 $ids['custom_field_id'][] = $customField['id'];
f6722559 1721
6a488035
TO
1722 return $ids;
1723 }
1724
1725 /**
1726 * Create a custom group with a single text custom field. See
1727 * participant:testCreateWithCustom for how to use this
1728 *
1729 * @param string $function __FUNCTION__
1730 * @param string $file __FILE__
1731 *
1732 * @return array $ids ids of created objects
1733 *
1734 */
1735 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 1736 $params = array('title' => $function);
6a488035 1737 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
f6722559 1738 $params['extends'] = $entity ? $entity : 'Contact';
1739 $customGroup = $this->CustomGroupCreate($params);
6a488035 1740 $customField = $this->customFieldCreate($customGroup['id'], $function);
80085473 1741 CRM_Core_PseudoConstant::flush();
6a488035
TO
1742
1743 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1744 }
1745
1746 /**
1747 * Function to delete custom group
1748 *
1749 * @param int $customGroupID
1750 */
1751 function customGroupDelete($customGroupID) {
1752
1753 $params['id'] = $customGroupID;
f6722559 1754 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
1755 }
1756
1757 /**
1758 * Function to create custom field
1759 *
1760 * @param int $customGroupID
1761 * @param string $name name of custom field
1762 * @param int $apiversion API version to use
1763 */
1764 function customFieldCreate($customGroupID, $name = "Cust Field") {
1765
1766 $params = array(
1767 'label' => $name,
1768 'name' => $name,
1769 'custom_group_id' => $customGroupID,
1770 'data_type' => 'String',
1771 'html_type' => 'Text',
1772 'is_searchable' => 1,
1773 'is_active' => 1,
f6722559 1774 'version' => $this->_apiversion,
6a488035
TO
1775 );
1776
1777 $result = civicrm_api('custom_field', 'create', $params);
1778
1779 if ($result['is_error'] == 0 && isset($result['id'])) {
1780 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1781 // force reset of enabled components to help grab custom fields
1782 CRM_Core_Component::getEnabledComponents(1);
1783 return $result;
1784 }
1785
1786 if (civicrm_error($result)
1787 || !(CRM_Utils_Array::value('customFieldId', $result['result']))
1788 ) {
1789 throw new Exception('Could not create Custom Field ' . $result['error_message']);
1790 }
1791 }
1792
1793 /**
1794 * Function to delete custom field
1795 *
1796 * @param int $customFieldID
1797 */
1798 function customFieldDelete($customFieldID) {
1799
1800 $params['id'] = $customFieldID;
f6722559 1801 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
1802 }
1803
1804 /**
1805 * Function to create note
1806 *
1807 * @params array $params name-value pair for an event
1808 *
1809 * @return array $note
1810 */
1811 function noteCreate($cId) {
1812 $params = array(
1813 'entity_table' => 'civicrm_contact',
1814 'entity_id' => $cId,
1815 'note' => 'hello I am testing Note',
1816 'contact_id' => $cId,
1817 'modified_date' => date('Ymd'),
1818 'subject' => 'Test Note',
6a488035
TO
1819 );
1820
f6722559 1821 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
1822 }
1823
1824 /**
1825 * Create test generated example in api/v3/examples.
1826 * To turn this off (e.g. on the server) set
1827 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1828 * in your settings file
1829 * @param array $params array as passed to civicrm_api function
1830 * @param array $result array as received from the civicrm_api function
1831 * @param string $function calling function - generally __FUNCTION__
1832 * @param string $filename called from file - generally __FILE__
1833 * @param string $description descriptive text for the example file
1834 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1835 * @param string $action - optional action - otherwise taken from function name
1836 */
1837 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1838 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1839 return;
1840 }
1841 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1842 //todo - this is a bit cludgey
1843 if (empty($action)) {
1844 if (strstr($function, 'Create')) {
1845 $action = empty($action) ? 'create' : $action;
1846 $entityAction = 'Create';
1847 }
1848 elseif (strstr($function, 'GetSingle')) {
1849 $action = empty($action) ? 'getsingle' : $action;
1850 $entityAction = 'GetSingle';
1851 }
1852 elseif (strstr($function, 'GetValue')) {
1853 $action = empty($action) ? 'getvalue' : $action;
1854 $entityAction = 'GetValue';
1855 }
1856 elseif (strstr($function, 'GetCount')) {
1857 $action = empty($action) ? 'getcount' : $action;
1858 $entityAction = 'GetCount';
1859 }
1860 elseif (strstr($function, 'Get')) {
1861 $action = empty($action) ? 'get' : $action;
1862 $entityAction = 'Get';
1863 }
1864 elseif (strstr($function, 'Delete')) {
1865 $action = empty($action) ? 'delete' : $action;
1866 $entityAction = 'Delete';
1867 }
1868 elseif (strstr($function, 'Update')) {
1869 $action = empty($action) ? 'update' : $action;
1870 $entityAction = 'Update';
1871 }
1872 elseif (strstr($function, 'Subscribe')) {
1873 $action = empty($action) ? 'subscribe' : $action;
1874 $entityAction = 'Subscribe';
1875 }
1876 elseif (strstr($function, 'Set')) {
1877 $action = empty($action) ? 'set' : $action;
1878 $entityAction = 'Set';
1879 }
1880 elseif (strstr($function, 'Apply')) {
1881 $action = empty($action) ? 'apply' : $action;
1882 $entityAction = 'Apply';
1883 }
1884 elseif (strstr($function, 'Replace')) {
1885 $action = empty($action) ? 'replace' : $action;
1886 $entityAction = 'Replace';
1887 }
1888 }
1889 else {
1890 $entityAction = ucwords($action);
1891 }
1892
1893 $fieldsToChange = array(
1894 'hash' => '67eac7789eaee00',
1895 'modified_date' => '2012-11-14 16:02:35',
fbda92d3 1896 'created_date' => '20120130621222105',
f6722559 1897 'create_date' => '20120130621222105',
6a488035 1898 );
fbda92d3 1899
6a488035
TO
1900 //swap out keys that change too often
1901 foreach ($fieldsToChange as $changeKey => $changeValue) {
1902 if (isset($result['values']) && is_array($result['values'])) {
1903 foreach ($result['values'] as $key => $value) {
1904 if (is_array($value) && array_key_exists($changeKey, $value)) {
1905 $result['values'][$key][$changeKey] = $changeValue;
1906 }
1907 }
1908 }
1909 }
1910
1911 // a cleverer person than me would do it in a single regex
1912 if (strstr($entity, 'UF')) {
1913 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1914 }
1915 else {
1916 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1917 }
1918 $smarty = CRM_Core_Smarty::singleton();
1919 $smarty->assign('testfunction', $function);
1920 $function = $fnPrefix . "_" . strtolower($action);
1921 $smarty->assign('function', $function);
1922 $smarty->assign('fnPrefix', $fnPrefix);
1923 $smarty->assign('params', $params);
1924 $smarty->assign('entity', $entity);
1925 $smarty->assign('filename', basename($filename));
1926 $smarty->assign('description', $description);
1927 $smarty->assign('result', $result);
1928
1929 $smarty->assign('action', $action);
1930 if (empty($subfile)) {
1931 if (file_exists('../tests/templates/documentFunction.tpl')) {
1932 $f = fopen("../api/v3/examples/$entity$entityAction.php", "w");
1933 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1934 fclose($f);
1935 }
1936 }
1937 else {
1938 if (file_exists('../tests/templates/documentFunction.tpl')) {
1939 if (!is_dir("../api/v3/examples/$entity")) {
1940 mkdir("../api/v3/examples/$entity");
1941 }
1942 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1943 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1944 fclose($f);
1945 }
1946 }
1947 }
1948
1949 /**
1950 * Function to delete note
1951 *
1952 * @params int $noteID
1953 *
1954 */
1955 function noteDelete($params) {
f6722559 1956 return $this->callAPISuccess('Note', 'delete', $params);
6a488035
TO
1957 }
1958
1959 /**
1960 * Function to create custom field with Option Values
1961 *
1962 * @param array $customGroup
1963 * @param string $name name of custom field
1964 */
1965 function customFieldOptionValueCreate($customGroup, $name) {
1966 $fieldParams = array(
1967 'custom_group_id' => $customGroup['id'],
1968 'name' => 'test_custom_group',
1969 'label' => 'Country',
1970 'html_type' => 'Select',
1971 'data_type' => 'String',
1972 'weight' => 4,
1973 'is_required' => 1,
1974 'is_searchable' => 0,
1975 'is_active' => 1,
6a488035
TO
1976 );
1977
1978 $optionGroup = array(
1979 'domain_id' => 1,
1980 'name' => 'option_group1',
1981 'label' => 'option_group_label1',
1982 );
1983
1984 $optionValue = array(
1985 'option_label' => array('Label1', 'Label2'),
1986 'option_value' => array('value1', 'value2'),
1987 'option_name' => array($name . '_1', $name . '_2'),
1988 'option_weight' => array(1, 2),
1989 'option_status' => 1,
1990 );
1991
1992 $params = array_merge($fieldParams, $optionGroup, $optionValue);
1993
f6722559 1994 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
1995 }
1996
1997 function confirmEntitiesDeleted($entities) {
1998 foreach ($entities as $entity) {
1999
f6722559 2000 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
2001 if ($result['error'] == 1 || $result['count'] > 0) {
2002 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2003 return TRUE;
2004 }
2005 }
2006 }
2007
2008 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2009 if ($dropCustomValueTables) {
2010 $tablesToTruncate[] = 'civicrm_custom_group';
2011 $tablesToTruncate[] = 'civicrm_custom_field';
2012 }
2013
2014 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2015 foreach ($tablesToTruncate as $table) {
2016 $sql = "TRUNCATE TABLE $table";
2017 CRM_Core_DAO::executeQuery($sql);
2018 }
2019 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2020
2021 if ($dropCustomValueTables) {
2022 $dbName = self::getDBName();
2023 $query = "
2024SELECT TABLE_NAME as tableName
2025FROM INFORMATION_SCHEMA.TABLES
2026WHERE TABLE_SCHEMA = '{$dbName}'
2027AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2028";
2029
2030 $tableDAO = CRM_Core_DAO::executeQuery($query);
2031 while ($tableDAO->fetch()) {
2032 $sql = "DROP TABLE {$tableDAO->tableName}";
2033 CRM_Core_DAO::executeQuery($sql);
2034 }
2035 }
2036 }
2037
2038 /*
2039 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2040 * Default behaviour is to also delete the entity
2041 * @param array $params params array to check agains
2042 * @param int $id id of the entity concerned
2043 * @param string $entity name of entity concerned (e.g. membership)
2044 * @param bool $delete should the entity be deleted as part of this check
2045 * @param string $errorText text to print on error
2046 *
2047 */
2048 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2049
f6722559 2050 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 2051 'id' => $id,
6a488035
TO
2052 ));
2053
2054 if ($delete) {
f6722559 2055 $this->callAPISuccess($entity, 'Delete', array(
6a488035 2056 'id' => $id,
6a488035
TO
2057 ));
2058 }
2059 $dateFields = $keys = array();
f6722559 2060 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
2061 foreach ($fields['values'] as $field => $settings) {
2062 if (array_key_exists($field, $result)) {
2063 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2064 }
2065 else {
2066 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2067 }
2068
2069 if (CRM_Utils_Array::value('type', $settings) == CRM_Utils_Type::T_DATE) {
2070 $dateFields[] = $field;
2071 }
2072 }
2073
2074 if (strtolower($entity) == 'contribution') {
2075 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2076 // this is not returned in id format
2077 unset($params['payment_instrument_id']);
2078 $params['contribution_source'] = $params['source'];
2079 unset($params['source']);
2080 }
2081
2082 foreach ($params as $key => $value) {
2083 if ($key == 'version' || substr($key, 0, 3) == 'api') {
2084 continue;
2085 }
2086 if (in_array($key, $dateFields)) {
2087 $value = date('Y-m-d', strtotime($value));
2088 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2089 }
2090 $this->assertEquals($value, $result[$keys[$key]], $key . " GetandCheck function determines that value: $value doesn't match " . print_r($result, TRUE) . $errorText);
2091 }
2092 }
2093
2094 /**
2095 * Function to get formatted values in the actual and expected result
2096 * @param array $actual actual calculated values
2097 * @param array $expected expected values
2098 *
2099 */
2100 function checkArrayEquals(&$actual, &$expected) {
2101 self::unsetId($actual);
2102 self::unsetId($expected);
2103 $this->assertEquals($actual, $expected);
2104 }
2105
2106 /**
2107 * Function to unset the key 'id' from the array
2108 * @param array $unformattedArray The array from which the 'id' has to be unset
2109 *
2110 */
2111 static function unsetId(&$unformattedArray) {
2112 $formattedArray = array();
2113 if (array_key_exists('id', $unformattedArray)) {
2114 unset($unformattedArray['id']);
2115 }
2116 if (CRM_Utils_Array::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2117 foreach ($unformattedArray['values'] as $key => $value) {
2118 if (is_Array($value)) {
2119 foreach ($value as $k => $v) {
2120 if ($k == 'id') {
2121 unset($value[$k]);
2122 }
2123 }
2124 }
2125 elseif ($key == 'id') {
2126 $unformattedArray[$key];
2127 }
2128 $formattedArray = array($value);
2129 }
2130 $unformattedArray['values'] = $formattedArray;
2131 }
2132 }
2133
2134 /**
2135 * Helper to enable/disable custom directory support
2136 *
2137 * @param array $customDirs with members:
2138 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2139 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2140 */
2141 function customDirectories($customDirs) {
2142 require_once 'CRM/Core/Config.php';
2143 $config = CRM_Core_Config::singleton();
2144
2145 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2146 unset($config->customPHPPathDir);
2147 }
2148 elseif ($customDirs['php_path'] === TRUE) {
2149 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2150 }
2151 else {
2152 $config->customPHPPathDir = $php_path;
2153 }
2154
2155 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2156 unset($config->customTemplateDir);
2157 }
2158 elseif ($customDirs['template_path'] === TRUE) {
2159 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2160 }
2161 else {
2162 $config->customTemplateDir = $template_path;
2163 }
2164 }
2165
2166 /**
2167 * Generate a temporary folder
2168 *
2169 * @return $string
2170 */
2171 function createTempDir($prefix = 'test-') {
2172 $tempDir = CRM_Utils_File::tempdir($prefix);
2173 $this->tempDirs[] = $tempDir;
2174 return $tempDir;
2175 }
2176
2177 function cleanTempDirs() {
2178 if (!is_array($this->tempDirs)) {
2179 // fix test errors where this is not set
2180 return;
2181 }
2182 foreach ($this->tempDirs as $tempDir) {
2183 if (is_dir($tempDir)) {
2184 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2185 }
2186 }
2187 }
2188
2189 /**
2190 * Temporarily replace the singleton extension with a different one
2191 */
2192 function setExtensionSystem(CRM_Extension_System $system) {
2193 if ($this->origExtensionSystem == NULL) {
2194 $this->origExtensionSystem = CRM_Extension_System::singleton();
2195 }
2196 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2197 }
2198
2199 function unsetExtensionSystem() {
2200 if ($this->origExtensionSystem !== NULL) {
2201 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2202 $this->origExtensionSystem = NULL;
2203 }
2204 }
f17d75bb
PN
2205
2206 function financialAccountDelete($name) {
2207 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2208 $financialAccount->name = $name;
2209 if($financialAccount->find(TRUE)) {
2210 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2211 $entityFinancialType->financial_account_id = $financialAccount->id;
2212 $entityFinancialType->delete();
2213 $financialAccount->delete();
2214 }
2215 }
6a488035
TO
2216}
2217
2218function CiviUnitTestCase_fatalErrorHandler($message) {
2219 throw new Exception("{$message['message']}: {$message['code']}");
2220}