Merge pull request #1277 from totten/master-reporttestcase
[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 */
eafce897 111 public $_eNoticeCompliant = TRUE;
6a488035
TO
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 }
626 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
6a488035
TO
627 }
628
feb2a730 629 /**
630 * check that api returned 'is_error' => 1
631 * else provide full message
632 * @param array $apiResult api result
633 * @param string $prefix extra test to add to message
634 */
64fe97da 635 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
feb2a730 636 if (!empty($prefix)) {
637 $prefix .= ': ';
638 }
64fe97da 639 if($expectedError && !empty($apiResult['is_error'])){
640 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
641 }
feb2a730 642 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
f6722559 643 $this->assertNotEmpty($apiResult['error_message']);
feb2a730 644 }
645
6a488035
TO
646 function assertType($expected, $actual, $message = '') {
647 return $this->assertInternalType($expected, $actual, $message);
648 }
54bd1003 649
c43d01f3 650 /**
651 * check that a deleted item has been deleted
652 */
653 function assertAPIDeleted($entity, $id) {
654 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
655 }
656
657
f6722559 658 /**
659 * check that api returned 'is_error' => 1
660 * else provide full message
661 * @param array $apiResult api result
662 * @param string $prefix extra test to add to message
663 */
664 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
665 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
666 foreach ($valuesToExclude as $value) {
667 if(isset($result[$value])) {
668 unset($result[$value]);
669 }
670 if(isset($expected[$value])) {
671 unset($expected[$value]);
672 }
673 }
674 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
675 }
676
54bd1003 677 /**
678 * This function exists to wrap api functions
791c263c 679 * so we can ensure they succeed & throw exceptions without litterering the test with checks
680 * @param string $entity
681 * @param string $action
682 * @param array $params
f6722559 683 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue, getcount, getsingle
791c263c 684 */
f6722559 685 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
fbda92d3 686 $params = array_merge(array(
f6722559 687 'version' => $this->_apiversion,
fbda92d3 688 'debug' => 1,
689 ),
690 $params
9443c775 691 );
f6722559 692 switch (strtolower($action)) {
693 case 'getvalue' :
694 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
695 case 'getsingle' :
696 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
697 case 'getcount' :
698 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
699 }
791c263c 700 $result = civicrm_api($entity, $action, $params);
54bd1003 701 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
702 return $result;
703 }
704
fbda92d3 705 /**
706 * This function exists to wrap api getValue function & check the result
707 * so we can ensure they succeed & throw exceptions without litterering the test with checks
708 * There is a type check in this
709 * @param string $entity
710 * @param array $params
711 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
c8950569
KJ
712 * - boolean
713 * - integer
714 * - double
715 * - string
716 * - array
717 * - object
fbda92d3 718 */
719 function callAPISuccessGetValue($entity, $params, $type = NULL) {
720 $params += array(
f6722559 721 'version' => $this->_apiversion,
fbda92d3 722 'debug' => 1,
723 );
724 $result = civicrm_api($entity, 'getvalue', $params);
725 if($type){
726 if($type == 'integer'){
727 // api seems to return integers as strings
728 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
729 }
730 else{
731 $this->assertType($type, $result, "returned result should have been of type $type but was " );
732 }
733 }
734 return $result;
735 }
c8950569 736
f6722559 737 /**
738 * This function exists to wrap api getsingle function & check the result
739 * so we can ensure they succeed & throw exceptions without litterering the test with checks
740 * @param string $entity
741 * @param array $params
742 * @param array $checkAgainst - array to compare result against
743 * - boolean
744 * - integer
745 * - double
746 * - string
747 * - array
748 * - object
749 */
750 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
751 $params += array(
752 'version' => $this->_apiversion,
753 'debug' => 1,
754 );
755 $result = civicrm_api($entity, 'getsingle', $params);
756 if(!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
757 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
758 }
759 if($checkAgainst){
760 // @todo - have gone with the fn that unsets id? should we check id?
761 $this->checkArrayEquals($result, $checkAgainst);
762 }
763 return $result;
764 }
765 /**
766 * This function exists to wrap api getValue function & check the result
767 * so we can ensure they succeed & throw exceptions without litterering the test with checks
768 * There is a type check in this
769 * @param string $entity
770 * @param array $params
771 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
772 * - boolean
773 * - integer
774 * - double
775 * - string
776 * - array
777 * - object
778 */
779 function callAPISuccessGetCount($entity, $params, $count = NULL) {
780 $params += array(
781 'version' => $this->_apiversion,
782 'debug' => 1,
783 );
784 $result = civicrm_api($entity, 'getcount', $params);
785 if(!is_integer($result) || !empty($result['is_error']) || isset($result['values'])) {
786 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
787 }
788 if(is_int($count)){
789 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
790 }
791 return $result;
792 }
54bd1003 793 /**
794 * This function exists to wrap api functions
795 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
796 *
797 * @param string $entity
798 * @param string $action
799 * @param array $params
800 * @param string $function - pass this in to create a generated example
801 * @param string $file - pass this in to create a generated example
802 */
9443c775 803 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
f6722559 804 $params['version'] = $this->_apiversion;
17400ace 805 $result = $this->callAPISuccess($entity, $action, $params);
9443c775 806 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
54bd1003 807 return $result;
808 }
809
810 /**
811 * This function exists to wrap api functions
812 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
813 * @param string $entity
814 * @param string $action
815 * @param array $params
64fe97da 816 * @param string $expectedErrorMessage error
54bd1003 817 */
64fe97da 818 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
9443c775
CW
819 if (is_array($params)) {
820 $params += array(
f6722559 821 'version' => $this->_apiversion,
9443c775
CW
822 );
823 }
54bd1003 824 $result = civicrm_api($entity, $action, $params);
825 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
791c263c 826 return $result;
827 }
9443c775 828
fbda92d3 829 /**
830 * Create required data based on $this->entity & $this->params
831 * This is just a way to set up the test data for delete & get functions
832 * so the distinction between set
833 * up & tested functions is clearer
834 *
835 * @return array api Result
836 */
837 public function createTestEntity(){
838 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
839 }
840
6a488035
TO
841 /**
842 * Generic function to create Organisation, to be used in test cases
843 *
844 * @param array parameters for civicrm_contact_add api function call
845 *
846 * @return int id of Organisation created
847 */
848 function organizationCreate($params = array()) {
849 if (!$params) {
850 $params = array();
851 }
852 $orgParams = array(
853 'organization_name' => 'Unit Test Organization',
854 'contact_type' => 'Organization',
6a488035
TO
855 );
856 return $this->_contactCreate(array_merge($orgParams, $params));
857 }
858
859 /**
860 * Generic function to create Individual, to be used in test cases
861 *
862 * @param array parameters for civicrm_contact_add api function call
863 *
864 * @return int id of Individual created
865 */
866 function individualCreate($params = NULL) {
867 if ($params === NULL) {
868 $params = array(
869 'first_name' => 'Anthony',
870 'middle_name' => 'J.',
871 'last_name' => 'Anderson',
872 'prefix_id' => 3,
873 'suffix_id' => 3,
874 'email' => 'anthony_anderson@civicrm.org',
875 'contact_type' => 'Individual',
876 );
877 }
6a488035
TO
878 return $this->_contactCreate($params);
879 }
880
881 /**
882 * Generic function to create Household, to be used in test cases
883 *
884 * @param array parameters for civicrm_contact_add api function call
885 *
886 * @return int id of Household created
887 */
888 function householdCreate($params = NULL) {
889 if ($params === NULL) {
890 $params = array(
891 'household_name' => 'Unit Test household',
892 'contact_type' => 'Household',
893 );
894 }
6a488035
TO
895 return $this->_contactCreate($params);
896 }
897
898 /**
899 * Private helper function for calling civicrm_contact_add
900 *
901 * @param array parameters for civicrm_contact_add api function call
902 *
903 * @return int id of Household created
904 */
905 private function _contactCreate($params) {
4732bb2f 906 $result = $this->callAPISuccess('contact', 'create', $params);
6a488035
TO
907 if (CRM_Utils_Array::value('is_error', $result) ||
908 !CRM_Utils_Array::value('id', $result)
909 ) {
ace01fda 910 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
911 }
912 return $result['id'];
913 }
914
915 function contactDelete($contactID) {
ace01fda
CW
916 $params = array(
917 'id' => $contactID,
ace01fda
CW
918 'skip_undelete' => 1,
919 'debug' => 1,
920 );
6a488035
TO
921 $domain = new CRM_Core_BAO_Domain;
922 $domain->contact_id = $contactID;
923 if ($domain->find(TRUE)) {
924 // we are finding tests trying to delete the domain contact in cleanup
925 //since this is mainly for cleanup lets put a safeguard here
926 return;
927 }
f6722559 928 $result = $this->callAPISuccess('contact', 'delete', $params);
929 return $result;
6a488035
TO
930 }
931
932 function contactTypeDelete($contactTypeId) {
933 require_once 'CRM/Contact/BAO/ContactType.php';
934 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
935 if (!$result) {
936 throw new Exception('Could not delete contact type');
937 }
938 }
939
940 function membershipTypeCreate($contactID, $contributionTypeID = 1, $version = 3) {
941 require_once 'CRM/Member/PseudoConstant.php';
942 CRM_Member_PseudoConstant::flush('membershipType');
943 CRM_Core_Config::clearDBCache();
944 $params = array(
945 'name' => 'General',
946 'duration_unit' => 'year',
947 'duration_interval' => 1,
948 'period_type' => 'rolling',
949 'member_of_contact_id' => $contactID,
950 'domain_id' => 1,
951 // FIXME: I know it's 1, cause it was loaded directly to the db.
952 // FIXME: when we load all the data, we'll need to address this to
953 // FIXME: avoid hunting numbers around.
954 'financial_type_id' => $contributionTypeID,
955 'is_active' => 1,
956 'version' => $version,
957 'sequential' => 1,
958 'visibility' => 1,
959 );
960
961 $result = civicrm_api('MembershipType', 'Create', $params);
962 require_once 'CRM/Member/PseudoConstant.php';
963 CRM_Member_PseudoConstant::flush('membershipType');
964 CRM_Utils_Cache::singleton()->flush();
965 if (CRM_Utils_Array::value('is_error', $result) ||
966 (!CRM_Utils_Array::value('id', $result) && !CRM_Utils_Array::value('id', $result['values'][0]))
967 ) {
968 throw new Exception('Could not create membership type, with message: ' . CRM_Utils_Array::value('error_message', $result));
969 }
970
971 return $result['id'];
972 }
973
974 function contactMembershipCreate($params) {
975 $pre = array(
976 'join_date' => '2007-01-21',
977 'start_date' => '2007-01-21',
978 'end_date' => '2007-12-21',
979 'source' => 'Payment',
6a488035
TO
980 );
981
982 foreach ($pre as $key => $val) {
983 if (!isset($params[$key])) {
984 $params[$key] = $val;
985 }
986 }
987
f6722559 988 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
989 return $result['id'];
990 }
991
992 /**
993 * Function to delete Membership Type
994 *
995 * @param int $membershipTypeID
996 */
997 function membershipTypeDelete($params) {
f6722559 998 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
999 return;
1000 }
1001
1002 function membershipDelete($membershipID) {
f6722559 1003 $deleteParams = array('id' => $membershipID);
1004 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
1005 return;
1006 }
1007
1008 function membershipStatusCreate($name = 'test member status') {
1009 $params['name'] = $name;
1010 $params['start_event'] = 'start_date';
1011 $params['end_event'] = 'end_date';
1012 $params['is_current_member'] = 1;
1013 $params['is_active'] = 1;
6a488035 1014
f6722559 1015 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 1016 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
1017 return $result['id'];
1018 }
1019
1020 function membershipStatusDelete($membershipStatusID) {
1021 if (!$membershipStatusID) {
1022 return;
1023 }
4732bb2f 1024 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
1025 return;
1026 }
1027
1028 function relationshipTypeCreate($params = NULL) {
1029 if (is_null($params)) {
1030 $params = array(
1031 'name_a_b' => 'Relation 1 for relationship type create',
1032 'name_b_a' => 'Relation 2 for relationship type create',
1033 'contact_type_a' => 'Individual',
1034 'contact_type_b' => 'Organization',
1035 'is_reserved' => 1,
1036 'is_active' => 1,
1037 );
1038 }
1039
f6722559 1040 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
1041 CRM_Core_PseudoConstant::flush('relationshipType');
1042
1043 return $result['id'];
1044 }
1045
1046 /**
1047 * Function to delete Relatinship Type
1048 *
1049 * @param int $relationshipTypeID
1050 */
1051 function relationshipTypeDelete($relationshipTypeID) {
1052 $params['id'] = $relationshipTypeID;
f6722559 1053 $this->callAPISuccess('relationship_type', 'delete', $params);
6a488035
TO
1054 }
1055
1056 function paymentProcessorTypeCreate($params = NULL) {
1057 if (is_null($params)) {
1058 $params = array(
1059 'name' => 'API_Test_PP',
1060 'title' => 'API Test Payment Processor',
1061 'class_name' => 'CRM_Core_Payment_APITest',
1062 'billing_mode' => 'form',
1063 'is_recur' => 0,
1064 'is_reserved' => 1,
1065 'is_active' => 1,
1066 );
1067 }
f6722559 1068 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 1069
6a488035
TO
1070 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1071
1072 return $result['id'];
1073 }
1074
1075 /**
1076 * Function to create Participant
1077 *
1078 * @param array $params array of contact id and event id values
1079 *
1080 * @return int $id of participant created
1081 */
1082 function participantCreate($params) {
94692f2d 1083 if(empty($params['contact_id'])){
1084 $params['contact_id'] = $this->individualCreate();
1085 }
1086 if(empty($params['event_id'])){
1087 $event = $this->eventCreate();
1088 $params['event_id'] = $event['id'];
1089 }
6a488035 1090 $defaults = array(
6a488035
TO
1091 'status_id' => 2,
1092 'role_id' => 1,
1093 'register_date' => 20070219,
1094 'source' => 'Wimbeldon',
1095 'event_level' => 'Payment',
94692f2d 1096 'debug' => 1,
6a488035
TO
1097 );
1098
1099 $params = array_merge($defaults, $params);
f6722559 1100 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
1101 return $result['id'];
1102 }
1103
1104 /**
1105 * Function to create Payment Processor
1106 *
1107 * @return object of Payment Processsor
1108 */
1109 function processorCreate() {
1110 $processorParams = array(
1111 'domain_id' => 1,
1112 'name' => 'Dummy',
1113 'payment_processor_type_id' => 10,
1114 'financial_account_id' => 12,
1115 'is_active' => 1,
1116 'user_name' => '',
1117 'url_site' => 'http://dummy.com',
1118 'url_recur' => 'http://dummy.com',
1119 'billing_mode' => 1,
1120 );
1121 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1122 return $paymentProcessor;
1123 }
1124
1125 /**
1126 * Function to create contribution page
1127 *
1128 * @return object of contribution page
1129 */
1130 function contributionPageCreate($params) {
1131 $this->_pageParams = array(
6a488035
TO
1132 'title' => 'Test Contribution Page',
1133 'financial_type_id' => 1,
1134 'currency' => 'USD',
1135 'financial_account_id' => 1,
1136 'payment_processor' => $params['processor_id'],
1137 'is_active' => 1,
1138 'is_allow_other_amount' => 1,
1139 'min_amount' => 10,
1140 'max_amount' => 1000,
1141 );
f6722559 1142 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
1143 return $contributionPage;
1144 }
1145
6a488035
TO
1146 /**
1147 * Function to create Tag
1148 *
fb32de45 1149 * @return array result of created tag
6a488035 1150 */
fb32de45 1151 function tagCreate($params = array()) {
1152 $defaults = array(
1153 'name' => 'New Tag3',
1154 'description' => 'This is description for Our New Tag ',
1155 'domain_id' => '1',
1156 );
1157 $params = array_merge($defaults, $params);
1158 $result = $this->callAPISuccess('Tag', 'create', $params);
1159 return $result['values'][$result['id']];
6a488035
TO
1160 }
1161
1162 /**
1163 * Function to delete Tag
1164 *
1165 * @param int $tagId id of the tag to be deleted
1166 */
1167 function tagDelete($tagId) {
1168 require_once 'api/api.php';
1169 $params = array(
1170 'tag_id' => $tagId,
6a488035 1171 );
f6722559 1172 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
1173 return $result['id'];
1174 }
1175
1176 /**
1177 * Add entity(s) to the tag
1178 *
1179 * @param array $params
6a488035
TO
1180 */
1181 function entityTagAdd($params) {
f6722559 1182 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
1183 return TRUE;
1184 }
1185
1186 /**
1187 * Function to create contribution
1188 *
1189 * @param int $cID contact_id
1190 * @param int $cTypeID id of financial type
1191 *
1192 * @return int id of created contribution
1193 */
1194 function pledgeCreate($cID) {
1195 $params = array(
1196 'contact_id' => $cID,
1197 'pledge_create_date' => date('Ymd'),
1198 'start_date' => date('Ymd'),
1199 'scheduled_date' => date('Ymd'),
1200 'amount' => 100.00,
1201 'pledge_status_id' => '2',
1202 'financial_type_id' => '1',
1203 'pledge_original_installment_amount' => 20,
1204 'frequency_interval' => 5,
1205 'frequency_unit' => 'year',
1206 'frequency_day' => 15,
1207 'installments' => 5,
6a488035
TO
1208 );
1209
f6722559 1210 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
1211 return $result['id'];
1212 }
1213
1214 /**
1215 * Function to delete contribution
1216 *
1217 * @param int $contributionId
1218 */
1219 function pledgeDelete($pledgeId) {
1220 $params = array(
1221 'pledge_id' => $pledgeId,
6a488035 1222 );
f6722559 1223 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
1224 }
1225
1226 /**
1227 * Function to create contribution
1228 *
1229 * @param int $cID contact_id
1230 * @param int $cTypeID id of financial type
1231 *
1232 * @return int id of created contribution
1233 */
1234 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1235 $params = array(
1236 'domain_id' => 1,
1237 'contact_id' => $cID,
1238 'receive_date' => date('Ymd'),
1239 'total_amount' => 100.00,
1240 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1241 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1242 'non_deductible_amount' => 10.00,
1243 'trxn_id' => $trxnID,
1244 'invoice_id' => $invoiceID,
1245 'source' => 'SSF',
6a488035
TO
1246 'contribution_status_id' => 1,
1247 // 'note' => 'Donating for Nobel Cause', *Fixme
1248 );
1249
1250 if ($isFee) {
1251 $params['fee_amount'] = 5.00;
1252 $params['net_amount'] = 95.00;
1253 }
1254
f6722559 1255 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
1256 return $result['id'];
1257 }
1258
1259 /**
1260 * Function to create online contribution
1261 *
1262 * @param int $financialType id of financial type
1263 *
1264 * @return int id of created contribution
1265 */
1266 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1267 $contribParams = array(
1268 'contact_id' => $params['contact_id'],
1269 'receive_date' => date('Ymd'),
1270 'total_amount' => 100.00,
1271 'financial_type_id' => $financialType,
1272 'contribution_page_id' => $params['contribution_page_id'],
1273 'trxn_id' => 12345,
1274 'invoice_id' => 67890,
1275 'source' => 'SSF',
6a488035 1276 );
f6722559 1277 $contribParams = array_merge($contribParams, $params);
1278 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
6a488035
TO
1279
1280 return $result['id'];
1281 }
1282
1283 /**
1284 * Function to delete contribution
1285 *
1286 * @param int $contributionId
1287 */
1288 function contributionDelete($contributionId) {
1289 $params = array(
1290 'contribution_id' => $contributionId,
6a488035 1291 );
f6722559 1292 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
1293 return $result;
1294 }
1295
1296 /**
1297 * Function to create an Event
1298 *
1299 * @param array $params name-value pair for an event
1300 *
1301 * @return array $event
1302 */
1303 function eventCreate($params = array()) {
1304 // if no contact was passed, make up a dummy event creator
1305 if (!isset($params['contact_id'])) {
1306 $params['contact_id'] = $this->_contactCreate(array(
1307 'contact_type' => 'Individual',
1308 'first_name' => 'Event',
1309 'last_name' => 'Creator',
6a488035
TO
1310 ));
1311 }
1312
1313 // set defaults for missing params
1314 $params = array_merge(array(
1315 'title' => 'Annual CiviCRM meet',
1316 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1317 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1318 'event_type_id' => 1,
1319 'is_public' => 1,
1320 'start_date' => 20081021,
1321 'end_date' => 20081023,
1322 'is_online_registration' => 1,
1323 'registration_start_date' => 20080601,
1324 'registration_end_date' => 20081015,
1325 'max_participants' => 100,
1326 'event_full_text' => 'Sorry! We are already full',
1327 'is_monetory' => 0,
1328 'is_active' => 1,
6a488035
TO
1329 'is_show_location' => 0,
1330 ), $params);
1331
8cba5814 1332 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1333 }
1334
1335 /**
1336 * Function to delete event
1337 *
1338 * @param int $id ID of the event
1339 */
1340 function eventDelete($id) {
1341 $params = array(
1342 'event_id' => $id,
6a488035 1343 );
8cba5814 1344 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1345 }
1346
1347 /**
1348 * Function to delete participant
1349 *
1350 * @param int $participantID
1351 */
1352 function participantDelete($participantID) {
1353 $params = array(
1354 'id' => $participantID,
6a488035 1355 );
8cba5814 1356 return $this->callAPISuccess('Participant', 'delete', $params);
6a488035
TO
1357 }
1358
1359 /**
1360 * Function to create participant payment
1361 *
1362 * @return int $id of created payment
1363 */
1364 function participantPaymentCreate($participantID, $contributionID = NULL) {
1365 //Create Participant Payment record With Values
1366 $params = array(
1367 'participant_id' => $participantID,
1368 'contribution_id' => $contributionID,
6a488035
TO
1369 );
1370
f6722559 1371 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1372 return $result['id'];
1373 }
1374
1375 /**
1376 * Function to delete participant payment
1377 *
1378 * @param int $paymentID
1379 */
1380 function participantPaymentDelete($paymentID) {
1381 $params = array(
1382 'id' => $paymentID,
6a488035 1383 );
f6722559 1384 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1385 }
1386
1387 /**
1388 * Function to add a Location
1389 *
1390 * @return int location id of created location
1391 */
1392 function locationAdd($contactID) {
1393 $address = array(
1394 1 => array(
1395 'location_type' => 'New Location Type',
1396 'is_primary' => 1,
1397 'name' => 'Saint Helier St',
1398 'county' => 'Marin',
1399 'country' => 'United States',
1400 'state_province' => 'Michigan',
1401 'supplemental_address_1' => 'Hallmark Ct',
1402 'supplemental_address_2' => 'Jersey Village',
1403 )
1404 );
1405
1406 $params = array(
1407 'contact_id' => $contactID,
1408 'address' => $address,
6a488035
TO
1409 'location_format' => '2.0',
1410 'location_type' => 'New Location Type',
1411 );
1412
f6722559 1413 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1414 return $result;
1415 }
1416
1417 /**
1418 * Function to delete Locations of contact
1419 *
1420 * @params array $pamars parameters
1421 */
1422 function locationDelete($params) {
f6722559 1423 $result = $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1424 }
1425
1426 /**
1427 * Function to add a Location Type
1428 *
1429 * @return int location id of created location
1430 */
1431 function locationTypeCreate($params = NULL) {
1432 if ($params === NULL) {
1433 $params = array(
1434 'name' => 'New Location Type',
1435 'vcard_name' => 'New Location Type',
1436 'description' => 'Location Type for Delete',
1437 'is_active' => 1,
1438 );
1439 }
1440
6a488035
TO
1441 $locationType = new CRM_Core_DAO_LocationType();
1442 $locationType->copyValues($params);
1443 $locationType->save();
1444 // clear getfields cache
2683ce94 1445 CRM_Core_PseudoConstant::flush();
f6722559 1446 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1447 return $locationType;
1448 }
1449
1450 /**
1451 * Function to delete a Location Type
1452 *
1453 * @param int location type id
1454 */
1455 function locationTypeDelete($locationTypeId) {
6a488035
TO
1456 $locationType = new CRM_Core_DAO_LocationType();
1457 $locationType->id = $locationTypeId;
1458 $locationType->delete();
1459 }
1460
1461 /**
1462 * Function to add a Group
1463 *
1464 * @params array to add group
1465 *
1466 * @return int groupId of created group
1467 *
1468 */
1469 function groupCreate($params = NULL) {
1470 if ($params === NULL) {
1471 $params = array(
1472 'name' => 'Test Group 1',
1473 'domain_id' => 1,
1474 'title' => 'New Test Group Created',
1475 'description' => 'New Test Group Created',
1476 'is_active' => 1,
1477 'visibility' => 'Public Pages',
1478 'group_type' => array(
1479 '1' => 1,
1480 '2' => 1,
1481 ),
6a488035
TO
1482 );
1483 }
1484
f6722559 1485 $result = $this->callAPISuccess('Group', 'create', $params);
1486 return $result['id'];
6a488035
TO
1487 }
1488
1489 /**
1490 * Function to delete a Group
1491 *
1492 * @param int $id
1493 */
1494 function groupDelete($gid) {
1495
1496 $params = array(
1497 'id' => $gid,
6a488035
TO
1498 );
1499
f6722559 1500 $this->callAPISuccess('Group', 'delete', $params);
6a488035
TO
1501 }
1502
1503 /**
1504 * Function to add a UF Join Entry
1505 *
1506 * @return int $id of created UF Join
1507 */
1508 function ufjoinCreate($params = NULL) {
1509 if ($params === NULL) {
1510 $params = array(
1511 'is_active' => 1,
1512 'module' => 'CiviEvent',
1513 'entity_table' => 'civicrm_event',
1514 'entity_id' => 3,
1515 'weight' => 1,
1516 'uf_group_id' => 1,
1517 );
1518 }
f6722559 1519 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1520 return $result;
1521 }
1522
1523 /**
1524 * Function to delete a UF Join Entry
1525 *
1526 * @param array with missing uf_group_id
1527 */
1528 function ufjoinDelete($params = NULL) {
1529 if ($params === NULL) {
1530 $params = array(
1531 'is_active' => 1,
1532 'module' => 'CiviEvent',
1533 'entity_table' => 'civicrm_event',
1534 'entity_id' => 3,
1535 'weight' => 1,
1536 'uf_group_id' => '',
1537 );
1538 }
1539
1540 crm_add_uf_join($params);
1541 }
1542
1543 /**
1544 * Function to create Group for a contact
1545 *
1546 * @param int $contactId
1547 */
1548 function contactGroupCreate($contactId) {
1549 $params = array(
1550 'contact_id.1' => $contactId,
1551 'group_id' => 1,
1552 );
1553
f6722559 1554 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
1555 }
1556
1557 /**
1558 * Function to delete Group for a contact
1559 *
1560 * @param array $params
1561 */
1562 function contactGroupDelete($contactId) {
1563 $params = array(
1564 'contact_id.1' => $contactId,
1565 'group_id' => 1,
1566 );
1567 civicrm_api('GroupContact', 'Delete', $params);
1568 }
1569
1570 /**
1571 * Function to create Activity
1572 *
1573 * @param int $contactId
1574 */
1575 function activityCreate($params = NULL) {
1576
1577 if ($params === NULL) {
1578 $individualSourceID = $this->individualCreate(NULL);
1579
1580 $contactParams = array(
1581 'first_name' => 'Julia',
1582 'Last_name' => 'Anderson',
1583 'prefix' => 'Ms.',
1584 'email' => 'julia_anderson@civicrm.org',
1585 'contact_type' => 'Individual',
6a488035
TO
1586 );
1587
1588 $individualTargetID = $this->individualCreate($contactParams);
1589
1590 $params = array(
1591 'source_contact_id' => $individualSourceID,
1592 'target_contact_id' => array($individualTargetID),
1593 'assignee_contact_id' => array($individualTargetID),
1594 'subject' => 'Discussion on warm beer',
1595 'activity_date_time' => date('Ymd'),
1596 'duration_hours' => 30,
1597 'duration_minutes' => 20,
1598 'location' => 'Baker Street',
1599 'details' => 'Lets schedule a meeting',
1600 'status_id' => 1,
1601 'activity_name' => 'Meeting',
6a488035
TO
1602 );
1603 }
1604
f6722559 1605 $result = $this->callAPISuccess('Activity', 'create', $params);
6a488035
TO
1606
1607 $result['target_contact_id'] = $individualTargetID;
1608 $result['assignee_contact_id'] = $individualTargetID;
1609 return $result;
1610 }
1611
1612 /**
1613 * Function to create an activity type
1614 *
1615 * @params array $params parameters
1616 */
1617 function activityTypeCreate($params) {
f6722559 1618 $result = $this->callAPISuccess('ActivityType', 'create', $params);
6a488035
TO
1619 return $result;
1620 }
1621
1622 /**
1623 * Function to delete activity type
1624 *
1625 * @params Integer $activityTypeId id of the activity type
1626 */
1627 function activityTypeDelete($activityTypeId) {
1628 $params['activity_type_id'] = $activityTypeId;
f6722559 1629 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
6a488035
TO
1630 return $result;
1631 }
1632
1633 /**
1634 * Function to create custom group
1635 *
1636 * @param string $className
1637 * @param string $title name of custom group
1638 */
f6722559 1639 function customGroupCreate($params = array()) {
1640 $defaults = array(
1641 'title' => 'new custom group',
1642 'extends' => 'Contact',
1643 'domain_id' => 1,
1644 'style' => 'Inline',
1645 'is_active' => 1,
1646 );
6a488035 1647
f6722559 1648 $params = array_merge($defaults, $params);
1649
1650 if (strlen($params['title']) > 13) {
1651 $params['title'] = substr($params['title'], 0, 13);
6a488035 1652 }
6a488035 1653
f6722559 1654 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1655 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
6a488035 1656
f6722559 1657 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1658 }
1659
1660 /**
1661 * existing function doesn't allow params to be over-ridden so need a new one
1662 * this one allows you to only pass in the params you want to change
1663 */
1664 function CustomGroupCreateByParams($params = array()) {
1665 $defaults = array(
1666 'title' => "API Custom Group",
1667 'extends' => 'Contact',
1668 'domain_id' => 1,
1669 'style' => 'Inline',
1670 'is_active' => 1,
6a488035
TO
1671 );
1672 $params = array_merge($defaults, $params);
f6722559 1673 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1674 }
1675
1676 /**
1677 * Create custom group with multi fields
1678 */
1679 function CustomGroupMultipleCreateByParams($params = array()) {
1680 $defaults = array(
1681 'style' => 'Tab',
1682 'is_multiple' => 1,
1683 );
1684 $params = array_merge($defaults, $params);
f6722559 1685 return $this->CustomGroupCreateByParams($params);
6a488035
TO
1686 }
1687
1688 /**
1689 * Create custom group with multi fields
1690 */
1691 function CustomGroupMultipleCreateWithFields($params = array()) {
1692 // also need to pass on $params['custom_field'] if not set but not in place yet
1693 $ids = array();
1694 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1695 $ids['custom_group_id'] = $customGroup['id'];
6a488035
TO
1696
1697 $customField = $this->customFieldCreate($ids['custom_group_id']);
1698
1699 $ids['custom_field_id'][] = $customField['id'];
f6722559 1700
6a488035
TO
1701 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_2');
1702 $ids['custom_field_id'][] = $customField['id'];
f6722559 1703
6a488035
TO
1704 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_3');
1705 $ids['custom_field_id'][] = $customField['id'];
f6722559 1706
6a488035
TO
1707 return $ids;
1708 }
1709
1710 /**
1711 * Create a custom group with a single text custom field. See
1712 * participant:testCreateWithCustom for how to use this
1713 *
1714 * @param string $function __FUNCTION__
1715 * @param string $file __FILE__
1716 *
1717 * @return array $ids ids of created objects
1718 *
1719 */
1720 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 1721 $params = array('title' => $function);
6a488035 1722 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
f6722559 1723 $params['extends'] = $entity ? $entity : 'Contact';
1724 $customGroup = $this->CustomGroupCreate($params);
6a488035 1725 $customField = $this->customFieldCreate($customGroup['id'], $function);
80085473 1726 CRM_Core_PseudoConstant::flush();
6a488035
TO
1727
1728 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1729 }
1730
1731 /**
1732 * Function to delete custom group
1733 *
1734 * @param int $customGroupID
1735 */
1736 function customGroupDelete($customGroupID) {
1737
1738 $params['id'] = $customGroupID;
f6722559 1739 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
1740 }
1741
1742 /**
1743 * Function to create custom field
1744 *
1745 * @param int $customGroupID
1746 * @param string $name name of custom field
1747 * @param int $apiversion API version to use
1748 */
1749 function customFieldCreate($customGroupID, $name = "Cust Field") {
1750
1751 $params = array(
1752 'label' => $name,
1753 'name' => $name,
1754 'custom_group_id' => $customGroupID,
1755 'data_type' => 'String',
1756 'html_type' => 'Text',
1757 'is_searchable' => 1,
1758 'is_active' => 1,
f6722559 1759 'version' => $this->_apiversion,
6a488035
TO
1760 );
1761
1762 $result = civicrm_api('custom_field', 'create', $params);
1763
1764 if ($result['is_error'] == 0 && isset($result['id'])) {
1765 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1766 // force reset of enabled components to help grab custom fields
1767 CRM_Core_Component::getEnabledComponents(1);
1768 return $result;
1769 }
1770
1771 if (civicrm_error($result)
1772 || !(CRM_Utils_Array::value('customFieldId', $result['result']))
1773 ) {
1774 throw new Exception('Could not create Custom Field ' . $result['error_message']);
1775 }
1776 }
1777
1778 /**
1779 * Function to delete custom field
1780 *
1781 * @param int $customFieldID
1782 */
1783 function customFieldDelete($customFieldID) {
1784
1785 $params['id'] = $customFieldID;
f6722559 1786 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
1787 }
1788
1789 /**
1790 * Function to create note
1791 *
1792 * @params array $params name-value pair for an event
1793 *
1794 * @return array $note
1795 */
1796 function noteCreate($cId) {
1797 $params = array(
1798 'entity_table' => 'civicrm_contact',
1799 'entity_id' => $cId,
1800 'note' => 'hello I am testing Note',
1801 'contact_id' => $cId,
1802 'modified_date' => date('Ymd'),
1803 'subject' => 'Test Note',
6a488035
TO
1804 );
1805
f6722559 1806 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
1807 }
1808
1809 /**
1810 * Create test generated example in api/v3/examples.
1811 * To turn this off (e.g. on the server) set
1812 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1813 * in your settings file
1814 * @param array $params array as passed to civicrm_api function
1815 * @param array $result array as received from the civicrm_api function
1816 * @param string $function calling function - generally __FUNCTION__
1817 * @param string $filename called from file - generally __FILE__
1818 * @param string $description descriptive text for the example file
1819 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1820 * @param string $action - optional action - otherwise taken from function name
1821 */
1822 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1823 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1824 return;
1825 }
1826 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1827 //todo - this is a bit cludgey
1828 if (empty($action)) {
1829 if (strstr($function, 'Create')) {
1830 $action = empty($action) ? 'create' : $action;
1831 $entityAction = 'Create';
1832 }
1833 elseif (strstr($function, 'GetSingle')) {
1834 $action = empty($action) ? 'getsingle' : $action;
1835 $entityAction = 'GetSingle';
1836 }
1837 elseif (strstr($function, 'GetValue')) {
1838 $action = empty($action) ? 'getvalue' : $action;
1839 $entityAction = 'GetValue';
1840 }
1841 elseif (strstr($function, 'GetCount')) {
1842 $action = empty($action) ? 'getcount' : $action;
1843 $entityAction = 'GetCount';
1844 }
1845 elseif (strstr($function, 'Get')) {
1846 $action = empty($action) ? 'get' : $action;
1847 $entityAction = 'Get';
1848 }
1849 elseif (strstr($function, 'Delete')) {
1850 $action = empty($action) ? 'delete' : $action;
1851 $entityAction = 'Delete';
1852 }
1853 elseif (strstr($function, 'Update')) {
1854 $action = empty($action) ? 'update' : $action;
1855 $entityAction = 'Update';
1856 }
1857 elseif (strstr($function, 'Subscribe')) {
1858 $action = empty($action) ? 'subscribe' : $action;
1859 $entityAction = 'Subscribe';
1860 }
1861 elseif (strstr($function, 'Set')) {
1862 $action = empty($action) ? 'set' : $action;
1863 $entityAction = 'Set';
1864 }
1865 elseif (strstr($function, 'Apply')) {
1866 $action = empty($action) ? 'apply' : $action;
1867 $entityAction = 'Apply';
1868 }
1869 elseif (strstr($function, 'Replace')) {
1870 $action = empty($action) ? 'replace' : $action;
1871 $entityAction = 'Replace';
1872 }
1873 }
1874 else {
1875 $entityAction = ucwords($action);
1876 }
1877
fdd48527 1878 $this->tidyExampleResult($result);
fb32de45 1879 if(isset($params['version'])) {
1880 unset($params['version']);
1881 }
6a488035
TO
1882 // a cleverer person than me would do it in a single regex
1883 if (strstr($entity, 'UF')) {
1884 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1885 }
1886 else {
1887 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1888 }
1889 $smarty = CRM_Core_Smarty::singleton();
1890 $smarty->assign('testfunction', $function);
1891 $function = $fnPrefix . "_" . strtolower($action);
1892 $smarty->assign('function', $function);
1893 $smarty->assign('fnPrefix', $fnPrefix);
1894 $smarty->assign('params', $params);
1895 $smarty->assign('entity', $entity);
1896 $smarty->assign('filename', basename($filename));
1897 $smarty->assign('description', $description);
1898 $smarty->assign('result', $result);
1899
1900 $smarty->assign('action', $action);
1901 if (empty($subfile)) {
1902 if (file_exists('../tests/templates/documentFunction.tpl')) {
1903 $f = fopen("../api/v3/examples/$entity$entityAction.php", "w");
1904 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1905 fclose($f);
1906 }
1907 }
1908 else {
1909 if (file_exists('../tests/templates/documentFunction.tpl')) {
1910 if (!is_dir("../api/v3/examples/$entity")) {
1911 mkdir("../api/v3/examples/$entity");
1912 }
1913 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1914 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1915 fclose($f);
1916 }
1917 }
1918 }
1919
fdd48527 1920 /**
1921 * Tidy up examples array so that fields that change often ..don't
1922 * and debug related fields are unset
1923 * @param array $params
1924 */
1925 function tidyExampleResult(&$result){
1926 if(!is_array($result)) {
1927 return;
1928 }
1929 $fieldsToChange = array(
1930 'hash' => '67eac7789eaee00',
1931 'modified_date' => '2012-11-14 16:02:35',
f27f2724 1932 'created_date' => '2013-07-28 08:49:19',
fdd48527 1933 'create_date' => '20120130621222105',
f27f2724 1934 'application_received_date' => '20130728084957',
1935 'in_date' => '2013-07-28 08:50:19',
1936 'scheduled_date' => '20130728085413',
1937 'approval_date' => '20130728085413',
1938 'pledge_start_date_high' => '20130726090416',
fdd48527 1939 );
1940
fb32de45 1941 $keysToUnset = array('xdebug', 'undefined_fields',);
fdd48527 1942 foreach ($keysToUnset as $unwantedKey) {
1943 if(isset($result[$unwantedKey])) {
1944 unset($result[$unwantedKey]);
1945 }
1946 }
1947
1948 if (isset($result['values']) && is_array($result['values'])) {
1949 foreach ($result['values'] as $index => &$values) {
f505e36c 1950 if(!is_array($values)) {
1951 continue;
1952 }
fdd48527 1953 foreach($values as $key => &$value) {
1954 if(substr($key, 0, 3) == 'api' && is_array($value)) {
1955 if(isset($value['is_error'])) {
1956 // we have a std nested result format
1957 $this->tidyExampleResult($value);
1958 }
1959 else{
1960 foreach ($value as &$nestedResult) {
1961 // this is an alternative syntax for nested results a keyed array of results
1962 $this->tidyExampleResult($nestedResult);
1963 }
1964 }
1965 }
1966 if(in_array($key, $keysToUnset)) {
1967 unset($values[$key]);
1968 }
1969 if(array_key_exists($key, $fieldsToChange)) {
1970 $value = $fieldsToChange[$key];
1971 }
1972 }
1973 }
1974 }
1975 }
1976
6a488035
TO
1977 /**
1978 * Function to delete note
1979 *
1980 * @params int $noteID
1981 *
1982 */
1983 function noteDelete($params) {
f6722559 1984 return $this->callAPISuccess('Note', 'delete', $params);
6a488035
TO
1985 }
1986
1987 /**
1988 * Function to create custom field with Option Values
1989 *
1990 * @param array $customGroup
1991 * @param string $name name of custom field
1992 */
1993 function customFieldOptionValueCreate($customGroup, $name) {
1994 $fieldParams = array(
1995 'custom_group_id' => $customGroup['id'],
1996 'name' => 'test_custom_group',
1997 'label' => 'Country',
1998 'html_type' => 'Select',
1999 'data_type' => 'String',
2000 'weight' => 4,
2001 'is_required' => 1,
2002 'is_searchable' => 0,
2003 'is_active' => 1,
6a488035
TO
2004 );
2005
2006 $optionGroup = array(
2007 'domain_id' => 1,
2008 'name' => 'option_group1',
2009 'label' => 'option_group_label1',
2010 );
2011
2012 $optionValue = array(
2013 'option_label' => array('Label1', 'Label2'),
2014 'option_value' => array('value1', 'value2'),
2015 'option_name' => array($name . '_1', $name . '_2'),
2016 'option_weight' => array(1, 2),
2017 'option_status' => 1,
2018 );
2019
2020 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2021
f6722559 2022 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
2023 }
2024
2025 function confirmEntitiesDeleted($entities) {
2026 foreach ($entities as $entity) {
2027
f6722559 2028 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
2029 if ($result['error'] == 1 || $result['count'] > 0) {
2030 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2031 return TRUE;
2032 }
2033 }
2034 }
2035
2036 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2037 if ($dropCustomValueTables) {
2038 $tablesToTruncate[] = 'civicrm_custom_group';
2039 $tablesToTruncate[] = 'civicrm_custom_field';
2040 }
2041
2042 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2043 foreach ($tablesToTruncate as $table) {
2044 $sql = "TRUNCATE TABLE $table";
2045 CRM_Core_DAO::executeQuery($sql);
2046 }
2047 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2048
2049 if ($dropCustomValueTables) {
2050 $dbName = self::getDBName();
2051 $query = "
2052SELECT TABLE_NAME as tableName
2053FROM INFORMATION_SCHEMA.TABLES
2054WHERE TABLE_SCHEMA = '{$dbName}'
2055AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2056";
2057
2058 $tableDAO = CRM_Core_DAO::executeQuery($query);
2059 while ($tableDAO->fetch()) {
2060 $sql = "DROP TABLE {$tableDAO->tableName}";
2061 CRM_Core_DAO::executeQuery($sql);
2062 }
2063 }
2064 }
2065
2066 /*
2067 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2068 * Default behaviour is to also delete the entity
2069 * @param array $params params array to check agains
2070 * @param int $id id of the entity concerned
2071 * @param string $entity name of entity concerned (e.g. membership)
2072 * @param bool $delete should the entity be deleted as part of this check
2073 * @param string $errorText text to print on error
2074 *
2075 */
2076 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2077
f6722559 2078 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 2079 'id' => $id,
6a488035
TO
2080 ));
2081
2082 if ($delete) {
f6722559 2083 $this->callAPISuccess($entity, 'Delete', array(
6a488035 2084 'id' => $id,
6a488035
TO
2085 ));
2086 }
b0aaad8c 2087 $dateFields = $keys = $dateTimeFields = array();
f6722559 2088 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
2089 foreach ($fields['values'] as $field => $settings) {
2090 if (array_key_exists($field, $result)) {
2091 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2092 }
2093 else {
2094 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2095 }
afd404ea 2096 $type = CRM_Utils_Array::value('type', $settings);
2097 if ($type == CRM_Utils_Type::T_DATE) {
2098 $dateFields[] = $settings['name'];
2099 // we should identify both real names & unique names as dates
2100 if($field != $settings['name']) {
2101 $dateFields[] = $field;
2102 }
2103 }
2104 if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2105 $dateTimeFields[] = $settings['name'];
2106 // we should identify both real names & unique names as dates
2107 if($field != $settings['name']) {
2108 $dateTimeFields[] = $field;
2109 }
6a488035
TO
2110 }
2111 }
2112
2113 if (strtolower($entity) == 'contribution') {
2114 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2115 // this is not returned in id format
2116 unset($params['payment_instrument_id']);
2117 $params['contribution_source'] = $params['source'];
2118 unset($params['source']);
2119 }
2120
2121 foreach ($params as $key => $value) {
afd404ea 2122 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
6a488035
TO
2123 continue;
2124 }
2125 if (in_array($key, $dateFields)) {
2126 $value = date('Y-m-d', strtotime($value));
2127 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2128 }
afd404ea 2129 if (in_array($key, $dateTimeFields)) {
2130 $value = date('Y-m-d H:i:s', strtotime($value));
a72cec08 2131 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
afd404ea 2132 }
2133 $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);
6a488035
TO
2134 }
2135 }
2136
2137 /**
2138 * Function to get formatted values in the actual and expected result
2139 * @param array $actual actual calculated values
2140 * @param array $expected expected values
2141 *
2142 */
2143 function checkArrayEquals(&$actual, &$expected) {
2144 self::unsetId($actual);
2145 self::unsetId($expected);
2146 $this->assertEquals($actual, $expected);
2147 }
2148
2149 /**
2150 * Function to unset the key 'id' from the array
2151 * @param array $unformattedArray The array from which the 'id' has to be unset
2152 *
2153 */
2154 static function unsetId(&$unformattedArray) {
2155 $formattedArray = array();
2156 if (array_key_exists('id', $unformattedArray)) {
2157 unset($unformattedArray['id']);
2158 }
2159 if (CRM_Utils_Array::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2160 foreach ($unformattedArray['values'] as $key => $value) {
2161 if (is_Array($value)) {
2162 foreach ($value as $k => $v) {
2163 if ($k == 'id') {
2164 unset($value[$k]);
2165 }
2166 }
2167 }
2168 elseif ($key == 'id') {
2169 $unformattedArray[$key];
2170 }
2171 $formattedArray = array($value);
2172 }
2173 $unformattedArray['values'] = $formattedArray;
2174 }
2175 }
2176
2177 /**
2178 * Helper to enable/disable custom directory support
2179 *
2180 * @param array $customDirs with members:
2181 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2182 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2183 */
2184 function customDirectories($customDirs) {
2185 require_once 'CRM/Core/Config.php';
2186 $config = CRM_Core_Config::singleton();
2187
2188 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2189 unset($config->customPHPPathDir);
2190 }
2191 elseif ($customDirs['php_path'] === TRUE) {
2192 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2193 }
2194 else {
2195 $config->customPHPPathDir = $php_path;
2196 }
2197
2198 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2199 unset($config->customTemplateDir);
2200 }
2201 elseif ($customDirs['template_path'] === TRUE) {
2202 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2203 }
2204 else {
2205 $config->customTemplateDir = $template_path;
2206 }
2207 }
2208
2209 /**
2210 * Generate a temporary folder
2211 *
2212 * @return $string
2213 */
2214 function createTempDir($prefix = 'test-') {
2215 $tempDir = CRM_Utils_File::tempdir($prefix);
2216 $this->tempDirs[] = $tempDir;
2217 return $tempDir;
2218 }
2219
2220 function cleanTempDirs() {
2221 if (!is_array($this->tempDirs)) {
2222 // fix test errors where this is not set
2223 return;
2224 }
2225 foreach ($this->tempDirs as $tempDir) {
2226 if (is_dir($tempDir)) {
2227 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2228 }
2229 }
2230 }
2231
2232 /**
2233 * Temporarily replace the singleton extension with a different one
2234 */
2235 function setExtensionSystem(CRM_Extension_System $system) {
2236 if ($this->origExtensionSystem == NULL) {
2237 $this->origExtensionSystem = CRM_Extension_System::singleton();
2238 }
2239 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2240 }
2241
2242 function unsetExtensionSystem() {
2243 if ($this->origExtensionSystem !== NULL) {
2244 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2245 $this->origExtensionSystem = NULL;
2246 }
2247 }
f17d75bb
PN
2248
2249 function financialAccountDelete($name) {
2250 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2251 $financialAccount->name = $name;
2252 if($financialAccount->find(TRUE)) {
2253 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2254 $entityFinancialType->financial_account_id = $financialAccount->id;
2255 $entityFinancialType->delete();
2256 $financialAccount->delete();
2257 }
2258 }
fb32de45 2259
2260 /**
2261 * Use $ids as an instruction to do test cleanup
2262 */
2263 function deleteFromIDSArray() {
2264 foreach ($this->ids as $entity => $ids) {
2265 foreach ($ids as $id) {
2266 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2267 }
2268 }
2269 }
6a488035
TO
2270}
2271
2272function CiviUnitTestCase_fatalErrorHandler($message) {
2273 throw new Exception("{$message['message']}: {$message['code']}");
2274}