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