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