Merge pull request #1328 from eileenmcnaughton/master
[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
75638074 943 function membershipTypeCreate($params = array()) {
6a488035
TO
944 CRM_Member_PseudoConstant::flush('membershipType');
945 CRM_Core_Config::clearDBCache();
75638074 946 $params = array_merge(array(
6a488035
TO
947 'name' => 'General',
948 'duration_unit' => 'year',
949 'duration_interval' => 1,
950 'period_type' => 'rolling',
75638074 951 'member_of_contact_id' => 1,
6a488035 952 'domain_id' => 1,
75638074 953 'financial_type_id' => 1,
6a488035 954 'is_active' => 1,
6a488035
TO
955 'sequential' => 1,
956 'visibility' => 1,
75638074 957 ), $params);
958
959 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
6a488035 960
6a488035
TO
961 CRM_Member_PseudoConstant::flush('membershipType');
962 CRM_Utils_Cache::singleton()->flush();
6a488035
TO
963
964 return $result['id'];
965 }
966
967 function contactMembershipCreate($params) {
968 $pre = array(
969 'join_date' => '2007-01-21',
970 'start_date' => '2007-01-21',
971 'end_date' => '2007-12-21',
972 'source' => 'Payment',
6a488035
TO
973 );
974
975 foreach ($pre as $key => $val) {
976 if (!isset($params[$key])) {
977 $params[$key] = $val;
978 }
979 }
980
f6722559 981 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
982 return $result['id'];
983 }
984
985 /**
986 * Function to delete Membership Type
987 *
988 * @param int $membershipTypeID
989 */
990 function membershipTypeDelete($params) {
f6722559 991 $result = $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
992 return;
993 }
994
995 function membershipDelete($membershipID) {
f6722559 996 $deleteParams = array('id' => $membershipID);
997 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
998 return;
999 }
1000
1001 function membershipStatusCreate($name = 'test member status') {
1002 $params['name'] = $name;
1003 $params['start_event'] = 'start_date';
1004 $params['end_event'] = 'end_date';
1005 $params['is_current_member'] = 1;
1006 $params['is_active'] = 1;
6a488035 1007
f6722559 1008 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 1009 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
1010 return $result['id'];
1011 }
1012
1013 function membershipStatusDelete($membershipStatusID) {
1014 if (!$membershipStatusID) {
1015 return;
1016 }
4732bb2f 1017 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
1018 return;
1019 }
1020
75638074 1021 function relationshipTypeCreate($params = array()) {
1022 $params = array_merge(array(
6a488035
TO
1023 'name_a_b' => 'Relation 1 for relationship type create',
1024 'name_b_a' => 'Relation 2 for relationship type create',
1025 'contact_type_a' => 'Individual',
1026 'contact_type_b' => 'Organization',
1027 'is_reserved' => 1,
1028 'is_active' => 1,
75638074 1029 ),
1030 $params
1031 );
6a488035 1032
f6722559 1033 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
1034 CRM_Core_PseudoConstant::flush('relationshipType');
1035
1036 return $result['id'];
1037 }
1038
1039 /**
1040 * Function to delete Relatinship Type
1041 *
1042 * @param int $relationshipTypeID
1043 */
1044 function relationshipTypeDelete($relationshipTypeID) {
1045 $params['id'] = $relationshipTypeID;
f6722559 1046 $this->callAPISuccess('relationship_type', 'delete', $params);
6a488035
TO
1047 }
1048
1049 function paymentProcessorTypeCreate($params = NULL) {
1050 if (is_null($params)) {
1051 $params = array(
1052 'name' => 'API_Test_PP',
1053 'title' => 'API Test Payment Processor',
1054 'class_name' => 'CRM_Core_Payment_APITest',
1055 'billing_mode' => 'form',
1056 'is_recur' => 0,
1057 'is_reserved' => 1,
1058 'is_active' => 1,
1059 );
1060 }
f6722559 1061 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 1062
6a488035
TO
1063 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1064
1065 return $result['id'];
1066 }
1067
1068 /**
1069 * Function to create Participant
1070 *
1071 * @param array $params array of contact id and event id values
1072 *
1073 * @return int $id of participant created
1074 */
1075 function participantCreate($params) {
94692f2d 1076 if(empty($params['contact_id'])){
1077 $params['contact_id'] = $this->individualCreate();
1078 }
1079 if(empty($params['event_id'])){
1080 $event = $this->eventCreate();
1081 $params['event_id'] = $event['id'];
1082 }
6a488035 1083 $defaults = array(
6a488035
TO
1084 'status_id' => 2,
1085 'role_id' => 1,
1086 'register_date' => 20070219,
1087 'source' => 'Wimbeldon',
1088 'event_level' => 'Payment',
94692f2d 1089 'debug' => 1,
6a488035
TO
1090 );
1091
1092 $params = array_merge($defaults, $params);
f6722559 1093 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
1094 return $result['id'];
1095 }
1096
1097 /**
1098 * Function to create Payment Processor
1099 *
1100 * @return object of Payment Processsor
1101 */
1102 function processorCreate() {
1103 $processorParams = array(
1104 'domain_id' => 1,
1105 'name' => 'Dummy',
1106 'payment_processor_type_id' => 10,
1107 'financial_account_id' => 12,
1108 'is_active' => 1,
1109 'user_name' => '',
1110 'url_site' => 'http://dummy.com',
1111 'url_recur' => 'http://dummy.com',
1112 'billing_mode' => 1,
1113 );
1114 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1115 return $paymentProcessor;
1116 }
1117
1118 /**
1119 * Function to create contribution page
1120 *
1121 * @return object of contribution page
1122 */
1123 function contributionPageCreate($params) {
1124 $this->_pageParams = array(
6a488035
TO
1125 'title' => 'Test Contribution Page',
1126 'financial_type_id' => 1,
1127 'currency' => 'USD',
1128 'financial_account_id' => 1,
1129 'payment_processor' => $params['processor_id'],
1130 'is_active' => 1,
1131 'is_allow_other_amount' => 1,
1132 'min_amount' => 10,
1133 'max_amount' => 1000,
1134 );
f6722559 1135 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
1136 return $contributionPage;
1137 }
1138
6a488035
TO
1139 /**
1140 * Function to create Tag
1141 *
fb32de45 1142 * @return array result of created tag
6a488035 1143 */
fb32de45 1144 function tagCreate($params = array()) {
1145 $defaults = array(
1146 'name' => 'New Tag3',
1147 'description' => 'This is description for Our New Tag ',
1148 'domain_id' => '1',
1149 );
1150 $params = array_merge($defaults, $params);
1151 $result = $this->callAPISuccess('Tag', 'create', $params);
1152 return $result['values'][$result['id']];
6a488035
TO
1153 }
1154
1155 /**
1156 * Function to delete Tag
1157 *
1158 * @param int $tagId id of the tag to be deleted
1159 */
1160 function tagDelete($tagId) {
1161 require_once 'api/api.php';
1162 $params = array(
1163 'tag_id' => $tagId,
6a488035 1164 );
f6722559 1165 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
1166 return $result['id'];
1167 }
1168
1169 /**
1170 * Add entity(s) to the tag
1171 *
1172 * @param array $params
6a488035
TO
1173 */
1174 function entityTagAdd($params) {
f6722559 1175 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
1176 return TRUE;
1177 }
1178
1179 /**
1180 * Function to create contribution
1181 *
1182 * @param int $cID contact_id
1183 * @param int $cTypeID id of financial type
1184 *
1185 * @return int id of created contribution
1186 */
1187 function pledgeCreate($cID) {
1188 $params = array(
1189 'contact_id' => $cID,
1190 'pledge_create_date' => date('Ymd'),
1191 'start_date' => date('Ymd'),
1192 'scheduled_date' => date('Ymd'),
1193 'amount' => 100.00,
1194 'pledge_status_id' => '2',
1195 'financial_type_id' => '1',
1196 'pledge_original_installment_amount' => 20,
1197 'frequency_interval' => 5,
1198 'frequency_unit' => 'year',
1199 'frequency_day' => 15,
1200 'installments' => 5,
6a488035
TO
1201 );
1202
f6722559 1203 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
1204 return $result['id'];
1205 }
1206
1207 /**
1208 * Function to delete contribution
1209 *
1210 * @param int $contributionId
1211 */
1212 function pledgeDelete($pledgeId) {
1213 $params = array(
1214 'pledge_id' => $pledgeId,
6a488035 1215 );
f6722559 1216 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
1217 }
1218
1219 /**
1220 * Function to create contribution
1221 *
1222 * @param int $cID contact_id
1223 * @param int $cTypeID id of financial type
1224 *
1225 * @return int id of created contribution
1226 */
1227 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1228 $params = array(
1229 'domain_id' => 1,
1230 'contact_id' => $cID,
1231 'receive_date' => date('Ymd'),
1232 'total_amount' => 100.00,
1233 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1234 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1235 'non_deductible_amount' => 10.00,
1236 'trxn_id' => $trxnID,
1237 'invoice_id' => $invoiceID,
1238 'source' => 'SSF',
6a488035
TO
1239 'contribution_status_id' => 1,
1240 // 'note' => 'Donating for Nobel Cause', *Fixme
1241 );
1242
1243 if ($isFee) {
1244 $params['fee_amount'] = 5.00;
1245 $params['net_amount'] = 95.00;
1246 }
1247
f6722559 1248 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
1249 return $result['id'];
1250 }
1251
1252 /**
1253 * Function to create online contribution
1254 *
1255 * @param int $financialType id of financial type
1256 *
1257 * @return int id of created contribution
1258 */
1259 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1260 $contribParams = array(
1261 'contact_id' => $params['contact_id'],
1262 'receive_date' => date('Ymd'),
1263 'total_amount' => 100.00,
1264 'financial_type_id' => $financialType,
1265 'contribution_page_id' => $params['contribution_page_id'],
1266 'trxn_id' => 12345,
1267 'invoice_id' => 67890,
1268 'source' => 'SSF',
6a488035 1269 );
f6722559 1270 $contribParams = array_merge($contribParams, $params);
1271 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
6a488035
TO
1272
1273 return $result['id'];
1274 }
1275
1276 /**
1277 * Function to delete contribution
1278 *
1279 * @param int $contributionId
1280 */
1281 function contributionDelete($contributionId) {
1282 $params = array(
1283 'contribution_id' => $contributionId,
6a488035 1284 );
f6722559 1285 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
1286 return $result;
1287 }
1288
1289 /**
1290 * Function to create an Event
1291 *
1292 * @param array $params name-value pair for an event
1293 *
1294 * @return array $event
1295 */
1296 function eventCreate($params = array()) {
1297 // if no contact was passed, make up a dummy event creator
1298 if (!isset($params['contact_id'])) {
1299 $params['contact_id'] = $this->_contactCreate(array(
1300 'contact_type' => 'Individual',
1301 'first_name' => 'Event',
1302 'last_name' => 'Creator',
6a488035
TO
1303 ));
1304 }
1305
1306 // set defaults for missing params
1307 $params = array_merge(array(
1308 'title' => 'Annual CiviCRM meet',
1309 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1310 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1311 'event_type_id' => 1,
1312 'is_public' => 1,
1313 'start_date' => 20081021,
1314 'end_date' => 20081023,
1315 'is_online_registration' => 1,
1316 'registration_start_date' => 20080601,
1317 'registration_end_date' => 20081015,
1318 'max_participants' => 100,
1319 'event_full_text' => 'Sorry! We are already full',
1320 'is_monetory' => 0,
1321 'is_active' => 1,
6a488035
TO
1322 'is_show_location' => 0,
1323 ), $params);
1324
8cba5814 1325 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1326 }
1327
1328 /**
1329 * Function to delete event
1330 *
1331 * @param int $id ID of the event
1332 */
1333 function eventDelete($id) {
1334 $params = array(
1335 'event_id' => $id,
6a488035 1336 );
8cba5814 1337 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1338 }
1339
1340 /**
1341 * Function to delete participant
1342 *
1343 * @param int $participantID
1344 */
1345 function participantDelete($participantID) {
1346 $params = array(
1347 'id' => $participantID,
6a488035 1348 );
8cba5814 1349 return $this->callAPISuccess('Participant', 'delete', $params);
6a488035
TO
1350 }
1351
1352 /**
1353 * Function to create participant payment
1354 *
1355 * @return int $id of created payment
1356 */
1357 function participantPaymentCreate($participantID, $contributionID = NULL) {
1358 //Create Participant Payment record With Values
1359 $params = array(
1360 'participant_id' => $participantID,
1361 'contribution_id' => $contributionID,
6a488035
TO
1362 );
1363
f6722559 1364 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1365 return $result['id'];
1366 }
1367
1368 /**
1369 * Function to delete participant payment
1370 *
1371 * @param int $paymentID
1372 */
1373 function participantPaymentDelete($paymentID) {
1374 $params = array(
1375 'id' => $paymentID,
6a488035 1376 );
f6722559 1377 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1378 }
1379
1380 /**
1381 * Function to add a Location
1382 *
1383 * @return int location id of created location
1384 */
1385 function locationAdd($contactID) {
1386 $address = array(
1387 1 => array(
1388 'location_type' => 'New Location Type',
1389 'is_primary' => 1,
1390 'name' => 'Saint Helier St',
1391 'county' => 'Marin',
1392 'country' => 'United States',
1393 'state_province' => 'Michigan',
1394 'supplemental_address_1' => 'Hallmark Ct',
1395 'supplemental_address_2' => 'Jersey Village',
1396 )
1397 );
1398
1399 $params = array(
1400 'contact_id' => $contactID,
1401 'address' => $address,
6a488035
TO
1402 'location_format' => '2.0',
1403 'location_type' => 'New Location Type',
1404 );
1405
f6722559 1406 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1407 return $result;
1408 }
1409
1410 /**
1411 * Function to delete Locations of contact
1412 *
1413 * @params array $pamars parameters
1414 */
1415 function locationDelete($params) {
f6722559 1416 $result = $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1417 }
1418
1419 /**
1420 * Function to add a Location Type
1421 *
1422 * @return int location id of created location
1423 */
1424 function locationTypeCreate($params = NULL) {
1425 if ($params === NULL) {
1426 $params = array(
1427 'name' => 'New Location Type',
1428 'vcard_name' => 'New Location Type',
1429 'description' => 'Location Type for Delete',
1430 'is_active' => 1,
1431 );
1432 }
1433
6a488035
TO
1434 $locationType = new CRM_Core_DAO_LocationType();
1435 $locationType->copyValues($params);
1436 $locationType->save();
1437 // clear getfields cache
2683ce94 1438 CRM_Core_PseudoConstant::flush();
f6722559 1439 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1440 return $locationType;
1441 }
1442
1443 /**
1444 * Function to delete a Location Type
1445 *
1446 * @param int location type id
1447 */
1448 function locationTypeDelete($locationTypeId) {
6a488035
TO
1449 $locationType = new CRM_Core_DAO_LocationType();
1450 $locationType->id = $locationTypeId;
1451 $locationType->delete();
1452 }
1453
1454 /**
1455 * Function to add a Group
1456 *
1457 * @params array to add group
1458 *
1459 * @return int groupId of created group
1460 *
1461 */
1462 function groupCreate($params = NULL) {
1463 if ($params === NULL) {
1464 $params = array(
1465 'name' => 'Test Group 1',
1466 'domain_id' => 1,
1467 'title' => 'New Test Group Created',
1468 'description' => 'New Test Group Created',
1469 'is_active' => 1,
1470 'visibility' => 'Public Pages',
1471 'group_type' => array(
1472 '1' => 1,
1473 '2' => 1,
1474 ),
6a488035
TO
1475 );
1476 }
1477
f6722559 1478 $result = $this->callAPISuccess('Group', 'create', $params);
1479 return $result['id'];
6a488035
TO
1480 }
1481
1482 /**
1483 * Function to delete a Group
1484 *
1485 * @param int $id
1486 */
1487 function groupDelete($gid) {
1488
1489 $params = array(
1490 'id' => $gid,
6a488035
TO
1491 );
1492
f6722559 1493 $this->callAPISuccess('Group', 'delete', $params);
6a488035
TO
1494 }
1495
1496 /**
1497 * Function to add a UF Join Entry
1498 *
1499 * @return int $id of created UF Join
1500 */
1501 function ufjoinCreate($params = NULL) {
1502 if ($params === NULL) {
1503 $params = array(
1504 'is_active' => 1,
1505 'module' => 'CiviEvent',
1506 'entity_table' => 'civicrm_event',
1507 'entity_id' => 3,
1508 'weight' => 1,
1509 'uf_group_id' => 1,
1510 );
1511 }
f6722559 1512 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1513 return $result;
1514 }
1515
1516 /**
1517 * Function to delete a UF Join Entry
1518 *
1519 * @param array with missing uf_group_id
1520 */
1521 function ufjoinDelete($params = NULL) {
1522 if ($params === NULL) {
1523 $params = array(
1524 'is_active' => 1,
1525 'module' => 'CiviEvent',
1526 'entity_table' => 'civicrm_event',
1527 'entity_id' => 3,
1528 'weight' => 1,
1529 'uf_group_id' => '',
1530 );
1531 }
1532
1533 crm_add_uf_join($params);
1534 }
1535
1536 /**
1537 * Function to create Group for a contact
1538 *
1539 * @param int $contactId
1540 */
1541 function contactGroupCreate($contactId) {
1542 $params = array(
1543 'contact_id.1' => $contactId,
1544 'group_id' => 1,
1545 );
1546
f6722559 1547 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
1548 }
1549
1550 /**
1551 * Function to delete Group for a contact
1552 *
1553 * @param array $params
1554 */
1555 function contactGroupDelete($contactId) {
1556 $params = array(
1557 'contact_id.1' => $contactId,
1558 'group_id' => 1,
1559 );
1560 civicrm_api('GroupContact', 'Delete', $params);
1561 }
1562
1563 /**
1564 * Function to create Activity
1565 *
1566 * @param int $contactId
1567 */
1568 function activityCreate($params = NULL) {
1569
1570 if ($params === NULL) {
1571 $individualSourceID = $this->individualCreate(NULL);
1572
1573 $contactParams = array(
1574 'first_name' => 'Julia',
1575 'Last_name' => 'Anderson',
1576 'prefix' => 'Ms.',
1577 'email' => 'julia_anderson@civicrm.org',
1578 'contact_type' => 'Individual',
6a488035
TO
1579 );
1580
1581 $individualTargetID = $this->individualCreate($contactParams);
1582
1583 $params = array(
1584 'source_contact_id' => $individualSourceID,
1585 'target_contact_id' => array($individualTargetID),
1586 'assignee_contact_id' => array($individualTargetID),
1587 'subject' => 'Discussion on warm beer',
1588 'activity_date_time' => date('Ymd'),
1589 'duration_hours' => 30,
1590 'duration_minutes' => 20,
1591 'location' => 'Baker Street',
1592 'details' => 'Lets schedule a meeting',
1593 'status_id' => 1,
1594 'activity_name' => 'Meeting',
6a488035
TO
1595 );
1596 }
1597
f6722559 1598 $result = $this->callAPISuccess('Activity', 'create', $params);
6a488035
TO
1599
1600 $result['target_contact_id'] = $individualTargetID;
1601 $result['assignee_contact_id'] = $individualTargetID;
1602 return $result;
1603 }
1604
1605 /**
1606 * Function to create an activity type
1607 *
1608 * @params array $params parameters
1609 */
1610 function activityTypeCreate($params) {
f6722559 1611 $result = $this->callAPISuccess('ActivityType', 'create', $params);
6a488035
TO
1612 return $result;
1613 }
1614
1615 /**
1616 * Function to delete activity type
1617 *
1618 * @params Integer $activityTypeId id of the activity type
1619 */
1620 function activityTypeDelete($activityTypeId) {
1621 $params['activity_type_id'] = $activityTypeId;
f6722559 1622 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
6a488035
TO
1623 return $result;
1624 }
1625
1626 /**
1627 * Function to create custom group
1628 *
1629 * @param string $className
1630 * @param string $title name of custom group
1631 */
f6722559 1632 function customGroupCreate($params = array()) {
1633 $defaults = array(
1634 'title' => 'new custom group',
1635 'extends' => 'Contact',
1636 'domain_id' => 1,
1637 'style' => 'Inline',
1638 'is_active' => 1,
1639 );
6a488035 1640
f6722559 1641 $params = array_merge($defaults, $params);
1642
1643 if (strlen($params['title']) > 13) {
1644 $params['title'] = substr($params['title'], 0, 13);
6a488035 1645 }
6a488035 1646
f6722559 1647 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1648 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
6a488035 1649
f6722559 1650 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1651 }
1652
1653 /**
1654 * existing function doesn't allow params to be over-ridden so need a new one
1655 * this one allows you to only pass in the params you want to change
1656 */
1657 function CustomGroupCreateByParams($params = array()) {
1658 $defaults = array(
1659 'title' => "API Custom Group",
1660 'extends' => 'Contact',
1661 'domain_id' => 1,
1662 'style' => 'Inline',
1663 'is_active' => 1,
6a488035
TO
1664 );
1665 $params = array_merge($defaults, $params);
f6722559 1666 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1667 }
1668
1669 /**
1670 * Create custom group with multi fields
1671 */
1672 function CustomGroupMultipleCreateByParams($params = array()) {
1673 $defaults = array(
1674 'style' => 'Tab',
1675 'is_multiple' => 1,
1676 );
1677 $params = array_merge($defaults, $params);
f6722559 1678 return $this->CustomGroupCreateByParams($params);
6a488035
TO
1679 }
1680
1681 /**
1682 * Create custom group with multi fields
1683 */
1684 function CustomGroupMultipleCreateWithFields($params = array()) {
1685 // also need to pass on $params['custom_field'] if not set but not in place yet
1686 $ids = array();
1687 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1688 $ids['custom_group_id'] = $customGroup['id'];
6a488035
TO
1689
1690 $customField = $this->customFieldCreate($ids['custom_group_id']);
1691
1692 $ids['custom_field_id'][] = $customField['id'];
f6722559 1693
6a488035
TO
1694 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_2');
1695 $ids['custom_field_id'][] = $customField['id'];
f6722559 1696
6a488035
TO
1697 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_3');
1698 $ids['custom_field_id'][] = $customField['id'];
f6722559 1699
6a488035
TO
1700 return $ids;
1701 }
1702
1703 /**
1704 * Create a custom group with a single text custom field. See
1705 * participant:testCreateWithCustom for how to use this
1706 *
1707 * @param string $function __FUNCTION__
1708 * @param string $file __FILE__
1709 *
1710 * @return array $ids ids of created objects
1711 *
1712 */
1713 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 1714 $params = array('title' => $function);
6a488035 1715 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
f6722559 1716 $params['extends'] = $entity ? $entity : 'Contact';
1717 $customGroup = $this->CustomGroupCreate($params);
6a488035 1718 $customField = $this->customFieldCreate($customGroup['id'], $function);
80085473 1719 CRM_Core_PseudoConstant::flush();
6a488035
TO
1720
1721 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1722 }
1723
1724 /**
1725 * Function to delete custom group
1726 *
1727 * @param int $customGroupID
1728 */
1729 function customGroupDelete($customGroupID) {
1730
1731 $params['id'] = $customGroupID;
f6722559 1732 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
1733 }
1734
1735 /**
1736 * Function to create custom field
1737 *
1738 * @param int $customGroupID
1739 * @param string $name name of custom field
1740 * @param int $apiversion API version to use
1741 */
1742 function customFieldCreate($customGroupID, $name = "Cust Field") {
1743
1744 $params = array(
1745 'label' => $name,
1746 'name' => $name,
1747 'custom_group_id' => $customGroupID,
1748 'data_type' => 'String',
1749 'html_type' => 'Text',
1750 'is_searchable' => 1,
1751 'is_active' => 1,
f6722559 1752 'version' => $this->_apiversion,
6a488035
TO
1753 );
1754
1755 $result = civicrm_api('custom_field', 'create', $params);
1756
1757 if ($result['is_error'] == 0 && isset($result['id'])) {
1758 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1759 // force reset of enabled components to help grab custom fields
1760 CRM_Core_Component::getEnabledComponents(1);
1761 return $result;
1762 }
1763
1764 if (civicrm_error($result)
1765 || !(CRM_Utils_Array::value('customFieldId', $result['result']))
1766 ) {
1767 throw new Exception('Could not create Custom Field ' . $result['error_message']);
1768 }
1769 }
1770
1771 /**
1772 * Function to delete custom field
1773 *
1774 * @param int $customFieldID
1775 */
1776 function customFieldDelete($customFieldID) {
1777
1778 $params['id'] = $customFieldID;
f6722559 1779 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
1780 }
1781
1782 /**
1783 * Function to create note
1784 *
1785 * @params array $params name-value pair for an event
1786 *
1787 * @return array $note
1788 */
1789 function noteCreate($cId) {
1790 $params = array(
1791 'entity_table' => 'civicrm_contact',
1792 'entity_id' => $cId,
1793 'note' => 'hello I am testing Note',
1794 'contact_id' => $cId,
1795 'modified_date' => date('Ymd'),
1796 'subject' => 'Test Note',
6a488035
TO
1797 );
1798
f6722559 1799 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
1800 }
1801
1802 /**
1803 * Create test generated example in api/v3/examples.
1804 * To turn this off (e.g. on the server) set
1805 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1806 * in your settings file
1807 * @param array $params array as passed to civicrm_api function
1808 * @param array $result array as received from the civicrm_api function
1809 * @param string $function calling function - generally __FUNCTION__
1810 * @param string $filename called from file - generally __FILE__
1811 * @param string $description descriptive text for the example file
1812 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1813 * @param string $action - optional action - otherwise taken from function name
1814 */
1815 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1816 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1817 return;
1818 }
1819 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1820 //todo - this is a bit cludgey
1821 if (empty($action)) {
1822 if (strstr($function, 'Create')) {
1823 $action = empty($action) ? 'create' : $action;
1824 $entityAction = 'Create';
1825 }
1826 elseif (strstr($function, 'GetSingle')) {
1827 $action = empty($action) ? 'getsingle' : $action;
1828 $entityAction = 'GetSingle';
1829 }
1830 elseif (strstr($function, 'GetValue')) {
1831 $action = empty($action) ? 'getvalue' : $action;
1832 $entityAction = 'GetValue';
1833 }
1834 elseif (strstr($function, 'GetCount')) {
1835 $action = empty($action) ? 'getcount' : $action;
1836 $entityAction = 'GetCount';
1837 }
1838 elseif (strstr($function, 'Get')) {
1839 $action = empty($action) ? 'get' : $action;
1840 $entityAction = 'Get';
1841 }
1842 elseif (strstr($function, 'Delete')) {
1843 $action = empty($action) ? 'delete' : $action;
1844 $entityAction = 'Delete';
1845 }
1846 elseif (strstr($function, 'Update')) {
1847 $action = empty($action) ? 'update' : $action;
1848 $entityAction = 'Update';
1849 }
1850 elseif (strstr($function, 'Subscribe')) {
1851 $action = empty($action) ? 'subscribe' : $action;
1852 $entityAction = 'Subscribe';
1853 }
1854 elseif (strstr($function, 'Set')) {
1855 $action = empty($action) ? 'set' : $action;
1856 $entityAction = 'Set';
1857 }
1858 elseif (strstr($function, 'Apply')) {
1859 $action = empty($action) ? 'apply' : $action;
1860 $entityAction = 'Apply';
1861 }
1862 elseif (strstr($function, 'Replace')) {
1863 $action = empty($action) ? 'replace' : $action;
1864 $entityAction = 'Replace';
1865 }
1866 }
1867 else {
1868 $entityAction = ucwords($action);
1869 }
1870
fdd48527 1871 $this->tidyExampleResult($result);
fb32de45 1872 if(isset($params['version'])) {
1873 unset($params['version']);
1874 }
6a488035
TO
1875 // a cleverer person than me would do it in a single regex
1876 if (strstr($entity, 'UF')) {
1877 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1878 }
1879 else {
1880 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1881 }
1882 $smarty = CRM_Core_Smarty::singleton();
1883 $smarty->assign('testfunction', $function);
1884 $function = $fnPrefix . "_" . strtolower($action);
1885 $smarty->assign('function', $function);
1886 $smarty->assign('fnPrefix', $fnPrefix);
1887 $smarty->assign('params', $params);
1888 $smarty->assign('entity', $entity);
1889 $smarty->assign('filename', basename($filename));
1890 $smarty->assign('description', $description);
1891 $smarty->assign('result', $result);
1892
1893 $smarty->assign('action', $action);
1894 if (empty($subfile)) {
1895 if (file_exists('../tests/templates/documentFunction.tpl')) {
1896 $f = fopen("../api/v3/examples/$entity$entityAction.php", "w");
1897 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1898 fclose($f);
1899 }
1900 }
1901 else {
1902 if (file_exists('../tests/templates/documentFunction.tpl')) {
1903 if (!is_dir("../api/v3/examples/$entity")) {
1904 mkdir("../api/v3/examples/$entity");
1905 }
1906 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
1907 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
1908 fclose($f);
1909 }
1910 }
1911 }
1912
fdd48527 1913 /**
1914 * Tidy up examples array so that fields that change often ..don't
1915 * and debug related fields are unset
1916 * @param array $params
1917 */
1918 function tidyExampleResult(&$result){
1919 if(!is_array($result)) {
1920 return;
1921 }
1922 $fieldsToChange = array(
1923 'hash' => '67eac7789eaee00',
1924 'modified_date' => '2012-11-14 16:02:35',
f27f2724 1925 'created_date' => '2013-07-28 08:49:19',
fdd48527 1926 'create_date' => '20120130621222105',
f27f2724 1927 'application_received_date' => '20130728084957',
1928 'in_date' => '2013-07-28 08:50:19',
1929 'scheduled_date' => '20130728085413',
1930 'approval_date' => '20130728085413',
1931 'pledge_start_date_high' => '20130726090416',
9f1b81e0 1932 'start_date' => '2013-07-29 00:00:00',
1933 'event_start_date' => '2013-07-29 00:00:00',
1934 'end_date' => '2013-08-04 00:00:00',
1935 'event_end_date' => '2013-08-04 00:00:00',
1936 'decision_date' => '20130805000000',
fdd48527 1937 );
1938
fb32de45 1939 $keysToUnset = array('xdebug', 'undefined_fields',);
fdd48527 1940 foreach ($keysToUnset as $unwantedKey) {
1941 if(isset($result[$unwantedKey])) {
1942 unset($result[$unwantedKey]);
1943 }
1944 }
9f1b81e0 1945 if (isset($result['values'])) {
1946 if(!is_array($result['values'])) {
1947 return;
1948 }
1949 $resultArray = &$result['values'];
1950 }
1951 elseif(is_array($result)) {
1952 $resultArray = &$result;
1953 }
1954 else {
1955 return;
1956 }
fdd48527 1957
9f1b81e0 1958 foreach ($resultArray as $index => &$values) {
f505e36c 1959 if(!is_array($values)) {
1960 continue;
1961 }
fdd48527 1962 foreach($values as $key => &$value) {
1963 if(substr($key, 0, 3) == 'api' && is_array($value)) {
1964 if(isset($value['is_error'])) {
1965 // we have a std nested result format
1966 $this->tidyExampleResult($value);
1967 }
1968 else{
1969 foreach ($value as &$nestedResult) {
1970 // this is an alternative syntax for nested results a keyed array of results
1971 $this->tidyExampleResult($nestedResult);
1972 }
1973 }
1974 }
1975 if(in_array($key, $keysToUnset)) {
1976 unset($values[$key]);
1977 }
9f1b81e0 1978 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
fdd48527 1979 $value = $fieldsToChange[$key];
1980 }
1981 }
fdd48527 1982 }
1983 }
1984
6a488035
TO
1985 /**
1986 * Function to delete note
1987 *
1988 * @params int $noteID
1989 *
1990 */
1991 function noteDelete($params) {
f6722559 1992 return $this->callAPISuccess('Note', 'delete', $params);
6a488035
TO
1993 }
1994
1995 /**
1996 * Function to create custom field with Option Values
1997 *
1998 * @param array $customGroup
1999 * @param string $name name of custom field
2000 */
2001 function customFieldOptionValueCreate($customGroup, $name) {
2002 $fieldParams = array(
2003 'custom_group_id' => $customGroup['id'],
2004 'name' => 'test_custom_group',
2005 'label' => 'Country',
2006 'html_type' => 'Select',
2007 'data_type' => 'String',
2008 'weight' => 4,
2009 'is_required' => 1,
2010 'is_searchable' => 0,
2011 'is_active' => 1,
6a488035
TO
2012 );
2013
2014 $optionGroup = array(
2015 'domain_id' => 1,
2016 'name' => 'option_group1',
2017 'label' => 'option_group_label1',
2018 );
2019
2020 $optionValue = array(
2021 'option_label' => array('Label1', 'Label2'),
2022 'option_value' => array('value1', 'value2'),
2023 'option_name' => array($name . '_1', $name . '_2'),
2024 'option_weight' => array(1, 2),
2025 'option_status' => 1,
2026 );
2027
2028 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2029
f6722559 2030 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
2031 }
2032
2033 function confirmEntitiesDeleted($entities) {
2034 foreach ($entities as $entity) {
2035
f6722559 2036 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
2037 if ($result['error'] == 1 || $result['count'] > 0) {
2038 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2039 return TRUE;
2040 }
2041 }
2042 }
2043
2044 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2045 if ($dropCustomValueTables) {
2046 $tablesToTruncate[] = 'civicrm_custom_group';
2047 $tablesToTruncate[] = 'civicrm_custom_field';
2048 }
2049
2050 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2051 foreach ($tablesToTruncate as $table) {
2052 $sql = "TRUNCATE TABLE $table";
2053 CRM_Core_DAO::executeQuery($sql);
2054 }
2055 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2056
2057 if ($dropCustomValueTables) {
2058 $dbName = self::getDBName();
2059 $query = "
2060SELECT TABLE_NAME as tableName
2061FROM INFORMATION_SCHEMA.TABLES
2062WHERE TABLE_SCHEMA = '{$dbName}'
2063AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2064";
2065
2066 $tableDAO = CRM_Core_DAO::executeQuery($query);
2067 while ($tableDAO->fetch()) {
2068 $sql = "DROP TABLE {$tableDAO->tableName}";
2069 CRM_Core_DAO::executeQuery($sql);
2070 }
2071 }
2072 }
2073
2074 /*
2075 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2076 * Default behaviour is to also delete the entity
2077 * @param array $params params array to check agains
2078 * @param int $id id of the entity concerned
2079 * @param string $entity name of entity concerned (e.g. membership)
2080 * @param bool $delete should the entity be deleted as part of this check
2081 * @param string $errorText text to print on error
2082 *
2083 */
2084 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2085
f6722559 2086 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 2087 'id' => $id,
6a488035
TO
2088 ));
2089
2090 if ($delete) {
f6722559 2091 $this->callAPISuccess($entity, 'Delete', array(
6a488035 2092 'id' => $id,
6a488035
TO
2093 ));
2094 }
b0aaad8c 2095 $dateFields = $keys = $dateTimeFields = array();
f6722559 2096 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
2097 foreach ($fields['values'] as $field => $settings) {
2098 if (array_key_exists($field, $result)) {
2099 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2100 }
2101 else {
2102 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2103 }
afd404ea 2104 $type = CRM_Utils_Array::value('type', $settings);
2105 if ($type == CRM_Utils_Type::T_DATE) {
2106 $dateFields[] = $settings['name'];
2107 // we should identify both real names & unique names as dates
2108 if($field != $settings['name']) {
2109 $dateFields[] = $field;
2110 }
2111 }
2112 if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2113 $dateTimeFields[] = $settings['name'];
2114 // we should identify both real names & unique names as dates
2115 if($field != $settings['name']) {
2116 $dateTimeFields[] = $field;
2117 }
6a488035
TO
2118 }
2119 }
2120
2121 if (strtolower($entity) == 'contribution') {
2122 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2123 // this is not returned in id format
2124 unset($params['payment_instrument_id']);
2125 $params['contribution_source'] = $params['source'];
2126 unset($params['source']);
2127 }
2128
2129 foreach ($params as $key => $value) {
afd404ea 2130 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
6a488035
TO
2131 continue;
2132 }
2133 if (in_array($key, $dateFields)) {
2134 $value = date('Y-m-d', strtotime($value));
2135 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2136 }
afd404ea 2137 if (in_array($key, $dateTimeFields)) {
2138 $value = date('Y-m-d H:i:s', strtotime($value));
a72cec08 2139 $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 2140 }
2141 $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
2142 }
2143 }
2144
2145 /**
2146 * Function to get formatted values in the actual and expected result
2147 * @param array $actual actual calculated values
2148 * @param array $expected expected values
2149 *
2150 */
2151 function checkArrayEquals(&$actual, &$expected) {
2152 self::unsetId($actual);
2153 self::unsetId($expected);
2154 $this->assertEquals($actual, $expected);
2155 }
2156
2157 /**
2158 * Function to unset the key 'id' from the array
2159 * @param array $unformattedArray The array from which the 'id' has to be unset
2160 *
2161 */
2162 static function unsetId(&$unformattedArray) {
2163 $formattedArray = array();
2164 if (array_key_exists('id', $unformattedArray)) {
2165 unset($unformattedArray['id']);
2166 }
2167 if (CRM_Utils_Array::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2168 foreach ($unformattedArray['values'] as $key => $value) {
2169 if (is_Array($value)) {
2170 foreach ($value as $k => $v) {
2171 if ($k == 'id') {
2172 unset($value[$k]);
2173 }
2174 }
2175 }
2176 elseif ($key == 'id') {
2177 $unformattedArray[$key];
2178 }
2179 $formattedArray = array($value);
2180 }
2181 $unformattedArray['values'] = $formattedArray;
2182 }
2183 }
2184
2185 /**
2186 * Helper to enable/disable custom directory support
2187 *
2188 * @param array $customDirs with members:
2189 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2190 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2191 */
2192 function customDirectories($customDirs) {
2193 require_once 'CRM/Core/Config.php';
2194 $config = CRM_Core_Config::singleton();
2195
2196 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2197 unset($config->customPHPPathDir);
2198 }
2199 elseif ($customDirs['php_path'] === TRUE) {
2200 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2201 }
2202 else {
2203 $config->customPHPPathDir = $php_path;
2204 }
2205
2206 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2207 unset($config->customTemplateDir);
2208 }
2209 elseif ($customDirs['template_path'] === TRUE) {
2210 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2211 }
2212 else {
2213 $config->customTemplateDir = $template_path;
2214 }
2215 }
2216
2217 /**
2218 * Generate a temporary folder
2219 *
2220 * @return $string
2221 */
2222 function createTempDir($prefix = 'test-') {
2223 $tempDir = CRM_Utils_File::tempdir($prefix);
2224 $this->tempDirs[] = $tempDir;
2225 return $tempDir;
2226 }
2227
2228 function cleanTempDirs() {
2229 if (!is_array($this->tempDirs)) {
2230 // fix test errors where this is not set
2231 return;
2232 }
2233 foreach ($this->tempDirs as $tempDir) {
2234 if (is_dir($tempDir)) {
2235 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2236 }
2237 }
2238 }
2239
2240 /**
2241 * Temporarily replace the singleton extension with a different one
2242 */
2243 function setExtensionSystem(CRM_Extension_System $system) {
2244 if ($this->origExtensionSystem == NULL) {
2245 $this->origExtensionSystem = CRM_Extension_System::singleton();
2246 }
2247 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2248 }
2249
2250 function unsetExtensionSystem() {
2251 if ($this->origExtensionSystem !== NULL) {
2252 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2253 $this->origExtensionSystem = NULL;
2254 }
2255 }
f17d75bb
PN
2256
2257 function financialAccountDelete($name) {
2258 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2259 $financialAccount->name = $name;
2260 if($financialAccount->find(TRUE)) {
2261 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2262 $entityFinancialType->financial_account_id = $financialAccount->id;
2263 $entityFinancialType->delete();
2264 $financialAccount->delete();
2265 }
2266 }
fb32de45 2267
2268 /**
2269 * Use $ids as an instruction to do test cleanup
2270 */
2271 function deleteFromIDSArray() {
2272 foreach ($this->ids as $entity => $ids) {
2273 foreach ($ids as $id) {
2274 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2275 }
2276 }
2277 }
5c2e58ae 2278
2b7d3f8a 2279 /**
2280 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2281 * (NB unclear if this is still required)
2282 */
2283 function _sethtmlGlobals() {
2284 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2285 'required' => array(
2286 'html_quickform_rule_required',
2287 'HTML/QuickForm/Rule/Required.php'
2288 ),
2289 'maxlength' => array(
2290 'html_quickform_rule_range',
2291 'HTML/QuickForm/Rule/Range.php'
2292 ),
2293 'minlength' => array(
2294 'html_quickform_rule_range',
2295 'HTML/QuickForm/Rule/Range.php'
2296 ),
2297 'rangelength' => array(
2298 'html_quickform_rule_range',
2299 'HTML/QuickForm/Rule/Range.php'
2300 ),
2301 'email' => array(
2302 'html_quickform_rule_email',
2303 'HTML/QuickForm/Rule/Email.php'
2304 ),
2305 'regex' => array(
2306 'html_quickform_rule_regex',
2307 'HTML/QuickForm/Rule/Regex.php'
2308 ),
2309 'lettersonly' => array(
2310 'html_quickform_rule_regex',
2311 'HTML/QuickForm/Rule/Regex.php'
2312 ),
2313 'alphanumeric' => array(
2314 'html_quickform_rule_regex',
2315 'HTML/QuickForm/Rule/Regex.php'
2316 ),
2317 'numeric' => array(
2318 'html_quickform_rule_regex',
2319 'HTML/QuickForm/Rule/Regex.php'
2320 ),
2321 'nopunctuation' => array(
2322 'html_quickform_rule_regex',
2323 'HTML/QuickForm/Rule/Regex.php'
2324 ),
2325 'nonzero' => array(
2326 'html_quickform_rule_regex',
2327 'HTML/QuickForm/Rule/Regex.php'
2328 ),
2329 'callback' => array(
2330 'html_quickform_rule_callback',
2331 'HTML/QuickForm/Rule/Callback.php'
2332 ),
2333 'compare' => array(
2334 'html_quickform_rule_compare',
2335 'HTML/QuickForm/Rule/Compare.php'
2336 )
2337 );
2338 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2339 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2340 'group' => array(
2341 'HTML/QuickForm/group.php',
2342 'HTML_QuickForm_group'
2343 ),
2344 'hidden' => array(
2345 'HTML/QuickForm/hidden.php',
2346 'HTML_QuickForm_hidden'
2347 ),
2348 'reset' => array(
2349 'HTML/QuickForm/reset.php',
2350 'HTML_QuickForm_reset'
2351 ),
2352 'checkbox' => array(
2353 'HTML/QuickForm/checkbox.php',
2354 'HTML_QuickForm_checkbox'
2355 ),
2356 'file' => array(
2357 'HTML/QuickForm/file.php',
2358 'HTML_QuickForm_file'
2359 ),
2360 'image' => array(
2361 'HTML/QuickForm/image.php',
2362 'HTML_QuickForm_image'
2363 ),
2364 'password' => array(
2365 'HTML/QuickForm/password.php',
2366 'HTML_QuickForm_password'
2367 ),
2368 'radio' => array(
2369 'HTML/QuickForm/radio.php',
2370 'HTML_QuickForm_radio'
2371 ),
2372 'button' => array(
2373 'HTML/QuickForm/button.php',
2374 'HTML_QuickForm_button'
2375 ),
2376 'submit' => array(
2377 'HTML/QuickForm/submit.php',
2378 'HTML_QuickForm_submit'
2379 ),
2380 'select' => array(
2381 'HTML/QuickForm/select.php',
2382 'HTML_QuickForm_select'
2383 ),
2384 'hiddenselect' => array(
2385 'HTML/QuickForm/hiddenselect.php',
2386 'HTML_QuickForm_hiddenselect'
2387 ),
2388 'text' => array(
2389 'HTML/QuickForm/text.php',
2390 'HTML_QuickForm_text'
2391 ),
2392 'textarea' => array(
2393 'HTML/QuickForm/textarea.php',
2394 'HTML_QuickForm_textarea'
2395 ),
2396 'fckeditor' => array(
2397 'HTML/QuickForm/fckeditor.php',
2398 'HTML_QuickForm_FCKEditor'
2399 ),
2400 'tinymce' => array(
2401 'HTML/QuickForm/tinymce.php',
2402 'HTML_QuickForm_TinyMCE'
2403 ),
2404 'dojoeditor' => array(
2405 'HTML/QuickForm/dojoeditor.php',
2406 'HTML_QuickForm_dojoeditor'
2407 ),
2408 'link' => array(
2409 'HTML/QuickForm/link.php',
2410 'HTML_QuickForm_link'
2411 ),
2412 'advcheckbox' => array(
2413 'HTML/QuickForm/advcheckbox.php',
2414 'HTML_QuickForm_advcheckbox'
2415 ),
2416 'date' => array(
2417 'HTML/QuickForm/date.php',
2418 'HTML_QuickForm_date'
2419 ),
2420 'static' => array(
2421 'HTML/QuickForm/static.php',
2422 'HTML_QuickForm_static'
2423 ),
2424 'header' => array(
2425 'HTML/QuickForm/header.php',
2426 'HTML_QuickForm_header'
2427 ),
2428 'html' => array(
2429 'HTML/QuickForm/html.php',
2430 'HTML_QuickForm_html'
2431 ),
2432 'hierselect' => array(
2433 'HTML/QuickForm/hierselect.php',
2434 'HTML_QuickForm_hierselect'
2435 ),
2436 'autocomplete' => array(
2437 'HTML/QuickForm/autocomplete.php',
2438 'HTML_QuickForm_autocomplete'
2439 ),
2440 'xbutton' => array(
2441 'HTML/QuickForm/xbutton.php',
2442 'HTML_QuickForm_xbutton'
2443 ),
2444 'advmultiselect' => array(
2445 'HTML/QuickForm/advmultiselect.php',
2446 'HTML_QuickForm_advmultiselect'
2447 )
2448 );
2449 }
2450
a86d27fc 2451/**
2452 * Create an instance of the paypal processor
2453 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2454 * this parent class & we don't have a structure for that yet
2455 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2456 * & the best protection agains that is the functions this class affords
2457 */
2458 function paymentProcessorCreate($params = array()) {
2459 $params = array_merge(array(
2460 'name' => 'demo',
2461 'domain_id' => CRM_Core_Config::domainID(),
2462 'payment_processor_type_id' => 'PayPal',
2463 'is_active' => 1,
2464 'is_default' => 0,
2465 'is_test' => 1,
2466 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2467 'password' => '1183377788',
2468 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2469 'url_site' => 'https://www.sandbox.paypal.com/',
2470 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2471 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2472 'class_name' => 'Payment_PayPalImpl',
2473 'billing_mode' => 3,
2474 'financial_type_id' => 1,
2475 ),
2476 $params);
2477 if(!is_numeric($params['payment_processor_type_id'])) {
2478 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2479 //here
2480 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2481 'name' => $params['payment_processor_type_id'],
2482 'return' => 'id',
2483 ), 'integer');
2484 }
2485 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2486 return $result['id'];
2487 }
2488
6a488035
TO
2489
2490function CiviUnitTestCase_fatalErrorHandler($message) {
2491 throw new Exception("{$message['message']}: {$message['code']}");
2492}
a86d27fc 2493}