b6d5a62298cea411e39d254154117dcb3f0d0bb6
[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 $params['email'] = strtolower(
1055 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1056 );
1057 $params['prefix_id'] = 3;
1058 $params['suffix_id'] = 3;
1059 }
1060 return $params;
1061 }
1062
1063 /**
1064 * Private helper function for calling civicrm_contact_add
1065 *
1066 * @param $params
1067 *
1068 * @throws Exception
1069 * @internal param \parameters $array for civicrm_contact_add api function call
1070 *
1071 * @return int id of Household created
1072 */
1073 private function _contactCreate($params) {
1074 $result = $this->callAPISuccess('contact', 'create', $params);
1075 if (!empty($result['is_error']) || empty($result['id'])) {
1076 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array::value('trace', $result));
1077 }
1078 return $result['id'];
1079 }
1080
1081 /**
1082 * @param $contactID
1083 *
1084 * @return array|int
1085 */
1086 function contactDelete($contactID) {
1087 $params = array(
1088 'id' => $contactID,
1089 'skip_undelete' => 1,
1090 'debug' => 1,
1091 );
1092 $domain = new CRM_Core_BAO_Domain;
1093 $domain->contact_id = $contactID;
1094 if ($domain->find(TRUE)) {
1095 // we are finding tests trying to delete the domain contact in cleanup
1096 //since this is mainly for cleanup lets put a safeguard here
1097 return;
1098 }
1099 $result = $this->callAPISuccess('contact', 'delete', $params);
1100 return $result;
1101 }
1102
1103 /**
1104 * @param $contactTypeId
1105 *
1106 * @throws Exception
1107 */
1108 function contactTypeDelete($contactTypeId) {
1109 require_once 'CRM/Contact/BAO/ContactType.php';
1110 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1111 if (!$result) {
1112 throw new Exception('Could not delete contact type');
1113 }
1114 }
1115
1116 /**
1117 * @param array $params
1118 *
1119 * @return mixed
1120 */
1121 function membershipTypeCreate($params = array()) {
1122 CRM_Member_PseudoConstant::flush('membershipType');
1123 CRM_Core_Config::clearDBCache();
1124 $memberOfOrganization = $this->organizationCreate();
1125 $params = array_merge(array(
1126 'name' => 'General',
1127 'duration_unit' => 'year',
1128 'duration_interval' => 1,
1129 'period_type' => 'rolling',
1130 'member_of_contact_id' => $memberOfOrganization,
1131 'domain_id' => 1,
1132 'financial_type_id' => 1,
1133 'is_active' => 1,
1134 'sequential' => 1,
1135 'visibility' => 'Public',
1136 ), $params);
1137
1138 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1139
1140 CRM_Member_PseudoConstant::flush('membershipType');
1141 CRM_Utils_Cache::singleton()->flush();
1142
1143 return $result['id'];
1144 }
1145
1146 /**
1147 * @param $params
1148 *
1149 * @return mixed
1150 */
1151 function contactMembershipCreate($params) {
1152 $pre = array(
1153 'join_date' => '2007-01-21',
1154 'start_date' => '2007-01-21',
1155 'end_date' => '2007-12-21',
1156 'source' => 'Payment',
1157 );
1158
1159 foreach ($pre as $key => $val) {
1160 if (!isset($params[$key])) {
1161 $params[$key] = $val;
1162 }
1163 }
1164
1165 $result = $this->callAPISuccess('Membership', 'create', $params);
1166 return $result['id'];
1167 }
1168
1169 /**
1170 * Function to delete Membership Type
1171 *
1172 * @param $params
1173 * @internal param int $membershipTypeID
1174 */
1175 function membershipTypeDelete($params) {
1176 $this->callAPISuccess('MembershipType', 'Delete', $params);
1177 }
1178
1179 /**
1180 * @param $membershipID
1181 */
1182 function membershipDelete($membershipID) {
1183 $deleteParams = array('id' => $membershipID);
1184 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1185 return;
1186 }
1187
1188 /**
1189 * @param string $name
1190 *
1191 * @return mixed
1192 */
1193 function membershipStatusCreate($name = 'test member status') {
1194 $params['name'] = $name;
1195 $params['start_event'] = 'start_date';
1196 $params['end_event'] = 'end_date';
1197 $params['is_current_member'] = 1;
1198 $params['is_active'] = 1;
1199
1200 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1201 CRM_Member_PseudoConstant::flush('membershipStatus');
1202 return $result['id'];
1203 }
1204
1205 /**
1206 * @param $membershipStatusID
1207 */
1208 function membershipStatusDelete($membershipStatusID) {
1209 if (!$membershipStatusID) {
1210 return;
1211 }
1212 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1213 return;
1214 }
1215
1216 /**
1217 * @param array $params
1218 *
1219 * @return mixed
1220 */
1221 function relationshipTypeCreate($params = array()) {
1222 $params = array_merge(array(
1223 'name_a_b' => 'Relation 1 for relationship type create',
1224 'name_b_a' => 'Relation 2 for relationship type create',
1225 'contact_type_a' => 'Individual',
1226 'contact_type_b' => 'Organization',
1227 'is_reserved' => 1,
1228 'is_active' => 1,
1229 ),
1230 $params
1231 );
1232
1233 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1234 CRM_Core_PseudoConstant::flush('relationshipType');
1235
1236 return $result['id'];
1237 }
1238
1239 /**
1240 * Function to delete Relatinship Type
1241 *
1242 * @param int $relationshipTypeID
1243 */
1244 function relationshipTypeDelete($relationshipTypeID) {
1245 $params['id'] = $relationshipTypeID;
1246 $this->callAPISuccess('relationship_type', 'delete', $params);
1247 }
1248
1249 /**
1250 * @param null $params
1251 *
1252 * @return mixed
1253 */
1254 function paymentProcessorTypeCreate($params = NULL) {
1255 if (is_null($params)) {
1256 $params = array(
1257 'name' => 'API_Test_PP',
1258 'title' => 'API Test Payment Processor',
1259 'class_name' => 'CRM_Core_Payment_APITest',
1260 'billing_mode' => 'form',
1261 'is_recur' => 0,
1262 'is_reserved' => 1,
1263 'is_active' => 1,
1264 );
1265 }
1266 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1267
1268 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1269
1270 return $result['id'];
1271 }
1272
1273 /**
1274 * Function to create Participant
1275 *
1276 * @param array $params array of contact id and event id values
1277 *
1278 * @return int $id of participant created
1279 */
1280 function participantCreate($params) {
1281 if(empty($params['contact_id'])){
1282 $params['contact_id'] = $this->individualCreate();
1283 }
1284 if(empty($params['event_id'])){
1285 $event = $this->eventCreate();
1286 $params['event_id'] = $event['id'];
1287 }
1288 $defaults = array(
1289 'status_id' => 2,
1290 'role_id' => 1,
1291 'register_date' => 20070219,
1292 'source' => 'Wimbeldon',
1293 'event_level' => 'Payment',
1294 'debug' => 1,
1295 );
1296
1297 $params = array_merge($defaults, $params);
1298 $result = $this->callAPISuccess('Participant', 'create', $params);
1299 return $result['id'];
1300 }
1301
1302 /**
1303 * Function to create Payment Processor
1304 *
1305 * @return object of Payment Processsor
1306 */
1307 function processorCreate() {
1308 $processorParams = array(
1309 'domain_id' => 1,
1310 'name' => 'Dummy',
1311 'payment_processor_type_id' => 10,
1312 'financial_account_id' => 12,
1313 'is_active' => 1,
1314 'user_name' => '',
1315 'url_site' => 'http://dummy.com',
1316 'url_recur' => 'http://dummy.com',
1317 'billing_mode' => 1,
1318 );
1319 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1320 return $paymentProcessor;
1321 }
1322
1323 /**
1324 * Function to create contribution page
1325 *
1326 * @param $params
1327 * @return object of contribution page
1328 */
1329 function contributionPageCreate($params) {
1330 $this->_pageParams = array(
1331 'title' => 'Test Contribution Page',
1332 'financial_type_id' => 1,
1333 'currency' => 'USD',
1334 'financial_account_id' => 1,
1335 'payment_processor' => $params['processor_id'],
1336 'is_active' => 1,
1337 'is_allow_other_amount' => 1,
1338 'min_amount' => 10,
1339 'max_amount' => 1000,
1340 );
1341 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1342 return $contributionPage;
1343 }
1344
1345 /**
1346 * Function to create Tag
1347 *
1348 * @param array $params
1349 * @return array result of created tag
1350 */
1351 function tagCreate($params = array()) {
1352 $defaults = array(
1353 'name' => 'New Tag3',
1354 'description' => 'This is description for Our New Tag ',
1355 'domain_id' => '1',
1356 );
1357 $params = array_merge($defaults, $params);
1358 $result = $this->callAPISuccess('Tag', 'create', $params);
1359 return $result['values'][$result['id']];
1360 }
1361
1362 /**
1363 * Function to delete Tag
1364 *
1365 * @param int $tagId id of the tag to be deleted
1366 */
1367 function tagDelete($tagId) {
1368 require_once 'api/api.php';
1369 $params = array(
1370 'tag_id' => $tagId,
1371 );
1372 $result = $this->callAPISuccess('Tag', 'delete', $params);
1373 return $result['id'];
1374 }
1375
1376 /**
1377 * Add entity(s) to the tag
1378 *
1379 * @param array $params
1380 *
1381 * @return bool
1382 */
1383 function entityTagAdd($params) {
1384 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1385 return TRUE;
1386 }
1387
1388 /**
1389 * Function to create contribution
1390 *
1391 * @param int $cID contact_id
1392 *
1393 * @internal param int $cTypeID id of financial type
1394 *
1395 * @return int id of created contribution
1396 */
1397 function pledgeCreate($cID) {
1398 $params = array(
1399 'contact_id' => $cID,
1400 'pledge_create_date' => date('Ymd'),
1401 'start_date' => date('Ymd'),
1402 'scheduled_date' => date('Ymd'),
1403 'amount' => 100.00,
1404 'pledge_status_id' => '2',
1405 'financial_type_id' => '1',
1406 'pledge_original_installment_amount' => 20,
1407 'frequency_interval' => 5,
1408 'frequency_unit' => 'year',
1409 'frequency_day' => 15,
1410 'installments' => 5,
1411 );
1412
1413 $result = $this->callAPISuccess('Pledge', 'create', $params);
1414 return $result['id'];
1415 }
1416
1417 /**
1418 * Function to delete contribution
1419 *
1420 * @param $pledgeId
1421 * @internal param int $contributionId
1422 */
1423 function pledgeDelete($pledgeId) {
1424 $params = array(
1425 'pledge_id' => $pledgeId,
1426 );
1427 $this->callAPISuccess('Pledge', 'delete', $params);
1428 }
1429
1430 /**
1431 * Function to create contribution
1432 *
1433 * @param int $cID contact_id
1434 * @param int $cTypeID id of financial type
1435 *
1436 * @param int $invoiceID
1437 * @param int $trxnID
1438 * @param int $paymentInstrumentID
1439 * @param bool $isFee
1440 * @return int id of created contribution
1441 */
1442 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1443 $params = array(
1444 'domain_id' => 1,
1445 'contact_id' => $cID,
1446 'receive_date' => date('Ymd'),
1447 'total_amount' => 100.00,
1448 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1449 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1450 'non_deductible_amount' => 10.00,
1451 'trxn_id' => $trxnID,
1452 'invoice_id' => $invoiceID,
1453 'source' => 'SSF',
1454 'contribution_status_id' => 1,
1455 // 'note' => 'Donating for Nobel Cause', *Fixme
1456 );
1457
1458 if ($isFee) {
1459 $params['fee_amount'] = 5.00;
1460 $params['net_amount'] = 95.00;
1461 }
1462
1463 $result = $this->callAPISuccess('contribution', 'create', $params);
1464 return $result['id'];
1465 }
1466
1467 /**
1468 * Function to create online contribution
1469 *
1470 * @param $params
1471 * @param int $financialType id of financial type
1472 *
1473 * @param int $invoiceID
1474 * @param int $trxnID
1475 * @return int id of created contribution
1476 */
1477 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1478 $contribParams = array(
1479 'contact_id' => $params['contact_id'],
1480 'receive_date' => date('Ymd'),
1481 'total_amount' => 100.00,
1482 'financial_type_id' => $financialType,
1483 'contribution_page_id' => $params['contribution_page_id'],
1484 'trxn_id' => 12345,
1485 'invoice_id' => 67890,
1486 'source' => 'SSF',
1487 );
1488 $contribParams = array_merge($contribParams, $params);
1489 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1490
1491 return $result['id'];
1492 }
1493
1494 /**
1495 * Function to delete contribution
1496 *
1497 * @param int $contributionId
1498 *
1499 * @return array|int
1500 */
1501 function contributionDelete($contributionId) {
1502 $params = array(
1503 'contribution_id' => $contributionId,
1504 );
1505 $result = $this->callAPISuccess('contribution', 'delete', $params);
1506 return $result;
1507 }
1508
1509 /**
1510 * Function to create an Event
1511 *
1512 * @param array $params name-value pair for an event
1513 *
1514 * @return array $event
1515 */
1516 function eventCreate($params = array()) {
1517 // if no contact was passed, make up a dummy event creator
1518 if (!isset($params['contact_id'])) {
1519 $params['contact_id'] = $this->_contactCreate(array(
1520 'contact_type' => 'Individual',
1521 'first_name' => 'Event',
1522 'last_name' => 'Creator',
1523 ));
1524 }
1525
1526 // set defaults for missing params
1527 $params = array_merge(array(
1528 'title' => 'Annual CiviCRM meet',
1529 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1530 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1531 'event_type_id' => 1,
1532 'is_public' => 1,
1533 'start_date' => 20081021,
1534 'end_date' => 20081023,
1535 'is_online_registration' => 1,
1536 'registration_start_date' => 20080601,
1537 'registration_end_date' => 20081015,
1538 'max_participants' => 100,
1539 'event_full_text' => 'Sorry! We are already full',
1540 'is_monetory' => 0,
1541 'is_active' => 1,
1542 'is_show_location' => 0,
1543 ), $params);
1544
1545 return $this->callAPISuccess('Event', 'create', $params);
1546 }
1547
1548 /**
1549 * Function to delete event
1550 *
1551 * @param int $id ID of the event
1552 *
1553 * @return array|int
1554 */
1555 function eventDelete($id) {
1556 $params = array(
1557 'event_id' => $id,
1558 );
1559 return $this->callAPISuccess('event', 'delete', $params);
1560 }
1561
1562 /**
1563 * Function to delete participant
1564 *
1565 * @param int $participantID
1566 *
1567 * @return array|int
1568 */
1569 function participantDelete($participantID) {
1570 $params = array(
1571 'id' => $participantID,
1572 );
1573 return $this->callAPISuccess('Participant', 'delete', $params);
1574 }
1575
1576 /**
1577 * Function to create participant payment
1578 *
1579 * @param $participantID
1580 * @param null $contributionID
1581 * @return int $id of created payment
1582 */
1583 function participantPaymentCreate($participantID, $contributionID = NULL) {
1584 //Create Participant Payment record With Values
1585 $params = array(
1586 'participant_id' => $participantID,
1587 'contribution_id' => $contributionID,
1588 );
1589
1590 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1591 return $result['id'];
1592 }
1593
1594 /**
1595 * Function to delete participant payment
1596 *
1597 * @param int $paymentID
1598 */
1599 function participantPaymentDelete($paymentID) {
1600 $params = array(
1601 'id' => $paymentID,
1602 );
1603 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1604 }
1605
1606 /**
1607 * Function to add a Location
1608 *
1609 * @param $contactID
1610 * @return int location id of created location
1611 */
1612 function locationAdd($contactID) {
1613 $address = array(
1614 1 => array(
1615 'location_type' => 'New Location Type',
1616 'is_primary' => 1,
1617 'name' => 'Saint Helier St',
1618 'county' => 'Marin',
1619 'country' => 'United States',
1620 'state_province' => 'Michigan',
1621 'supplemental_address_1' => 'Hallmark Ct',
1622 'supplemental_address_2' => 'Jersey Village',
1623 )
1624 );
1625
1626 $params = array(
1627 'contact_id' => $contactID,
1628 'address' => $address,
1629 'location_format' => '2.0',
1630 'location_type' => 'New Location Type',
1631 );
1632
1633 $result = $this->callAPISuccess('Location', 'create', $params);
1634 return $result;
1635 }
1636
1637 /**
1638 * Function to delete Locations of contact
1639 *
1640 * @params array $pamars parameters
1641 */
1642 function locationDelete($params) {
1643 $result = $this->callAPISuccess('Location', 'delete', $params);
1644 }
1645
1646 /**
1647 * Function to add a Location Type
1648 *
1649 * @param null $params
1650 * @return int location id of created location
1651 */
1652 function locationTypeCreate($params = NULL) {
1653 if ($params === NULL) {
1654 $params = array(
1655 'name' => 'New Location Type',
1656 'vcard_name' => 'New Location Type',
1657 'description' => 'Location Type for Delete',
1658 'is_active' => 1,
1659 );
1660 }
1661
1662 $locationType = new CRM_Core_DAO_LocationType();
1663 $locationType->copyValues($params);
1664 $locationType->save();
1665 // clear getfields cache
1666 CRM_Core_PseudoConstant::flush();
1667 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1668 return $locationType;
1669 }
1670
1671 /**
1672 * Function to delete a Location Type
1673 *
1674 * @param int location type id
1675 */
1676 function locationTypeDelete($locationTypeId) {
1677 $locationType = new CRM_Core_DAO_LocationType();
1678 $locationType->id = $locationTypeId;
1679 $locationType->delete();
1680 }
1681
1682 /**
1683 * Function to add a Group
1684 *
1685 * @params array to add group
1686 *
1687 * @param array $params
1688 * @return int groupId of created group
1689 */
1690 function groupCreate($params = array()) {
1691 $params = array_merge(array(
1692 'name' => 'Test Group 1',
1693 'domain_id' => 1,
1694 'title' => 'New Test Group Created',
1695 'description' => 'New Test Group Created',
1696 'is_active' => 1,
1697 'visibility' => 'Public Pages',
1698 'group_type' => array(
1699 '1' => 1,
1700 '2' => 1,
1701 ),
1702 ), $params);
1703
1704 $result = $this->callAPISuccess('Group', 'create', $params);
1705 return $result['id'];
1706 }
1707
1708 /**
1709 * Function to delete a Group
1710 *
1711 * @param $gid
1712 * @internal param int $id
1713 */
1714 function groupDelete($gid) {
1715
1716 $params = array(
1717 'id' => $gid,
1718 );
1719
1720 $this->callAPISuccess('Group', 'delete', $params);
1721 }
1722
1723 /**
1724 * Create a UFField
1725 * @param array $params
1726 */
1727 function uFFieldCreate($params = array()) {
1728 $params = array_merge(array(
1729 'uf_group_id' => 1,
1730 'field_name' => 'first_name',
1731 'is_active' => 1,
1732 'is_required' => 1,
1733 'visibility' => 'Public Pages and Listings',
1734 'is_searchable' => '1',
1735 'label' => 'first_name',
1736 'field_type' => 'Individual',
1737 'weight' => 1,
1738 ), $params);
1739 $this->callAPISuccess('uf_field', 'create', $params);
1740 }
1741
1742 /**
1743 * Function to add a UF Join Entry
1744 *
1745 * @param null $params
1746 * @return int $id of created UF Join
1747 */
1748 function ufjoinCreate($params = NULL) {
1749 if ($params === NULL) {
1750 $params = array(
1751 'is_active' => 1,
1752 'module' => 'CiviEvent',
1753 'entity_table' => 'civicrm_event',
1754 'entity_id' => 3,
1755 'weight' => 1,
1756 'uf_group_id' => 1,
1757 );
1758 }
1759 $result = $this->callAPISuccess('uf_join', 'create', $params);
1760 return $result;
1761 }
1762
1763 /**
1764 * Function to delete a UF Join Entry
1765 *
1766 * @param array with missing uf_group_id
1767 */
1768 function ufjoinDelete($params = NULL) {
1769 if ($params === NULL) {
1770 $params = array(
1771 'is_active' => 1,
1772 'module' => 'CiviEvent',
1773 'entity_table' => 'civicrm_event',
1774 'entity_id' => 3,
1775 'weight' => 1,
1776 'uf_group_id' => '',
1777 );
1778 }
1779
1780 crm_add_uf_join($params);
1781 }
1782
1783 /**
1784 * Function to create Group for a contact
1785 *
1786 * @param int $contactId
1787 */
1788 function contactGroupCreate($contactId) {
1789 $params = array(
1790 'contact_id.1' => $contactId,
1791 'group_id' => 1,
1792 );
1793
1794 $this->callAPISuccess('GroupContact', 'Create', $params);
1795 }
1796
1797 /**
1798 * Function to delete Group for a contact
1799 *
1800 * @param $contactId
1801 * @internal param array $params
1802 */
1803 function contactGroupDelete($contactId) {
1804 $params = array(
1805 'contact_id.1' => $contactId,
1806 'group_id' => 1,
1807 );
1808 $this->civicrm_api('GroupContact', 'Delete', $params);
1809 }
1810
1811 /**
1812 * Function to create Activity
1813 *
1814 * @param null $params
1815 * @return array|int
1816 * @internal param int $contactId
1817 */
1818 function activityCreate($params = NULL) {
1819
1820 if ($params === NULL) {
1821 $individualSourceID = $this->individualCreate();
1822
1823 $contactParams = array(
1824 'first_name' => 'Julia',
1825 'Last_name' => 'Anderson',
1826 'prefix' => 'Ms.',
1827 'email' => 'julia_anderson@civicrm.org',
1828 'contact_type' => 'Individual',
1829 );
1830
1831 $individualTargetID = $this->individualCreate($contactParams);
1832
1833 $params = array(
1834 'source_contact_id' => $individualSourceID,
1835 'target_contact_id' => array($individualTargetID),
1836 'assignee_contact_id' => array($individualTargetID),
1837 'subject' => 'Discussion on warm beer',
1838 'activity_date_time' => date('Ymd'),
1839 'duration_hours' => 30,
1840 'duration_minutes' => 20,
1841 'location' => 'Baker Street',
1842 'details' => 'Lets schedule a meeting',
1843 'status_id' => 1,
1844 'activity_name' => 'Meeting',
1845 );
1846 }
1847
1848 $result = $this->callAPISuccess('Activity', 'create', $params);
1849
1850 $result['target_contact_id'] = $individualTargetID;
1851 $result['assignee_contact_id'] = $individualTargetID;
1852 return $result;
1853 }
1854
1855 /**
1856 * Function to create an activity type
1857 *
1858 * @params array $params parameters
1859 */
1860 function activityTypeCreate($params) {
1861 $result = $this->callAPISuccess('ActivityType', 'create', $params);
1862 return $result;
1863 }
1864
1865 /**
1866 * Function to delete activity type
1867 *
1868 * @params Integer $activityTypeId id of the activity type
1869 */
1870 function activityTypeDelete($activityTypeId) {
1871 $params['activity_type_id'] = $activityTypeId;
1872 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
1873 return $result;
1874 }
1875
1876 /**
1877 * Function to create custom group
1878 *
1879 * @param array $params
1880 * @return array|int
1881 * @internal param string $className
1882 * @internal param string $title name of custom group
1883 */
1884 function customGroupCreate($params = array()) {
1885 $defaults = array(
1886 'title' => 'new custom group',
1887 'extends' => 'Contact',
1888 'domain_id' => 1,
1889 'style' => 'Inline',
1890 'is_active' => 1,
1891 );
1892
1893 $params = array_merge($defaults, $params);
1894
1895 if (strlen($params['title']) > 13) {
1896 $params['title'] = substr($params['title'], 0, 13);
1897 }
1898
1899 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1900 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
1901
1902 return $this->callAPISuccess('custom_group', 'create', $params);
1903 }
1904
1905 /**
1906 * existing function doesn't allow params to be over-ridden so need a new one
1907 * this one allows you to only pass in the params you want to change
1908 */
1909 function CustomGroupCreateByParams($params = array()) {
1910 $defaults = array(
1911 'title' => "API Custom Group",
1912 'extends' => 'Contact',
1913 'domain_id' => 1,
1914 'style' => 'Inline',
1915 'is_active' => 1,
1916 );
1917 $params = array_merge($defaults, $params);
1918 return $this->callAPISuccess('custom_group', 'create', $params);
1919 }
1920
1921 /**
1922 * Create custom group with multi fields
1923 */
1924 function CustomGroupMultipleCreateByParams($params = array()) {
1925 $defaults = array(
1926 'style' => 'Tab',
1927 'is_multiple' => 1,
1928 );
1929 $params = array_merge($defaults, $params);
1930 return $this->CustomGroupCreateByParams($params);
1931 }
1932
1933 /**
1934 * Create custom group with multi fields
1935 */
1936 function CustomGroupMultipleCreateWithFields($params = array()) {
1937 // also need to pass on $params['custom_field'] if not set but not in place yet
1938 $ids = array();
1939 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1940 $ids['custom_group_id'] = $customGroup['id'];
1941
1942 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
1943
1944 $ids['custom_field_id'][] = $customField['id'];
1945
1946 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
1947 $ids['custom_field_id'][] = $customField['id'];
1948
1949 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
1950 $ids['custom_field_id'][] = $customField['id'];
1951
1952 return $ids;
1953 }
1954
1955 /**
1956 * Create a custom group with a single text custom field. See
1957 * participant:testCreateWithCustom for how to use this
1958 *
1959 * @param string $function __FUNCTION__
1960 * @param $filename
1961 * @internal param string $file __FILE__
1962 *
1963 * @return array $ids ids of created objects
1964 */
1965 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1966 $params = array('title' => $function);
1967 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1968 $params['extends'] = $entity ? $entity : 'Contact';
1969 $customGroup = $this->CustomGroupCreate($params);
1970 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1971 CRM_Core_PseudoConstant::flush();
1972
1973 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1974 }
1975
1976 /**
1977 * Function to delete custom group
1978 *
1979 * @param int $customGroupID
1980 *
1981 * @return array|int
1982 */
1983 function customGroupDelete($customGroupID) {
1984 $params['id'] = $customGroupID;
1985 return $this->callAPISuccess('custom_group', 'delete', $params);
1986 }
1987
1988 /**
1989 * Function to create custom field
1990 *
1991 * @param array $params (custom_group_id) is required
1992 * @return array|int
1993 * @internal param string $name name of custom field
1994 * @internal param int $apiversion API version to use
1995 */
1996 function customFieldCreate($params) {
1997 $params = array_merge(array(
1998 'label' => 'Custom Field',
1999 'data_type' => 'String',
2000 'html_type' => 'Text',
2001 'is_searchable' => 1,
2002 'is_active' => 1,
2003 'default_value' => 'defaultValue',
2004 ), $params);
2005
2006 $result = $this->callAPISuccess('custom_field', 'create', $params);
2007
2008 if ($result['is_error'] == 0 && isset($result['id'])) {
2009 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2010 // force reset of enabled components to help grab custom fields
2011 CRM_Core_Component::getEnabledComponents(1);
2012 return $result;
2013 }
2014 }
2015
2016 /**
2017 * Function to delete custom field
2018 *
2019 * @param int $customFieldID
2020 *
2021 * @return array|int
2022 */
2023 function customFieldDelete($customFieldID) {
2024
2025 $params['id'] = $customFieldID;
2026 return $this->callAPISuccess('custom_field', 'delete', $params);
2027 }
2028
2029 /**
2030 * Function to create note
2031 *
2032 * @params array $params name-value pair for an event
2033 *
2034 * @param $cId
2035 * @return array $note
2036 */
2037 function noteCreate($cId) {
2038 $params = array(
2039 'entity_table' => 'civicrm_contact',
2040 'entity_id' => $cId,
2041 'note' => 'hello I am testing Note',
2042 'contact_id' => $cId,
2043 'modified_date' => date('Ymd'),
2044 'subject' => 'Test Note',
2045 );
2046
2047 return $this->callAPISuccess('Note', 'create', $params);
2048 }
2049
2050 /**
2051 * Enable CiviCampaign Component
2052 */
2053 function enableCiviCampaign() {
2054 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2055 // force reload of config object
2056 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2057 //flush cache by calling with reset
2058 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2059 }
2060
2061 /**
2062 * Create test generated example in api/v3/examples.
2063 * To turn this off (e.g. on the server) set
2064 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2065 * in your settings file
2066 * @param array $params array as passed to civicrm_api function
2067 * @param array $result array as received from the civicrm_api function
2068 * @param string $function calling function - generally __FUNCTION__
2069 * @param string $filename called from file - generally __FILE__
2070 * @param string $description descriptive text for the example file
2071 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2072 * @param string $action - optional action - otherwise taken from function name
2073 */
2074 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2075 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2076 return;
2077 }
2078 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2079 //todo - this is a bit cludgey
2080 if (empty($action)) {
2081 if (strstr($function, 'Create')) {
2082 $action = empty($action) ? 'create' : $action;
2083 $entityAction = 'Create';
2084 }
2085 elseif (strstr($function, 'GetSingle')) {
2086 $action = empty($action) ? 'getsingle' : $action;
2087 $entityAction = 'GetSingle';
2088 }
2089 elseif (strstr($function, 'GetValue')) {
2090 $action = empty($action) ? 'getvalue' : $action;
2091 $entityAction = 'GetValue';
2092 }
2093 elseif (strstr($function, 'GetCount')) {
2094 $action = empty($action) ? 'getcount' : $action;
2095 $entityAction = 'GetCount';
2096 }
2097 elseif (strstr($function, 'GetFields')) {
2098 $action = empty($action) ? 'getfields' : $action;
2099 $entityAction = 'GetFields';
2100 }
2101 elseif (strstr($function, 'GetList')) {
2102 $action = empty($action) ? 'getlist' : $action;
2103 $entityAction = 'GetList';
2104 }
2105 elseif (strstr($function, 'Get')) {
2106 $action = empty($action) ? 'get' : $action;
2107 $entityAction = 'Get';
2108 }
2109 elseif (strstr($function, 'Delete')) {
2110 $action = empty($action) ? 'delete' : $action;
2111 $entityAction = 'Delete';
2112 }
2113 elseif (strstr($function, 'Update')) {
2114 $action = empty($action) ? 'update' : $action;
2115 $entityAction = 'Update';
2116 }
2117 elseif (strstr($function, 'Subscribe')) {
2118 $action = empty($action) ? 'subscribe' : $action;
2119 $entityAction = 'Subscribe';
2120 }
2121 elseif (strstr($function, 'Submit')) {
2122 $action = empty($action) ? 'submit' : $action;
2123 $entityAction = 'Submit';
2124 }
2125 elseif (strstr($function, 'Apply')) {
2126 $action = empty($action) ? 'apply' : $action;
2127 $entityAction = 'Apply';
2128 }
2129 elseif (strstr($function, 'Replace')) {
2130 $action = empty($action) ? 'replace' : $action;
2131 $entityAction = 'Replace';
2132 }
2133 }
2134 else {
2135 $entityAction = ucwords($action);
2136 }
2137
2138 $this->tidyExampleResult($result);
2139 if(isset($params['version'])) {
2140 unset($params['version']);
2141 }
2142 // a cleverer person than me would do it in a single regex
2143 if (strstr($entity, 'UF')) {
2144 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2145 }
2146 else {
2147 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2148 }
2149 $smarty = CRM_Core_Smarty::singleton();
2150 $smarty->assign('testfunction', $function);
2151 $function = $fnPrefix . "_" . strtolower($action);
2152 $smarty->assign('function', $function);
2153 $smarty->assign('fnPrefix', $fnPrefix);
2154 $smarty->assign('params', $params);
2155 $smarty->assign('entity', $entity);
2156 $smarty->assign('filename', basename($filename));
2157 $smarty->assign('description', $description);
2158 $smarty->assign('result', $result);
2159
2160 $smarty->assign('action', $action);
2161 if (empty($subfile)) {
2162 $subfile = $entityAction;
2163 }
2164 if (file_exists('../tests/templates/documentFunction.tpl')) {
2165 if (!is_dir("../api/v3/examples/$entity")) {
2166 mkdir("../api/v3/examples/$entity");
2167 }
2168 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2169 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2170 fclose($f);
2171 }
2172 }
2173
2174 /**
2175 * Tidy up examples array so that fields that change often ..don't
2176 * and debug related fields are unset
2177 *
2178 * @param $result
2179 *
2180 * @internal param array $params
2181 */
2182 function tidyExampleResult(&$result){
2183 if(!is_array($result)) {
2184 return;
2185 }
2186 $fieldsToChange = array(
2187 'hash' => '67eac7789eaee00',
2188 'modified_date' => '2012-11-14 16:02:35',
2189 'created_date' => '2013-07-28 08:49:19',
2190 'create_date' => '20120130621222105',
2191 'application_received_date' => '20130728084957',
2192 'in_date' => '2013-07-28 08:50:19',
2193 'scheduled_date' => '20130728085413',
2194 'approval_date' => '20130728085413',
2195 'pledge_start_date_high' => '20130726090416',
2196 'start_date' => '2013-07-29 00:00:00',
2197 'event_start_date' => '2013-07-29 00:00:00',
2198 'end_date' => '2013-08-04 00:00:00',
2199 'event_end_date' => '2013-08-04 00:00:00',
2200 'decision_date' => '20130805000000',
2201 );
2202
2203 $keysToUnset = array('xdebug', 'undefined_fields',);
2204 foreach ($keysToUnset as $unwantedKey) {
2205 if(isset($result[$unwantedKey])) {
2206 unset($result[$unwantedKey]);
2207 }
2208 }
2209 if (isset($result['values'])) {
2210 if(!is_array($result['values'])) {
2211 return;
2212 }
2213 $resultArray = &$result['values'];
2214 }
2215 elseif(is_array($result)) {
2216 $resultArray = &$result;
2217 }
2218 else {
2219 return;
2220 }
2221
2222 foreach ($resultArray as $index => &$values) {
2223 if(!is_array($values)) {
2224 continue;
2225 }
2226 foreach($values as $key => &$value) {
2227 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2228 if(isset($value['is_error'])) {
2229 // we have a std nested result format
2230 $this->tidyExampleResult($value);
2231 }
2232 else{
2233 foreach ($value as &$nestedResult) {
2234 // this is an alternative syntax for nested results a keyed array of results
2235 $this->tidyExampleResult($nestedResult);
2236 }
2237 }
2238 }
2239 if(in_array($key, $keysToUnset)) {
2240 unset($values[$key]);
2241 break;
2242 }
2243 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
2244 $value = $fieldsToChange[$key];
2245 }
2246 if(is_string($value)) {
2247 $value = addslashes($value);
2248 }
2249 }
2250 }
2251 }
2252
2253 /**
2254 * Function to delete note
2255 *
2256 * @params int $noteID
2257 *
2258 */
2259 function noteDelete($params) {
2260 return $this->callAPISuccess('Note', 'delete', $params);
2261 }
2262
2263 /**
2264 * Function to create custom field with Option Values
2265 *
2266 * @param array $customGroup
2267 * @param string $name name of custom field
2268 *
2269 * @return array|int
2270 */
2271 function customFieldOptionValueCreate($customGroup, $name) {
2272 $fieldParams = array(
2273 'custom_group_id' => $customGroup['id'],
2274 'name' => 'test_custom_group',
2275 'label' => 'Country',
2276 'html_type' => 'Select',
2277 'data_type' => 'String',
2278 'weight' => 4,
2279 'is_required' => 1,
2280 'is_searchable' => 0,
2281 'is_active' => 1,
2282 );
2283
2284 $optionGroup = array(
2285 'domain_id' => 1,
2286 'name' => 'option_group1',
2287 'label' => 'option_group_label1',
2288 );
2289
2290 $optionValue = array(
2291 'option_label' => array('Label1', 'Label2'),
2292 'option_value' => array('value1', 'value2'),
2293 'option_name' => array($name . '_1', $name . '_2'),
2294 'option_weight' => array(1, 2),
2295 'option_status' => 1,
2296 );
2297
2298 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2299
2300 return $this->callAPISuccess('custom_field', 'create', $params);
2301 }
2302
2303 /**
2304 * @param $entities
2305 *
2306 * @return bool
2307 */
2308 function confirmEntitiesDeleted($entities) {
2309 foreach ($entities as $entity) {
2310
2311 $result = $this->callAPISuccess($entity, 'Get', array());
2312 if ($result['error'] == 1 || $result['count'] > 0) {
2313 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2314 return TRUE;
2315 }
2316 }
2317 }
2318
2319 /**
2320 * @param $tablesToTruncate
2321 * @param bool $dropCustomValueTables
2322 */
2323 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2324 if ($dropCustomValueTables) {
2325 $tablesToTruncate[] = 'civicrm_custom_group';
2326 $tablesToTruncate[] = 'civicrm_custom_field';
2327 }
2328
2329 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2330
2331 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2332 foreach ($tablesToTruncate as $table) {
2333 $sql = "TRUNCATE TABLE $table";
2334 CRM_Core_DAO::executeQuery($sql);
2335 }
2336 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2337
2338 if ($dropCustomValueTables) {
2339 $dbName = self::getDBName();
2340 $query = "
2341 SELECT TABLE_NAME as tableName
2342 FROM INFORMATION_SCHEMA.TABLES
2343 WHERE TABLE_SCHEMA = '{$dbName}'
2344 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2345 ";
2346
2347 $tableDAO = CRM_Core_DAO::executeQuery($query);
2348 while ($tableDAO->fetch()) {
2349 $sql = "DROP TABLE {$tableDAO->tableName}";
2350 CRM_Core_DAO::executeQuery($sql);
2351 }
2352 }
2353 }
2354
2355 /**
2356 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2357 */
2358 function quickCleanUpFinancialEntities() {
2359 $tablesToTruncate = array(
2360 'civicrm_contribution',
2361 'civicrm_financial_trxn',
2362 'civicrm_contribution_recur',
2363 'civicrm_line_item',
2364 'civicrm_contribution_page',
2365 'civicrm_payment_processor',
2366 'civicrm_entity_financial_trxn',
2367 'civicrm_membership',
2368 'civicrm_membership_type',
2369 'civicrm_membership_payment',
2370 'civicrm_membership_log',
2371 'civicrm_membership_block',
2372 'civicrm_event',
2373 'civicrm_participant',
2374 'civicrm_participant_payment',
2375 'civicrm_pledge',
2376 'civicrm_price_set_entity',
2377 );
2378 $this->quickCleanup($tablesToTruncate);
2379 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2380 }
2381 /*
2382 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2383 * Default behaviour is to also delete the entity
2384 * @param array $params params array to check agains
2385 * @param int $id id of the entity concerned
2386 * @param string $entity name of entity concerned (e.g. membership)
2387 * @param bool $delete should the entity be deleted as part of this check
2388 * @param string $errorText text to print on error
2389 *
2390 */
2391 /**
2392 * @param $params
2393 * @param $id
2394 * @param $entity
2395 * @param int $delete
2396 * @param string $errorText
2397 *
2398 * @throws Exception
2399 */
2400 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2401
2402 $result = $this->callAPISuccessGetSingle($entity, array(
2403 'id' => $id,
2404 ));
2405
2406 if ($delete) {
2407 $this->callAPISuccess($entity, 'Delete', array(
2408 'id' => $id,
2409 ));
2410 }
2411 $dateFields = $keys = $dateTimeFields = array();
2412 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2413 foreach ($fields['values'] as $field => $settings) {
2414 if (array_key_exists($field, $result)) {
2415 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2416 }
2417 else {
2418 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2419 }
2420 $type = CRM_Utils_Array::value('type', $settings);
2421 if ($type == CRM_Utils_Type::T_DATE) {
2422 $dateFields[] = $settings['name'];
2423 // we should identify both real names & unique names as dates
2424 if($field != $settings['name']) {
2425 $dateFields[] = $field;
2426 }
2427 }
2428 if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2429 $dateTimeFields[] = $settings['name'];
2430 // we should identify both real names & unique names as dates
2431 if($field != $settings['name']) {
2432 $dateTimeFields[] = $field;
2433 }
2434 }
2435 }
2436
2437 if (strtolower($entity) == 'contribution') {
2438 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2439 // this is not returned in id format
2440 unset($params['payment_instrument_id']);
2441 $params['contribution_source'] = $params['source'];
2442 unset($params['source']);
2443 }
2444
2445 foreach ($params as $key => $value) {
2446 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2447 continue;
2448 }
2449 if (in_array($key, $dateFields)) {
2450 $value = date('Y-m-d', strtotime($value));
2451 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2452 }
2453 if (in_array($key, $dateTimeFields)) {
2454 $value = date('Y-m-d H:i:s', strtotime($value));
2455 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2456 }
2457 $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);
2458 }
2459 }
2460
2461 /**
2462 * Function to get formatted values in the actual and expected result
2463 * @param array $actual actual calculated values
2464 * @param array $expected expected values
2465 *
2466 */
2467 function checkArrayEquals(&$actual, &$expected) {
2468 self::unsetId($actual);
2469 self::unsetId($expected);
2470 $this->assertEquals($actual, $expected);
2471 }
2472
2473 /**
2474 * Function to unset the key 'id' from the array
2475 * @param array $unformattedArray The array from which the 'id' has to be unset
2476 *
2477 */
2478 static function unsetId(&$unformattedArray) {
2479 $formattedArray = array();
2480 if (array_key_exists('id', $unformattedArray)) {
2481 unset($unformattedArray['id']);
2482 }
2483 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2484 foreach ($unformattedArray['values'] as $key => $value) {
2485 if (is_Array($value)) {
2486 foreach ($value as $k => $v) {
2487 if ($k == 'id') {
2488 unset($value[$k]);
2489 }
2490 }
2491 }
2492 elseif ($key == 'id') {
2493 $unformattedArray[$key];
2494 }
2495 $formattedArray = array($value);
2496 }
2497 $unformattedArray['values'] = $formattedArray;
2498 }
2499 }
2500
2501 /**
2502 * Helper to enable/disable custom directory support
2503 *
2504 * @param array $customDirs with members:
2505 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2506 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2507 */
2508 function customDirectories($customDirs) {
2509 require_once 'CRM/Core/Config.php';
2510 $config = CRM_Core_Config::singleton();
2511
2512 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2513 unset($config->customPHPPathDir);
2514 }
2515 elseif ($customDirs['php_path'] === TRUE) {
2516 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2517 }
2518 else {
2519 $config->customPHPPathDir = $php_path;
2520 }
2521
2522 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2523 unset($config->customTemplateDir);
2524 }
2525 elseif ($customDirs['template_path'] === TRUE) {
2526 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2527 }
2528 else {
2529 $config->customTemplateDir = $template_path;
2530 }
2531 }
2532
2533 /**
2534 * Generate a temporary folder
2535 *
2536 * @param string $prefix
2537 * @return string $string
2538 */
2539 function createTempDir($prefix = 'test-') {
2540 $tempDir = CRM_Utils_File::tempdir($prefix);
2541 $this->tempDirs[] = $tempDir;
2542 return $tempDir;
2543 }
2544
2545 function cleanTempDirs() {
2546 if (!is_array($this->tempDirs)) {
2547 // fix test errors where this is not set
2548 return;
2549 }
2550 foreach ($this->tempDirs as $tempDir) {
2551 if (is_dir($tempDir)) {
2552 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2553 }
2554 }
2555 }
2556
2557 /**
2558 * Temporarily replace the singleton extension with a different one
2559 */
2560 function setExtensionSystem(CRM_Extension_System $system) {
2561 if ($this->origExtensionSystem == NULL) {
2562 $this->origExtensionSystem = CRM_Extension_System::singleton();
2563 }
2564 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2565 }
2566
2567 function unsetExtensionSystem() {
2568 if ($this->origExtensionSystem !== NULL) {
2569 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2570 $this->origExtensionSystem = NULL;
2571 }
2572 }
2573
2574 /**
2575 * Temporarily alter the settings-metadata to add a mock setting.
2576 *
2577 * WARNING: The setting metadata will disappear on the next cache-clear.
2578 *
2579 * @param $extras
2580 * @return void
2581 */
2582 function setMockSettingsMetaData($extras) {
2583 CRM_Core_BAO_Setting::$_cache = array();
2584 $this->callAPISuccess('system','flush', array());
2585 CRM_Core_BAO_Setting::$_cache = array();
2586
2587 CRM_Utils_Hook::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2588 $metadata = array_merge($metadata, $extras);
2589 });
2590
2591 $fields = $this->callAPISuccess('setting', 'getfields', array());
2592 foreach ($extras as $key => $spec) {
2593 $this->assertNotEmpty($spec['title']);
2594 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2595 }
2596 }
2597
2598 /**
2599 * @param $name
2600 */
2601 function financialAccountDelete($name) {
2602 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2603 $financialAccount->name = $name;
2604 if($financialAccount->find(TRUE)) {
2605 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2606 $entityFinancialType->financial_account_id = $financialAccount->id;
2607 $entityFinancialType->delete();
2608 $financialAccount->delete();
2609 }
2610 }
2611
2612 /**
2613 * Use $ids as an instruction to do test cleanup
2614 */
2615 function deleteFromIDSArray() {
2616 foreach ($this->ids as $entity => $ids) {
2617 foreach ($ids as $id) {
2618 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2619 }
2620 }
2621 }
2622
2623 /**
2624 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2625 * (NB unclear if this is still required)
2626 */
2627 function _sethtmlGlobals() {
2628 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2629 'required' => array(
2630 'html_quickform_rule_required',
2631 'HTML/QuickForm/Rule/Required.php'
2632 ),
2633 'maxlength' => array(
2634 'html_quickform_rule_range',
2635 'HTML/QuickForm/Rule/Range.php'
2636 ),
2637 'minlength' => array(
2638 'html_quickform_rule_range',
2639 'HTML/QuickForm/Rule/Range.php'
2640 ),
2641 'rangelength' => array(
2642 'html_quickform_rule_range',
2643 'HTML/QuickForm/Rule/Range.php'
2644 ),
2645 'email' => array(
2646 'html_quickform_rule_email',
2647 'HTML/QuickForm/Rule/Email.php'
2648 ),
2649 'regex' => array(
2650 'html_quickform_rule_regex',
2651 'HTML/QuickForm/Rule/Regex.php'
2652 ),
2653 'lettersonly' => array(
2654 'html_quickform_rule_regex',
2655 'HTML/QuickForm/Rule/Regex.php'
2656 ),
2657 'alphanumeric' => array(
2658 'html_quickform_rule_regex',
2659 'HTML/QuickForm/Rule/Regex.php'
2660 ),
2661 'numeric' => array(
2662 'html_quickform_rule_regex',
2663 'HTML/QuickForm/Rule/Regex.php'
2664 ),
2665 'nopunctuation' => array(
2666 'html_quickform_rule_regex',
2667 'HTML/QuickForm/Rule/Regex.php'
2668 ),
2669 'nonzero' => array(
2670 'html_quickform_rule_regex',
2671 'HTML/QuickForm/Rule/Regex.php'
2672 ),
2673 'callback' => array(
2674 'html_quickform_rule_callback',
2675 'HTML/QuickForm/Rule/Callback.php'
2676 ),
2677 'compare' => array(
2678 'html_quickform_rule_compare',
2679 'HTML/QuickForm/Rule/Compare.php'
2680 )
2681 );
2682 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2683 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2684 'group' => array(
2685 'HTML/QuickForm/group.php',
2686 'HTML_QuickForm_group'
2687 ),
2688 'hidden' => array(
2689 'HTML/QuickForm/hidden.php',
2690 'HTML_QuickForm_hidden'
2691 ),
2692 'reset' => array(
2693 'HTML/QuickForm/reset.php',
2694 'HTML_QuickForm_reset'
2695 ),
2696 'checkbox' => array(
2697 'HTML/QuickForm/checkbox.php',
2698 'HTML_QuickForm_checkbox'
2699 ),
2700 'file' => array(
2701 'HTML/QuickForm/file.php',
2702 'HTML_QuickForm_file'
2703 ),
2704 'image' => array(
2705 'HTML/QuickForm/image.php',
2706 'HTML_QuickForm_image'
2707 ),
2708 'password' => array(
2709 'HTML/QuickForm/password.php',
2710 'HTML_QuickForm_password'
2711 ),
2712 'radio' => array(
2713 'HTML/QuickForm/radio.php',
2714 'HTML_QuickForm_radio'
2715 ),
2716 'button' => array(
2717 'HTML/QuickForm/button.php',
2718 'HTML_QuickForm_button'
2719 ),
2720 'submit' => array(
2721 'HTML/QuickForm/submit.php',
2722 'HTML_QuickForm_submit'
2723 ),
2724 'select' => array(
2725 'HTML/QuickForm/select.php',
2726 'HTML_QuickForm_select'
2727 ),
2728 'hiddenselect' => array(
2729 'HTML/QuickForm/hiddenselect.php',
2730 'HTML_QuickForm_hiddenselect'
2731 ),
2732 'text' => array(
2733 'HTML/QuickForm/text.php',
2734 'HTML_QuickForm_text'
2735 ),
2736 'textarea' => array(
2737 'HTML/QuickForm/textarea.php',
2738 'HTML_QuickForm_textarea'
2739 ),
2740 'fckeditor' => array(
2741 'HTML/QuickForm/fckeditor.php',
2742 'HTML_QuickForm_FCKEditor'
2743 ),
2744 'tinymce' => array(
2745 'HTML/QuickForm/tinymce.php',
2746 'HTML_QuickForm_TinyMCE'
2747 ),
2748 'dojoeditor' => array(
2749 'HTML/QuickForm/dojoeditor.php',
2750 'HTML_QuickForm_dojoeditor'
2751 ),
2752 'link' => array(
2753 'HTML/QuickForm/link.php',
2754 'HTML_QuickForm_link'
2755 ),
2756 'advcheckbox' => array(
2757 'HTML/QuickForm/advcheckbox.php',
2758 'HTML_QuickForm_advcheckbox'
2759 ),
2760 'date' => array(
2761 'HTML/QuickForm/date.php',
2762 'HTML_QuickForm_date'
2763 ),
2764 'static' => array(
2765 'HTML/QuickForm/static.php',
2766 'HTML_QuickForm_static'
2767 ),
2768 'header' => array(
2769 'HTML/QuickForm/header.php',
2770 'HTML_QuickForm_header'
2771 ),
2772 'html' => array(
2773 'HTML/QuickForm/html.php',
2774 'HTML_QuickForm_html'
2775 ),
2776 'hierselect' => array(
2777 'HTML/QuickForm/hierselect.php',
2778 'HTML_QuickForm_hierselect'
2779 ),
2780 'autocomplete' => array(
2781 'HTML/QuickForm/autocomplete.php',
2782 'HTML_QuickForm_autocomplete'
2783 ),
2784 'xbutton' => array(
2785 'HTML/QuickForm/xbutton.php',
2786 'HTML_QuickForm_xbutton'
2787 ),
2788 'advmultiselect' => array(
2789 'HTML/QuickForm/advmultiselect.php',
2790 'HTML_QuickForm_advmultiselect'
2791 )
2792 );
2793 }
2794
2795 /**
2796 * Set up an acl allowing contact to see 2 specified groups
2797 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2798 *
2799 * You need to have precreated these groups & created the user e.g
2800 * $this->createLoggedInUser();
2801 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2802 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2803 *
2804 */
2805 function setupACL() {
2806 global $_REQUEST;
2807 $_REQUEST = $this->_params;
2808 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2809 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2810 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2811 'label' => 'pick me',
2812 'value' => 55,
2813 ));
2814
2815
2816 CRM_Core_DAO::executeQuery("
2817 TRUNCATE civicrm_acl_cache
2818 ");
2819
2820 CRM_Core_DAO::executeQuery("
2821 TRUNCATE civicrm_acl_contact_cache
2822 ");
2823
2824
2825 CRM_Core_DAO::executeQuery("
2826 INSERT INTO civicrm_acl_entity_role (
2827 `acl_role_id`, `entity_table`, `entity_id`
2828 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2829 ");
2830
2831 CRM_Core_DAO::executeQuery("
2832 INSERT INTO civicrm_acl (
2833 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2834 )
2835 VALUES (
2836 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2837 );
2838 ");
2839
2840 CRM_Core_DAO::executeQuery("
2841 INSERT INTO civicrm_acl (
2842 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2843 )
2844 VALUES (
2845 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2846 );
2847 ");
2848 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2849 $this->callAPISuccess('group_contact', 'create', array(
2850 'group_id' => $this->_permissionedGroup,
2851 'contact_id' => $this->_loggedInUser,
2852 ));
2853 //flush cache
2854 CRM_ACL_BAO_Cache::resetCache();
2855 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
2856 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2857 }
2858
2859 /**
2860 * alter default price set so that the field numbers are not all 1 (hiding errors)
2861 */
2862 function offsetDefaultPriceSet() {
2863 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2864 $firstID = $contributionPriceSet['id'];
2865 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2866 unset($contributionPriceSet['id']);
2867 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2868 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2869 unset($priceField['id']);
2870 $priceField['price_set_id'] = $newPriceSet['id'];
2871 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2872 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2873
2874 unset($priceFieldValue['id']);
2875 //create some padding to use up ids
2876 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2877 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2878 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2879
2880 }
2881
2882 /**
2883 * Create an instance of the paypal processor
2884 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2885 * this parent class & we don't have a structure for that yet
2886 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2887 * & the best protection agains that is the functions this class affords
2888 */
2889 function paymentProcessorCreate($params = array()) {
2890 $params = array_merge(array(
2891 'name' => 'demo',
2892 'domain_id' => CRM_Core_Config::domainID(),
2893 'payment_processor_type_id' => 'PayPal',
2894 'is_active' => 1,
2895 'is_default' => 0,
2896 'is_test' => 1,
2897 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2898 'password' => '1183377788',
2899 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2900 'url_site' => 'https://www.sandbox.paypal.com/',
2901 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2902 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2903 'class_name' => 'Payment_PayPalImpl',
2904 'billing_mode' => 3,
2905 'financial_type_id' => 1,
2906 ),
2907 $params);
2908 if(!is_numeric($params['payment_processor_type_id'])) {
2909 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2910 //here
2911 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2912 'name' => $params['payment_processor_type_id'],
2913 'return' => 'id',
2914 ), 'integer');
2915 }
2916 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2917 return $result['id'];
2918 }
2919
2920
2921 /**
2922 * @param $message
2923 *
2924 * @throws Exception
2925 */function CiviUnitTestCase_fatalErrorHandler($message) {
2926 throw new Exception("{$message['message']}: {$message['code']}");
2927 }
2928 }