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