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