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