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