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