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