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