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